From f0fe8e9d58855ccabe67e355b23436d24378b1fa Mon Sep 17 00:00:00 2001 From: LunaStev Date: Fri, 30 Oct 2026 20:38:51 +0900 Subject: [PATCH 1/8] build: verify explicit ISA product composition Signed-off-by: LunaStev --- .github/workflows/quality.yml | 12 ++++--- CONTRIBUTING.md | 4 ++- tools/check_product_graph.py | 60 +++++++++++++++++++++++++++++++++++ tools/test_product_graph.py | 30 ++++++++++++++++++ 4 files changed, 100 insertions(+), 6 deletions(-) create mode 100644 tools/check_product_graph.py create mode 100644 tools/test_product_graph.py diff --git a/.github/workflows/quality.yml b/.github/workflows/quality.yml index af4ead5..0024002 100644 --- a/.github/workflows/quality.yml +++ b/.github/workflows/quality.yml @@ -95,11 +95,11 @@ jobs: fail-fast: false matrix: include: - - { name: none, flags: '' } - - { name: amd64, flags: '--features asm-amd64' } - - { name: aarch64, flags: '--features asm-aarch64' } - - { name: riscv64, flags: '--features asm-riscv64' } - - { name: loongarch64, flags: '--features asm-loongarch64' } + - { name: none, flags: '', graph_flags: '' } + - { name: amd64, flags: '--features asm-amd64', graph_flags: '--isa amd64' } + - { name: aarch64, flags: '--features asm-aarch64', graph_flags: '--isa aarch64' } + - { name: riscv64, flags: '--features asm-riscv64', graph_flags: '--isa riscv64' } + - { name: loongarch64, flags: '--features asm-loongarch64', graph_flags: '--isa loongarch64' } env: WHALE_ASMOBJ_DIR: ${{ github.workspace }}/.ci-asmobj/x86_64-unknown-linux-gnu steps: @@ -114,6 +114,8 @@ jobs: - run: rustup toolchain install stable --profile minimal - name: Check selected assembler registration and integration run: python tools/ci.py run --name reduced-isa -- cargo test -p whale --no-default-features ${{ matrix.flags }} --locked + - name: Check selected production dependency graph + run: python tools/ci.py run --name product-graph -- python tools/check_product_graph.py ${{ matrix.graph_flags }} - name: Retain command logs and reproduction evidence if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 387f0a5..0633624 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -41,7 +41,9 @@ IR remains Rust. Official and contributed architectures follow the same process. Central enum, dispatch and build-list edits are expected. Run `python3 tools/check_module_layers.py` -to check dependency direction. See [BUILDING.md](BUILDING.md#select-assembler-outputs-and-host-machines) +to check dependency direction, and `python3 tools/check_product_graph.py --isa amd64` +to check that a selected product links only the requested ISA crate. Omit `--isa` +for a product without assemblers. See [BUILDING.md](BUILDING.md#select-assembler-outputs-and-host-machines) for product selection and executable-host versus output-target settings. ## 3. Submit a contribution diff --git a/tools/check_product_graph.py b/tools/check_product_graph.py new file mode 100644 index 0000000..c66a387 --- /dev/null +++ b/tools/check_product_graph.py @@ -0,0 +1,60 @@ +"""Verify that an explicitly selected Whale product contains only its ISA crates.""" + +import argparse +from pathlib import Path +import subprocess +import sys + + +ROOT = Path(__file__).resolve().parents[1] +ISAS = frozenset({"amd64", "aarch64", "riscv64", "loongarch64"}) + + +def package_names(tree): + """Read package identities from Cargo's one-package-per-line tree output.""" + names = set() + for line in tree.splitlines(): + name, separator, _ = line.partition(" v") + if not separator or not name or any(char.isspace() for char in name): + raise ValueError(f"unexpected cargo tree package: {line!r}") + names.add(name) + if "whale" not in names: + raise ValueError("cargo tree omitted the Whale product") + return names + + +def check_product(root, selected): + unknown = set(selected) - ISAS + if unknown: + raise ValueError(f"unknown ISA selection: {sorted(unknown)}") + command = [ + "cargo", "tree", "-p", "whale", "--no-default-features", + "--locked", "--offline", "-e", "normal,build", "--prefix", "none", + "--format", "{p}", + ] + if selected: + command += ["--features", ",".join(f"asm-{isa}" for isa in sorted(selected))] + result = subprocess.run(command, cwd=root, capture_output=True, text=True, check=False) + if result.returncode: + raise ValueError(f"cargo tree failed ({result.returncode}): {result.stderr.strip()}") + actual = package_names(result.stdout) & ISAS + if actual != set(selected): + raise ValueError(f"selected ISA crates {sorted(selected)}, product contains {sorted(actual)}") + return actual + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", type=Path, default=ROOT) + parser.add_argument("--isa", choices=sorted(ISAS), action="append", default=[]) + args = parser.parse_args() + try: + selected = set(args.isa) + actual = check_product(args.root, selected) + print(f"product ISA crates: {', '.join(sorted(actual)) or '(none)'}") + except ValueError as error: + parser.exit(1, f"product graph: {error}\n") + + +if __name__ == "__main__": + main() diff --git a/tools/test_product_graph.py b/tools/test_product_graph.py new file mode 100644 index 0000000..9c9a6c9 --- /dev/null +++ b/tools/test_product_graph.py @@ -0,0 +1,30 @@ +"""Regression tests for selected Cargo product graph validation.""" + +import unittest +from unittest.mock import patch + +from check_product_graph import check_product, package_names + + +class ProductGraphTests(unittest.TestCase): + def test_package_names_rejects_malformed_output(self): + for output in ("", "whale v0.1.0\ninvalid", "amd64 v0.1.0"): + with self.subTest(output=output), self.assertRaises(ValueError): + package_names(output) + + def test_selected_crates_must_match(self): + result = type("Result", (), {"returncode": 0, "stdout": "whale v0.1.0\namd64 v0.1.0\n", "stderr": ""})() + with patch("check_product_graph.subprocess.run", return_value=result): + self.assertEqual(check_product(".", {"amd64"}), {"amd64"}) + with self.assertRaisesRegex(ValueError, "product contains"): + check_product(".", set()) + + def test_cargo_failure_is_reported(self): + result = type("Result", (), {"returncode": 7, "stdout": "", "stderr": "offline unavailable"})() + with patch("check_product_graph.subprocess.run", return_value=result): + with self.assertRaisesRegex(ValueError, "offline unavailable"): + check_product(".", set()) + + +if __name__ == "__main__": + unittest.main() From aba4ad52ca64cf381f3d77ccf19385997f3ae8bf Mon Sep 17 00:00:00 2001 From: LunaStev Date: Fri, 30 Oct 2026 20:53:21 +0900 Subject: [PATCH 2/8] build: lock Wave module provenance and Meson rebuild edges Signed-off-by: LunaStev --- .gitattributes | 1 + .github/workflows/asmobj.yml | 35 ++++++++++++++++++++++++ BUILDING.md | 5 ++-- assembler/asmobj/meson.build | 1 + toolchain/build.rs | 51 ++++++++++++++++++++++++++++++++-- tools/build_asmobj.py | 17 ++++++++---- tools/meson_cargo.py | 29 ++++++++++++++++---- tools/test_build_asmobj.py | 53 +++++++++++++++++++++++++++++++----- tools/test_meson_build.py | 6 +++- 9 files changed, 175 insertions(+), 23 deletions(-) diff --git a/.gitattributes b/.gitattributes index 85d0ecf..655fbbe 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,4 +1,5 @@ *.wave text eol=lf linguist-language=Wave +toolchain/src/assembly_object.rs text eol=lf *.ps1 linguist-vendored *.sh linguist-vendored Makefile linguist-vendored diff --git a/.github/workflows/asmobj.yml b/.github/workflows/asmobj.yml index 86bc421..0307021 100644 --- a/.github/workflows/asmobj.yml +++ b/.github/workflows/asmobj.yml @@ -92,9 +92,44 @@ jobs: -Dwave-source="$GITHUB_WORKSPACE/.asmobj-bootstrap-source" \ -Dwave-bootstrap-dir="$RUNNER_TEMP/asmobj-bootstrap" -Dsocket-cli=true meson compile -C "$RUNNER_TEMP/whale-meson" + warm_build="$(meson compile -C "$RUNNER_TEMP/whale-meson")" + printf '%s\n' "$warm_build" + printf '%s\n' "$warm_build" | grep -F 'ninja: no work to do.' meson test -C "$RUNNER_TEMP/whale-meson" --print-errorlogs DESTDIR="$RUNNER_TEMP/whale-meson-install" meson install -C "$RUNNER_TEMP/whale-meson" "$RUNNER_TEMP/whale-meson-install/usr/local/bin/whale" --version + - name: Verify isolated minimal and single-ISA Meson products + run: | + meson setup "$RUNNER_TEMP/whale-minimal" \ + -Dasmobj-dir="$GITHUB_WORKSPACE/.ci-asmobj/x86_64-unknown-linux-gnu" \ + -Dasm-amd64=false -Dasm-aarch64=false -Dasm-riscv64=false -Dasm-loongarch64=false + meson compile -C "$RUNNER_TEMP/whale-minimal" + meson test -C "$RUNNER_TEMP/whale-minimal" --print-errorlogs + meson setup "$RUNNER_TEMP/whale-aarch64-output" \ + -Dasmobj-dir="$GITHUB_WORKSPACE/.ci-asmobj/x86_64-unknown-linux-gnu" \ + -Dasm-amd64=false -Dasm-riscv64=false -Dasm-loongarch64=false + meson compile -C "$RUNNER_TEMP/whale-aarch64-output" + meson test -C "$RUNNER_TEMP/whale-aarch64-output" --print-errorlogs + - name: Check cross host test registration without executing foreign code + run: | + cat > "$RUNNER_TEMP/aarch64-cross.ini" <<'EOF' + [host_machine] + system = 'linux' + cpu_family = 'aarch64' + cpu = 'aarch64' + endian = 'little' + EOF + meson setup "$RUNNER_TEMP/whale-cross" --cross-file "$RUNNER_TEMP/aarch64-cross.ini" \ + -Dcargo-host-target=aarch64-unknown-linux-gnu \ + -Dasmobj-dir="$GITHUB_WORKSPACE/.ci-asmobj/aarch64-unknown-linux-gnu" + meson introspect --tests "$RUNNER_TEMP/whale-cross" | \ + python3 -c 'import json,sys; assert {t["name"] for t in json.load(sys.stdin)} == {"build-helper"}' + meson setup "$RUNNER_TEMP/whale-cross-runner" --cross-file "$RUNNER_TEMP/aarch64-cross.ini" \ + -Dcargo-host-target=aarch64-unknown-linux-gnu \ + -Dasmobj-dir="$GITHUB_WORKSPACE/.ci-asmobj/aarch64-unknown-linux-gnu" \ + '-Dhost-runner=["/bin/true"]' + meson introspect --tests "$RUNNER_TEMP/whale-cross-runner" | \ + python3 -c 'import json,sys; tests={t["name"]:t for t in json.load(sys.stdin)}; assert set(tests)=={"build-helper","cli-smoke"}; assert "--runner-arg=/bin/true" in tests["cli-smoke"]["cmd"]' - name: Retain target-specific archives and provenance uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: diff --git a/BUILDING.md b/BUILDING.md index bd740e3..3445c07 100644 --- a/BUILDING.md +++ b/BUILDING.md @@ -65,8 +65,9 @@ meson test -C /tmp/whale-prebuilt --print-errorlogs Meson requires either `wave-source` or `asmobj-dir`; `asmobj` is part of the product. Explicit archive metadata is checked before linking. The helper records -the pinned compiler, std, source and archive hashes. Failed compilation or -archiving preserves the previous complete publication. Ambient environment +the pinned compiler, std, Rust/LLVM bootstrap requirements, ABI, source and archive +hashes. Changing the Rust/Wave boundary requires rebuilding the archive. Failed +compilation or archiving preserves the previous complete publication. Ambient environment variables cannot select a different module for a Meson product. For work confined to Rust components, ordinary Cargo builds remain available: diff --git a/assembler/asmobj/meson.build b/assembler/asmobj/meson.build index efee8b3..4078573 100644 --- a/assembler/asmobj/meson.build +++ b/assembler/asmobj/meson.build @@ -21,6 +21,7 @@ if asmobj_directory == '' output: [archive_name, 'asmobj.meta', 'provenance.json'], command: [python, files('../../tools/build_asmobj.py'), arguments], depend_files: files('model.wave', 'sections.wave', 'symbols.wave', 'relocations.wave', 'entry.wave', + '../../toolchain/src/assembly_object.rs', '../../tools/build_asmobj.py', '../../tools/wave_bootstrap.py'), depends: wave_bootstrap, console: true) asmobj_dependencies += [asmobj_module] diff --git a/toolchain/build.rs b/toolchain/build.rs index 3402119..66ea28f 100644 --- a/toolchain/build.rs +++ b/toolchain/build.rs @@ -22,6 +22,17 @@ fn archive_hash(path: &std::path::Path) -> String { } } +fn bounded_hash(path: &std::path::Path, maximum: u64, label: &str) -> String { + let mut bytes = Vec::new(); + fs::File::open(path) + .unwrap_or_else(|_| panic!("missing {label}")) + .take(maximum + 1) + .read_to_end(&mut bytes) + .unwrap_or_else(|_| panic!("cannot read {label}")); + assert!(bytes.len() as u64 <= maximum, "oversized {label}"); + hash(&bytes) +} + fn main() { println!("cargo:rustc-check-cfg=cfg(whale_asmobj)"); println!("cargo:rerun-if-env-changed=WHALE_ASMOBJ_DIR"); @@ -34,8 +45,10 @@ fn main() { "libwhale_asmobj.a" }); let metadata = directory.join("asmobj.meta"); + let provenance = directory.join("provenance.json"); println!("cargo:rerun-if-changed={}", archive.display()); println!("cargo:rerun-if-changed={}", metadata.display()); + println!("cargo:rerun-if-changed={}", provenance.display()); let mut text = String::new(); fs::File::open(&metadata) .expect("missing asmobj.meta; build with tools/build_asmobj.py") @@ -47,14 +60,33 @@ fn main() { for line in text.lines() { let (key, value) = line.split_once('=').expect("malformed asmobj metadata"); assert!( - ["schema", "target", "source_fnv64", "archive_fnv64"].contains(&key) + [ + "schema", + "target", + "wave_revision", + "opt_level", + "source_fnv64", + "abi_fnv64", + "archive_fnv64", + "provenance_fnv64" + ] + .contains(&key) && fields.insert(key, value).is_none(), "invalid asmobj metadata fields" ); } - assert_eq!(fields.len(), 4, "incomplete asmobj metadata"); - assert_eq!(fields.get("schema"), Some(&"1"), "unsupported asmobj metadata"); + assert_eq!(fields.len(), 8, "incomplete asmobj metadata"); + assert_eq!(fields.get("schema"), Some(&"2"), "unsupported asmobj metadata"); assert_eq!(fields.get("target"), Some(&target.as_str()), "asmobj archive target mismatch"); + assert_eq!( + fields.get("wave_revision"), + Some(&"e0952ed65d07e14c6ed0aa64f3c9a5532dd7533b"), + "asmobj Wave compiler revision mismatch" + ); + assert!( + [Some(&"0"), Some(&"2")].contains(&fields.get("opt_level")), + "unsupported asmobj optimization level" + ); let root = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap()).join("../assembler/asmobj"); let mut source = Vec::new(); @@ -75,11 +107,24 @@ fn main() { Some(&hash(&source).as_str()), "stale asmobj archive; rebuild with tools/build_asmobj.py" ); + let abi_path = + PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap()).join("src/assembly_object.rs"); + println!("cargo:rerun-if-changed={}", abi_path.display()); + assert_eq!( + fields.get("abi_fnv64"), + Some(&bounded_hash(&abi_path, 1024 * 1024, "asmobj ABI source").as_str()), + "stale asmobj ABI; rebuild with tools/build_asmobj.py" + ); assert_eq!( fields.get("archive_fnv64"), Some(&archive_hash(&archive).as_str()), "corrupt asmobj archive" ); + assert_eq!( + fields.get("provenance_fnv64"), + Some(&bounded_hash(&provenance, 16 * 1024, "asmobj provenance").as_str()), + "corrupt asmobj provenance" + ); println!("cargo:rustc-link-search=native={}", directory.display()); println!("cargo:rustc-link-lib=static=whale_asmobj"); println!("cargo:rustc-cfg=whale_asmobj"); diff --git a/tools/build_asmobj.py b/tools/build_asmobj.py index 93cdf13..8148e9c 100644 --- a/tools/build_asmobj.py +++ b/tools/build_asmobj.py @@ -7,9 +7,10 @@ import os from pathlib import Path import tempfile -from wave_bootstrap import DEFAULT_RUST_TOOLCHAIN, WAVE_REVISION, ensure_bootstrap, run, digest +from wave_bootstrap import DEFAULT_RUST_TOOLCHAIN, RUST_VERSION, WAVE_REVISION, ensure_bootstrap, run, digest SOURCES = ('model.wave', 'sections.wave', 'symbols.wave', 'relocations.wave', 'entry.wave') +ABI_SOURCE = 'toolchain/src/assembly_object.rs' TARGETS = ('x86_64-unknown-linux-gnu', 'aarch64-unknown-linux-gnu', 'riscv64gc-unknown-linux-gnu', 'x86_64-pc-windows-msvc', 'aarch64-pc-windows-msvc', 'x86_64-apple-darwin', 'aarch64-apple-darwin') @@ -23,9 +24,11 @@ def fnv64(data): def source_bytes(root): return b'\n'.join((root / 'assembler/asmobj' / name).read_bytes() for name in SOURCES) -def metadata(source, archive, target): - return (f'schema=1\ntarget={target}\nsource_fnv64={fnv64(source)}\n' - f'archive_fnv64={fnv64(archive)}\n') +def metadata(source, abi, archive, provenance, target, opt_level): + return (f'schema=2\ntarget={target}\nwave_revision={WAVE_REVISION}\n' + f'opt_level={opt_level}\nsource_fnv64={fnv64(source)}\n' + f'abi_fnv64={fnv64(abi)}\narchive_fnv64={fnv64(archive)}\n' + f'provenance_fnv64={fnv64(provenance)}\n') def main(): parser = argparse.ArgumentParser(description=__doc__) @@ -43,6 +46,7 @@ def main(): output.mkdir(parents=True, exist_ok=True) root = Path(__file__).resolve().parents[1] source = source_bytes(root) + abi = (root / ABI_SOURCE).read_bytes() bootstrap = ensure_bootstrap(args.wave_source, args.bootstrap_dir or output / 'bootstrap-cache', rust_toolchain=args.rust_toolchain, allow_network=args.allow_network) # Only code generation is cross-target; this never executes a foreign object. @@ -72,11 +76,14 @@ def main(): provenance = temporary / 'provenance.json' provenance.write_text(json.dumps({'wave_revision': WAVE_REVISION, 'target': args.target, 'opt_level': args.opt_level, 'source_sha256': hashlib.sha256(source).hexdigest(), + 'abi_sha256': hashlib.sha256(abi).hexdigest(), 'archive_sha256': digest(archive), 'compiler_sha256': digest(bootstrap.compiler), + 'bootstrap_rust_version': RUST_VERSION, 'required_llvm_major': 21, 'std_sha256': bootstrap.metadata['std_sha256'], 'bootstrap_provenance': str(bootstrap.provenance)}, indent=2) + '\n') fingerprint = temporary / 'asmobj.meta' - fingerprint.write_text(metadata(source, archive.read_bytes(), args.target)) + fingerprint.write_text(metadata(source, abi, archive.read_bytes(), + provenance.read_bytes(), args.target, args.opt_level)) staged = (archive, provenance, fingerprint) previous = {} for path in staged: diff --git a/tools/meson_cargo.py b/tools/meson_cargo.py index 16a6539..9cafa07 100644 --- a/tools/meson_cargo.py +++ b/tools/meson_cargo.py @@ -130,7 +130,9 @@ def cargo_dependencies(path): def source_dependencies(source, features): """Explicit source-tree components, with directories tracking new files.""" - dependencies = {source, source / "Cargo.toml", source / "Cargo.lock", Path(__file__).resolve()} + # The repository root also receives unrelated tool state (for example + # .git and editor directories). Tracking it makes every warm build dirty. + dependencies = {source / "Cargo.toml", source / "Cargo.lock", Path(__file__).resolve()} components = [*COMPONENTS, *("assembler/" + arch for arch in ASSEMBLERS if "asm-" + arch in features)] for component in ["", *components]: root = source / component @@ -201,20 +203,37 @@ def build(arguments): contents = make_escape(output) + ": " + " ".join(make_escape(path) for path in sorted(dependencies)) + "\n" candidate = None candidate_depfile = None + previous_depfile = None try: candidate = _temporary_copy(binary, output) with tempfile.NamedTemporaryFile(prefix=".whale-deps-", dir=depfile.parent, delete=False) as temporary: candidate_depfile = Path(temporary.name) temporary.write(contents.encode("utf-8")) - # Prepare both before publishing. Dependency output failure cannot - # replace the last-good executable. - os.replace(candidate_depfile, depfile) - os.replace(candidate, output) + # Keep the old depfile until the executable has also been published. + # A failed second replacement must not leave new dependencies paired + # with the last-good executable. + if depfile.exists(): + with tempfile.NamedTemporaryFile(prefix=".whale-old-deps-", dir=depfile.parent, + delete=False) as temporary: + previous_depfile = Path(temporary.name) + os.replace(depfile, previous_depfile) + try: + os.replace(candidate_depfile, depfile) + os.replace(candidate, output) + except OSError: + if previous_depfile is None: + depfile.unlink(missing_ok=True) + else: + os.replace(previous_depfile, depfile) + previous_depfile = None + raise finally: if candidate is not None: candidate.unlink(missing_ok=True) if candidate_depfile is not None: candidate_depfile.unlink(missing_ok=True) + if previous_depfile is not None: + previous_depfile.unlink(missing_ok=True) def smoke(arguments): diff --git a/tools/test_build_asmobj.py b/tools/test_build_asmobj.py index 3414093..adb0f1e 100644 --- a/tools/test_build_asmobj.py +++ b/tools/test_build_asmobj.py @@ -128,16 +128,22 @@ def fake_run(command, **kwargs): if not failure: self.assertEqual(len(calls), 2) source_bytes = helper.source_bytes(ROOT) + abi_bytes = (ROOT / helper.ABI_SOURCE).read_bytes() + provenance_bytes = (output / "provenance.json").read_bytes() self.assertEqual((output / "asmobj.meta").read_text(), - helper.metadata(source_bytes, b"new archive", target)) + helper.metadata(source_bytes, abi_bytes, b"new archive", + provenance_bytes, target, "0")) provenance = json.loads((output / "provenance.json").read_text()) self.assertEqual(provenance, { "wave_revision": helper.WAVE_REVISION, "target": target, "opt_level": "0", "source_sha256": hashlib.sha256(source_bytes).hexdigest(), + "abi_sha256": hashlib.sha256(abi_bytes).hexdigest(), "archive_sha256": hashlib.sha256(b"new archive").hexdigest(), "compiler_sha256": hashlib.sha256(b"pinned compiler").hexdigest(), + "bootstrap_rust_version": helper.RUST_VERSION, + "required_llvm_major": 21, "std_sha256": "1" * 64, "bootstrap_provenance": str(bootstrap.provenance), }) @@ -207,6 +213,8 @@ def tearDownClass(cls): def make_project(root, target=NATIVE): manifest = root / "toolchain" manifest.mkdir() + (manifest / "src").mkdir() + (manifest / "src/assembly_object.rs").write_bytes(b"asmobj ffi boundary") sources = root / "assembler/asmobj" sources.mkdir(parents=True) for index, name in enumerate(helper.SOURCES): @@ -216,8 +224,11 @@ def make_project(root, target=NATIVE): archive = archive_dir / ("whale_asmobj.lib" if "msvc" in target else "libwhale_asmobj.a") archive.write_bytes(b"archive") source_bytes = b"\n".join((sources / name).read_bytes() for name in helper.SOURCES) + provenance = archive_dir / "provenance.json" + provenance.write_bytes(b'{"wave_revision":"pinned"}\n') metadata = archive_dir / "asmobj.meta" - metadata.write_text(helper.metadata(source_bytes, b"archive", target)) + metadata.write_text(helper.metadata(source_bytes, b"asmobj ffi boundary", b"archive", + provenance.read_bytes(), target, "2")) return manifest, sources, archive_dir, archive, metadata def run_guard(self, corruption=None, *, enabled=True, target=NATIVE): @@ -227,6 +238,12 @@ def run_guard(self, corruption=None, *, enabled=True, target=NATIVE): (sources / helper.SOURCES[2]).write_bytes(b"changed source") elif corruption == "archive": archive.write_bytes(b"changed archive") + elif corruption == "abi": + (manifest / "src/assembly_object.rs").write_bytes(b"changed ffi boundary") + elif corruption == "provenance": + (archive_dir / "provenance.json").write_bytes(b"changed provenance") + elif corruption == "oversized-provenance": + (archive_dir / "provenance.json").write_bytes(b"x" * 16385) elif corruption == "missing-archive": archive.unlink() elif corruption == "missing-source": @@ -246,7 +263,9 @@ def run_guard(self, corruption=None, *, enabled=True, target=NATIVE): elif corruption == "invalid-utf8": metadata.write_bytes(b"\xff") elif corruption == "schema": - metadata.write_text(metadata.read_text().replace("schema=1", "schema=2")) + metadata.write_text(metadata.read_text().replace("schema=2", "schema=3")) + elif corruption == "revision": + metadata.write_text(metadata.read_text().replace(helper.WAVE_REVISION, "0" * 40)) elif corruption == "target": metadata.write_text(metadata.read_text().replace("target=" + target, "target=aarch64-unknown-linux-gnu")) environment = os.environ.copy() @@ -259,7 +278,8 @@ def run_guard(self, corruption=None, *, enabled=True, target=NATIVE): def test_matching_guard_watches_all_five_sources_and_published_artifacts(self): result = self.run_guard() self.assertEqual(result.returncode, 0, result.stderr) - for name in (*helper.SOURCES, "asmobj.meta", "libwhale_asmobj.a"): + for name in (*helper.SOURCES, "asmobj.meta", "provenance.json", "libwhale_asmobj.a", + "assembly_object.rs"): self.assertIn(name, result.stdout) self.assertIn("cargo:rustc-cfg=whale_asmobj", result.stdout) self.assertIn("cargo:rustc-link-lib=static=whale_asmobj", result.stdout) @@ -267,7 +287,10 @@ def test_matching_guard_watches_all_five_sources_and_published_artifacts(self): def test_mismatched_or_invalid_artifacts_fail_before_link_selection(self): expectations = { "source": "stale asmobj", "archive": "corrupt asmobj", + "abi": "stale asmobj ABI", "provenance": "corrupt asmobj provenance", + "oversized-provenance": "oversized asmobj provenance", "target": "target mismatch", "oversized": "oversized", + "revision": "compiler revision mismatch", "duplicate": "metadata fields", "unknown": "metadata fields", "incomplete": "incomplete", "malformed": "malformed", "invalid-utf8": "invalid asmobj metadata", "schema": "unsupported", @@ -305,7 +328,6 @@ def test_cargo_rechecks_warm_source_and_archive_changes(self): self.assertEqual(len(hosts), 1) with tempfile.TemporaryDirectory() as temporary: manifest, sources, archive_dir, archive, metadata = self.make_project(Path(temporary).resolve(), hosts[0]) - (manifest / "src").mkdir() (manifest / "src/lib.rs").write_text("pub fn marker() {}\n") (manifest / "Cargo.toml").write_text( '[package]\nname="asmobj-guard-probe"\nversion="0.0.0"\nedition="2021"\n') @@ -333,8 +355,18 @@ def check(success, reason=None): check(False, "corrupt asmobj archive") archive.write_bytes(b"archive") check(True) + abi = manifest / "src/assembly_object.rs" + abi.write_bytes(b"changed ffi boundary") + check(False, "stale asmobj ABI") + abi.write_bytes(b"asmobj ffi boundary") + check(True) + provenance = archive_dir / "provenance.json" + provenance.write_bytes(b"changed provenance") + check(False, "corrupt asmobj provenance") + provenance.write_bytes(b'{"wave_revision":"pinned"}\n') + check(True) original_metadata = metadata.read_text() - metadata.write_text(original_metadata.replace("schema=1", "schema=2")) + metadata.write_text(original_metadata.replace("schema=2", "schema=3")) check(False, "unsupported asmobj metadata") metadata.write_text(original_metadata) check(True) @@ -348,27 +380,34 @@ def test_autocrlf_checkout_preserves_wave_source_fingerprint(self): root = Path(temporary).resolve() sources = root / "assembler/asmobj" sources.mkdir(parents=True) + abi = root / helper.ABI_SOURCE + abi.parent.mkdir(parents=True) shutil.copyfile(ROOT / ".gitattributes", root / ".gitattributes") for name in helper.SOURCES: shutil.copyfile(ROOT / "assembler/asmobj" / name, sources / name) + shutil.copyfile(ROOT / helper.ABI_SOURCE, abi) original = helper.source_bytes(root) + original_abi = abi.read_bytes() environment = {key: value for key, value in os.environ.items() if not key.startswith("GIT_")} environment.update(GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull) git = shutil.which("git") or "git" for arguments in (["init", "--quiet"], ["config", "core.autocrlf", "true"], - ["add", ".gitattributes", "assembler/asmobj"]): + ["add", ".gitattributes", "assembler/asmobj", helper.ABI_SOURCE]): subprocess.run([git, *arguments], cwd=root, env=environment, check=True, capture_output=True) for name in helper.SOURCES: (sources / name).unlink() + abi.unlink() subprocess.run([git, "checkout-index", "--all", "--force"], cwd=root, env=environment, check=True, capture_output=True) checked_out = helper.source_bytes(root) self.assertNotIn(b"\r\n", checked_out) self.assertEqual(checked_out, original) self.assertEqual(helper.fnv64(checked_out), helper.fnv64(original)) + self.assertNotIn(b"\r\n", abi.read_bytes()) + self.assertEqual(abi.read_bytes(), original_abi) def test_asmobj_is_a_complete_wave_module_with_five_role_files(self): module = ROOT / "assembler/asmobj" diff --git a/tools/test_meson_build.py b/tools/test_meson_build.py index 0b082b3..f9c6cc2 100644 --- a/tools/test_meson_build.py +++ b/tools/test_meson_build.py @@ -108,15 +108,18 @@ def test_malformed_depfile_fails_instead_of_publishing_untracked_binary(self): def test_source_dirs_and_manifests_track_additions_without_disabled_isas(self): with tempfile.TemporaryDirectory() as temporary: source = Path(temporary).resolve() - for name in ["src", "assembler/amd64/src", "assembler/aarch64/src"]: + for name in ["src", "toolchain/src", "assembler/amd64/src", "assembler/aarch64/src"]: (source / name).mkdir(parents=True) (source / name / "lib.rs").write_text("// source") + (source / "toolchain/src/assembly_object.rs").write_text("// ffi boundary") (source / "Cargo.toml").write_text("manifest") dependencies = source_dependencies(source, ["asm-aarch64"]) + self.assertNotIn(source, dependencies) self.assertIn(source / "assembler/aarch64/src", dependencies) self.assertIn(source / "assembler/aarch64/src/lib.rs", dependencies) self.assertNotIn(source / "assembler/amd64/src/lib.rs", dependencies) self.assertIn(source / "Cargo.toml", dependencies) + self.assertIn(source / "toolchain/src/assembly_object.rs", dependencies) class PublicationTests(unittest.TestCase): @@ -191,6 +194,7 @@ def replace(source, destination): with self.assertRaises(OSError): build(self.arguments) self.assertEqual(self.output.read_bytes(), b"previous") + self.assertEqual(self.depfile.read_bytes(), b"previous dependencies") self.assertEqual(list(self.root.glob(".whale-*")), []) def test_root_cargo_target_dir_is_rejected_before_running_cargo(self): From 3a3be4e5ade51efa8662419c8f954b6ed3b81bd4 Mon Sep 17 00:00:00 2001 From: LunaStev Date: Fri, 30 Oct 2026 21:47:20 +0900 Subject: [PATCH 3/8] ir: move model, text, verification and frontend lowering to Wave Implement the complete typed body/global builder model, versioned parser, bounded canonical printer, layout and SSA verifier in role-separated Wave sources. Lower the supported AST and pinned Wave typed-HIR boundary through Wave, preserving evaluation order, source identities and transactional errors. Keep Rust allocation/typed transport and explicit conformance references. Numeric evaluation and runtime migration remain the following ordered batches. Validate actual Wave O0/O2 against independent bounded native vectors, all workspace features, CLI publication, Meson install and Rust 1.86 checks. Signed-off-by: LunaStev --- .gitattributes | 1 + .github/workflows/asmobj.yml | 26 + BUILDING.md | 10 +- CONTRIBUTING.md | 4 +- README.md | 3 + ir/build.rs | 173 ++ ir/builder.wave | 205 ++ ir/builder_body.wave | 293 +++ ir/builder_namespace.wave | 432 ++++ ir/cfg.wave | 216 ++ ir/entry.wave | 63 + ir/expression_parser.wave | 292 +++ ir/header.wave | 160 ++ ir/instruction_parser.wave | 671 ++++++ ir/layout.wave | 83 + ir/lexer.wave | 311 +++ ir/literal.wave | 110 + ir/lower_driver.wave | 327 +++ ir/lower_expression.wave | 356 +++ ir/lower_hir.wave | 279 +++ ir/lower_limits.wave | 138 ++ ir/lower_model.wave | 325 +++ ir/lower_output.wave | 264 +++ ir/lower_statement.wave | 147 ++ ir/lower_storage.wave | 226 ++ ir/meson.build | 53 + ir/model.wave | 68 + ir/module_parser.wave | 354 +++ ir/printer.wave | 2083 ++++++++++++++++++ ir/shape.wave | 151 ++ ir/source.wave | 154 ++ ir/src/builder.rs | 890 ++++++-- ir/src/builder/body.rs | 1996 +++++++++++++++++ ir/src/builder/namespace.rs | 771 +++++++ ir/src/builder/wave.rs | 737 +++++++ ir/src/diagnostic.rs | 7 + ir/src/function.rs | 1 + ir/src/layout.rs | 81 +- ir/src/lib.rs | 9 + ir/src/lower_ast/error.rs | 1 + ir/src/lower_ast/limits.rs | 166 ++ ir/src/lower_ast/mod.rs | 34 + ir/src/lower_ast/wave_hir.rs | 635 ++++++ ir/src/lower_ast/wave_limits.rs | 426 ++++ ir/src/lower_ast/wave_lower.rs | 1931 ++++++++++++++++ ir/src/parser/instruction.rs | 34 +- ir/src/parser/lexer.rs | 74 +- ir/src/parser/mod.rs | 26 + ir/src/parser/syntax.rs | 236 +- ir/src/parser/wave_expression.rs | 470 ++++ ir/src/parser/wave_header.rs | 232 ++ ir/src/parser/wave_instruction.rs | 990 +++++++++ ir/src/parser/wave_lexer.rs | 206 ++ ir/src/parser/wave_literal.rs | 210 ++ ir/src/parser/wave_module.rs | 499 +++++ ir/src/parser/wave_text.rs | 26 + ir/src/parser/wave_type.rs | 368 ++++ ir/src/printer.rs | 624 ++---- ir/src/printer_reference.rs | 519 +++++ ir/src/printer_tests.rs | 598 +++++ ir/src/printer_wave.rs | 711 ++++++ ir/src/source.rs | 106 + ir/src/source_wave.rs | 208 ++ ir/src/verifier.rs | 416 +++- ir/src/verifier/calls.rs | 152 +- ir/src/verifier/cfg.rs | 351 +-- ir/src/verifier/operands.rs | 31 +- ir/src/verifier/wave_cfg.rs | 185 ++ ir/src/verifier/wave_index.rs | 170 ++ ir/src/verifier/wave_semantics.rs | 937 ++++++++ ir/src/verifier/wave_shape.rs | 194 ++ ir/src/verifier/wave_ssa.rs | 284 +++ ir/src/wave_layout.rs | 244 ++ ir/tests/builder_checked.rs | 133 ++ ir/tests/fixtures/README.md | 9 +- ir/tests/fixtures/wave_typed_hir_scalar.json | 189 ++ ir/tests/frontend_error_order.rs | 141 ++ ir/tests/frontend_storage.rs | 21 + ir/tests/source_metadata.rs | 15 +- ir/tests/verification_scaling.rs | 6 +- ir/tests/wave_ast_lowering.rs | 448 ++++ ir/tests/wave_typed_hir.rs | 282 +++ ir/type_parser.wave | 248 +++ ir/verifier_index.wave | 67 + ir/verifier_ssa.wave | 182 ++ ir/verify.wave | 616 ++++++ meson.build | 10 +- meson.options | 2 + src/commands/ir.rs | 50 +- src/commands/output.rs | 2 +- tests/text_ir_cli.rs | 72 + tools/build_wave_ir.py | 150 ++ tools/check_wave_hir_fixture.py | 97 + tools/check_wave_ir_ast_limits.py | 288 +++ tools/check_wave_ir_body.py | 284 +++ tools/check_wave_ir_builder.py | 264 +++ tools/check_wave_ir_cfg.py | 188 ++ tools/check_wave_ir_expression.py | 148 ++ tools/check_wave_ir_header.py | 89 + tools/check_wave_ir_hir.py | 94 + tools/check_wave_ir_instruction.py | 248 +++ tools/check_wave_ir_layout.py | 178 ++ tools/check_wave_ir_lexer.py | 93 + tools/check_wave_ir_literal.py | 103 + tools/check_wave_ir_lower_type.py | 124 ++ tools/check_wave_ir_lowering.py | 243 ++ tools/check_wave_ir_printer.py | 101 + tools/check_wave_ir_shape.py | 131 ++ tools/check_wave_ir_source.py | 129 ++ tools/check_wave_ir_ssa.py | 164 ++ tools/check_wave_ir_type.py | 127 ++ tools/check_wave_ir_verifier.py | 189 ++ tools/meson_cargo.py | 15 +- tools/test_build_asmobj.py | 3 - tools/test_build_wave_ir.py | 191 ++ tools/test_meson_build.py | 12 +- tools/wave_hir_fixture.rs | 216 ++ tools/wave_ir_verifier_oracle.py | 124 ++ 118 files changed, 30251 insertions(+), 999 deletions(-) create mode 100644 ir/build.rs create mode 100644 ir/builder.wave create mode 100644 ir/builder_body.wave create mode 100644 ir/builder_namespace.wave create mode 100644 ir/cfg.wave create mode 100644 ir/entry.wave create mode 100644 ir/expression_parser.wave create mode 100644 ir/header.wave create mode 100644 ir/instruction_parser.wave create mode 100644 ir/layout.wave create mode 100644 ir/lexer.wave create mode 100644 ir/literal.wave create mode 100644 ir/lower_driver.wave create mode 100644 ir/lower_expression.wave create mode 100644 ir/lower_hir.wave create mode 100644 ir/lower_limits.wave create mode 100644 ir/lower_model.wave create mode 100644 ir/lower_output.wave create mode 100644 ir/lower_statement.wave create mode 100644 ir/lower_storage.wave create mode 100644 ir/meson.build create mode 100644 ir/model.wave create mode 100644 ir/module_parser.wave create mode 100644 ir/printer.wave create mode 100644 ir/shape.wave create mode 100644 ir/source.wave create mode 100644 ir/src/builder/body.rs create mode 100644 ir/src/builder/namespace.rs create mode 100644 ir/src/builder/wave.rs create mode 100644 ir/src/lower_ast/wave_hir.rs create mode 100644 ir/src/lower_ast/wave_limits.rs create mode 100644 ir/src/lower_ast/wave_lower.rs create mode 100644 ir/src/parser/wave_expression.rs create mode 100644 ir/src/parser/wave_header.rs create mode 100644 ir/src/parser/wave_instruction.rs create mode 100644 ir/src/parser/wave_lexer.rs create mode 100644 ir/src/parser/wave_literal.rs create mode 100644 ir/src/parser/wave_module.rs create mode 100644 ir/src/parser/wave_text.rs create mode 100644 ir/src/parser/wave_type.rs create mode 100644 ir/src/printer_reference.rs create mode 100644 ir/src/printer_tests.rs create mode 100644 ir/src/printer_wave.rs create mode 100644 ir/src/source_wave.rs create mode 100644 ir/src/verifier/wave_cfg.rs create mode 100644 ir/src/verifier/wave_index.rs create mode 100644 ir/src/verifier/wave_semantics.rs create mode 100644 ir/src/verifier/wave_shape.rs create mode 100644 ir/src/verifier/wave_ssa.rs create mode 100644 ir/src/wave_layout.rs create mode 100644 ir/tests/fixtures/wave_typed_hir_scalar.json create mode 100644 ir/tests/frontend_error_order.rs create mode 100644 ir/tests/wave_ast_lowering.rs create mode 100644 ir/tests/wave_typed_hir.rs create mode 100644 ir/type_parser.wave create mode 100644 ir/verifier_index.wave create mode 100644 ir/verifier_ssa.wave create mode 100644 ir/verify.wave create mode 100644 tools/build_wave_ir.py create mode 100644 tools/check_wave_hir_fixture.py create mode 100644 tools/check_wave_ir_ast_limits.py create mode 100644 tools/check_wave_ir_body.py create mode 100644 tools/check_wave_ir_builder.py create mode 100644 tools/check_wave_ir_cfg.py create mode 100644 tools/check_wave_ir_expression.py create mode 100644 tools/check_wave_ir_header.py create mode 100644 tools/check_wave_ir_hir.py create mode 100644 tools/check_wave_ir_instruction.py create mode 100644 tools/check_wave_ir_layout.py create mode 100644 tools/check_wave_ir_lexer.py create mode 100644 tools/check_wave_ir_literal.py create mode 100644 tools/check_wave_ir_lower_type.py create mode 100644 tools/check_wave_ir_lowering.py create mode 100644 tools/check_wave_ir_printer.py create mode 100644 tools/check_wave_ir_shape.py create mode 100644 tools/check_wave_ir_source.py create mode 100644 tools/check_wave_ir_ssa.py create mode 100644 tools/check_wave_ir_type.py create mode 100644 tools/check_wave_ir_verifier.py create mode 100644 tools/test_build_wave_ir.py create mode 100644 tools/wave_hir_fixture.rs create mode 100644 tools/wave_ir_verifier_oracle.py diff --git a/.gitattributes b/.gitattributes index 655fbbe..8275a2b 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,5 +1,6 @@ *.wave text eol=lf linguist-language=Wave toolchain/src/assembly_object.rs text eol=lf +ir/src/wave_layout.rs text eol=lf *.ps1 linguist-vendored *.sh linguist-vendored Makefile linguist-vendored diff --git a/.github/workflows/asmobj.yml b/.github/workflows/asmobj.yml index 0307021..17d6d56 100644 --- a/.github/workflows/asmobj.yml +++ b/.github/workflows/asmobj.yml @@ -84,6 +84,32 @@ jobs: "$asmobj_python" tools/check_asmobj.py \ --library "$RUNNER_TEMP/asmobj-o$optimization.so" --cases 10000 done + - name: Run actual Wave IR module at O0 and O2 + run: | + cargo fetch --locked + for optimization in 0 2; do + python3 tools/build_wave_ir.py --wave-source .asmobj-bootstrap-source \ + --bootstrap-dir "$RUNNER_TEMP/asmobj-bootstrap" --rust-toolchain 1.89.0 \ + --out-dir "$RUNNER_TEMP/wave-ir-o$optimization" --opt-level "$optimization" + cc -shared -Wl,--whole-archive "$RUNNER_TEMP/wave-ir-o$optimization/libwhale_wave_ir.a" \ + -Wl,--no-whole-archive -o "$RUNNER_TEMP/wave-ir-o$optimization.so" + ir_python="$(command -v python3)" + for component in layout lexer header type literal expression instruction source \ + builder body printer verifier ssa ast_limits lower_type lowering hir cfg shape; do + ir_cases=10000 + if [ "$component" = literal ]; then ir_cases=100000; fi + if [ "$component" = builder ]; then ir_cases=30000; fi + timeout 180s python3 tools/fuzz_limits.py --memory-mib 512 -- "$ir_python" \ + "tools/check_wave_ir_$component.py" \ + --library "$RUNNER_TEMP/wave-ir-o$optimization.so" --cases "$ir_cases" + done + done + WHALE_WAVE_IR_DIR="$RUNNER_TEMP/wave-ir-o2" \ + cargo test -p ir --all-features --locked --offline + - name: Reproduce the pinned typed HIR fixture + run: | + python3 tools/check_wave_hir_fixture.py --wave-source .asmobj-bootstrap-source \ + --target-dir "$RUNNER_TEMP/wave-hir-fixture" --rust-toolchain 1.89.0 - name: Build, test and install the Meson source product run: | python3 -m pip install --disable-pip-version-check meson==1.8.5 diff --git a/BUILDING.md b/BUILDING.md index 3445c07..1c6c40e 100644 --- a/BUILDING.md +++ b/BUILDING.md @@ -1,8 +1,9 @@ # Building Whale with Meson -Meson configures the product, compiles the Wave `asmobj` module, then builds the -Rust components with Cargo. `assembler/asmobj/` is implemented entirely in Wave; -the remaining assembler, IR, object, linker and CLI implementations remain Rust. +Meson configures the product, compiles the Wave `asmobj` and IR sources, then +builds Rust components with Cargo. `assembler/asmobj/` is entirely Wave. IR model, +parsing, printing, layout and verification run in Wave when its archive is selected; +Rust supplies typed transport and retained reference implementations. Generated files and Cargo outputs stay in the selected build directory. ## Build, test and install @@ -69,6 +70,9 @@ the pinned compiler, std, Rust/LLVM bootstrap requirements, ABI, source and arch hashes. Changing the Rust/Wave boundary requires rebuilding the archive. Failed compilation or archiving preserves the previous complete publication. Ambient environment variables cannot select a different module for a Meson product. +Source builds also compile the Wave IR model, parser, printer, layout and verifier. +With a prebuilt `asmobj`, pass `-Dwave-ir-dir=/absolute/path/to/built-wave-ir` +to use them. Ordinary Cargo keeps the Rust reference during the IR migration. For work confined to Rust components, ordinary Cargo builds remain available: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0633624..8ed6093 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -21,7 +21,7 @@ executable does not need the Wave compiler at runtime. | `assembler/src/` | Shared Rust assembly types and helpers | | `assembler/asmobj/` | Complete Wave assembly-to-object module | | `toolchain/`, `backend-api/` | Rust composition, backend interfaces and external data calls to `asmobj` | -| `ir/`, `target-spec/` | Rust IR semantics, target identities and layouts | +| `ir/`, `target-spec/` | Wave IR model, parser, printer, layout and verifier; Rust data transport and target contracts | | `object/`, `linker/` | Rust object formats, relocations and executable layout | | `reverse/` | Rust image inspection; decoder and CFG currently unavailable | | `src/`, `tests/` | CLI and integration tests | @@ -30,7 +30,7 @@ executable does not need the Wave compiler at runtime. Split source files by role. Shared modules must not import a concrete ISA. `asmobj` contains only Wave sources; its Rust data boundary lives in `toolchain/src/assembly_object.rs`. Object serialization belongs to `object`. -IR remains Rust. +IR reference algorithms remain available for comparison during the Wave migration. ### Adding an assembler or IR target diff --git a/README.md b/README.md index 2272d9c..85f6d6b 100644 --- a/README.md +++ b/README.md @@ -558,6 +558,9 @@ cargo run --locked -- ir verify ir/tests/fixtures/calls-v3.wir cargo run --locked -- ir print ir/tests/fixtures/calls-v3.wir -o canonical.wir ``` +`ir print` and `ir lower` stream output under `--max-output N` (default 64 MiB). +An output error preserves the existing destination file. + `ir::parse_module` reads **and verifies** formats 3, 4, 5, 6, 7 and 8. Print-parse-print preserves explicit scoped IDs, quoted names, entry and block order, types, exact integer/float payloads, constant-expression trees, alignment, signatures diff --git a/ir/build.rs b/ir/build.rs new file mode 100644 index 0000000..badcfd8 --- /dev/null +++ b/ir/build.rs @@ -0,0 +1,173 @@ +// SPDX-License-Identifier: MPL-2.0 +use std::{collections::BTreeMap, env, fs, io::Read, path::PathBuf}; + +const PIN: &str = "e0952ed65d07e14c6ed0aa64f3c9a5532dd7533b"; + +const SOURCES: &[&str] = &[ + "model.wave", + "layout.wave", + "lexer.wave", + "header.wave", + "type_parser.wave", + "literal.wave", + "expression_parser.wave", + "instruction_parser.wave", + "module_parser.wave", + "lower_hir.wave", + "lower_model.wave", + "lower_output.wave", + "lower_expression.wave", + "lower_storage.wave", + "lower_statement.wave", + "lower_driver.wave", + "builder.wave", + "builder_namespace.wave", + "builder_body.wave", + "verify.wave", + "verifier_index.wave", + "verifier_ssa.wave", + "printer.wave", + "cfg.wave", + "shape.wave", + "source.wave", + "lower_limits.wave", + "entry.wave", +]; + +const ABI_SOURCES: &[&str] = &[ + "src/wave_layout.rs", + "src/source_wave.rs", + "src/lower_ast/wave_limits.rs", + "src/parser/wave_lexer.rs", + "src/parser/wave_header.rs", + "src/parser/wave_text.rs", + "src/parser/wave_type.rs", + "src/parser/wave_literal.rs", + "src/parser/wave_expression.rs", + "src/parser/wave_instruction.rs", + "src/parser/wave_module.rs", + "src/lower_ast/wave_hir.rs", + "src/lower_ast/wave_lower.rs", + "src/builder/wave.rs", + "src/builder/namespace.rs", + "src/builder/body.rs", + "src/verifier/wave_semantics.rs", + "src/verifier/wave_index.rs", + "src/verifier/wave_ssa.rs", + "src/printer_wave.rs", + "src/verifier/wave_cfg.rs", + "src/verifier/wave_shape.rs", +]; + +fn update(hash: u64, bytes: &[u8]) -> u64 { + bytes.iter().fold(hash, |h, byte| (h ^ u64::from(*byte)).wrapping_mul(0x100000001b3)) +} + +fn hash(bytes: &[u8]) -> String { + format!("{:016x}", update(0xcbf29ce484222325, bytes)) +} + +fn hash_file(path: &std::path::Path, maximum: Option) -> String { + let mut file = fs::File::open(path) + .unwrap_or_else(|_| panic!("missing Wave IR artifact {}", path.display())); + let mut value = 0xcbf29ce484222325; + let mut seen = 0; + let mut buffer = [0; 16384]; + loop { + let count = file.read(&mut buffer).expect("cannot read Wave IR artifact"); + if count == 0 { + return format!("{value:016x}"); + } + seen += count as u64; + if maximum.is_some_and(|limit| seen > limit) { + panic!("oversized Wave IR artifact {}", path.display()); + } + value = update(value, &buffer[..count]); + } +} + +fn main() { + println!("cargo:rustc-check-cfg=cfg(whale_wave_ir)"); + println!("cargo:rerun-if-env-changed=WHALE_WAVE_IR_DIR"); + let Some(directory) = env::var_os("WHALE_WAVE_IR_DIR") else { return }; + let directory = PathBuf::from(directory).canonicalize().expect("WHALE_WAVE_IR_DIR must exist"); + let target = env::var("TARGET").expect("Cargo target required"); + let archive = directory.join(if target.contains("msvc") { + "whale_wave_ir.lib" + } else { + "libwhale_wave_ir.a" + }); + let metadata = directory.join("wave-ir.meta"); + let provenance = directory.join("provenance.json"); + for path in [&archive, &metadata, &provenance] { + println!("cargo:rerun-if-changed={}", path.display()); + } + let mut text = String::new(); + fs::File::open(&metadata) + .expect("missing wave-ir.meta; build with tools/build_wave_ir.py") + .take(4097) + .read_to_string(&mut text) + .expect("invalid Wave IR metadata"); + assert!(text.len() <= 4096, "oversized Wave IR metadata"); + let mut fields = BTreeMap::new(); + for line in text.lines() { + let (key, value) = line.split_once('=').expect("malformed Wave IR metadata"); + assert!( + [ + "schema", + "target", + "wave_revision", + "opt_level", + "source_fnv64", + "abi_fnv64", + "archive_fnv64", + "provenance_fnv64" + ] + .contains(&key) + && fields.insert(key, value).is_none(), + "invalid Wave IR metadata fields" + ); + } + assert_eq!(fields.len(), 8, "incomplete Wave IR metadata"); + assert_eq!(fields.get("schema"), Some(&"1"), "unsupported Wave IR metadata"); + assert_eq!(fields.get("target"), Some(&target.as_str()), "Wave IR target mismatch"); + assert_eq!(fields.get("wave_revision"), Some(&PIN), "Wave IR compiler revision mismatch"); + assert!( + [Some(&"0"), Some(&"2")].contains(&fields.get("opt_level")), + "unsupported Wave IR optimization level" + ); + let root = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap()); + let mut source = Vec::new(); + for (index, name) in SOURCES.iter().enumerate() { + let path = root.join(name); + println!("cargo:rerun-if-changed={}", path.display()); + if index != 0 { + source.push(b'\n'); + } + source.extend(fs::read(path).expect("missing Wave IR source")); + } + assert_eq!(fields.get("source_fnv64"), Some(&hash(&source).as_str()), "stale Wave IR archive"); + let mut abi = Vec::new(); + for (index, name) in ABI_SOURCES.iter().enumerate() { + let path = root.join(name); + println!("cargo:rerun-if-changed={}", path.display()); + if index != 0 { + abi.push(b'\n'); + } + abi.extend(fs::read(path).expect("missing Wave IR ABI source")); + } + assert_eq!(fields.get("abi_fnv64"), Some(&hash(&abi).as_str()), "stale Wave IR ABI"); + assert_eq!( + fields.get("archive_fnv64"), + Some(&hash_file(&archive, None).as_str()), + "corrupt Wave IR archive" + ); + assert_eq!( + fields.get("provenance_fnv64"), + Some(&hash_file(&provenance, Some(16 * 1024)).as_str()), + "corrupt Wave IR provenance" + ); + println!("cargo:rustc-link-search=native={}", directory.display()); + println!("cargo:rustc-link-lib=static=whale_wave_ir"); + println!("cargo:rustc-cfg=whale_wave_ir"); +} diff --git a/ir/builder.wave b/ir/builder.wave new file mode 100644 index 0000000..a028252 --- /dev/null +++ b/ir/builder.wave @@ -0,0 +1,205 @@ +// SPDX-License-Identifier: MPL-2.0 +// Exact typed construction model. Memory is owned by the caller; Wave validates +// a transaction completely before publishing identities, types or block state. +// Type tags match the typed IR inventory, never storage-size equivalence classes. +struct IrBuilderType { kind: u64; depth: u64; children: u64; auxiliary: u64; } + +struct IrBuilderValue { id: u64; first_type: u64; type_count: u64; } + +struct IrBuilderBlock { id: u64; terminated: u64; non_phi: u64; } + +struct IrBuilderState { next_value: u64; next_block: u64; type_count: u64; instruction_count: u64; namespace_nodes: u64; namespace_bytes: u64; next_function: u64; next_global: u64; work: u64; } + +struct IrBuilderResult { status: u64; detail: u64; value: u64; work: u64; } + +// 1 invalid transport/model; 2 depth; 3 nodes; 4 work; 5 identity overflow; +// 6 unknown block; 7 terminated block; 8 unknown value; 9 phi order. +fun ir_builder_type_check(types: ptr, count: u64, depth_limit: u64, + node_limit: u64, work_limit: u64, result: ptr) -> i32 { + if (!ir_span_valid(types as ptr, count, 32) || count == 0) { return 1; } + if (count > node_limit) { return 3; } + if (count > work_limit) { return 4; } + var remaining: array; + var level: u64 = 0; + remaining[0] = 1; + var index: u64 = 0; + while (index < count) { + while (remaining[level] == 0 && level > 0) { level -= 1; } + var node: IrBuilderType = types[index]; + result.detail = index; + if (remaining[level] == 0 || node.depth != level) { return 1; } + if (level > depth_limit || level > 257) { return 2; } + if (node.kind > 21) { return 1; } + if (node.kind <= 16 && node.children != 0) { return 1; } + // Pointer/array have one child. Function pointer stores return first, + // then parameters, and convention/variadic bits in auxiliary. + if ((node.kind == 17 || node.kind == 19) && node.children != 1) { return 1; } + if (node.kind == 18 && (node.children == 0 || node.auxiliary > 3)) { return 1; } + if (node.children > count - index - 1) { return 1; } + remaining[level] -= 1; + if (node.children != 0) { + if (level == depth_limit || level == 257) { return 2; } + level += 1; + remaining[level] = node.children; + } + index += 1; + } + while (level > 0 && remaining[level] == 0) { level -= 1; } + if (remaining[level] != 0) { return 1; } + result.work = count; + return 0; +} + +export(c) fun whale_ir_builder_type(types: ptr, count: u64, + depth_limit: u64, node_limit: u64, work_limit: u64, + result: ptr) -> i32 { + if (result == null) { return 1; } + result.status = 0; result.detail = 0; result.value = 0; result.work = 0; + var status: i32 = ir_builder_type_check(types, count, depth_limit, node_limit, work_limit, result); + result.status = status as u64; + return status; +} + +// mode 0 probes without mutation; mode 1 publishes the complete append. +// kind 0 appends a typed value; kind 1 appends a basic block. +export(c) fun whale_ir_builder_allocate(state: ptr, kind: u64, + types: ptr, count: u64, depth_limit: u64, node_limit: u64, + work_limit: u64, mode: u64, output_types: ptr, type_capacity: u64, + output_values: ptr, value_capacity: u64, + output_blocks: ptr, block_capacity: u64, + result: ptr) -> i32 { + if (result == null) { return 1; } + result.status = 0; result.detail = 0; result.value = 0; result.work = 0; + if (state == null || kind > 1 || mode > 1 || state.type_count > node_limit || state.work > work_limit) { + result.status = 1; return 1; + } + var used_nodes: u64 = state.namespace_nodes; + if (used_nodes > node_limit || state.type_count > node_limit - used_nodes) { result.status = 3; return 3; } + used_nodes += state.type_count; + if (state.next_value > node_limit - used_nodes) { result.status = 3; return 3; } + used_nodes += state.next_value; + if (state.next_block > node_limit - used_nodes) { result.status = 3; return 3; } + used_nodes += state.next_block; + if (state.instruction_count > node_limit - used_nodes) { result.status = 3; return 3; } + used_nodes += state.instruction_count; + if (used_nodes == node_limit) { result.status = 3; return 3; } + var cost: u64 = 1; + if (kind == 0) { + var status: i32 = ir_builder_type_check(types, count, depth_limit, + node_limit - used_nodes - 1, work_limit - state.work, result); + if (status != 0) { result.status = status as u64; return status; } + if (count > (18446744073709551615 - 1) / 2) { result.status = 4; return 4; } + cost = count * 2 + 1; + if (state.next_value >= 4294967295) { result.status = 5; return 5; } + result.value = state.next_value; + } else { + if (state.next_block >= 4294967295) { result.status = 5; return 5; } + result.value = state.next_block; + } + if (cost > work_limit - state.work) { result.status = 4; return 4; } + result.work = cost; + if (mode == 0) { return 0; } + if (kind == 0) { + if (state.type_count > type_capacity || count > type_capacity - state.type_count + || state.next_value >= value_capacity + || !ir_span_valid(output_types as ptr, type_capacity, 32) + || !ir_span_valid(output_values as ptr, value_capacity, 24)) { + result.status = 1; return 1; + } + var index: u64 = 0; + while (index < count) { output_types[state.type_count + index] = types[index]; index += 1; } + output_values[state.next_value].id = state.next_value; + output_values[state.next_value].first_type = state.type_count; + output_values[state.next_value].type_count = count; + state.type_count += count; + state.next_value += 1; + } else { + if (state.next_block >= block_capacity || !ir_span_valid(output_blocks as ptr, block_capacity, 24)) { + result.status = 1; return 1; + } + output_blocks[state.next_block].id = state.next_block; + output_blocks[state.next_block].terminated = 0; + output_blocks[state.next_block].non_phi = 0; + state.next_block += 1; + } + state.work += cost; + return 0; +} + +// The complete instruction inventory is expressed as operation kind 0..33: +// GlobalAddr, LifetimeEnd, PtrDiff, ConstDecl, Const, Undef, Mov, Bin, Neg, +// Not, Cmp, ICmp, FCmp, Select, Cast, Phi, Extract, Checked, Alloca, +// VolatileLoad, VolatileStore, Load, Uninit, Store, Gep, Memcpy, Memset, +// NullFunction, FunctionAddr, Call, TrapIf; Br, CBr/Switch, Ret/Trap. +// check_only skips publication. Op 34 checks identities, 35 checks insertion; +// op 36 inserts an entry-hoisted alloca before its existing terminator. +export(c) fun whale_ir_builder_order(state: ptr, node_limit: u64, blocks: ptr, block_count: u64, + first_block: u64, first_value: u64, value_end: u64, block: u64, + op: u64, operands: ptr, operand_count: u64, + targets: ptr, target_count: u64, check_only: u64, + max_work: u64, result: ptr) -> i32 { + if (result == null) { return 1; } + result.status = 0; result.detail = block; result.value = 0; result.work = 0; + if (state == null || op > 36 || check_only > 1 || first_block > block_count || first_value > value_end + || !ir_span_valid(blocks as ptr, block_count, 24) + || !ir_span_valid(operands as ptr, operand_count, 8) + || !ir_span_valid(targets as ptr, target_count, 8)) { result.status = 1; return 1; } + if (state.work > max_work) { result.status = 4; return 4; } + var available_work: u64 = max_work - state.work; + if (op >= 34 && op != 36) { available_work = max_work; } + if (operand_count > available_work || target_count > available_work - operand_count + || available_work - operand_count - target_count < 1) { result.status = 4; return 4; } + if (op < 34 || op == 36) { + var expected: u64 = 0; + if (op == 1 || op == 6 || op == 8 || op == 9 || op == 14 || op == 16 + || op == 19 || op == 21 || op == 22 || op == 30) { expected = 1; } + if (op == 2 || op == 7 || op == 10 || op == 11 || op == 12 || op == 17 + || op == 20 || op == 23) { expected = 2; } + if (op == 13 || op == 25 || op == 26) { expected = 3; } + if (op != 15 && op != 24 && op != 29 && op != 32 && op != 33 && operand_count != expected) { + result.status = 1; return 1; + } + if ((op == 15 && operand_count != target_count) || (op == 24 && operand_count == 0) + || (op == 31 && target_count != 1) || (op == 32 && (operand_count != 1 || target_count == 0)) + || (op == 33 && (operand_count > 1 || target_count != 0))) { result.status = 1; return 1; } + if (op != 15 && op != 31 && op != 32 && target_count != 0) { result.status = 1; return 1; } + var nodes: u64 = state.namespace_nodes; + if (nodes > node_limit || state.type_count > node_limit - nodes) { result.status = 3; return 3; } + nodes += state.type_count; + if (nodes > node_limit || state.next_value > node_limit - nodes) { result.status = 3; return 3; } + nodes += state.next_value; + if (state.next_block > node_limit - nodes) { result.status = 3; return 3; } + nodes += state.next_block; + if (state.instruction_count >= node_limit - nodes) { result.status = 3; return 3; } + nodes += state.instruction_count + 1; + if (operand_count > node_limit - nodes || target_count > node_limit - nodes - operand_count) { + result.status = 3; return 3; + } + } + if (block < first_block || block >= block_count || blocks[block].id != block) { result.status = 6; return 6; } + if (op != 34 && op != 36 && blocks[block].terminated != 0) { result.status = 7; return 7; } + var index: u64 = 0; + while (index < operand_count) { + if (operands[index] < first_value || operands[index] >= value_end) { + result.detail = operands[index]; result.status = 8; return 8; + } + index += 1; + } + index = 0; + while (index < target_count) { + if (targets[index] < first_block || targets[index] >= block_count + || blocks[targets[index]].id != targets[index]) { + result.detail = targets[index]; result.status = 6; return 6; + } + index += 1; + } + if (op == 15 && blocks[block].non_phi != 0) { result.status = 9; return 9; } + result.work = operand_count + target_count + 1; + if (check_only == 0 && (op < 34 || op == 36)) { + state.instruction_count += operand_count + target_count + 1; + state.work += result.work; + if (op >= 31 && op <= 33) { blocks[block].terminated = 1; } + else { if (op != 15) { blocks[block].non_phi = 1; } } + } + return 0; +} diff --git a/ir/builder_body.wave b/ir/builder_body.wave new file mode 100644 index 0000000..38bd1d6 --- /dev/null +++ b/ir/builder_body.wave @@ -0,0 +1,293 @@ +// SPDX-License-Identifier: MPL-2.0 +// Complete instruction/terminator bodies. Typed atoms and UTF-8 bytes are +// validated before a single model field is published. Linked block records +// retain insertion order and entry-hoisted allocations independently of Rust. +struct IrBodyAtom { kind: u64; a: u64; b: u64; c: u64; } + +struct IrBodyRecord { op: u64; block: u64; first: u64; count: u64; byte_first: u64; byte_count: u64; next: u64; } + +struct IrBodyBlock { head: u64; tail: u64; count: u64; terminator: u64; prefix_tail: u64; prefix_count: u64; } + +struct IrBodyState { atoms: u64; bytes: u64; records: u64; globals: u64; work: u64; } + +struct IrBodyGlobal { id: u64; first: u64; count: u64; byte_first: u64; byte_count: u64; } + +struct IrBodyResult { status: u64; detail: u64; ordinal: u64; work: u64; } + +struct IrBodyReader { atoms: ptr; count: u64; at: u64; bytes: ptr; byte_count: u64; byte_at: u64; depth: u64; const_depth: u64; work: u64; max_work: u64; result: ptr; } + +fun ir_body_fail(r: ptr, status: u64) -> bool { r.result.status = status; r.result.detail = r.at; return false; } + +fun ir_body_charge(r: ptr, n: u64) -> bool { + if (n > r.max_work - r.work) { return ir_body_fail(r, 4); } + r.work += n; return true; +} + +fun ir_body_atom(r: ptr, kind: u64) -> bool { + if (!ir_body_charge(r, 1)) { return false; } + if (r.at >= r.count || r.atoms[r.at].kind != kind) { return ir_body_fail(r, 1); } + r.at += 1; return true; +} + +fun ir_body_uint(r: ptr, maximum: u64) -> bool { + if (!ir_body_atom(r, 0)) { return false; } + var atom: ptr = &r.atoms[r.at - 1]; + return (atom.a <= maximum && atom.b == 0 && atom.c == 0) || ir_body_fail(r, 1); +} + +fun ir_body_constant(r: ptr) -> bool { + if (!ir_body_atom(r, 1)) { return false; } + var atom: ptr = &r.atoms[r.at - 1]; + if (atom.a > 5 || (atom.a == 0 && (atom.b > 1 || atom.c != 0)) + || (atom.a == 3 && (atom.b > 65535 || atom.c != 0)) + || (atom.a == 4 && (atom.b > 4294967295 || atom.c != 0)) + || (atom.a == 5 && atom.c != 0)) { return ir_body_fail(r, 1); } + return true; +} + +fun ir_body_string(r: ptr) -> bool { + if (!ir_body_atom(r, 2)) { return false; } + var atom: ptr = &r.atoms[r.at - 1]; + if (atom.c != 0 || atom.a != r.byte_at || atom.a > r.byte_count || atom.b > r.byte_count - atom.a) { return ir_body_fail(r, 1); } + var end: u64 = atom.a + atom.b; var width: u64 = 0; var cp: u64 = 0; + while (r.byte_at < end) { + if (!ir_lex_utf8(r.bytes, end, r.byte_at, &width, &cp)) { return ir_body_fail(r, 1); } + if (!ir_body_charge(r, width)) { return false; } + r.byte_at += width; + } + return true; +} + +fun ir_body_type(r: ptr, depth: u64) -> bool { + if (depth > r.depth) { return ir_body_fail(r, 2); } + if (!ir_body_atom(r, 3)) { return false; } + var atom: IrBodyAtom = r.atoms[r.at - 1]; + if (atom.a > 21 || (atom.a <= 16 && (atom.b != 0 || atom.c != 0)) + || ((atom.a == 17 || atom.a == 19) && atom.b != 1) + || (atom.a == 17 && atom.c != 0) + || (atom.a == 18 && (atom.b == 0 || atom.c > 3)) + || ((atom.a == 20 || atom.a == 21) && atom.c != 0) + || atom.b > r.count - r.at) { return ir_body_fail(r, 1); } + var i: u64 = 0; + while (i < atom.b) { if (!ir_body_type(r, depth + 1)) { return false; } i += 1; } + return true; +} + +fun ir_body_expression(r: ptr, depth: u64) -> bool { + if (depth > r.const_depth) { return ir_body_fail(r, 2); } + if (!ir_body_atom(r, 4)) { return false; } + var atom: IrBodyAtom = r.atoms[r.at - 1]; + if (atom.a > 6 || (atom.a <= 2 && (atom.b != 0 || atom.c != 0)) + || ((atom.a == 3 || atom.a == 4) && (atom.b != 0 || atom.c != 1)) + || (atom.a == 5 && (atom.b > 11 || atom.c != 2)) + || (atom.a == 6 && (atom.b > 5 || atom.c != 2))) { return ir_body_fail(r, 1); } + if (!ir_body_type(r, 0)) { return false; } + if (atom.a == 0 && !ir_body_constant(r)) { return false; } + if ((atom.a == 1 || atom.a == 2) && !ir_body_uint(r, 4294967295)) { return false; } + var i: u64 = 0; + while (i < atom.c) { if (!ir_body_expression(r, depth + 1)) { return false; } i += 1; } + return true; +} + +fun ir_body_list(r: ptr, kind: u64) -> bool { + if (!ir_body_atom(r, 5)) { return false; } + var atom: IrBodyAtom = r.atoms[r.at - 1]; + if (atom.a != kind || atom.c != 0 || atom.b > r.count - r.at) { return ir_body_fail(r, 1); } + var i: u64 = 0; + while (i < atom.b) { + if (kind == 2) { if (!ir_body_constant(r)) { return false; } } + else { if (!ir_body_uint(r, 4294967295)) { return false; } } + if (kind != 0 && !ir_body_uint(r, 4294967295)) { return false; } + i += 1; + } + return true; +} + +fun ir_body_optional(r: ptr) -> bool { + if (!ir_body_uint(r, 1)) { return false; } + if (r.atoms[r.at - 1].a != 0) { return ir_body_uint(r, 4294967295); } + return true; +} + +fun ir_body_schema(r: ptr, op: u64) -> bool { + if (op == 0) { return ir_body_uint(r, 4294967295) && ir_body_uint(r, 4294967295) && ir_body_type(r, 0); } + else if (op == 1) { return ir_body_uint(r, 4294967295); } + else if (op == 2) { return ir_body_uint(r, 4294967295) && ir_body_uint(r, 4294967295) && ir_body_uint(r, 4294967295); } + else if (op == 3) { return ir_body_uint(r, 4294967295) && ir_body_string(r) && ir_body_expression(r, 0) && ir_body_constant(r); } + else if (op == 4) { return ir_body_uint(r, 4294967295) && ir_body_type(r, 0) && ir_body_constant(r); } + else if (op == 5) { return ir_body_uint(r, 4294967295) && ir_body_type(r, 0); } + else if (op == 6) { return ir_body_uint(r, 4294967295) && ir_body_type(r, 0) && ir_body_uint(r, 4294967295); } + else if (op == 7) { return ir_body_uint(r, 4294967295) && ir_body_uint(r, 17) && ir_body_type(r, 0) && ir_body_uint(r, 4294967295) && ir_body_uint(r, 4294967295); } + else if (op == 8) { return ir_body_uint(r, 4294967295) && ir_body_type(r, 0) && ir_body_uint(r, 4294967295); } + else if (op == 9) { return ir_body_uint(r, 4294967295) && ir_body_type(r, 0) && ir_body_uint(r, 4294967295); } + else if (op == 10) { return ir_body_uint(r, 4294967295) && ir_body_uint(r, 15) && ir_body_type(r, 0) && ir_body_uint(r, 4294967295) && ir_body_uint(r, 4294967295); } + else if (op == 11) { return ir_body_uint(r, 4294967295) && ir_body_uint(r, 9) && ir_body_type(r, 0) && ir_body_uint(r, 4294967295) && ir_body_uint(r, 4294967295); } + else if (op == 12) { return ir_body_uint(r, 4294967295) && ir_body_uint(r, 13) && ir_body_type(r, 0) && ir_body_uint(r, 4294967295) && ir_body_uint(r, 4294967295); } + else if (op == 13) { return ir_body_uint(r, 4294967295) && ir_body_type(r, 0) && ir_body_uint(r, 4294967295) && ir_body_uint(r, 4294967295) && ir_body_uint(r, 4294967295); } + else if (op == 14) { return ir_body_uint(r, 4294967295) && ir_body_uint(r, 12) && ir_body_type(r, 0) && ir_body_type(r, 0) && ir_body_uint(r, 4294967295); } + else if (op == 15) { return ir_body_uint(r, 4294967295) && ir_body_type(r, 0) && ir_body_list(r, 1); } + else if (op == 16) { return ir_body_uint(r, 4294967295) && ir_body_type(r, 0) && ir_body_uint(r, 4294967295) && ir_body_uint(r, 4294967295); } + else if (op == 17) { return ir_body_uint(r, 4294967295) && ir_body_uint(r, 5) && ir_body_type(r, 0) && ir_body_uint(r, 4294967295) && ir_body_uint(r, 4294967295); } + else if (op == 18) { return ir_body_uint(r, 4294967295) && ir_body_type(r, 0) && ir_body_uint(r, 4294967295); } + else if (op == 19) { return ir_body_uint(r, 4294967295) && ir_body_type(r, 0) && ir_body_uint(r, 4294967295) && ir_body_uint(r, 4294967295); } + else if (op == 20) { return ir_body_type(r, 0) && ir_body_uint(r, 4294967295) && ir_body_uint(r, 4294967295) && ir_body_uint(r, 4294967295); } + else if (op == 21) { return ir_body_uint(r, 4294967295) && ir_body_type(r, 0) && ir_body_uint(r, 4294967295) && ir_body_uint(r, 4294967295); } + else if (op == 22) { return ir_body_type(r, 0) && ir_body_uint(r, 4294967295) && ir_body_uint(r, 4294967295); } + else if (op == 23) { return ir_body_type(r, 0) && ir_body_uint(r, 4294967295) && ir_body_uint(r, 4294967295) && ir_body_uint(r, 4294967295); } + else if (op == 24) { return ir_body_uint(r, 4294967295) && ir_body_type(r, 0) && ir_body_uint(r, 4294967295) && ir_body_list(r, 0); } + else if (op == 25) { return ir_body_uint(r, 4294967295) && ir_body_uint(r, 4294967295) && ir_body_uint(r, 4294967295) && ir_body_uint(r, 4294967295); } + else if (op == 26) { return ir_body_uint(r, 4294967295) && ir_body_uint(r, 4294967295) && ir_body_uint(r, 4294967295) && ir_body_uint(r, 4294967295); } + else if (op == 27) { return ir_body_uint(r, 4294967295) && ir_body_type(r, 0); } + else if (op == 28) { return ir_body_uint(r, 4294967295) && ir_body_uint(r, 4294967295) && ir_body_type(r, 0); } + else if (op == 29) { return ir_body_optional(r) && ir_body_type(r, 0) && ir_body_uint(r, 1) && ir_body_uint(r, 1) && ir_body_uint(r, 4294967295) && ir_body_list(r, 0); } + else if (op == 30) { return ir_body_uint(r, 4294967295) && ir_body_string(r); } + else if (op == 31) { return ir_body_uint(r, 4294967295); } + else if (op == 32) { return ir_body_uint(r, 4294967295) && ir_body_uint(r, 4294967295) && ir_body_uint(r, 4294967295); } + else if (op == 33) { return ir_body_type(r, 0) && ir_body_uint(r, 4294967295) && ir_body_uint(r, 4294967295) && ir_body_list(r, 2); } + else if (op == 34) { return ir_body_type(r, 0) && ir_body_optional(r); } + else if (op == 35) { return ir_body_string(r); } + return ir_body_fail(r, 1); +} + +// mode0 validates/probes; mode1 publishes. hoist1 inserts an alloca at the end +// of the existing alloca prefix, even when entry already has a terminator. +export(c) fun whale_ir_builder_body(state: ptr, blocks: ptr, block_count: u64, + block: u64, op: u64, hoist: u64, atoms: ptr, atom_count: u64, + bytes: ptr, byte_count: u64, depth: u64, const_depth: u64, + node_limit: u64, byte_limit: u64, work_limit: u64, mode: u64, + output_atoms: ptr, atom_capacity: u64, output_bytes: ptr, byte_capacity: u64, + records: ptr, record_capacity: u64, result: ptr) -> i32 { + if (result == null) { return 1; } + result.status = 0; result.detail = 0; result.ordinal = 0; result.work = 0; + if (state == null || op > 35 || hoist > 1 || mode > 1 || block >= block_count + || depth > 257 || const_depth > 256 || (hoist != 0 && op != 18) + || !ir_span_valid(blocks as ptr, block_count, 48) + || !ir_span_valid(atoms as ptr, atom_count, 32) + || !ir_span_valid(bytes, byte_count, 1) + || !ir_span_valid(records as ptr, state.records, 56)) { result.status = 1; return 1; } + if (state.atoms > node_limit || atom_count > node_limit - state.atoms + || state.records >= node_limit) { result.status = 3; return 3; } + if (state.bytes > byte_limit || byte_count > byte_limit - state.bytes) { result.status = 10; return 10; } + if (state.work > work_limit) { result.status = 4; return 4; } + var model: ptr = &blocks[block]; + if (model.count > state.records || (model.count == 0 && (model.head != 18446744073709551615 || model.tail != 18446744073709551615)) + || (model.count != 0 && (model.head >= state.records || model.tail >= state.records)) + || (model.terminator != 18446744073709551615 && model.terminator >= state.records) + || model.prefix_count > model.count + || (model.prefix_count == 0 && model.prefix_tail != 18446744073709551615) + || (model.prefix_count != 0 && model.prefix_tail >= state.records)) { result.status = 1; return 1; } + if (model.prefix_count != 0 && (records[model.prefix_tail].block != block + || records[model.prefix_tail].op != 18)) { result.status = 1; return 1; } + if (model.terminator != 18446744073709551615 && hoist == 0) { result.status = 7; return 7; } + var reader: IrBodyReader; + reader.atoms = atoms; reader.count = atom_count; reader.at = 0; + reader.bytes = bytes; reader.byte_count = byte_count; reader.byte_at = 0; + reader.depth = depth; reader.const_depth = const_depth; reader.work = 0; + reader.max_work = work_limit - state.work; reader.result = result; + if (!ir_body_schema(&reader, op)) { result.work = reader.work; return result.status as i32; } + if (reader.at != atom_count || reader.byte_at != byte_count) { result.status = 1; return 1; } + var previous: u64 = model.tail; var next: u64 = 18446744073709551615; + var ordinal: u64 = model.count; + if (hoist != 0) { + // Prefix ownership is part of the Wave block model. Hoisting performs + // one indexed splice regardless of how many allocas already precede it. + previous = model.prefix_tail; ordinal = model.prefix_count; + next = model.head; + if (previous != 18446744073709551615) { next = records[previous].next; } + if (next != 18446744073709551615 && (next >= state.records + || records[next].block != block || records[next].op == 18)) { result.status = 1; return 1; } + } else { + if (previous != 18446744073709551615 && (records[previous].block != block + || records[previous].next != 18446744073709551615)) { result.status = 1; return 1; } + } + if (!ir_body_charge(&reader, atom_count) || !ir_body_charge(&reader, byte_count) + || !ir_body_charge(&reader, 1)) { return result.status as i32; } + result.ordinal = ordinal; result.work = reader.work; + if (mode == 0) { return 0; } + if (state.atoms > atom_capacity || atom_count > atom_capacity - state.atoms + || state.bytes > byte_capacity || byte_count > byte_capacity - state.bytes + || state.records >= record_capacity + || !ir_span_valid(output_atoms as ptr, atom_capacity, 32) + || !ir_span_valid(output_bytes, byte_capacity, 1) + || !ir_span_valid(records as ptr, record_capacity, 56)) { result.status = 1; return 1; } + var i: u64 = 0; + while (i < atom_count) { + output_atoms[state.atoms + i] = atoms[i]; + if (atoms[i].kind == 2) { output_atoms[state.atoms + i].a += state.bytes; } + i += 1; + } + i = 0; + while (i < byte_count) { output_bytes[state.bytes + i] = bytes[i]; i += 1; } + var index: u64 = state.records; + records[index].op = op; records[index].block = block; + records[index].first = state.atoms; records[index].count = atom_count; + records[index].byte_first = state.bytes; records[index].byte_count = byte_count; + records[index].next = next; + if (op >= 31) { model.terminator = index; } + else { + if (previous == 18446744073709551615) { model.head = index; } + else { records[previous].next = index; } + if (next == 18446744073709551615) { model.tail = index; } + if (op == 18 && (hoist != 0 || model.prefix_count == model.count)) { + model.prefix_tail = index; model.prefix_count += 1; + } + model.count += 1; + } + state.atoms += atom_count; state.bytes += byte_count; state.records += 1; state.work += reader.work; + return 0; +} + +// Global constants have an independent module record/schema, sharing only the +// typed atom arena and its cumulative byte/node/work budget with function bodies. +export(c) fun whale_ir_builder_global(state: ptr, id: u64, + globals: ptr, global_capacity: u64, + atoms: ptr, atom_count: u64, bytes: ptr, byte_count: u64, + depth: u64, const_depth: u64, node_limit: u64, byte_limit: u64, + work_limit: u64, mode: u64, output_atoms: ptr, atom_capacity: u64, + output_bytes: ptr, byte_capacity: u64, result: ptr) -> i32 { + if (result == null) { return 1; } + result.status = 0; result.detail = 0; result.ordinal = 0; result.work = 0; + if (state == null || id > 4294967295 || mode > 1 || depth > 257 || const_depth > 256 + || state.globals > global_capacity + || !ir_span_valid(globals as ptr, global_capacity, 40) + || !ir_span_valid(atoms as ptr, atom_count, 32) + || !ir_span_valid(bytes, byte_count, 1)) { result.status = 1; return 1; } + if (state.globals != 0 && globals[state.globals - 1].id >= id) { result.status = 1; return 1; } + if (state.atoms > node_limit || atom_count > node_limit - state.atoms + || state.globals >= node_limit) { result.status = 3; return 3; } + if (state.bytes > byte_limit || byte_count > byte_limit - state.bytes) { result.status = 10; return 10; } + if (state.work > work_limit) { result.status = 4; return 4; } + var reader: IrBodyReader; + reader.atoms = atoms; reader.count = atom_count; reader.at = 0; + reader.bytes = bytes; reader.byte_count = byte_count; reader.byte_at = 0; + reader.depth = depth; reader.const_depth = const_depth; reader.work = 0; + reader.max_work = work_limit - state.work; reader.result = result; + if (!ir_body_string(&reader) || !ir_body_expression(&reader, 0) + || !ir_body_constant(&reader) || !ir_body_uint(&reader, 4294967295)) { + result.work = reader.work; return result.status as i32; + } + if (reader.at != atom_count || reader.byte_at != byte_count) { result.status = 1; return 1; } + if (!ir_body_charge(&reader, atom_count) || !ir_body_charge(&reader, byte_count) + || !ir_body_charge(&reader, 1)) { result.work = reader.work; return result.status as i32; } + result.ordinal = state.globals; result.work = reader.work; + if (mode == 0) { return 0; } + if (state.globals >= global_capacity + || state.atoms > atom_capacity || atom_count > atom_capacity - state.atoms + || state.bytes > byte_capacity || byte_count > byte_capacity - state.bytes + || !ir_span_valid(output_atoms as ptr, atom_capacity, 32) + || !ir_span_valid(output_bytes, byte_capacity, 1)) { result.status = 1; return 1; } + var i: u64 = 0; + while (i < atom_count) { + output_atoms[state.atoms + i] = atoms[i]; + if (atoms[i].kind == 2) { output_atoms[state.atoms + i].a += state.bytes; } + i += 1; + } + i = 0; + while (i < byte_count) { output_bytes[state.bytes + i] = bytes[i]; i += 1; } + var record: ptr = &globals[state.globals]; + record.id = id; record.first = state.atoms; record.count = atom_count; + record.byte_first = state.bytes; record.byte_count = byte_count; + state.atoms += atom_count; state.bytes += byte_count; + state.globals += 1; state.work += reader.work; + return 0; +} diff --git a/ir/builder_namespace.wave b/ir/builder_namespace.wave new file mode 100644 index 0000000..3af94a8 --- /dev/null +++ b/ir/builder_namespace.wave @@ -0,0 +1,432 @@ +// SPDX-License-Identifier: MPL-2.0 +// Module-owned function/global namespaces. String/type memory stays in the +// caller's immutable arena; Wave owns identity, equality and collision rules. +struct IrBuilderNamespace { + kind: u64; id: u64; flags: u64; + name: ptr; name_count: u64; + link: ptr; link_count: u64; + types: ptr; type_count: u64; + defined: u64; align: u64; initializer: u64; low: u64; high: u64; +} + +fun ir_builder_namespace_bytes_equal(a: ptr, an: u64, b: ptr, bn: u64, + result: ptr, work: u64) -> bool { + if (result.work >= work) { result.status = 4; return false; } + result.work += 1; + if (an != bn) { return false; } + var index: u64 = 0; + while (index < an) { + if (result.work >= work) { result.status = 4; return false; } + result.work += 1; + if (a[index] != b[index]) { return false; } + index += 1; + } + return true; +} + +fun ir_builder_namespace_signature(types: ptr, count: u64) -> i32 { + // A void root return, or ptr, is valid; every other occurrence is + // invalid. Function-pointer nodes identify their immediate return child. + var parents: array; + var indices: array; + var child_number: array; + var index: u64 = 0; + while (index < count) { + var depth: u64 = types[index].depth; + var kind: u64 = types[index].kind; + if (depth > 257) { return 17; } + if (kind == 18 && types[index].auxiliary >= 2) { return 17; } + if (index != 0) { + var parent: u64 = parents[depth - 1]; + var ordinal: u64 = child_number[depth - 1]; + child_number[depth - 1] += 1; + if (kind == 0 && parent != 17 && !(parent == 18 && ordinal == 0)) { return 17; } + if (parent == 18 && (types[indices[depth - 1]].auxiliary & 1) != 0 + && (kind == 19 || kind == 20 || kind == 21)) { return 18; } + } else { if (kind != 18 && kind == 0) { return 17; } } + parents[depth] = kind; + indices[depth] = index; + child_number[depth] = 0; + index += 1; + } + return 0; +} + +// Namespace errors: 10 duplicate global name, 11 link collision, 12 conflicting +// function declaration, 16 link-name contract, 17 malformed callable signature, +// 18 unsupported SysV64 aggregate signature. detail=1 means existing declaration. +export(c) fun whale_ir_builder_namespace(state: ptr, + entries: ptr, entry_count: u64, candidate: ptr, + mode: u64, legacy: u64, depth_limit: u64, node_limit: u64, byte_limit: u64, + work_limit: u64, output: ptr, output_capacity: u64, + result: ptr) -> i32 { + if (result == null) { return 1; } + result.status = 0; result.detail = 0; result.value = 0; result.work = 0; + if (state == null || candidate == null || mode > 1 || legacy > 1 || candidate.kind > 2 + || !ir_span_valid(entries as ptr, entry_count, 112) + || !ir_span_valid(candidate.name, candidate.name_count, 1) + || !ir_span_valid(candidate.link, candidate.link_count, 1) + ) { result.status = 1; return 1; } + if (state.work > work_limit) { result.status = 4; return 4; } + if (state.namespace_nodes > node_limit) { result.status = 3; return 3; } + if (state.namespace_bytes > byte_limit) { result.status = 19; return 19; } + var available: u64 = work_limit - state.work; + var type_result: IrBuilderResult; + var status: i32 = ir_builder_type_check(candidate.types, candidate.type_count, + depth_limit, node_limit, available, &type_result); + if (status != 0) { result.status = status as u64; return status; } + result.work = type_result.work; + if (legacy == 0) { + var kind: u64 = candidate.types[0].kind; + if (candidate.kind == 0 && kind != 18) { result.status = 17; return 17; } + if (candidate.kind == 2 && (kind == 0 || kind > 18)) { result.status = 24; return 24; } + if (candidate.type_count > available - result.work) { result.status = 4; return 4; } + result.work += candidate.type_count; + status = ir_builder_namespace_signature(candidate.types, candidate.type_count); + if (status != 0) { result.status = status as u64; return status; } + if (candidate.kind == 2) { + if (!ir_power_two(candidate.align)) { result.status = 25; return 25; } + if (candidate.initializer == 0 && (candidate.flags & 4) != 0) { result.status = 26; return 26; } + if (candidate.initializer != 0 && !ir_builder_namespace_literal(kind, + candidate.initializer, candidate.low, candidate.high)) { result.status = 27; return 27; } + } + var has_link: bool = (candidate.flags & 2) != 0; + var external: bool = (candidate.flags & 1) != 0; + if ((external && (!has_link || candidate.link_count == 0)) || (!external && has_link)) { + result.status = 16; return 16; + } + var link_index: u64 = 0; + while (link_index < candidate.link_count) { + if (result.work >= available) { result.status = 4; return 4; } + result.work += 1; + if (candidate.link[link_index] == 0) { result.status = 16; return 16; } + link_index += 1; + } + } + var index: u64 = 0; + while (index < entry_count) { + if (result.work >= available) { result.status = 4; return 4; } + result.work += 1; + var existing: ptr = &entries[index]; + if (!ir_span_valid(existing.name, existing.name_count, 1) + || !ir_span_valid(existing.link, existing.link_count, 1) + || !ir_span_valid(existing.types as ptr, existing.type_count, 32)) { + result.status = 1; return 1; + } + if (legacy == 0 && ((candidate.kind == 0 && existing.kind == 0) + || (candidate.kind != 0 && existing.kind != 0))) { + var same_name: bool = ir_builder_namespace_bytes_equal(candidate.name, candidate.name_count, + existing.name, existing.name_count, result, available); + if (result.status != 0) { return result.status as i32; } + if (same_name) { + if (candidate.kind != 0) { result.status = 10; return 10; } + var same: bool = candidate.flags == existing.flags + && candidate.type_count == existing.type_count; + if (same) { + same = ir_builder_namespace_bytes_equal(candidate.link, candidate.link_count, + existing.link, existing.link_count, result, available); + if (result.status != 0) { return result.status as i32; } + } + var node: u64 = 0; + while (same && node < candidate.type_count) { + if (result.work >= available) { result.status = 4; return 4; } + result.work += 1; + if (candidate.types[node].kind != existing.types[node].kind + || candidate.types[node].depth != existing.types[node].depth + || candidate.types[node].children != existing.types[node].children + || candidate.types[node].auxiliary != existing.types[node].auxiliary) { same = false; } + node += 1; + } + if (!same) { result.status = 12; return 12; } + result.value = existing.id; result.detail = 1; + if (mode == 1) { state.work += result.work; } + return 0; + } + } + if (legacy == 0 && (candidate.flags & 2) != 0 && (existing.flags & 2) != 0) { + var same_link: bool = ir_builder_namespace_bytes_equal(candidate.link, candidate.link_count, + existing.link, existing.link_count, result, available); + if (result.status != 0) { return result.status as i32; } + if (same_link) { result.status = 11; return 11; } + } + index += 1; + } + var used: u64 = state.type_count; + if (used > node_limit || state.next_value > node_limit - used) { result.status = 3; return 3; } + used += state.next_value; + if (state.next_block > node_limit - used) { result.status = 3; return 3; } + used += state.next_block; + if (state.instruction_count > node_limit - used) { result.status = 3; return 3; } + used += state.instruction_count; + if (state.namespace_nodes >= node_limit - used) { result.status = 3; return 3; } + used += state.namespace_nodes + 1; + if (candidate.type_count > node_limit - used) { result.status = 3; return 3; } + if (candidate.name_count > byte_limit - state.namespace_bytes + || candidate.link_count > byte_limit - state.namespace_bytes - candidate.name_count) { result.status = 19; return 19; } + var copy: u64 = candidate.name_count + candidate.link_count; + if (candidate.type_count >= available || copy > available - candidate.type_count - 1) { result.status = 4; return 4; } + copy += candidate.type_count + 1; + if (result.work > available - copy) { result.status = 4; return 4; } + result.work += copy; + if (candidate.kind == 0) { + if (state.next_function >= 4294967295) { result.status = 5; return 5; } + result.value = state.next_function; + } else { + if (state.next_global >= 4294967295) { result.status = 5; return 5; } + result.value = state.next_global; + } + if (mode == 0) { return 0; } + if (entry_count >= output_capacity || !ir_span_valid(output as ptr, output_capacity, 112)) { + result.status = 1; return 1; + } + output[entry_count] = candidate[0]; output[entry_count].id = result.value; + if (candidate.kind == 0) { state.next_function += 1; } else { state.next_global += 1; } + state.namespace_nodes += candidate.type_count + 1; + state.namespace_bytes += candidate.name_count + candidate.link_count; + state.work += result.work; + return 0; +} + +fun ir_builder_namespace_literal(kind: u64, literal: u64, low: u64, high: u64) -> bool { + if (kind == 1) { return literal == 3 && low <= 1 && high == 0; } + if (kind >= 14 && kind <= 16) { return literal == kind - 10; } + var signed: bool = kind == 2 || (kind >= 4 && kind <= 8); + var unsigned: bool = kind == 3 || (kind >= 9 && kind <= 13); + if (!signed && !unsigned) { return false; } + if ((signed && literal != 1) || (unsigned && literal != 2)) { return false; } + var width: u64 = 1; + if (kind == 4 || kind == 9) { width = 8; } + if (kind == 5 || kind == 10) { width = 16; } + if (kind == 6 || kind == 11) { width = 32; } + if (kind == 7 || kind == 12) { width = 64; } + if (kind == 8 || kind == 13) { return true; } + var one: u64 = 1; + if (unsigned) { return high == 0 && (width == 64 || low < (one << width)); } + var top: u64 = one << (width - 1); + return (high == 0 && low < top) + || (high == 18446744073709551615 && low >= 18446744073709551615 - top + 1); +} + +// Queries do not publish definition state. Marking occurs only when a complete +// FunctionBuilder is committed, so dropping an unfinished builder remains safe. +export(c) fun whale_ir_builder_definition(entries: ptr, count: u64, + id: u64, parameter_count: u64, mode: u64, max_work: u64, result: ptr) -> i32 { + if (result == null) { return 1; } + result.status = 0; result.detail = 0; result.value = 0; result.work = 0; + if (mode > 1 || !ir_span_valid(entries as ptr, count, 112)) { result.status = 1; return 1; } + var index: u64 = 0; + while (index < count) { + if (result.work >= max_work) { result.status = 4; return 4; } + result.work += 1; + if (entries[index].kind == 0 && entries[index].id == id) { + if (entries[index].type_count > max_work - result.work) { result.status = 4; return 4; } + result.work += entries[index].type_count; + var signature_status: i32 = ir_builder_namespace_signature(entries[index].types, entries[index].type_count); + if (signature_status != 0 && mode == 0) { result.status = signature_status as u64; return signature_status; } + if (entries[index].defined != 0) { result.status = 14; return 14; } + if (entries[index].type_count == 0 || entries[index].types[0].kind != 18 + || entries[index].types[0].children != parameter_count + 1) { result.status = 15; return 15; } + result.value = index; + if (mode == 1) { entries[index].defined = 1; } + return 0; + } + index += 1; + } + result.status = 13; return 13; +} + +export(c) fun whale_ir_builder_function_lookup(entries: ptr, count: u64, + name: ptr, name_count: u64, max_work: u64, result: ptr) -> i32 { + if (result == null) { return 1; } + result.status = 0; result.detail = 0; result.value = 0; result.work = 0; + if (!ir_span_valid(entries as ptr, count, 112) || !ir_span_valid(name, name_count, 1)) { result.status = 1; return 1; } + var index: u64 = 0; + while (index < count) { + if (result.work >= max_work) { result.status = 4; return 4; } + result.work += 1; + if (entries[index].kind == 0) { + var same: bool = ir_builder_namespace_bytes_equal(entries[index].name, + entries[index].name_count, name, name_count, result, max_work); + if (result.status != 0) { return result.status as i32; } + if (same) { result.value = entries[index].id; return 0; } + } + index += 1; + } + result.status = 13; return 13; +} + +fun ir_builder_subtree_end(types: ptr, count: u64, begin: u64, + result: ptr, work: u64) -> u64 { + var end: u64 = begin + 1; + while (end < count && types[end].depth > types[begin].depth) { + if (result.work >= work) { result.status = 4; return end; } + result.work += 1; end += 1; + } + return end; +} + +// 21 non-function pointer, 22 argument count, 23 argument type (detail=index). +export(c) fun whale_ir_builder_call(types: ptr, type_count: u64, + values: ptr, value_count: u64, first_value: u64, + entries: ptr, entry_count: u64, indirect: u64, callee: u64, + arguments: ptr, argument_count: u64, check_arguments: u64, + max_work: u64, result: ptr) -> i32 { + if (result == null) { return 1; } + result.status = 0; result.detail = 0; result.value = 0; result.work = 0; + if (indirect > 1 || check_arguments > 1 || first_value > value_count + || !ir_span_valid(types as ptr, type_count, 32) + || !ir_span_valid(values as ptr, value_count, 24) + || !ir_span_valid(entries as ptr, entry_count, 112) + || !ir_span_valid(arguments as ptr, argument_count, 8)) { result.status = 1; return 1; } + var signature: ptr = null; + var signature_count: u64 = 0; + if (indirect == 1) { + if (callee < first_value || callee >= value_count) { result.status = 8; result.detail = callee; return 8; } + if (values[callee].first_type > type_count + || values[callee].type_count > type_count - values[callee].first_type + || values[callee].type_count == 0) { result.status = 1; return 1; } + signature = &types[values[callee].first_type]; signature_count = values[callee].type_count; + if (signature[0].kind != 18) { result.status = 21; result.detail = callee; return 21; } + } else { + var index: u64 = 0; + while (index < entry_count) { + if (result.work >= max_work) { result.status = 4; return 4; } + result.work += 1; + if (entries[index].kind == 0 && entries[index].id == callee) { + signature = entries[index].types; signature_count = entries[index].type_count; break; + } + index += 1; + } + if (signature == null) { result.status = 13; result.detail = callee; return 13; } + } + if (!ir_span_valid(signature as ptr, signature_count, 32) + || signature_count == 0 || signature[0].kind != 18 || signature[0].children == 0) { + result.status = 1; return 1; + } + var status: i32 = ir_builder_namespace_signature(signature, signature_count); + if (status != 0) { result.status = status as u64; return status; } + if (signature_count > max_work - result.work) { result.status = 4; return 4; } + result.work += signature_count; + if (check_arguments == 0) { return 0; } + var parameter_count: u64 = signature[0].children - 1; + if (argument_count != parameter_count) { result.status = 22; result.detail = parameter_count; return 22; } + var expected: u64 = ir_builder_subtree_end(signature, signature_count, 1, result, max_work); + var argument: u64 = 0; + while (argument < argument_count) { + if (result.status != 0) { return result.status as i32; } + var value: u64 = arguments[argument]; + if (value < first_value || value >= value_count) { result.status = 8; result.detail = value; return 8; } + var actual: u64 = values[value].first_type; + var actual_count: u64 = values[value].type_count; + if (actual > type_count || actual_count > type_count - actual || actual_count == 0 || expected >= signature_count) { + result.status = 1; return 1; + } + var end: u64 = ir_builder_subtree_end(signature, signature_count, expected, result, max_work); + if (result.status != 0) { return result.status as i32; } + var same: bool = actual_count == end - expected; + var offset: u64 = 0; + while (same && offset < actual_count) { + if (result.work >= max_work) { result.status = 4; return 4; } + result.work += 1; + if (types[actual + offset].kind != signature[expected + offset].kind + || types[actual + offset].children != signature[expected + offset].children + || types[actual + offset].auxiliary != signature[expected + offset].auxiliary + || types[actual + offset].depth + signature[expected].depth != signature[expected + offset].depth) { same = false; } + offset += 1; + } + if (!same) { result.status = 23; result.detail = argument; return 23; } + expected = end; argument += 1; + } + return 0; +} + +export(c) fun whale_ir_builder_signature(types: ptr, count: u64, + depth: u64, nodes: u64, work: u64, result: ptr) -> i32 { + if (result == null) { return 1; } + result.status = 0; result.detail = 0; result.value = 0; result.work = 0; + var status: i32 = ir_builder_type_check(types, count, depth, nodes, work, result); + if (status != 0) { result.status = status as u64; return status; } + if (count > work - result.work) { result.status = 4; return 4; } + result.work += count; + status = ir_builder_namespace_signature(types, count); + result.status = status as u64; return status; +} + +export(c) fun whale_ir_builder_pointer(types: ptr, type_count: u64, + values: ptr, value_count: u64, first_value: u64, + lhs: u64, rhs: u64, pair: u64, max_work: u64, result: ptr) -> i32 { + if (result == null) { return 1; } + result.status = 0; result.detail = 0; result.value = 0; result.work = 0; + if (pair > 1 || first_value > value_count + || !ir_span_valid(types as ptr, type_count, 32) + || !ir_span_valid(values as ptr, value_count, 24)) { result.status = 1; return 1; } + if (lhs < first_value || lhs >= value_count) { result.status = 8; result.detail = lhs; return 8; } + if (pair == 1 && (rhs < first_value || rhs >= value_count)) { result.status = 8; result.detail = rhs; return 8; } + var left: u64 = values[lhs].first_type; + var count: u64 = values[lhs].type_count; + if (left >= type_count || count > type_count - left || count == 0) { result.status = 1; return 1; } + if (types[left].kind != 17) { result.status = 28; return 28; } + if (pair == 0) { return 0; } + var right: u64 = values[rhs].first_type; + if (right > type_count || values[rhs].type_count > type_count - right) { result.status = 1; return 1; } + if (count != values[rhs].type_count) { result.status = 28; return 28; } + var index: u64 = 0; + while (index < count) { + if (result.work >= max_work) { result.status = 4; return 4; } + result.work += 1; + if (types[left + index].kind != types[right + index].kind + || types[left + index].children != types[right + index].children + || types[left + index].depth != types[right + index].depth + || types[left + index].auxiliary != types[right + index].auxiliary) { result.status = 28; return 28; } + index += 1; + } + return 0; +} + +export(c) fun whale_ir_builder_function_capacity(state: ptr, + entries: ptr, count: u64, id: u64, node_limit: u64, + work_limit: u64, result: ptr) -> i32 { + if (result == null) { return 1; } + result.status = 0; result.detail = 0; result.value = 0; result.work = 0; + if (state == null || !ir_span_valid(entries as ptr, count, 112)) { result.status = 1; return 1; } + if (state.work > work_limit) { result.status = 4; return 4; } + var available: u64 = work_limit - state.work; + var index: u64 = 0; + while (index < count) { + if (result.work >= available) { result.status = 4; return 4; } + result.work += 1; + if (entries[index].kind == 0 && entries[index].id == id) { + var types: ptr = entries[index].types; + var type_count: u64 = entries[index].type_count; + if (type_count < 2 || !ir_span_valid(types as ptr, type_count, 32) + || types[0].kind != 18 || types[0].children == 0) { result.status = 1; return 1; } + var end: u64 = ir_builder_subtree_end(types, type_count, 1, result, available); + if (result.status != 0) { return result.status as i32; } + var parameter_nodes: u64 = type_count - end; + var parameters: u64 = types[0].children - 1; + if (state.next_value > 4294967295 || parameters > 4294967295 - state.next_value + || state.next_block >= 4294967295) { result.status = 5; return 5; } + var used: u64 = state.namespace_nodes; + if (used > node_limit || state.type_count > node_limit - used) { result.status = 3; return 3; } + used += state.type_count; + if (state.next_value > node_limit - used) { result.status = 3; return 3; } + used += state.next_value; + if (state.next_block > node_limit - used) { result.status = 3; return 3; } + used += state.next_block; + if (state.instruction_count > node_limit - used) { result.status = 3; return 3; } + used += state.instruction_count; + if (used == node_limit) { result.status = 3; return 3; } + used += 1; + if (parameter_nodes > node_limit - used || parameters > node_limit - used - parameter_nodes) { + result.status = 3; return 3; + } + if (parameter_nodes > available / 2) { result.status = 4; return 4; } + var cost: u64 = parameter_nodes * 2; + if (parameters >= available - cost) { result.status = 4; return 4; } + result.work = cost + parameters + 1; + return 0; + } + index += 1; + } + result.status = 13; return 13; +} diff --git a/ir/cfg.wave b/ir/cfg.wave new file mode 100644 index 0000000..5cd0755 --- /dev/null +++ b/ir/cfg.wave @@ -0,0 +1,216 @@ +// SPDX-License-Identifier: MPL-2.0 +// Structural CFG traversal for the IR verifier. Input is a caller-owned flat +// successor graph; the published reverse postorder is unchanged on failure. +struct IrCfgBlock { + first: u64; + count: u64; +} + +struct IrCfgResult { + status: u64; // 1 entry predecessor, 2 capacity, 3 work, 5 invalid graph + index: u64; // predecessor block for status 1 + count: u64; + work: u64; +} + +fun ir_cfg_charge(work: ptr, limit: u64) -> bool { + if (work[0] >= limit) { return false; } + work[0] += 1; + return true; +} + +fun ir_cfg_error(result: ptr, status: u64, index: u64, work: u64) -> i32 { + result.status = status; result.index = index; result.work = work; + return status as i32; +} + +export(c) fun whale_ir_cfg_rpo(blocks: ptr, block_count: u64, + edges: ptr, edge_count: u64, entry: u64, max_work: u64, + scratch_seen: ptr, seen_capacity: u64, + scratch_stack_block: ptr, scratch_stack_next: ptr, stack_capacity: u64, + scratch_order: ptr, scratch_capacity: u64, + output_order: ptr, output_capacity: u64, result: ptr) -> i32 { + if (result == null) { return 5; } + result.status = 0; result.index = 0; result.count = 0; result.work = 0; + if (entry >= block_count || !ir_span_valid(blocks as ptr, block_count, 16) + || !ir_span_valid(edges as ptr, edge_count, 8) + || !ir_span_valid(scratch_seen, block_count, 1) + || !ir_span_valid(scratch_stack_block as ptr, block_count, 8) + || !ir_span_valid(scratch_stack_next as ptr, block_count, 8) + || !ir_span_valid(scratch_order as ptr, block_count, 8) + || !ir_span_valid(output_order as ptr, block_count, 8)) { + return ir_cfg_error(result, 5, 0, 0); + } + if (block_count > seen_capacity || block_count > stack_capacity + || block_count > scratch_capacity || block_count > output_capacity) { + return ir_cfg_error(result, 2, 0, 0); + } + var work: u64 = 0; + var block: u64 = 0; + var current: ptr = &blocks[entry]; + while (block < block_count) { + if (!ir_cfg_charge(&work, max_work)) { return ir_cfg_error(result, 3, block, work); } + current = &blocks[block]; + if (current.first > edge_count || current.count > edge_count - current.first) { + return ir_cfg_error(result, 5, block, work); + } + scratch_seen[block] = 0; + var edge: u64 = 0; + while (edge < current.count) { + if (!ir_cfg_charge(&work, max_work)) { + return ir_cfg_error(result, 3, block, work); + } + var target: u64 = edges[current.first + edge]; + if (target >= block_count) { return ir_cfg_error(result, 5, block, work); } + if (target == entry) { return ir_cfg_error(result, 1, block, work); } + edge += 1; + } + block += 1; + } + scratch_seen[entry] = 1; + scratch_stack_block[0] = entry; + scratch_stack_next[0] = 0; + var depth: u64 = 1; + var count: u64 = 0; + while (depth != 0) { + if (!ir_cfg_charge(&work, max_work)) { return ir_cfg_error(result, 3, 0, work); } + var top: u64 = depth - 1; + block = scratch_stack_block[top]; + current = &blocks[block]; + if (scratch_stack_next[top] == current.count) { + scratch_order[count] = block; + count += 1; + depth -= 1; + } + else { + var target: u64 = edges[current.first + scratch_stack_next[top]]; + scratch_stack_next[top] += 1; + if (scratch_seen[target] == 0) { + scratch_seen[target] = 1; + scratch_stack_block[depth] = target; + scratch_stack_next[depth] = 0; + depth += 1; + } + } + } + if (count > max_work - work) { return ir_cfg_error(result, 3, 0, work); } + var index: u64 = 0; + while (index < count) { + output_order[index] = scratch_order[count - 1 - index]; + index += 1; + } + result.count = count; result.work = work + count; + return 0; +} + +// Cooper-style iterative immediate dominators over reverse postorder. The +// unvisited sentinel is kept in the caller-owned result for unreachable +// blocks, which remain present for later identity/type checks. +export(c) fun whale_ir_cfg_idom(blocks: ptr, block_count: u64, + predecessors: ptr, predecessor_count: u64, + order: ptr, order_count: u64, entry: u64, max_work: u64, + scratch_rank: ptr, rank_capacity: u64, + scratch_idom: ptr, idom_capacity: u64, + output_idom: ptr, output_capacity: u64, + result: ptr) -> i32 { + if (result == null) { return 5; } + result.status = 0; result.index = 0; result.count = 0; result.work = 0; + if (entry >= block_count || order_count == 0 || order_count > block_count + || !ir_span_valid(blocks as ptr, block_count, 16) + || !ir_span_valid(predecessors as ptr, predecessor_count, 8) + || !ir_span_valid(order as ptr, order_count, 8) + || !ir_span_valid(scratch_rank as ptr, block_count, 8) + || !ir_span_valid(scratch_idom as ptr, block_count, 8) + || !ir_span_valid(output_idom as ptr, block_count, 8)) { + return ir_cfg_error(result, 5, 0, 0); + } + if (block_count > rank_capacity || block_count > idom_capacity + || block_count > output_capacity) { + return ir_cfg_error(result, 2, 0, 0); + } + var sentinel: u64 = 18446744073709551615; + var work: u64 = 0; + var index: u64 = 0; + while (index < block_count) { + if (!ir_cfg_charge(&work, max_work)) { return ir_cfg_error(result, 3, index, work); } + scratch_rank[index] = sentinel; + scratch_idom[index] = sentinel; + var b: ptr = &blocks[index]; + if (b.first > predecessor_count || b.count > predecessor_count - b.first) { + return ir_cfg_error(result, 5, index, work); + } + var e: u64 = 0; + while (e < b.count) { + if (!ir_cfg_charge(&work, max_work)) { + return ir_cfg_error(result, 3, index, work); + } + if (predecessors[b.first + e] >= block_count) { + return ir_cfg_error(result, 5, index, work); + } + e += 1; + } + index += 1; + } + if (order[0] != entry) { return ir_cfg_error(result, 5, 0, work); } + index = 0; + while (index < order_count) { + if (!ir_cfg_charge(&work, max_work)) { return ir_cfg_error(result, 3, index, work); } + var block: u64 = order[index]; + if (block >= block_count || scratch_rank[block] != sentinel) { + return ir_cfg_error(result, 5, index, work); + } + scratch_rank[block] = index; + index += 1; + } + scratch_idom[entry] = entry; + var changed: bool = true; + while (changed) { + changed = false; + index = 1; + while (index < order_count) { + if (!ir_cfg_charge(&work, max_work)) { return ir_cfg_error(result, 3, index, work); } + var block: u64 = order[index]; + var b: ptr = &blocks[block]; + var next: u64 = sentinel; + var e: u64 = 0; + while (e < b.count) { + if (!ir_cfg_charge(&work, max_work)) { + return ir_cfg_error(result, 3, block, work); + } + var pred: u64 = predecessors[b.first + e]; + if (scratch_idom[pred] != sentinel) { + if (next == sentinel) { next = pred; } + else { + var a: u64 = next; + var c: u64 = pred; + while (a != c) { + if (!ir_cfg_charge(&work, max_work)) { + return ir_cfg_error(result, 3, block, work); + } + if (scratch_rank[a] > scratch_rank[c]) { + a = scratch_idom[a]; + } + else { c = scratch_idom[c]; } + } + next = a; + } + } + e += 1; + } + if (next == sentinel) { return ir_cfg_error(result, 5, block, work); } + if (next != scratch_idom[block]) { + scratch_idom[block] = next; + changed = true; + } + index += 1; + } + } + if (block_count > max_work - work) { return ir_cfg_error(result, 3, 0, work); } + index = 0; + while (index < block_count) { + output_idom[index] = scratch_idom[index]; + index += 1; + } + result.count = block_count; result.work = work + block_count; + return 0; +} diff --git a/ir/entry.wave b/ir/entry.wave new file mode 100644 index 0000000..6330716 --- /dev/null +++ b/ir/entry.wave @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: MPL-2.0 +// Status: 1 invalid graph/type, 2 depth, 3 overflow, 4 capacity, +// 5 invalid transport/target, 6 work budget. Only result is written on error. +export(c) fun whale_ir_layout(storage: ptr, nodes: ptr, node_count: u64, + edges: ptr, edge_count: u64, root: u64, max_depth: u64, max_work: u64, + scratch: ptr, scratch_count: u64, scratch_offsets: ptr, + scratch_offset_count: u64, output: ptr, output_count: u64, + output_offsets: ptr, output_offset_count: u64, + result: ptr) -> i32 { + if (result == null) { return 5; } + result.status = 0; + result.index = 0; + if (!ir_storage_valid(storage) || root >= node_count + || !ir_span_valid(nodes as ptr, node_count, 32) + || !ir_span_valid(edges as ptr, edge_count, 8)) { + result.status = 5; return 5; + } + if (node_count > scratch_count || edge_count > scratch_offset_count + || node_count > output_count || edge_count > output_offset_count) { + result.status = 4; return 4; + } + if (!ir_span_valid(scratch as ptr, node_count, 40) + || !ir_span_valid(output as ptr, node_count, 40) + || !ir_span_valid(scratch_offsets as ptr, edge_count, 8) + || !ir_span_valid(output_offsets as ptr, edge_count, 8)) { + result.status = 5; return 5; + } + if (node_count > max_work || edge_count > max_work - node_count) { + result.status = 6; return 6; + } + // Reserve the final copy before preflight so a successful analysis cannot + // fail after it starts publishing output. Repeated edge visits are charged + // individually below, rather than assuming disjoint input ranges. + var output_work: u64 = node_count + edge_count; + var work: u64 = max_work - output_work; + var depth: u64 = max_depth; + if (depth > 256) { depth = 256; } + var index: u64 = 0; + while (index < node_count) { + if (work == 0) { result.status = 6; return 6; } + work -= 1; + scratch[index].size = 0; scratch[index].align = 0; scratch[index].stride = 0; + scratch[index].allocation_align = 0; scratch[index].depth = 0; + index += 1; + } + index = 0; + while (index < edge_count) { + if (work == 0) { result.status = 6; return 6; } + work -= 1; + scratch_offsets[index] = 0; + index += 1; + } + result.index = root; + var status: i32 = ir_layout_node(root, nodes, node_count, edges, edge_count, + storage, depth, scratch, scratch_offsets, &work); + if (status != 0) { result.status = status as u64; return status; } + index = 0; + while (index < node_count) { output[index] = scratch[index]; index += 1; } + index = 0; + while (index < edge_count) { output_offsets[index] = scratch_offsets[index]; index += 1; } + result.index = root; + return 0; +} diff --git a/ir/expression_parser.wave b/ir/expression_parser.wave new file mode 100644 index 0000000..d7706da --- /dev/null +++ b/ir/expression_parser.wave @@ -0,0 +1,292 @@ +// SPDX-License-Identifier: MPL-2.0 +// Preserved constant-expression grammar, separate from numeric evaluation. +struct IrParsedExpression { + kind: u64; + op: u64; + type_first: u64; + type_count: u64; + low: u64; + high: u64; +} + +struct IrExpressionResult { + status: u64; // 1 syntax, 2 constant depth, 3 nodes, 4 work, 5 capacity, + // 6 transport, 7 nested type error, 8 literal error + reason: u64; + at: u64; + expected: u64; + detail: u64; + next: u64; + expressions: u64; + types: u64; + spent: u64; + work: u64; +} + +struct IrExpressionMeta { first: u64; count: u64; } + +struct IrExpressionParser { + tokens: ptr; + token_count: u64; + at: u64; + format: u64; + max_depth: u64; + max_type_depth: u64; + max_nodes: u64; + max_work: u64; + work: u64; + spent: u64; + expressions: u64; + types: u64; + mode: u64; + type_scratch: ptr; + type_capacity: u64; + expression_scratch: ptr; + expression_capacity: u64; + result: ptr; +} + +fun ir_expression_word(token: ptr, code: u64) -> bool { + var first: u64 = 0; + var second: u64 = 0; + var length: u64 = 0; + if (code == 0) { first = 32773617136986466; second = 0; length = 7; } // bit_not + else if (code == 1) { first = 6776174; second = 0; length = 3; } // neg + else if (code == 2) { first = 6579297; second = 0; length = 3; } // add + else if (code == 3) { first = 6452595; second = 0; length = 3; } // sub + else if (code == 4) { first = 7107949; second = 0; length = 3; } // mul + else if (code == 5) { first = 28268862163413346; second = 0; length = 7; } // bit_and + else if (code == 6) { first = 125822668400994; second = 0; length = 6; } // bit_or + else if (code == 7) { first = 32210710133238114; second = 0; length = 7; } // bit_xor + else if (code == 8) { first = 7760228; second = 0; length = 3; } // div + else if (code == 9) { first = 7169394; second = 0; length = 3; } // rem + else if (code == 10) { first = 7308321248854501491; second = 29798; length = 10; } // shift_left + else if (code == 11) { first = 7598240474866477171; second = 7628903; length = 11; } // shift_right + else if (code == 12) { first = 6875977810685947756; second = 6581857; length = 11; } // logical_and + else if (code == 13) { first = 6875977810685947756; second = 29295; length = 10; } // logical_or + else if (code == 14) { first = 29029; second = 0; length = 2; } // eq + else if (code == 15) { first = 25966; second = 0; length = 2; } // ne + else if (code == 16) { first = 29804; second = 0; length = 2; } // lt + else if (code == 17) { first = 25964; second = 0; length = 2; } // le + else if (code == 18) { first = 29799; second = 0; length = 2; } // gt + else if (code == 19) { first = 25959; second = 0; length = 2; } // ge + else if (code == 20) { first = 40; second = 0; length = 1; } // ( + else if (code == 21) { first = 41; second = 0; length = 1; } // ) + else if (code == 22) { first = 44; second = 0; length = 1; } // , + else { return false; } + if (token.kind == 1 || token.kind == 3 || token.length != length) { return false; } + var i: u64 = 0; + var packed: u64 = 0; + while (i < length) { + packed = first; + if (i >= 8) { packed = second; } + if (token.data[i] as u64 != ((packed >> ((i & 7) * 8)) & 255)) { return false; } + i += 1; + } + return true; +} + +fun ir_expression_fail(p: ptr, status: u64, reason: u64, + at: u64, expected: u64, detail: u64) -> bool { + p.result.status = status; p.result.reason = reason; p.result.at = at; + p.result.expected = expected; p.result.detail = detail; + return false; +} + +fun ir_expression_charge(p: ptr, amount: u64) -> bool { + if (amount > p.max_work - p.work) { return ir_expression_fail(p, 4, 0, p.at, 0, 0); } + p.work += amount; return true; +} + +fun ir_expression_read(p: ptr) -> bool { + if (!ir_expression_charge(p, 1)) { return false; } + if (p.at >= p.token_count) { return ir_expression_fail(p, 6, 0, p.at, 0, 0); } + var token: ptr = &p.tokens[p.at]; + if (token.kind > 3 || !ir_span_valid(token.data, token.length, 1)) { + return ir_expression_fail(p, 6, 0, p.at, 0, 0); + } + return true; +} + +fun ir_expression_expect(p: ptr, code: u64) -> bool { + if (!ir_expression_read(p)) { return false; } + if (!ir_expression_word(&p.tokens[p.at], code)) { + return ir_expression_fail(p, 1, 1, p.at, code, 0); + } + p.at += 1; return true; +} + +fun ir_expression_emit(p: ptr, kind: u64, op: u64, + meta: ptr, low: u64, high: u64) -> bool { + // Include the compatibility model's type materialization before allocation. + if (!ir_expression_charge(p, 2 + meta.count)) { return false; } + if (p.mode == 1) { + if (p.expressions >= p.expression_capacity) { return ir_expression_fail(p, 5, 0, p.at, 0, 0); } + p.expression_scratch[p.expressions].kind = kind; + p.expression_scratch[p.expressions].op = op; + p.expression_scratch[p.expressions].type_first = meta.first; + p.expression_scratch[p.expressions].type_count = meta.count; + p.expression_scratch[p.expressions].low = low; + p.expression_scratch[p.expressions].high = high; + } + p.expressions += 1; return true; +} + +fun ir_expression_id(p: ptr, output: ptr) -> bool { + var token: ptr = &p.tokens[p.at]; + if (token.length == 2) { return ir_expression_fail(p, 1, 4, p.at, 0, 0); } + var index: u64 = 2; + var value: u64 = 0; + var octet: u64 = 0; + var digit: u64 = 0; + var overflow: bool = false; + while (index < token.length) { + if (!ir_expression_charge(p, 1)) { return false; } + octet = token.data[index] as u64; + if (octet < 48 || octet > 57) { return ir_expression_fail(p, 1, 4, p.at, 0, 0); } + digit = octet - 48; + if (value > (4294967295 - digit) / 10) { overflow = true; } + if (!overflow) { value = value * 10 + digit; } + index += 1; + } + if (overflow) { return ir_expression_fail(p, 1, 5, p.at, 0, 0); } + output[0] = value; p.at += 1; return true; +} + +fun ir_expression_node(p: ptr, depth: u64, meta: ptr) -> bool { + if (depth > p.max_depth) { return ir_expression_fail(p, 2, 0, p.at, 0, 0); } + if (p.spent >= p.max_nodes) { return ir_expression_fail(p, 3, 0, p.at, 0, 0); } + p.spent += 1; + if (!ir_expression_read(p)) { return false; } + var token: ptr = &p.tokens[p.at]; + var code: u64 = 0; + while (code < 20 && !ir_expression_word(token, code)) { code += 1; } + if (code < 20) { + if ((code == 0 || (code >= 5 && code <= 13)) && p.format < 5) { + return ir_expression_fail(p, 1, 2, p.at, 0, 0); + } + if (code == 1 && p.format < 8) { return ir_expression_fail(p, 1, 3, p.at, 0, 0); } + p.at += 1; + if (!ir_expression_expect(p, 20)) { return false; } + var left: IrExpressionMeta = IrExpressionMeta { first: 0, count: 0 }; + var right: IrExpressionMeta = IrExpressionMeta { first: 0, count: 0 }; + if (!ir_expression_node(p, depth + 1, &left)) { return false; } + if (code >= 2) { + if (!ir_expression_expect(p, 22) || !ir_expression_node(p, depth + 1, &right)) { return false; } + } + if (!ir_expression_expect(p, 21)) { return false; } + meta.first = left.first; meta.count = left.count; + if (code < 2) { return ir_expression_emit(p, 3 + code, 0, meta, 0, 0); } + if (code >= 14) { + if (!ir_expression_charge(p, 2)) { return false; } + if (p.mode == 1) { + if (p.types >= p.type_capacity) { return ir_expression_fail(p, 5, 0, p.at, 0, 0); } + p.type_scratch[p.types].kind = 1; p.type_scratch[p.types].value = 0; p.type_scratch[p.types].count = 0; + } + meta.first = p.types; meta.count = 1; p.types += 1; + return ir_expression_emit(p, 6, code - 14, meta, 0, 0); + } + return ir_expression_emit(p, 5, code - 2, meta, 0, 0); + } + var type_start: u64 = p.at; + var parsed: IrTypeParseResult = IrTypeParseResult { status: 0, reason: 0, at: 0, + expected: 0, next: 0, nodes: 0, work: 0 }; + var type_pointer: ptr = null; + var capacity: u64 = 0; + if (p.mode == 1) { + if (p.types > p.type_capacity) { return ir_expression_fail(p, 5, 0, p.at, 0, 0); } + type_pointer = &p.type_scratch[p.types]; capacity = p.type_capacity - p.types; + } + var status: i32 = whale_ir_parse_type(p.tokens, p.token_count, p.at, 0, + p.max_type_depth, p.max_nodes - p.spent, p.max_work - p.work, p.mode, + type_pointer, capacity, type_pointer, capacity, &parsed); + p.work += parsed.work; + if (status != 0) { + return ir_expression_fail(p, 7, parsed.status, parsed.at, parsed.reason, parsed.expected); + } + if (!ir_expression_charge(p, parsed.nodes)) { return false; } + meta.first = p.types; meta.count = parsed.nodes; + p.types += parsed.nodes; p.spent += parsed.nodes; p.at = parsed.next; + if (!ir_expression_read(p)) { return false; } + token = &p.tokens[p.at]; + var reference: u64 = 0; + var reference_kind: u64 = 0; + if (token.kind != 1 && token.kind != 3 && token.length >= 2) { + if (token.data[0] == 64 && token.data[1] == 103) { reference_kind = 1; } + else if (token.data[0] == 37 && token.data[1] == 118) { reference_kind = 2; } + } + if (reference_kind != 0) { + if (!ir_expression_id(p, &reference)) { return false; } + return ir_expression_emit(p, reference_kind, reference, meta, 0, 0); + } + var root_kind: u64 = 0; + while (root_kind < 22 && !ir_type_word(&p.tokens[type_start], root_kind)) { root_kind += 1; } + var category: u64 = 0; + var width: u64 = 0; + if (root_kind == 1) { category = 1; width = 1; } + else if (root_kind == 2 || (root_kind >= 4 && root_kind <= 8)) { category = 2; } + else if (root_kind == 3 || (root_kind >= 9 && root_kind <= 13)) { category = 3; } + else if (root_kind >= 14 && root_kind <= 16) { category = 4; } + if (root_kind == 2 || root_kind == 3) { width = 1; } + else if (root_kind == 4 || root_kind == 9) { width = 8; } + else if (root_kind == 5 || root_kind == 10 || root_kind == 14) { width = 16; } + else if (root_kind == 6 || root_kind == 11 || root_kind == 15) { width = 32; } + else if (root_kind == 7 || root_kind == 12 || root_kind == 16) { width = 64; } + else if (root_kind == 8 || root_kind == 13) { width = 128; } + var literal: IrLiteralResult = IrLiteralResult { status: 0, low: 0, high: 0, work: 0 }; + // Strings and EOF have the same diagnostic spelling used by the grammar + // transport; neither spelling is a valid literal in any scalar category. + if (token.kind == 1 || token.kind == 3) { + if (category == 0) { return ir_expression_fail(p, 8, 8, p.at, width, 0); } + if (category == 1) { return ir_expression_fail(p, 8, 1, p.at, width, 0); } + if (category == 2) { return ir_expression_fail(p, 8, 2, p.at, width, 0); } + if (category == 3) { return ir_expression_fail(p, 8, 4, p.at, width, 0); } + return ir_expression_fail(p, 8, 6, p.at, width, 0); + } + status = whale_ir_parse_literal(token.data, token.length, category, width, + p.max_work - p.work, &literal); + p.work += literal.work; + if (status != 0) { return ir_expression_fail(p, 8, literal.status, p.at, width, 0); } + p.at += 1; + return ir_expression_emit(p, 0, 0, meta, literal.low, literal.high); +} + +export(c) fun whale_ir_parse_expression(tokens: ptr, token_count: u64, + start: u64, depth: u64, format: u64, max_depth: u64, max_type_depth: u64, + max_nodes: u64, max_work: u64, mode: u64, + type_scratch: ptr, type_capacity: u64, + expression_scratch: ptr, expression_capacity: u64, + output_types: ptr, output_type_capacity: u64, + output_expressions: ptr, output_expression_capacity: u64, + result: ptr) -> i32 { + if (result == null) { return 6; } + result.status = 0; result.reason = 0; result.at = start; result.expected = 0; + result.detail = 0; result.next = 0; result.expressions = 0; result.types = 0; + result.spent = 0; result.work = 0; + if (mode > 1 || max_depth > 256 || max_type_depth > 256 || start >= token_count + || !ir_span_valid(tokens as ptr, token_count, 24) + || (mode == 1 && (!ir_span_valid(type_scratch as ptr, type_capacity, 24) + || !ir_span_valid(expression_scratch as ptr, expression_capacity, 48) + || !ir_span_valid(output_types as ptr, output_type_capacity, 24) + || !ir_span_valid(output_expressions as ptr, output_expression_capacity, 48)))) { + result.status = 6; return 6; + } + var p: IrExpressionParser = IrExpressionParser { tokens: tokens, token_count: token_count, + at: start, format: format, max_depth: max_depth, max_type_depth: max_type_depth, + max_nodes: max_nodes, max_work: max_work, work: 0, spent: 0, expressions: 0, + types: 0, mode: mode, type_scratch: type_scratch, type_capacity: type_capacity, + expression_scratch: expression_scratch, expression_capacity: expression_capacity, result: result }; + var meta: IrExpressionMeta = IrExpressionMeta { first: 0, count: 0 }; + if (!ir_expression_node(&p, depth, &meta)) { result.work = p.work; return result.status as i32; } + if (mode == 1 && (p.types > output_type_capacity || p.expressions > output_expression_capacity)) { + result.status = 5; result.work = p.work; return 5; + } + var index: u64 = 0; + if (mode == 1) { + while (index < p.types) { output_types[index] = type_scratch[index]; index += 1; } + index = 0; + while (index < p.expressions) { output_expressions[index] = expression_scratch[index]; index += 1; } + } + result.next = p.at; result.expressions = p.expressions; result.types = p.types; + result.spent = p.spent; result.work = p.work; return 0; +} diff --git a/ir/header.wave b/ir/header.wave new file mode 100644 index 0000000..c731941 --- /dev/null +++ b/ir/header.wave @@ -0,0 +1,160 @@ +// SPDX-License-Identifier: MPL-2.0 +// Versioned IR header parser. Token text is borrowed from the caller and the +// payload is published only after every required field has been checked. +struct IrTextToken { + data: ptr; + length: u64; + kind: u64; // 0 word, 1 decoded string, 2 mark, 3 EOF +} + +struct IrHeaderResult { + status: u64; // 0 success, 1 expected token, 2 decimal, 3 range, + // 4 format, 5 semantics, 6 string, 7 byte order, 8 transport, + // 9 word + at: u64; + expected: u64; + version: u64; + ptr_bits: u64; + endian: u64; // 0 little, 1 big + target_index: u64; + next: u64; +} + +// Pack expected ASCII bytes into three u64 words. Exact byte comparison avoids +// both hash collisions and the pinned compiler's exported string-literal +// symbols, which would collide with independently linked Wave modules. +fun ir_header_equal(token: ptr, expected: u64) -> bool { + var length: u64 = 0; + var first: u64 = 0; + var second: u64 = 0; + var third: u64 = 0; + if (expected == 0) { length = 6; first = 111516500389741; } + else if (expected == 1 || expected == 9) { length = 1; first = 123; } + else if (expected == 2) { length = 14; first = 8529664181059874662; second = 121424789598821; } + else if (expected == 4) { length = 17; first = 7163384699739268467; second = 8028074745930342259; third = 110; } + else if (expected == 6) { length = 6; first = 127978876068212; } + else if (expected == 8) { length = 10; first = 8032558528511369572; second = 29813; } + else if (expected == 10) { length = 3; first = 7500912; } + else if (expected == 11 || expected == 15) { length = 1; first = 61; } + else if (expected == 13) { length = 1; first = 44; } + else if (expected == 14) { length = 6; first = 121364659072613; } + else if (expected == 16) { length = 6; first = 111516484659564; } + else if (expected == 18) { length = 3; first = 6777186; } + else if (expected == 17) { length = 1; first = 125; } + else { return false; } + if (token.kind == 1 || token.kind == 3 || token.length != length) { return false; } + var i: u64 = 0; + while (i < length) { + var word: u64 = first; + if (i >= 16) { word = third; } + else if (i >= 8) { word = second; } + if (token.data[i] as u64 != ((word >> ((i & 7) * 8)) & 255)) { return false; } + i += 1; + } + return true; +} + +fun ir_header_number(token: ptr, value: ptr) -> u64 { + if (token.kind != 0 || token.length == 0) { return 2; } + var n: u64 = 0; + var i: u64 = 0; + var overflow: bool = false; + var b: u64 = 0; + var digit: u64 = 0; + while (i < token.length) { + b = token.data[i] as u64; + if (b < 48 || b > 57) { return 2; } + digit = b - 48; + if (n > (4294967295 - digit) / 10) { overflow = true; } + if (!overflow) { n = n * 10 + digit; } + i += 1; + } + if (overflow) { return 3; } + value[0] = n; + return 0; +} + +fun ir_header_expect(tokens: ptr, count: u64, at: ptr, + expected: u64, result: ptr) -> bool { + if (at[0] >= count || !ir_header_equal(&tokens[at[0]], expected)) { + result.status = 1; result.at = at[0]; result.expected = expected; + return false; + } + at[0] += 1; + return true; +} + +export(c) fun whale_ir_header(tokens: ptr, count: u64, + max_format: u64, semantics: u64, result: ptr) -> i32 { + if (result == null) { return 8; } + result.status = 8; result.at = 0; result.expected = 0; + result.version = 0; result.ptr_bits = 0; result.endian = 0; + result.target_index = 0; result.next = 0; + if (!ir_span_valid(tokens as ptr, count, 24) || count == 0) { return 8; } + // The Rust bridge supplies UTF-8 spans from the Wave lexer. Validate the + // borrow before touching it, including tokens selected on error paths. + var i: u64 = 0; + while (i < count && i < 18) { + if (tokens[i].kind > 3 || !ir_span_valid(tokens[i].data, tokens[i].length, 1)) { + return 8; + } + i += 1; + } + var at: u64 = 0; + var version: u64 = 0; + var ptr_bits: u64 = 0; + var endian: u64 = 0; + var target_index: u64 = 0; + if (!ir_header_expect(tokens, count, &at, 0, result) + || !ir_header_expect(tokens, count, &at, 1, result) + || !ir_header_expect(tokens, count, &at, 2, result)) { + return result.status as i32; + } + result.at = at; + if (at >= count) { result.status = 2; return 2; } + result.status = ir_header_number(&tokens[at], &version); + if (result.status != 0) { return result.status as i32; } + at += 1; + if (version < 3 || version > max_format) { + result.status = 4; result.at = at - 1; return 4; + } + if (!ir_header_expect(tokens, count, &at, 4, result)) { + return 1; + } + result.at = at; + if (at >= count) { result.status = 2; return 2; } + result.status = ir_header_number(&tokens[at], &i); + if (result.status != 0) { return result.status as i32; } + at += 1; + if (i != semantics) { result.status = 5; result.at = at - 1; return 5; } + if (!ir_header_expect(tokens, count, &at, 6, result)) { return 1; } + if (at >= count) { result.status = 6; result.at = at; return 6; } + if (tokens[at].kind != 1) { result.status = 6; result.at = at; return 6; } + target_index = at; at += 1; + if (!ir_header_expect(tokens, count, &at, 8, result) + || !ir_header_expect(tokens, count, &at, 9, result) + || !ir_header_expect(tokens, count, &at, 10, result) + || !ir_header_expect(tokens, count, &at, 11, result)) { + return 1; + } + result.at = at; + if (at >= count) { result.status = 2; return 2; } + result.status = ir_header_number(&tokens[at], &ptr_bits); + if (result.status != 0) { return result.status as i32; } + at += 1; + if (!ir_header_expect(tokens, count, &at, 13, result) + || !ir_header_expect(tokens, count, &at, 14, result) + || !ir_header_expect(tokens, count, &at, 15, result)) { + return 1; + } + if (at >= count) { result.status = 9; result.at = at; return 9; } + if (tokens[at].kind != 0) { result.status = 9; result.at = at; return 9; } + if (ir_header_equal(&tokens[at], 16)) { endian = 0; } + else if (ir_header_equal(&tokens[at], 18)) { endian = 1; } + else { result.status = 7; result.at = at; return 7; } + at += 1; + if (!ir_header_expect(tokens, count, &at, 17, result)) { return 1; } + result.version = version; result.ptr_bits = ptr_bits; result.endian = endian; + result.target_index = target_index; result.next = at; result.status = 0; + return 0; +} diff --git a/ir/instruction_parser.wave b/ir/instruction_parser.wave new file mode 100644 index 0000000..de01d49 --- /dev/null +++ b/ir/instruction_parser.wave @@ -0,0 +1,671 @@ +// SPDX-License-Identifier: MPL-2.0 +// Versioned instruction/terminator grammar. Primitive production selection, +// list loops, result presence and diagnostics run in Wave. Nested type/literal/ +// constant-expression requests call the other Wave-owned grammar kernels. +struct IrInstructionState { + phase: u64; at: u64; format: u64; mode: u64; op: u64; sub: u64; + op_at: u64; has_dst: u64; dst: u64; annotation_kind: u64; type_kind: u64; + a: u64; b: u64; c: u64; d: u64; e: u64; name: u64; aux: u64; + nodes: u64; work: u64; +} + +struct IrInstructionEvent { + status: u64; reason: u64; at: u64; expected: u64; + event: u64; role: u64; op: u64; sub: u64; has_dst: u64; dst: u64; + a: u64; b: u64; c: u64; d: u64; e: u64; name: u64; aux: u64; + next: u64; nodes: u64; work: u64; +} + +struct IrInstructionParser { + tokens: ptr; count: u64; state: ptr; + max_nodes: u64; max_work: u64; result: ptr; +} + +fun ir_instruction_word(token: ptr, code: u64) -> bool { + var first: u64 = 0; var second: u64 = 0; var length: u64 = 0; + if (code == 0) { first = 58; second = 0; length = 1; } // : + else if (code == 1) { first = 61; second = 0; length = 1; } // = + else if (code == 2) { first = 44; second = 0; length = 1; } // , + else if (code == 3) { first = 91; second = 0; length = 1; } // [ + else if (code == 4) { first = 93; second = 0; length = 1; } // ] + else if (code == 5) { first = 40; second = 0; length = 1; } // ( + else if (code == 6) { first = 41; second = 0; length = 1; } // ) + else if (code == 7) { first = 60; second = 0; length = 1; } // < + else if (code == 8) { first = 62; second = 0; length = 1; } // > + else if (code == 9) { first = 1819242338; second = 0; length = 4; } // bool + else if (code == 10) { first = 7500912; second = 0; length = 3; } // ptr + else if (code == 11) { first = 14453; second = 0; length = 2; } // u8 + else if (code == 12) { first = 3421813; second = 0; length = 3; } // u64 + else if (code == 13) { first = 474181364833; second = 0; length = 5; } // align + else if (code == 14) { first = 465557414252; second = 0; length = 5; } // label + else if (code == 15) { first = 121424956188018; second = 0; length = 6; } // reason + else if (code == 16) { first = 28532; second = 0; length = 2; } // to + else if (code == 17) { first = 15933; second = 0; length = 2; } // => + else if (code == 18) { first = 8386658473162862185; second = 0; length = 8; } // indirect + else if (code == 19) { first = 435610019959; second = 0; length = 5; } // whale + else if (code == 20) { first = 57408520157555; second = 0; length = 6; } // sysv64 + else if (code == 21) { first = 7016445909985619047; second = 7496804; length = 11; } // global_addr + else if (code == 22) { first = 7308613718930516332; second = 1684956511; length = 12; } // lifetime_end + else if (code == 23) { first = 28823050467308656; second = 0; length = 7; } // ptrdiff + else if (code == 24) { first = 7306069449259249507; second = 27747; length = 10; } // const_decl + else if (code == 25) { first = 500152823651; second = 0; length = 5; } // const + else if (code == 26) { first = 439787744885; second = 0; length = 5; } // undef + else if (code == 27) { first = 7761773; second = 0; length = 3; } // mov + else if (code == 28) { first = 6776174; second = 0; length = 3; } // neg + else if (code == 29) { first = 7630702; second = 0; length = 3; } // not + else if (code == 30) { first = 7368035; second = 0; length = 3; } // cmp + else if (code == 31) { first = 1886217065; second = 0; length = 4; } // icmp + else if (code == 32) { first = 1886217062; second = 0; length = 4; } // fcmp + else if (code == 33) { first = 127970252186995; second = 0; length = 6; } // select + else if (code == 34) { first = 6908016; second = 0; length = 3; } // phi + else if (code == 35) { first = 32760367481649253; second = 0; length = 7; } // extract + else if (code == 36) { first = 107079699033185; second = 0; length = 6; } // alloca + else if (code == 37) { first = 7308332243887091574; second = 431131421791; length = 13; } // volatile_load + else if (code == 38) { first = 7308332243887091574; second = 111542170579807; length = 14; } // volatile_store + else if (code == 39) { first = 1684107116; second = 0; length = 4; } // load + else if (code == 40) { first = 127996172791413; second = 0; length = 6; } // uninit + else if (code == 41) { first = 435711603827; second = 0; length = 5; } // store + else if (code == 42) { first = 7365991; second = 0; length = 3; } // gep + else if (code == 43) { first = 133523611411821; second = 0; length = 6; } // memcpy + else if (code == 44) { first = 127979077068141; second = 0; length = 6; } // memset + else if (code == 45) { first = 7959380476474193262; second = 474315584611; length = 13; } // null_function + else if (code == 46) { first = 7957695015192261990; second = 491310571871; length = 13; } // function_addr + else if (code == 47) { first = 1819042147; second = 0; length = 4; } // call + else if (code == 48) { first = 28826306252730996; second = 0; length = 7; } // trap_if + else if (code == 49) { first = 29282; second = 0; length = 2; } // br + else if (code == 50) { first = 7496291; second = 0; length = 3; } // cbr + else if (code == 51) { first = 114776364119923; second = 0; length = 6; } // switch + else if (code == 52) { first = 7628146; second = 0; length = 3; } // ret + else if (code == 53) { first = 1885434484; second = 0; length = 4; } // trap + else if (code == 54) { first = 6579297; second = 0; length = 3; } // add + else if (code == 55) { first = 6452595; second = 0; length = 3; } // sub + else if (code == 56) { first = 7107949; second = 0; length = 3; } // mul + else if (code == 57) { first = 1986618485; second = 0; length = 4; } // udiv + else if (code == 58) { first = 1986618483; second = 0; length = 4; } // sdiv + else if (code == 59) { first = 1835364981; second = 0; length = 4; } // urem + else if (code == 60) { first = 1835364979; second = 0; length = 4; } // srem + else if (code == 61) { first = 1684300134; second = 0; length = 4; } // fadd + else if (code == 62) { first = 1651864422; second = 0; length = 4; } // fsub + else if (code == 63) { first = 1819635046; second = 0; length = 4; } // fmul + else if (code == 64) { first = 1986618470; second = 0; length = 4; } // fdiv + else if (code == 65) { first = 1835364966; second = 0; length = 4; } // frem + else if (code == 66) { first = 6581857; second = 0; length = 3; } // and + else if (code == 67) { first = 29295; second = 0; length = 2; } // or + else if (code == 68) { first = 7499640; second = 0; length = 3; } // xor + else if (code == 69) { first = 7104627; second = 0; length = 3; } // shl + else if (code == 70) { first = 1919447916; second = 0; length = 4; } // lshr + else if (code == 71) { first = 1919447905; second = 0; length = 4; } // ashr + else if (code == 72) { first = 6873730443177715811; second = 7630441; length = 11; } // checked_int + else if (code == 73) { first = 1954047354; second = 0; length = 4; } // zext + else if (code == 74) { first = 1954047347; second = 0; length = 4; } // sext + else if (code == 75) { first = 427054953076; second = 0; length = 5; } // trunc + else if (code == 76) { first = 1954047334; second = 0; length = 4; } // fext + else if (code == 77) { first = 109326067987558; second = 0; length = 6; } // ftrunc + else if (code == 78) { first = 126853577667689; second = 0; length = 6; } // itof_s + else if (code == 79) { first = 129052600923241; second = 0; length = 6; } // itof_u + else if (code == 80) { first = 126853627999334; second = 0; length = 6; } // ftoi_s + else if (code == 81) { first = 129052651254886; second = 0; length = 6; } // ftoi_u + else if (code == 82) { first = 32777959416031586; second = 0; length = 7; } // bitcast + else if (code == 83) { first = 8389759083253757040; second = 0; length = 8; } // ptrtoint + else if (code == 84) { first = 8247340441619689065; second = 0; length = 8; } // inttoptr + else if (code == 85) { first = 7739545220993540469; second = 0; length = 8; } // uadd_chk + else if (code == 86) { first = 7739545220961104757; second = 0; length = 8; } // usub_chk + else if (code == 87) { first = 7739545221128875381; second = 0; length = 8; } // umul_chk + else if (code == 88) { first = 7739545220993540467; second = 0; length = 8; } // sadd_chk + else if (code == 89) { first = 7739545220961104755; second = 0; length = 8; } // ssub_chk + else if (code == 90) { first = 7739545221128875379; second = 0; length = 8; } // smul_chk + else if (code == 91) { first = 29029; second = 0; length = 2; } // eq + else if (code == 92) { first = 25966; second = 0; length = 2; } // ne + else if (code == 93) { first = 7629939; second = 0; length = 3; } // slt + else if (code == 94) { first = 6646899; second = 0; length = 3; } // sle + else if (code == 95) { first = 7628659; second = 0; length = 3; } // sgt + else if (code == 96) { first = 6645619; second = 0; length = 3; } // sge + else if (code == 97) { first = 7629941; second = 0; length = 3; } // ult + else if (code == 98) { first = 6646901; second = 0; length = 3; } // ule + else if (code == 99) { first = 7628661; second = 0; length = 3; } // ugt + else if (code == 100) { first = 6645621; second = 0; length = 3; } // uge + else if (code == 101) { first = 7431526; second = 0; length = 3; } // feq + else if (code == 102) { first = 6647398; second = 0; length = 3; } // fne + else if (code == 103) { first = 7629926; second = 0; length = 3; } // flt + else if (code == 104) { first = 6646886; second = 0; length = 3; } // fle + else if (code == 105) { first = 7628646; second = 0; length = 3; } // fgt + else if (code == 106) { first = 6645606; second = 0; length = 3; } // fge + else if (code == 107) { first = 7431535; second = 0; length = 3; } // oeq + else if (code == 108) { first = 6647407; second = 0; length = 3; } // one + else if (code == 109) { first = 7629935; second = 0; length = 3; } // olt + else if (code == 110) { first = 6646895; second = 0; length = 3; } // ole + else if (code == 111) { first = 7628655; second = 0; length = 3; } // ogt + else if (code == 112) { first = 6645615; second = 0; length = 3; } // oge + else if (code == 113) { first = 6582895; second = 0; length = 3; } // ord + else if (code == 114) { first = 7302773; second = 0; length = 3; } // uno + else if (code == 115) { first = 7431541; second = 0; length = 3; } // ueq + else if (code == 116) { first = 6647413; second = 0; length = 3; } // une + else { return false; } + if (token.kind == 1 || token.kind == 3 || token.length != length) { return false; } + var index: u64 = 0; + while (index < length) { + var packed: u64 = first; if (index >= 8) { packed = second; } + if (token.data[index] as u64 != ((packed >> ((index & 7) * 8)) & 255)) { return false; } + index += 1; + } + return true; +} + +fun ir_instruction_opcode(token: ptr, sub: ptr) -> u64 { + if (ir_instruction_word(token, 21)) { sub[0] = 0; return 0; } // global_addr + if (ir_instruction_word(token, 22)) { sub[0] = 0; return 1; } // lifetime_end + if (ir_instruction_word(token, 23)) { sub[0] = 0; return 2; } // ptrdiff + if (ir_instruction_word(token, 24)) { sub[0] = 0; return 3; } // const_decl + if (ir_instruction_word(token, 25)) { sub[0] = 0; return 4; } // const + if (ir_instruction_word(token, 26)) { sub[0] = 0; return 5; } // undef + if (ir_instruction_word(token, 27)) { sub[0] = 0; return 6; } // mov + if (ir_instruction_word(token, 28)) { sub[0] = 0; return 8; } // neg + if (ir_instruction_word(token, 29)) { sub[0] = 0; return 9; } // not + if (ir_instruction_word(token, 30)) { sub[0] = 0; return 10; } // cmp + if (ir_instruction_word(token, 31)) { sub[0] = 0; return 11; } // icmp + if (ir_instruction_word(token, 32)) { sub[0] = 0; return 12; } // fcmp + if (ir_instruction_word(token, 33)) { sub[0] = 0; return 13; } // select + if (ir_instruction_word(token, 34)) { sub[0] = 0; return 15; } // phi + if (ir_instruction_word(token, 35)) { sub[0] = 0; return 16; } // extract + if (ir_instruction_word(token, 36)) { sub[0] = 0; return 18; } // alloca + if (ir_instruction_word(token, 37)) { sub[0] = 0; return 19; } // volatile_load + if (ir_instruction_word(token, 38)) { sub[0] = 0; return 20; } // volatile_store + if (ir_instruction_word(token, 39)) { sub[0] = 0; return 21; } // load + if (ir_instruction_word(token, 40)) { sub[0] = 0; return 22; } // uninit + if (ir_instruction_word(token, 41)) { sub[0] = 0; return 23; } // store + if (ir_instruction_word(token, 42)) { sub[0] = 0; return 24; } // gep + if (ir_instruction_word(token, 43)) { sub[0] = 0; return 25; } // memcpy + if (ir_instruction_word(token, 44)) { sub[0] = 0; return 26; } // memset + if (ir_instruction_word(token, 45)) { sub[0] = 0; return 27; } // null_function + if (ir_instruction_word(token, 46)) { sub[0] = 0; return 28; } // function_addr + if (ir_instruction_word(token, 47)) { sub[0] = 0; return 29; } // call + if (ir_instruction_word(token, 48)) { sub[0] = 0; return 30; } // trap_if + if (ir_instruction_word(token, 49)) { sub[0] = 0; return 31; } // br + if (ir_instruction_word(token, 50)) { sub[0] = 0; return 32; } // cbr + if (ir_instruction_word(token, 51)) { sub[0] = 0; return 33; } // switch + if (ir_instruction_word(token, 52)) { sub[0] = 0; return 34; } // ret + if (ir_instruction_word(token, 53)) { sub[0] = 0; return 35; } // trap + if (ir_instruction_word(token, 54)) { sub[0] = 0; return 7; } // add + if (ir_instruction_word(token, 55)) { sub[0] = 1; return 7; } // sub + if (ir_instruction_word(token, 56)) { sub[0] = 2; return 7; } // mul + if (ir_instruction_word(token, 57)) { sub[0] = 3; return 7; } // udiv + if (ir_instruction_word(token, 58)) { sub[0] = 4; return 7; } // sdiv + if (ir_instruction_word(token, 59)) { sub[0] = 5; return 7; } // urem + if (ir_instruction_word(token, 60)) { sub[0] = 6; return 7; } // srem + if (ir_instruction_word(token, 61)) { sub[0] = 7; return 7; } // fadd + if (ir_instruction_word(token, 62)) { sub[0] = 8; return 7; } // fsub + if (ir_instruction_word(token, 63)) { sub[0] = 9; return 7; } // fmul + if (ir_instruction_word(token, 64)) { sub[0] = 10; return 7; } // fdiv + if (ir_instruction_word(token, 65)) { sub[0] = 11; return 7; } // frem + if (ir_instruction_word(token, 66)) { sub[0] = 12; return 7; } // and + if (ir_instruction_word(token, 67)) { sub[0] = 13; return 7; } // or + if (ir_instruction_word(token, 68)) { sub[0] = 14; return 7; } // xor + if (ir_instruction_word(token, 69)) { sub[0] = 15; return 7; } // shl + if (ir_instruction_word(token, 70)) { sub[0] = 16; return 7; } // lshr + if (ir_instruction_word(token, 71)) { sub[0] = 17; return 7; } // ashr + if (ir_instruction_word(token, 72)) { sub[0] = 0; return 14; } // checked_int + if (ir_instruction_word(token, 73)) { sub[0] = 1; return 14; } // zext + if (ir_instruction_word(token, 74)) { sub[0] = 2; return 14; } // sext + if (ir_instruction_word(token, 75)) { sub[0] = 3; return 14; } // trunc + if (ir_instruction_word(token, 76)) { sub[0] = 4; return 14; } // fext + if (ir_instruction_word(token, 77)) { sub[0] = 5; return 14; } // ftrunc + if (ir_instruction_word(token, 78)) { sub[0] = 6; return 14; } // itof_s + if (ir_instruction_word(token, 79)) { sub[0] = 7; return 14; } // itof_u + if (ir_instruction_word(token, 80)) { sub[0] = 8; return 14; } // ftoi_s + if (ir_instruction_word(token, 81)) { sub[0] = 9; return 14; } // ftoi_u + if (ir_instruction_word(token, 82)) { sub[0] = 10; return 14; } // bitcast + if (ir_instruction_word(token, 83)) { sub[0] = 11; return 14; } // ptrtoint + if (ir_instruction_word(token, 84)) { sub[0] = 12; return 14; } // inttoptr + if (ir_instruction_word(token, 85)) { sub[0] = 0; return 17; } // uadd_chk + if (ir_instruction_word(token, 86)) { sub[0] = 1; return 17; } // usub_chk + if (ir_instruction_word(token, 87)) { sub[0] = 2; return 17; } // umul_chk + if (ir_instruction_word(token, 88)) { sub[0] = 3; return 17; } // sadd_chk + if (ir_instruction_word(token, 89)) { sub[0] = 4; return 17; } // ssub_chk + if (ir_instruction_word(token, 90)) { sub[0] = 5; return 17; } // smul_chk + return 18446744073709551615; +} + +fun ir_instruction_predicate(token: ptr, op: u64) -> u64 { + if (op == 10) { + if (ir_instruction_word(token, 91)) { return 0; } // eq + if (ir_instruction_word(token, 92)) { return 1; } // ne + if (ir_instruction_word(token, 93)) { return 2; } // slt + if (ir_instruction_word(token, 94)) { return 3; } // sle + if (ir_instruction_word(token, 95)) { return 4; } // sgt + if (ir_instruction_word(token, 96)) { return 5; } // sge + if (ir_instruction_word(token, 97)) { return 6; } // ult + if (ir_instruction_word(token, 98)) { return 7; } // ule + if (ir_instruction_word(token, 99)) { return 8; } // ugt + if (ir_instruction_word(token, 100)) { return 9; } // uge + if (ir_instruction_word(token, 101)) { return 10; } // feq + if (ir_instruction_word(token, 102)) { return 11; } // fne + if (ir_instruction_word(token, 103)) { return 12; } // flt + if (ir_instruction_word(token, 104)) { return 13; } // fle + if (ir_instruction_word(token, 105)) { return 14; } // fgt + if (ir_instruction_word(token, 106)) { return 15; } // fge + } + if (op == 11) { + if (ir_instruction_word(token, 91)) { return 0; } // eq + if (ir_instruction_word(token, 92)) { return 1; } // ne + if (ir_instruction_word(token, 97)) { return 2; } // ult + if (ir_instruction_word(token, 98)) { return 3; } // ule + if (ir_instruction_word(token, 99)) { return 4; } // ugt + if (ir_instruction_word(token, 100)) { return 5; } // uge + if (ir_instruction_word(token, 93)) { return 6; } // slt + if (ir_instruction_word(token, 94)) { return 7; } // sle + if (ir_instruction_word(token, 95)) { return 8; } // sgt + if (ir_instruction_word(token, 96)) { return 9; } // sge + } + if (op == 12) { + if (ir_instruction_word(token, 107)) { return 0; } // oeq + if (ir_instruction_word(token, 108)) { return 1; } // one + if (ir_instruction_word(token, 109)) { return 2; } // olt + if (ir_instruction_word(token, 110)) { return 3; } // ole + if (ir_instruction_word(token, 111)) { return 4; } // ogt + if (ir_instruction_word(token, 112)) { return 5; } // oge + if (ir_instruction_word(token, 113)) { return 6; } // ord + if (ir_instruction_word(token, 114)) { return 7; } // uno + if (ir_instruction_word(token, 115)) { return 8; } // ueq + if (ir_instruction_word(token, 116)) { return 9; } // une + if (ir_instruction_word(token, 97)) { return 10; } // ult + if (ir_instruction_word(token, 98)) { return 11; } // ule + if (ir_instruction_word(token, 99)) { return 12; } // ugt + if (ir_instruction_word(token, 100)) { return 13; } // uge + } + return 18446744073709551615; +} + +fun ir_instruction_fail(p: ptr, status: u64, reason: u64, + at: u64, expected: u64) -> bool { + p.result.status = status; p.result.reason = reason; p.result.at = at; + p.result.expected = expected; return false; +} + +fun ir_instruction_read(p: ptr) -> bool { + if (p.state.at >= p.count) { return ir_instruction_fail(p, 6, 0, p.state.at, 0); } + var token: ptr = &p.tokens[p.state.at]; + if (token.kind > 3 || !ir_span_valid(token.data, token.length, 1)) { return ir_instruction_fail(p, 6, 0, p.state.at, 0); } + if (token.length >= p.max_work - p.state.work) { return ir_instruction_fail(p, 4, 0, p.state.at, 0); } + p.state.work += token.length + 1; return true; +} + +fun ir_instruction_eat(p: ptr, code: u64) -> bool { + if (!ir_instruction_read(p)) { return false; } + if (!ir_instruction_word(&p.tokens[p.state.at], code)) { return false; } + p.state.at += 1; return true; +} + +fun ir_instruction_expect(p: ptr, code: u64) -> bool { + if (ir_instruction_eat(p, code)) { return true; } + if (p.result.status != 0) { return false; } + return ir_instruction_fail(p, 1, 1, p.state.at, code); +} + +fun ir_instruction_id(p: ptr, prefix: u64, output: ptr) -> bool { + if (!ir_instruction_read(p)) { return false; } + var token: ptr = &p.tokens[p.state.at]; + var first: u64 = 37; var second: u64 = 118; + if (prefix == 1) { second = 98; } + if (prefix == 2) { first = 64; second = 103; } + if (prefix == 3) { first = 64; second = 102; } + if (token.length < 2 || token.kind != 0 || token.data[0] as u64 != first || token.data[1] as u64 != second) { + return ir_instruction_fail(p, 1, 6, p.state.at, prefix); + } + if (token.length == 2) { return ir_instruction_fail(p, 1, 7, p.state.at, 0); } + var index: u64 = 2; var value: u64 = 0; var overflow: bool = false; + while (index < token.length) { + var digit: u64 = token.data[index] as u64; + if (digit < 48 || digit > 57) { return ir_instruction_fail(p, 1, 7, p.state.at, 0); } + digit -= 48; + if (value > (4294967295 - digit) / 10) { overflow = true; } + if (!overflow) { value = value * 10 + digit; } + index += 1; + } + if (overflow) { return ir_instruction_fail(p, 1, 8, p.state.at, 0); } + output[0] = value; p.state.at += 1; return true; +} + +fun ir_instruction_number(p: ptr, output: ptr) -> bool { + if (!ir_instruction_read(p)) { return false; } + var token: ptr = &p.tokens[p.state.at]; + if (token.kind != 0 || token.length == 0) { return ir_instruction_fail(p, 1, 4, p.state.at, 0); } + var index: u64 = 0; var value: u64 = 0; var overflow: bool = false; + while (index < token.length) { + var digit: u64 = token.data[index] as u64; + if (digit < 48 || digit > 57) { return ir_instruction_fail(p, 1, 4, p.state.at, 0); } + digit -= 48; + if (value > (4294967295 - digit) / 10) { overflow = true; } + if (!overflow) { value = value * 10 + digit; } + index += 1; + } + if (overflow) { return ir_instruction_fail(p, 1, 5, p.state.at, 0); } + output[0] = value; p.state.at += 1; return true; +} + +fun ir_instruction_string(p: ptr) -> bool { + if (!ir_instruction_read(p)) { return false; } + if (p.tokens[p.state.at].kind != 1) { return ir_instruction_fail(p, 1, 3, p.state.at, 0); } + p.state.name = p.state.at; p.state.at += 1; return true; +} + +fun ir_instruction_node(p: ptr) -> bool { + if (p.state.nodes >= p.max_nodes) { return ir_instruction_fail(p, 3, 0, p.state.at, 0); } + p.state.nodes += 1; return true; +} + +fun ir_instruction_request(p: ptr, event: u64, role: u64, phase: u64) -> bool { + p.result.event = event; p.result.role = role; p.state.phase = phase; return true; +} + +fun ir_instruction_align(p: ptr) -> bool { + return ir_instruction_expect(p, 2) && ir_instruction_expect(p, 13) + && ir_instruction_number(p, &p.state.d); +} + +fun ir_instruction_byte_pointer(p: ptr) -> bool { + return ir_instruction_expect(p, 10) && ir_instruction_expect(p, 7) + && ir_instruction_expect(p, 11) && ir_instruction_expect(p, 8); +} + +fun ir_instruction_prefix(p: ptr) -> bool { + if (p.state.phase == 0) { + if (!ir_instruction_read(p)) { return false; } + var token: ptr = &p.tokens[p.state.at]; + if (p.state.mode == 0 && token.length >= 2 && token.kind == 0 + && token.data[0] == 37 && token.data[1] == 118) { + if (!ir_instruction_id(p, 0, &p.state.dst) || !ir_instruction_expect(p, 0)) { return false; } + p.state.has_dst = 1; + return ir_instruction_request(p, 100, 0, 1); + } + p.state.phase = 2; + } + if (p.state.phase == 1) { + p.state.annotation_kind = p.state.type_kind; + if (!ir_instruction_expect(p, 1)) { return false; } + p.state.phase = 2; + } + if (p.state.phase == 2) { + if (!ir_instruction_read(p)) { return false; } + if (p.tokens[p.state.at].kind != 0) { return ir_instruction_fail(p, 1, 2, p.state.at, 0); } + p.state.op_at = p.state.at; + p.state.op = ir_instruction_opcode(&p.tokens[p.state.at], &p.state.sub); + p.state.at += 1; + var op: u64 = p.state.op; + if (p.state.mode == 1) { + if (op < 31 || op > 35) { return ir_instruction_fail(p, 1, 25, p.state.at, 0); } + } else { + if (op > 30) { return ir_instruction_fail(p, 1, 23, p.state.op_at, 0); } + if ((op == 0 || op == 1 || op == 2) && p.state.format < 6) { + return ir_instruction_fail(p, 1, 11, p.state.at, 0); + } + var required: bool = op != 1 && op != 19 && op != 20 && op != 21 + && op != 22 && op != 23 && op != 25 && op != 26 && op != 29 && op != 30; + if (required && p.state.has_dst == 0) { return ir_instruction_fail(p, 1, 9, p.state.at, 0); } + } + p.state.phase = 20; + } + return true; +} + +fun ir_instruction_common(p: ptr) -> bool { + var op: u64 = p.state.op; + if (op == 0) { + if (p.state.annotation_kind != 17) { return ir_instruction_fail(p, 1, 10, p.state.at, 0); } + if (!ir_instruction_id(p, 2, &p.state.a)) { return false; } + } else if (op == 1) { + if (!ir_instruction_id(p, 0, &p.state.a)) { return false; } + } else if (op == 2) { + if (!ir_instruction_id(p, 0, &p.state.a) || !ir_instruction_expect(p, 2) + || !ir_instruction_id(p, 0, &p.state.b)) { return false; } + } else if (op == 3) { + if (p.state.phase == 20) { + if (!ir_instruction_string(p)) { return false; } + return ir_instruction_request(p, 102, 0, 21); + } + if (p.state.phase == 21) { + if (!ir_instruction_expect(p, 17) || !ir_instruction_expect(p, 25)) { return false; } + return ir_instruction_request(p, 100, 1, 22); + } + if (p.state.phase == 22) { return ir_instruction_request(p, 110, 8, 23); } + return ir_instruction_request(p, 101, 1, 900); + } else if (op == 4) { + if (p.state.phase == 20) { return ir_instruction_request(p, 100, 1, 21); } + return ir_instruction_request(p, 101, 1, 900); + } else if (op == 5) { + return ir_instruction_request(p, 100, 1, 900); + } else if (op == 6 || op == 8 || op == 9) { + if (p.state.phase == 20) { return ir_instruction_request(p, 100, 1, 21); } + if (!ir_instruction_id(p, 0, &p.state.a)) { return false; } + if (op == 8 && p.state.format < 8) { return ir_instruction_fail(p, 1, 12, p.state.at, 0); } + } else if (op == 7 || op == 17) { + if (p.state.phase == 20) { return ir_instruction_request(p, 100, 1, 21); } + if (!ir_instruction_id(p, 0, &p.state.a) || !ir_instruction_expect(p, 2) + || !ir_instruction_id(p, 0, &p.state.b)) { return false; } + } else if (op == 10 || op == 11 || op == 12) { + if (p.state.phase == 20) { + if (!ir_instruction_read(p)) { return false; } + if (p.tokens[p.state.at].kind != 0) { return ir_instruction_fail(p, 1, 2, p.state.at, 0); } + var token: ptr = &p.tokens[p.state.at]; + p.state.sub = ir_instruction_predicate(token, op); + p.state.aux = 0; + if (ir_instruction_word(token, 91) || ir_instruction_word(token, 92)) { p.state.aux = 1; } + p.state.at += 1; + return ir_instruction_request(p, 100, 1, 21); + } + if (p.state.format < 6 && p.state.type_kind == 17 && p.state.aux == 0) { + return ir_instruction_fail(p, 1, 13, p.state.at, 0); + } + if (!ir_instruction_id(p, 0, &p.state.a) || !ir_instruction_expect(p, 2) + || !ir_instruction_id(p, 0, &p.state.b)) { return false; } + if (p.state.sub == 18446744073709551615) { + var reason: u64 = 14; if (op == 11) { reason = 15; } if (op == 12) { reason = 16; } + return ir_instruction_fail(p, 1, reason, p.state.at, 0); + } + } else if (op == 13) { + if (p.state.phase == 20) { + if (!ir_instruction_expect(p, 9) || !ir_instruction_id(p, 0, &p.state.a) + || !ir_instruction_expect(p, 2)) { return false; } + return ir_instruction_request(p, 100, 1, 21); + } + if (p.state.phase == 21) { + if (!ir_instruction_id(p, 0, &p.state.b) || !ir_instruction_expect(p, 2)) { return false; } + return ir_instruction_request(p, 100, 2, 22); + } + if (p.state.phase == 22) { return ir_instruction_request(p, 110, 6, 23); } + if (!ir_instruction_id(p, 0, &p.state.c)) { return false; } + } else if (op == 14) { + if (p.state.phase == 20) { return ir_instruction_request(p, 100, 1, 21); } + if (p.state.phase == 21) { + if (!ir_instruction_id(p, 0, &p.state.a) || !ir_instruction_expect(p, 16)) { return false; } + return ir_instruction_request(p, 100, 2, 22); + } + if (p.state.sub == 0 && p.state.format < 8) { return ir_instruction_fail(p, 1, 17, p.state.at, 0); } + } else if (op == 16) { + if (!ir_instruction_id(p, 0, &p.state.a) || !ir_instruction_expect(p, 2) + || !ir_instruction_number(p, &p.state.d)) { return false; } + } else if (op == 18) { + if (p.state.phase == 20) { return ir_instruction_request(p, 100, 1, 21); } + if (!ir_instruction_align(p)) { return false; } + } else if (op >= 19 && op <= 23) { + if (p.state.phase == 20) { + if ((op == 19 || op == 20) && p.state.format < 8) { return ir_instruction_fail(p, 1, 19, p.state.at, 0); } + if (op == 22 && p.state.format < 4) { return ir_instruction_fail(p, 1, 18, p.state.at, 0); } + return ir_instruction_request(p, 100, 1, 21); + } + if (p.state.phase == 21) { + if ((op == 20 || op == 23) && !ir_instruction_id(p, 0, &p.state.a)) { return false; } + if (!ir_instruction_expect(p, 2)) { return false; } + return ir_instruction_request(p, 100, 2, 22); + } + if (p.state.phase == 22) { return ir_instruction_request(p, 110, 7, 23); } + if (!ir_instruction_id(p, 0, &p.state.b) || !ir_instruction_align(p)) { return false; } + if ((op == 19 || op == 21) && p.state.has_dst == 0) { return ir_instruction_fail(p, 1, 20, p.state.at, 0); } + } else if (op == 25 || op == 26) { + if (!ir_instruction_byte_pointer(p) || !ir_instruction_id(p, 0, &p.state.a) + || !ir_instruction_expect(p, 2)) { return false; } + if (op == 25) { if (!ir_instruction_byte_pointer(p)) { return false; } } + else { if (!ir_instruction_expect(p, 11)) { return false; } } + if (!ir_instruction_id(p, 0, &p.state.b) || !ir_instruction_expect(p, 2) + || !ir_instruction_expect(p, 12) || !ir_instruction_id(p, 0, &p.state.c) + || !ir_instruction_align(p)) { return false; } + } else if (op == 27 || op == 28) { + if (p.state.annotation_kind != 18) { return ir_instruction_fail(p, 1, 21, p.state.at, 0); } + if (op == 28 && !ir_instruction_id(p, 3, &p.state.a)) { return false; } + } else if (op == 30) { + if (!ir_instruction_expect(p, 9) || !ir_instruction_id(p, 0, &p.state.a) + || !ir_instruction_expect(p, 2) || !ir_instruction_expect(p, 15) + || !ir_instruction_expect(p, 1) || !ir_instruction_string(p)) { return false; } + } else { return ir_instruction_fail(p, 6, 0, p.state.at, 0); } + p.state.phase = 900; return true; +} + +fun ir_instruction_lists(p: ptr) -> bool { + var op: u64 = p.state.op; + if (op == 15) { + if (p.state.phase == 20) { return ir_instruction_request(p, 100, 1, 21); } + if (p.state.phase == 21) { + if (!ir_instruction_read(p)) { return false; } + if (p.state.aux == 0 && !ir_instruction_word(&p.tokens[p.state.at], 3)) { p.state.phase = 900; return true; } + if (!ir_instruction_node(p) || !ir_instruction_expect(p, 3) + || !ir_instruction_id(p, 0, &p.state.a) || !ir_instruction_expect(p, 2) + || !ir_instruction_id(p, 1, &p.state.b) || !ir_instruction_expect(p, 4)) { return false; } + return ir_instruction_request(p, 200, 0, 22); + } + if (ir_instruction_eat(p, 2)) { p.state.aux = 1; p.state.phase = 21; } + else { if (p.result.status != 0) { return false; } p.state.phase = 900; } + return true; + } + if (op == 24) { + if (p.state.phase == 20) { + if (!ir_instruction_id(p, 0, &p.state.a)) { return false; } + p.state.phase = 21; + } + if (!ir_instruction_eat(p, 2)) { + if (p.result.status != 0) { return false; } + p.state.phase = 900; return true; + } + if (!ir_instruction_node(p) || !ir_instruction_id(p, 0, &p.state.b)) { return false; } + return ir_instruction_request(p, 201, 0, 21); + } + if (p.state.phase == 20) { + if (!ir_instruction_read(p)) { return false; } + if (p.tokens[p.state.at].kind != 0) { return ir_instruction_fail(p, 1, 2, p.state.at, 0); } + if (ir_instruction_word(&p.tokens[p.state.at], 19)) { p.state.sub = 0; } + else if (ir_instruction_word(&p.tokens[p.state.at], 20)) { p.state.sub = 1; } + else { return ir_instruction_fail(p, 1, 22, p.state.at, 0); } + p.state.at += 1; + return ir_instruction_request(p, 100, 1, 21); + } + if (p.state.phase == 21) { + p.state.aux = p.state.type_kind; + p.state.e = 0; + if (ir_instruction_eat(p, 18)) { + p.state.e = 1; + if (!ir_instruction_id(p, 0, &p.state.a)) { return false; } + } else { + if (p.result.status != 0 || !ir_instruction_id(p, 3, &p.state.a)) { return false; } + } + if (!ir_instruction_expect(p, 5)) { return false; } + p.state.phase = 22; + } + if (p.state.phase == 22 || p.state.phase == 23) { + if (ir_instruction_eat(p, 6)) { p.state.phase = 900; return true; } + if (p.result.status != 0) { return false; } + if (p.state.phase == 23 && !ir_instruction_expect(p, 2)) { return false; } + } + if (!ir_instruction_node(p) || !ir_instruction_id(p, 0, &p.state.b)) { return false; } + return ir_instruction_request(p, 201, 0, 23); +} + +fun ir_instruction_terminator(p: ptr) -> bool { + var op: u64 = p.state.op; + if (op == 31) { + if (!ir_instruction_expect(p, 14) || !ir_instruction_id(p, 1, &p.state.a)) { return false; } + } else if (op == 32) { + if (!ir_instruction_expect(p, 9) || !ir_instruction_id(p, 0, &p.state.a) + || !ir_instruction_expect(p, 2) || !ir_instruction_expect(p, 14) + || !ir_instruction_id(p, 1, &p.state.b) || !ir_instruction_expect(p, 2) + || !ir_instruction_expect(p, 14) || !ir_instruction_id(p, 1, &p.state.c)) { return false; } + } else if (op == 33) { + if (p.state.phase == 20) { return ir_instruction_request(p, 100, 1, 21); } + if (p.state.phase == 21) { + if (!ir_instruction_id(p, 0, &p.state.a) || !ir_instruction_expect(p, 2) + || !ir_instruction_expect(p, 14) || !ir_instruction_id(p, 1, &p.state.b) + || !ir_instruction_expect(p, 3)) { return false; } + p.state.phase = 22; + } + if (p.state.phase == 22 || p.state.phase == 24) { + if (ir_instruction_eat(p, 4)) { p.state.phase = 900; return true; } + if (p.result.status != 0) { return false; } + if (p.state.phase == 24 && !ir_instruction_expect(p, 2)) { return false; } + if (!ir_instruction_node(p)) { return false; } + return ir_instruction_request(p, 101, 1, 23); + } + if (!ir_instruction_expect(p, 0) || !ir_instruction_id(p, 1, &p.state.c)) { return false; } + return ir_instruction_request(p, 202, 0, 24); + } else if (op == 34) { + if (p.state.phase == 20) { return ir_instruction_request(p, 100, 1, 21); } + p.state.aux = 0; + if (p.state.type_kind != 0) { + p.state.aux = 1; + if (!ir_instruction_id(p, 0, &p.state.a)) { return false; } + } + } else if (op == 35) { + if (!ir_instruction_expect(p, 15) || !ir_instruction_expect(p, 1) + || !ir_instruction_string(p)) { return false; } + } else { return ir_instruction_fail(p, 6, 0, p.state.at, 0); } + p.state.phase = 900; return true; +} + +fun ir_instruction_final(p: ptr) -> bool { + if (p.state.phase == 901 || p.state.mode == 1) { + return ir_instruction_request(p, 1, 0, 902); + } + var op: u64 = p.state.op; + var produces: bool = op != 1 && op != 20 && op != 22 && op != 23 + && op != 25 && op != 26 && op != 30 && !(op == 29 && p.state.aux == 0); + if ((produces && p.state.has_dst == 0) || (!produces && p.state.has_dst != 0)) { + return ir_instruction_fail(p, 1, 24, p.state.at, 0); + } + var comparison: u64 = 0; + if (!produces || op == 0 || op == 16 || op == 24 || op == 27 || op == 28) { + return ir_instruction_request(p, 1, 0, 902); + } + if (op == 3) { comparison = 9; } + if (op == 2) { comparison = 2; } + if (op == 10 || op == 11 || op == 12) { comparison = 1; } + if (op == 14) { comparison = 5; } + if (op == 17) { comparison = 4; } + if (op == 18) { comparison = 3; } + return ir_instruction_request(p, 110, comparison, 901); +} + +export(c) fun whale_ir_instruction_step(tokens: ptr, token_count: u64, + state: ptr, max_nodes: u64, max_work: u64, + result: ptr) -> i32 { + if (result == null) { return 6; } + result.status = 0; result.reason = 0; result.at = 0; result.expected = 0; + result.event = 0; result.role = 0; result.nodes = 0; result.work = 0; + if (state == null || state.mode > 1 || state.format < 3 || state.format > 8 + || state.at >= token_count || !ir_span_valid(tokens as ptr, token_count, 24)) { + result.status = 6; return 6; + } + state.nodes = 0; state.work = 0; + var parser: IrInstructionParser; + parser.tokens = tokens; parser.count = token_count; parser.state = state; + parser.max_nodes = max_nodes; parser.max_work = max_work; parser.result = result; + while (result.status == 0 && result.event == 0) { + if (state.phase < 20) { if (!ir_instruction_prefix(&parser)) { break; } } + else if (state.phase == 900 || state.phase == 901) { if (!ir_instruction_final(&parser)) { break; } } + else if (state.phase >= 20 && state.phase <= 30) { + if (state.mode == 1) { if (!ir_instruction_terminator(&parser)) { break; } } + else if (state.op == 15 || state.op == 24 || state.op == 29) { if (!ir_instruction_lists(&parser)) { break; } } + else { if (!ir_instruction_common(&parser)) { break; } } + } else { ir_instruction_fail(&parser, 6, 0, state.at, 0); break; } + } + result.op = state.op; result.sub = state.sub; result.has_dst = state.has_dst; result.dst = state.dst; + result.a = state.a; result.b = state.b; result.c = state.c; result.d = state.d; + result.e = state.e; result.name = state.name; result.aux = state.aux; + result.next = state.at; result.nodes = state.nodes; result.work = state.work; + return result.status as i32; +} diff --git a/ir/layout.wave b/ir/layout.wave new file mode 100644 index 0000000..9fb24fb --- /dev/null +++ b/ir/layout.wave @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: MPL-2.0 +// Walk the root in source order, preserving the reference layout's first-error +// precedence. Every node and edge visit consumes work, including repeated DAG +// references. The aggregate depth bound also bounds native call-stack use. +fun ir_layout_scalar(kind: u64, storage: ptr, layout: ptr) -> bool { + layout.stride = 0; + layout.depth = 0; + if (kind == 1) { layout.size = 1; layout.align = storage.scalar_align1; } + else if (kind == 2) { layout.size = 2; layout.align = storage.scalar_align2; } + else if (kind == 3) { layout.size = 4; layout.align = storage.scalar_align4; } + else if (kind == 4) { layout.size = 8; layout.align = storage.scalar_align8; } + else if (kind == 5) { layout.size = 16; layout.align = storage.scalar_align16; } + else if (kind == 6 || kind == 7) { + layout.size = storage.ptr_bits / 8; + layout.align = storage.pointer_align; + } + else { return false; } + layout.allocation_align = layout.align; + return true; +} + +fun ir_layout_node(index: u64, nodes: ptr, node_count: u64, + edges: ptr, edge_count: u64, storage: ptr, remaining_depth: u64, + scratch: ptr, offsets: ptr, work: ptr) -> i32 { + if (work[0] == 0) { return 6; } + work[0] -= 1; + var node: ptr = &nodes[index]; + var layout: ptr = &scratch[index]; + if (node.kind == 0) { return 1; } + if ((node.kind == 6 || node.kind == 7) && node.child >= node_count) { return 1; } + if (ir_layout_scalar(node.kind, storage, layout)) { return 0; } + if (node.kind != 8 && node.kind != 9 && node.kind != 10) { return 1; } + if (remaining_depth == 0) { return 2; } + if (node.kind == 8) { + if (node.child >= index) { return 1; } + var status: i32 = ir_layout_node(node.child, nodes, node_count, edges, edge_count, + storage, remaining_depth - 1, scratch, offsets, work); + if (status != 0) { return status; } + var child: ptr = &scratch[node.child]; + if (node.count != 0 && child.size > 18446744073709551615 / node.count) { return 3; } + layout.size = child.size * node.count; + layout.align = child.align; + layout.stride = child.size; + layout.depth = child.depth + 1; + layout.allocation_align = child.align; + if (storage.has_large_array != 0 && layout.size >= storage.large_array_threshold + && storage.large_array_align > layout.allocation_align) { + layout.allocation_align = storage.large_array_align; + } + } + else { + if (node.first > edge_count || node.count > edge_count - node.first) { return 1; } + layout.size = 0; + layout.align = 1; + layout.stride = 0; + layout.depth = 1; + var field: u64 = 0; + while (field < node.count) { + if (work[0] == 0) { return 6; } + work[0] -= 1; + var child_index: u64 = edges[node.first + field]; + if (child_index >= index) { return 1; } + var status: i32 = ir_layout_node(child_index, nodes, node_count, edges, edge_count, + storage, remaining_depth - 1, scratch, offsets, work); + if (status != 0) { return status; } + var child: ptr = &scratch[child_index]; + if (child.align > layout.align) { layout.align = child.align; } + var aligned: u64 = 0; + if (!ir_align_up(layout.size, child.align, &aligned)) { return 3; } + offsets[node.first + field] = aligned; + if (child.size > 18446744073709551615 - aligned) { return 3; } + layout.size = aligned + child.size; + if (child.depth + 1 > layout.depth) { layout.depth = child.depth + 1; } + field += 1; + } + var padded: u64 = 0; + if (!ir_align_up(layout.size, layout.align, &padded)) { return 3; } + layout.size = padded; + layout.allocation_align = layout.align; + } + if (storage.ptr_bits == 32 && layout.size > 4294967295) { return 3; } + return 0; +} diff --git a/ir/lexer.wave b/ir/lexer.wave new file mode 100644 index 0000000..e0046fa --- /dev/null +++ b/ir/lexer.wave @@ -0,0 +1,311 @@ +// SPDX-License-Identifier: MPL-2.0 +// Bounded tokenization for the versioned Whale IR text format. The caller +// owns both scratch and published buffers; errors leave published data alone. +struct IrToken { + kind: u64; // 0 word, 1 decoded string, 2 punctuation, 3 EOF + start: u64; + end: u64; + line: u64; + column: u64; + decoded_start: u64; + decoded_len: u64; +} + +struct IrLexResult { + status: u64; // 1 malformed source, 2 token limit, 3 decoded-byte limit, 4 work limit + reason: u64; // syntax detail: invalid UTF-8, unterminated string/escape, Unicode/escape/control + offset: u64; + line: u64; + column: u64; + token_count: u64; + decoded_count: u64; +} + +fun ir_lex_space(cp: u64) -> bool { + return (cp >= 9 && cp <= 13) || cp == 32 || cp == 133 || cp == 160 + || cp == 5760 || (cp >= 8192 && cp <= 8202) || cp == 8232 + || cp == 8233 || cp == 8239 || cp == 8287 || cp == 12288; +} + +fun ir_lex_control(cp: u64) -> bool { + return cp < 32 || (cp >= 127 && cp <= 159) || cp == 8232 || cp == 8233; +} + +fun ir_lex_hex(octet: u8) -> i32 { + if (octet >= 48 && octet <= 57) { return (octet - 48) as i32; } + if (octet >= 65 && octet <= 70) { return (octet - 55) as i32; } + if (octet >= 97 && octet <= 102) { return (octet - 87) as i32; } + return -1; +} + +fun ir_lex_mark(cp: u64) -> bool { + return cp == 123 || cp == 125 || cp == 40 || cp == 41 || cp == 91 + || cp == 93 || cp == 60 || cp == 62 || cp == 44 || cp == 58 + || cp == 61 || cp == 34; +} + +// Return zero for invalid UTF-8. The source has already been span checked. +fun ir_lex_utf8(source: ptr, length: u64, at: u64, width: ptr, cp: ptr) -> bool { + if (at >= length) { return false; } + var first: u64 = source[at] as u64; + if (first < 128) { width[0] = 1; cp[0] = first; return true; } + var count: u64 = 0; + var value: u64 = 0; + var minimum: u64 = 0; + if (first >= 194 && first <= 223) { count = 2; value = first & 31; minimum = 128; } + else if (first >= 224 && first <= 239) { count = 3; value = first & 15; minimum = 2048; } + else if (first >= 240 && first <= 244) { count = 4; value = first & 7; minimum = 65536; } + else { return false; } + if (count > length - at) { return false; } + var index: u64 = 1; + while (index < count) { + var next: u64 = source[at + index] as u64; + if (next < 128 || next > 191) { return false; } + value = (value << 6) | (next & 63); + index += 1; + } + if (value < minimum || value > 1114111 || (value >= 55296 && value <= 57343)) { + return false; + } + width[0] = count; + cp[0] = value; + return true; +} + +fun ir_lex_advance(cp: u64, width: u64, at: ptr, line: ptr, column: ptr) { + at[0] += width; + if (cp == 10) { line[0] += 1; column[0] = 1; } + else { column[0] += 1; } +} + +fun ir_lex_emit(cp: u64, output: ptr, at: ptr, capacity: u64) -> bool { + var width: u64 = 1; + if (cp >= 65536) { width = 4; } + else if (cp >= 2048) { width = 3; } + else if (cp >= 128) { width = 2; } + if (at[0] > capacity || width > capacity - at[0]) { return false; } + var p: u64 = at[0]; + if (output == null) { at[0] += width; return true; } + if (width == 1) { output[p] = cp as u8; } + else if (width == 2) { + output[p] = (192 | (cp >> 6)) as u8; + output[p + 1] = (128 | (cp & 63)) as u8; + } + else if (width == 3) { + output[p] = (224 | (cp >> 12)) as u8; + output[p + 1] = (128 | ((cp >> 6) & 63)) as u8; + output[p + 2] = (128 | (cp & 63)) as u8; + } + else { + output[p] = (240 | (cp >> 18)) as u8; + output[p + 1] = (128 | ((cp >> 12) & 63)) as u8; + output[p + 2] = (128 | ((cp >> 6) & 63)) as u8; + output[p + 3] = (128 | (cp & 63)) as u8; + } + at[0] += width; + return true; +} + +fun ir_lex_error(result: ptr, status: u64, at: u64, line: u64, + column: u64) -> i32 { + result.status = status; + result.offset = at; + result.line = line; + result.column = column; + return status as i32; +} + +fun ir_lex_syntax_error(result: ptr, reason: u64, at: u64, + line: u64, column: u64) -> i32 { + result.reason = reason; + return ir_lex_error(result, 1, at, line, column); +} + +export(c) fun whale_ir_lex(source: ptr, length: u64, max_tokens: u64, max_work: u64, + mode: u64, // 0 preflight counts; 1 publish after exact allocation + scratch_tokens: ptr, token_capacity: u64, scratch_decoded: ptr, + decoded_capacity: u64, output_tokens: ptr, output_token_capacity: u64, + output_decoded: ptr, output_decoded_capacity: u64, + result: ptr) -> i32 { + if (result == null) { return 5; } + result.status = 0; result.reason = 0; result.offset = 0; result.line = 1; result.column = 1; + result.token_count = 0; result.decoded_count = 0; + if (mode > 1 || !ir_span_valid(source, length, 1) + || (mode == 1 && (!ir_span_valid(scratch_tokens as ptr, token_capacity, 56) + || !ir_span_valid(output_tokens as ptr, output_token_capacity, 56) + || !ir_span_valid(scratch_decoded, decoded_capacity, 1) + || !ir_span_valid(output_decoded, output_decoded_capacity, 1)))) { + result.status = 5; return 5; + } + var at: u64 = 0; + var line: u64 = 1; + var column: u64 = 1; + var count: u64 = 0; + var decoded: u64 = 0; + var work: u64 = 0; + // The pinned Wave O0 compiler allocates local declarations at their + // lexical site. Keep reusable locals outside token loops so a long IR + // source cannot grow the native stack one token at a time. + var width: u64 = 0; + var cp: u64 = 0; + var token: IrToken = IrToken { kind: 0, start: 0, end: 0, line: 1, + column: 1, decoded_start: 0, decoded_len: 0 }; + var closed: bool = false; + var digits: u64 = 0; + var digit: i32 = 0; + var capacity: u64 = 0; + while (at < length) { + if (work >= max_work) { return ir_lex_error(result, 4, at, line, column); } + work += 1; + width = 0; + cp = 0; + if (!ir_lex_utf8(source, length, at, &width, &cp)) { + return ir_lex_syntax_error(result, 1, at, line, column); + } + if (ir_lex_space(cp)) { + ir_lex_advance(cp, width, &at, &line, &column); + continue; + } + if (cp == 47 && at + 1 < length && source[at + 1] == 47) { + while (at < length && source[at] != 10) { + if (work >= max_work) { return ir_lex_error(result, 4, at, line, column); } + work += 1; + if (!ir_lex_utf8(source, length, at, &width, &cp)) { + return ir_lex_syntax_error(result, 1, at, line, column); + } + ir_lex_advance(cp, width, &at, &line, &column); + } + continue; + } + if (count >= max_tokens || (mode == 1 + && (count >= token_capacity || count >= output_token_capacity))) { + return ir_lex_error(result, 2, at, line, column); + } + token.kind = 0; + token.start = at; + token.end = at; + token.line = line; + token.column = column; + token.decoded_start = decoded; + token.decoded_len = 0; + if (cp == 34) { + token.kind = 1; + ir_lex_advance(cp, width, &at, &line, &column); + closed = false; + while (at < length) { + if (work >= max_work) { return ir_lex_error(result, 4, at, line, column); } + work += 1; + if (!ir_lex_utf8(source, length, at, &width, &cp)) { + return ir_lex_syntax_error(result, 1, at, line, column); + } + if (cp == 34) { + ir_lex_advance(cp, width, &at, &line, &column); + closed = true; break; + } + if (cp == 92) { + ir_lex_advance(cp, width, &at, &line, &column); + if (at == length) { return ir_lex_syntax_error(result, 3, at, line, column); } + if (!ir_lex_utf8(source, length, at, &width, &cp)) { + return ir_lex_syntax_error(result, 1, at, line, column); + } + ir_lex_advance(cp, width, &at, &line, &column); + if (cp == 110) { cp = 10; } + else if (cp == 114) { cp = 13; } + else if (cp == 116) { cp = 9; } + else if (cp == 48) { cp = 0; } + else if (cp == 117) { + if (at >= length || source[at] != 123) { + return ir_lex_syntax_error(result, 4, at, line, column); + } + ir_lex_advance(123, 1, &at, &line, &column); + digits = 0; + cp = 0; + while (at < length) { + digit = ir_lex_hex(source[at]); + if (digit < 0) { break; } + if (work >= max_work) { return ir_lex_error(result, 4, at, line, column); } + work += 1; + if (digits < 6) { cp = (cp << 4) | (digit as u64); } + digits += 1; + ir_lex_advance(source[at] as u64, 1, &at, &line, &column); + } + if (digits == 0 || digits > 6 || at >= length || source[at] != 125) { + return ir_lex_syntax_error(result, 5, at, line, column); + } + ir_lex_advance(125, 1, &at, &line, &column); + if (cp > 1114111 || (cp >= 55296 && cp <= 57343)) { + return ir_lex_syntax_error(result, 8, at, line, column); + } + } + else if (cp != 34 && cp != 92) { + return ir_lex_syntax_error(result, 6, at, line, column); + } + } + else { + if (ir_lex_control(cp)) { + return ir_lex_syntax_error(result, 7, token.start, token.line, token.column); + } + ir_lex_advance(cp, width, &at, &line, &column); + } + capacity = decoded_capacity; + if (mode == 0) { capacity = length; } + if (!ir_lex_emit(cp, scratch_decoded, &decoded, capacity)) { + return ir_lex_error(result, 3, at, line, column); + } + } + if (!closed) { return ir_lex_syntax_error(result, 2, token.start, token.line, token.column); } + token.decoded_len = decoded - token.decoded_start; + } + else if (ir_lex_mark(cp) + || ((cp == 45 || cp == 61) && at + 1 < length && source[at + 1] == 62)) { + token.kind = 2; + ir_lex_advance(cp, width, &at, &line, &column); + if ((cp == 45 || cp == 61) && at < length && source[at] == 62) { + ir_lex_advance(62, 1, &at, &line, &column); + } + } + else { + while (at < length) { + if (work >= max_work) { return ir_lex_error(result, 4, at, line, column); } + work += 1; + if (!ir_lex_utf8(source, length, at, &width, &cp)) { + return ir_lex_syntax_error(result, 1, at, line, column); + } + if (ir_lex_space(cp) || ir_lex_mark(cp)) { break; } + ir_lex_advance(cp, width, &at, &line, &column); + } + } + token.end = at; + if (mode == 1) { scratch_tokens[count] = token; } + count += 1; + } + if (mode == 1 && (count >= token_capacity || count >= output_token_capacity)) { + return ir_lex_error(result, 2, at, line, column); + } + if (mode == 1) { + scratch_tokens[count] = IrToken { kind: 3, start: at, end: at, line: line, + column: column, decoded_start: decoded, decoded_len: 0 }; + } + count += 1; + if (mode == 1 && decoded > output_decoded_capacity) { + return ir_lex_error(result, 3, at, line, column); + } + // Include publication in the same work ceiling as scanning. Count-only + // preflight charges the identical amount, so it cannot promise a later + // pass that exceeds the caller's budget. + if (count > max_work - work || decoded > max_work - work - count) { + return ir_lex_error(result, 4, at, line, column); + } + if (mode == 0) { + result.offset = at; result.line = line; result.column = column; + result.token_count = count; result.decoded_count = decoded; + return 0; + } + var index: u64 = 0; + while (index < count) { output_tokens[index] = scratch_tokens[index]; index += 1; } + index = 0; + while (index < decoded) { output_decoded[index] = scratch_decoded[index]; index += 1; } + result.offset = at; result.line = line; result.column = column; + result.token_count = count; result.decoded_count = decoded; + return 0; +} diff --git a/ir/literal.wave b/ir/literal.wave new file mode 100644 index 0000000..99bd8e9 --- /dev/null +++ b/ir/literal.wave @@ -0,0 +1,110 @@ +// SPDX-License-Identifier: MPL-2.0 +// Exact scalar text decoding. Integer arithmetic uses four 32-bit limbs so +// parsing i128/u128 never depends on host overflow or compiler-runtime helpers. +struct IrLiteralResult { + status: u64; + low: u64; + high: u64; + work: u64; +} + +export(c) fun whale_ir_parse_literal(source: ptr, length: u64, + category: u64, width: u64, max_work: u64, result: ptr) -> i32 { + if (result == null) { return 11; } + result.status = 0; result.low = 0; result.high = 0; result.work = 0; + if (!ir_span_valid(source, length, 1) || category > 4) { + result.status = 11; return 11; + } + if (length > max_work) { result.status = 10; return 10; } + result.work = length; + if (category == 0) { result.status = 8; return 8; } + if (category == 1) { + if (length == 4 && source[0] == 116 && source[1] == 114 + && source[2] == 117 && source[3] == 101) { result.low = 1; return 0; } + if (length == 5 && source[0] == 102 && source[1] == 97 + && source[2] == 108 && source[3] == 115 && source[4] == 101) { return 0; } + result.status = 1; return 1; + } + var low: u64 = 0; + var high: u64 = 0; + var at: u64 = 0; + var octet: u64 = 0; + var digit: u64 = 0; + if (category == 4) { + if (width != 16 && width != 32 && width != 64) { result.status = 11; return 11; } + if (length < 2 || source[0] != 48 || source[1] != 120) { result.status = 6; return 6; } + if (length != width / 4 + 2) { result.status = 7; return 7; } + at = 2; + while (at < length) { + octet = source[at] as u64; + if (octet >= 48 && octet <= 57) { digit = octet - 48; } + else if (octet >= 65 && octet <= 70) { digit = octet - 55; } + else if (octet >= 97 && octet <= 102) { digit = octet - 87; } + else { result.status = 7; return 7; } + low = (low << 4) | digit; + at += 1; + } + result.low = low; return 0; + } + if (width == 0 || width > 128) { result.status = 11; return 11; } + var negative: bool = false; + if (category == 2 && length != 0 && source[0] == 45) { negative = true; at = 1; } + var syntax: u64 = 2; + var range: u64 = 3; + if (category == 3) { syntax = 4; range = 5; } + if (at == length) { result.status = syntax; return syntax as i32; } + var overflow: bool = false; + var limb0: u64 = 0; + var limb1: u64 = 0; + var limb2: u64 = 0; + var limb3: u64 = 0; + while (at < length) { + octet = source[at] as u64; + if (octet < 48 || octet > 57) { result.status = syntax; return syntax as i32; } + digit = octet - 48; + // Preserve lexical error precedence even after the magnitude overflows. + if (!overflow) { + limb0 = (low & 4294967295) * 10 + digit; + limb1 = (low >> 32) * 10 + (limb0 >> 32); + limb2 = (high & 4294967295) * 10 + (limb1 >> 32); + limb3 = (high >> 32) * 10 + (limb2 >> 32); + if ((limb3 >> 32) != 0) { overflow = true; } + else { + low = (limb0 & 4294967295) | (limb1 << 32); + high = (limb2 & 4294967295) | (limb3 << 32); + } + } + at += 1; + } + if (overflow) { result.status = range; return range as i32; } + if (category == 2) { + if (high > 9223372036854775808 + || (high == 9223372036854775808 && (low != 0 || !negative))) { + result.status = 3; return 3; + } + if (width < 128) { + if (width > 64) { + if (high > (1 as u64 << (width - 65)) + || (high == (1 as u64 << (width - 65)) && (low != 0 || !negative))) { + result.status = 9; return 9; + } + } else if (high != 0 || low > (1 as u64 << (width - 1)) + || (low == (1 as u64 << (width - 1)) && !negative)) { + result.status = 9; return 9; + } + } + if (negative) { + low = ~low + 1; + high = ~high; + if (low == 0) { high += 1; } + } + } else if (width < 128) { + if (width >= 64) { + if (width == 64) { + if (high != 0) { result.status = 9; return 9; } + } else if (high >= (1 as u64 << (width - 64))) { result.status = 9; return 9; } + } else if (high != 0 || low >= (1 as u64 << width)) { result.status = 9; return 9; } + } + result.low = low; result.high = high; + return 0; +} diff --git a/ir/lower_driver.wave b/ir/lower_driver.wave new file mode 100644 index 0000000..df9ccf3 --- /dev/null +++ b/ir/lower_driver.wave @@ -0,0 +1,327 @@ +// SPDX-License-Identifier: MPL-2.0 +// The complete AST lowering transaction has no host callbacks. The first pass +// counts flat output; the second publishes records into exactly sized buffers. +fun ir_lower_signature_type(p: ptr, ty: u64, depth: u64, node: u64) -> bool { + if (!ir_lower_charge(p.core, 1, node)) { return false; } + if (depth > p.core.max_depth) { return ir_lower_fail(p.core, 2, node, 0, 0, 0); } + if (ty >= p.core.type_count) { return ir_lower_fail(p.core, 21, node, 0, 0, 1); } + var t: ptr = &p.core.types[ty]; + if (t.kind == 0) { return ir_lower_fail(p.core, 21, node, 0, 0, 1); } + if (t.kind == 18) { return ir_lower_signature_validate(p, ty, depth + 1, node); } + if (t.kind == 17) { + if (t.child == 0) { return true; } + return ir_lower_signature_type(p, t.child, depth + 1, node); + } + if (t.kind == 19) { return ir_lower_signature_type(p, t.child, depth + 1, node); } + var at: u64 = 0; + if (t.kind == 20 || t.kind == 21) { + while (at < t.count) { + if (!ir_lower_signature_type(p, p.core.type_edges[t.first + at], depth + 1, node)) { return false; } + at += 1; + } + } + return true; +} + +fun ir_lower_signature_validate(p: ptr, ty: u64, depth: u64, node: u64) -> bool { + if (depth > p.core.max_depth) { return ir_lower_fail(p.core, 2, node, 0, 0, 0); } + if (ty >= p.core.type_count || p.core.types[ty].kind != 18) { + return ir_lower_fail(p.core, 21, node, 0, 0, 1); + } + var t: ptr = &p.core.types[ty]; + if (t.child != 0) { + if (t.auxiliary == 1 && ir_lower_aggregate(p.core, t.child)) { return ir_lower_fail(p.core, 21, node, 0, 0, 1); } + if (!ir_lower_signature_type(p, t.child, depth + 1, node)) { return false; } + } + var at: u64 = 0; + while (at < t.count) { + var param: u64 = p.core.type_edges[t.first + at]; + if (t.auxiliary == 1 && ir_lower_aggregate(p.core, param)) { return ir_lower_fail(p.core, 21, node, 0, 0, 1); } + if (!ir_lower_signature_type(p, param, depth + 1, node)) { return false; } + at += 1; + } + return true; +} + +fun ir_lower_scalar_signature(p: ptr, ty: u64, node: u64) -> bool { + var signature: ptr = &p.core.types[ty]; + if (ir_lower_aggregate(p.core, signature.child)) { return ir_lower_fail(p.core, 18, node, 0, 0, 9); } + var at: u64 = 0; + while (at < signature.count) { + var kind: u64 = p.core.types[p.core.type_edges[signature.first + at]].kind; + if (kind == 20 || kind == 21) { return ir_lower_fail(p.core, 18, node, 0, 0, 9); } + at += 1; + } + return true; +} + +fun ir_lower_function_signature(p: ptr, node: u64, output: ptr) -> bool { + var n: ptr = &p.core.nodes[node]; + if (!ir_lower_edges(p.core, n.b, n.c, node)) { return false; } + var saved: u64 = p.core.temporary_count; + if (n.c > p.core.temporary_capacity - saved) { return ir_lower_fail(p.core, 4, node, 0, 0, 0); } + p.core.temporary_count += n.c; + var at: u64 = 0; + while (at < n.c) { + var parameter: u64 = p.core.edges[n.b + at]; + if (!ir_lower_node(p.core, parameter, 0) || p.core.nodes[parameter].tag != 204) { + return ir_lower_fail(p.core, 3, parameter, 0, 0, 0); + } + var ty: u64 = 0; + if (!ir_lower_type(p.core, p.core.nodes[parameter].b, 0, &ty)) { return false; } + p.core.temporary[saved + at] = ty; at += 1; + } + var ret: u64 = 0; + if (!ir_lower_type(p.core, n.d, 0, &ret)) { return false; } + if (n.g > 1) { return ir_lower_fail(p.core, 21, node, 0, 0, 1); } + var success: bool = ir_lower_type_intern(p.core, 18, ret, + &p.core.temporary[saved], n.c, n.g, node, output); + p.core.temporary_count = saved; return success; +} + +fun ir_lower_declare(p: ptr, name: u64, signature: u64, linkage: u64, + link: u64, node: u64) -> bool { + if (!ir_lower_name(p.core, name, node) || !ir_lower_scalar_signature(p, signature, node) + || !ir_lower_signature_validate(p, signature, 0, node)) { return false; } + if (linkage > 1 || (linkage == 0 && link != 18446744073709551615) + || (linkage == 1 && link == 18446744073709551615)) { + return ir_lower_fail(p.core, 21, node, name, 0, 9); + } + if (link != 18446744073709551615) { + if (!ir_lower_name(p.core, link, node)) { return false; } + var s: ptr = &p.core.names[link]; + if (s.length == 0) { return ir_lower_fail(p.core, 21, node, name, 0, 9); } + var at: u64 = 0; + while (at < s.length) { + if (!ir_lower_charge(p.core, 1, node)) { return false; } + if (s.data[at] == 0) { return ir_lower_fail(p.core, 21, node, name, 0, 9); } + at += 1; + } + } + var existing: u64 = p.declaration_map[name]; + if (existing != 18446744073709551615) { + var d: ptr = &p.declarations[existing]; + if (d.signature != signature || d.linkage != linkage || d.link_name != link) { + return ir_lower_fail(p.core, 21, node, name, 0, 6); + } + return true; + } + if (link != 18446744073709551615 && p.field_slots[link] != 18446744073709551615) { + return ir_lower_fail(p.core, 21, node, link, 0, 10); + } + if (p.declaration_count >= p.declaration_capacity) { return ir_lower_fail(p.core, 4, node, 0, 0, 0); } + var id: u64 = p.declaration_count; + p.declarations[id].name = name; p.declarations[id].signature = signature; + p.declarations[id].linkage = linkage; p.declarations[id].link_name = link; + p.declarations[id].defined = 0; p.declarations[id].source = node; + p.declaration_map[name] = id; + if (link != 18446744073709551615) { p.field_slots[link] = id; } + p.declaration_count += 1; return ir_lower_expand(p, 1, node); +} + +fun ir_lower_function(p: ptr, node: u64) -> bool { + var n: ptr = &p.core.nodes[node]; + var declaration: u64 = p.declaration_map[n.a]; + if (declaration == 18446744073709551615 || p.function_count >= p.function_capacity) { + return ir_lower_fail(p.core, 4, node, 0, 0, 0); + } + if (p.declarations[declaration].defined != 0) { return ir_lower_fail(p.core, 21, node, declaration, 0, 8); } + p.declarations[declaration].defined = 1; + var signature: u64 = p.declarations[declaration].signature; + var f: ptr = &p.functions[p.function_count]; + f.declaration = declaration; f.first_param = p.next_value; f.param_count = n.c; + f.first_block = p.block_count; f.block_count = 0; f.source = node; + p.current_function = p.function_count; p.return_type = p.core.types[signature].child; + var at: u64 = 0; + // Parameter SSA values all precede stack slots, matching canonical O0 IDs. + while (at < n.c) { + var value: u64 = 0; + if (!ir_lower_value(p, p.core.type_edges[p.core.types[signature].first + at], node, &value)) { return false; } + at += 1; + } + if (!ir_lower_block(p, 0, node, &p.entry)) { return false; } + p.current_block = p.entry; f.entry = p.entry; + at = 0; + while (at < n.c) { + var parameter: u64 = p.core.edges[n.b + at]; + var ty: u64 = p.core.type_edges[p.core.types[signature].first + at]; + var slot: u64 = 0; + if (!ir_lower_layout(p.core, ty, parameter) + || !ir_lower_alloca(p, ty, p.core.layouts[ty].allocation_align, parameter, &slot) + || !ir_lower_emit(p, 23, 18446744073709551615, ty, f.first_param + at, + slot, p.core.layouts[ty].allocation_align, 0, 0, null, 0, false, parameter) + || !ir_lower_bind(p, p.core.nodes[parameter].a, ty, slot, 0, 0, parameter)) { return false; } + at += 1; + } + if (!ir_lower_statements(p, n.e, n.f, 1, node)) { return false; } + if (p.blocks[p.current_block].term_kind == 0) { + if (p.return_type == 0) { + if (!ir_lower_term(p, 3, 0, 18446744073709551615, 0, 0, node)) { return false; } + } else if (!ir_lower_term(p, 4, 0, 0, 0, 0, node)) { return false; } + } + f.block_count = p.block_count - f.first_block; p.function_count += 1; + return ir_lower_restore(p, 0, node); +} + +fun ir_lower_program(p: ptr, root: u64) -> bool { + if (!ir_lower_node(p.core, root, 0) || p.core.nodes[root].tag != 200) { return ir_lower_fail(p.core, 3, root, 0, 0, 0); } + var program: ptr = &p.core.nodes[root]; + if (!ir_lower_edges(p.core, program.a, program.b, root) + || !ir_lower_edges(p.core, program.c, program.d, root) + || !ir_lower_edges(p.core, program.e, program.f, root)) { return false; } + var at: u64 = 0; + // Validate all duplicate definitions/parameters before inspecting signatures. + while (at < program.f) { + var function: u64 = p.core.edges[program.e + at]; + if (!ir_lower_node(p.core, function, 0) || p.core.nodes[function].tag != 203) { + return ir_lower_fail(p.core, 3, function, 0, 0, 0); + } + var f: ptr = &p.core.nodes[function]; + if (!ir_lower_name(p.core, f.a, function) || !ir_lower_edges(p.core, f.b, f.c, function)) { return false; } + if (p.local_slots[f.a] != 18446744073709551615) { return ir_lower_fail(p.core, 8, function, 0, 0, f.a); } + p.local_slots[f.a] = function; + var marker: u64 = p.core.marker; p.core.marker += 1; + var index: u64 = 0; + while (index < f.c) { + var param: u64 = p.core.edges[f.b + index]; + if (!ir_lower_node(p.core, param, 0) || p.core.nodes[param].tag != 204) { return ir_lower_fail(p.core, 3, param, 0, 0, 0); } + var name: u64 = p.core.nodes[param].a; + if (!ir_lower_name(p.core, name, param)) { return false; } + if (p.core.name_marks[name] == marker) { return ir_lower_fail(p.core, 9, function, f.a, 0, name); } + p.core.name_marks[name] = marker; index += 1; + } + at += 1; + } + at = 0; + while (at < program.b) { + var node: u64 = p.core.edges[program.a + at]; + if (!ir_lower_node(p.core, node, 0) || p.core.nodes[node].tag != 201) { return ir_lower_fail(p.core, 3, node, 0, 0, 0); } + var n: ptr = &p.core.nodes[node]; + var signature: u64 = 0; + if (!ir_lower_type(p.core, n.b, 0, &signature)) { return false; } + if (p.core.types[signature].kind != 18) { return ir_lower_fail(p.core, 3, node, 0, 0, 0); } + if (!ir_lower_declare(p, n.a, signature, n.c, n.d, node)) { return false; } + at += 1; + } + at = 0; + while (at < program.f) { + var node: u64 = p.core.edges[program.e + at]; + var n: ptr = &p.core.nodes[node]; var signature: u64 = 0; + if (!ir_lower_function_signature(p, node, &signature) + || !ir_lower_declare(p, n.a, signature, n.h, n.i, node)) { return false; } + at += 1; + } + at = 0; + while (at < program.b) { + var node: u64 = p.core.edges[program.a + at]; + var n: ptr = &p.core.nodes[node]; + if (n.c == 0 && p.local_slots[n.a] == 18446744073709551615) { + return ir_lower_fail(p.core, 21, node, p.declaration_map[n.a], 0, 7); + } + at += 1; + } + at = 0; + // Reuse prepass/link registry workspace only after its whole scope ends. + while (at < p.core.name_count) { + p.local_slots[at] = 18446744073709551615; p.field_slots[at] = 18446744073709551615; at += 1; + } + at = 0; + while (at < program.d) { + var node: u64 = p.core.edges[program.c + at]; + if (!ir_lower_node(p.core, node, 0) || p.core.nodes[node].tag != 202) { return ir_lower_fail(p.core, 3, node, 0, 0, 0); } + var n: ptr = &p.core.nodes[node]; + if (!ir_lower_name(p.core, n.a, node)) { return false; } + if (p.global_slots[n.a] != 18446744073709551615) { return ir_lower_fail(p.core, 10, node, 0, 0, n.a); } + var ty: u64 = 0; var value: IrLowerValue; + if (!ir_lower_type(p.core, n.b, 0, &ty) + || !ir_lower_preserve_constant(p, n.c, 1, &value)) { return false; } + if (!ir_lower_evaluate_request(p, value.value, 0, p.global_count, node)) { return false; } + if (ty != value.ty) { return ir_lower_mismatch(p, n.c, ty, value.ty); } + if (!ir_lower_layout(p.core, ty, node)) { return false; } + if (p.global_count >= p.global_capacity) { return ir_lower_fail(p.core, 4, node, 0, 0, 0); } + var id: u64 = p.global_count; + p.globals[id].name = n.a; p.globals[id].ty = ty; p.globals[id].expression = value.value; + p.globals[id].align = p.core.layouts[ty].allocation_align; + p.globals[id].annotation = 18446744073709551615; p.globals[id].source = node; + if (p.core.nodes[n.c].tag == 0) { + p.globals[id].annotation = p.core.nodes[n.c].a; + if (!ir_lower_complete_source(p, p.core.nodes[n.c].a, node)) { return false; } + } + p.global_bindings[id].name = n.a; p.global_bindings[id].ty = ty; + p.global_bindings[id].value = id; p.global_bindings[id].kind = 2; + p.global_bindings[id].constant = value.value; + p.global_slots[n.a] = id; p.global_count += 1; + if (!ir_lower_expand(p, 1, node)) { return false; } + at += 1; + } + at = 0; + while (at < program.f) { + if (!ir_lower_function(p, p.core.edges[program.e + at])) { return false; } + at += 1; + } + return true; +} + +fun ir_lower_driver_initialize(p: ptr) -> bool { + if (!ir_lower_initialize(p.core)) { return false; } + p.expansion = 0; p.instruction_count = 0; p.output_edge_count = 0; + p.block_count = 0; p.declaration_count = 0; p.function_count = 0; p.global_count = 0; + p.global_binding_count = 0; p.binding_count = 0; p.loop_count = 0; + p.source_count = 0; p.mapping_count = 0; p.source_work = 0; + p.field_binding_count = 0; p.next_value = 0; p.current_function = 0; + p.current_block = 18446744073709551615; p.entry = 18446744073709551615; + p.return_type = 0; p.error_index = 0; p.request_count = 0; + if (p.mode > 1 || !ir_span_valid(p.blocks as ptr, p.block_capacity, 112) + || !ir_span_valid(p.declarations as ptr, p.declaration_capacity, 48) + || !ir_span_valid(p.functions as ptr, p.function_capacity, 56) + || !ir_span_valid(p.globals as ptr, p.global_capacity, 48) + || !ir_span_valid(p.global_bindings as ptr, p.global_capacity, 40) + || !ir_span_valid(p.bindings as ptr, p.binding_capacity, 40) + || !ir_span_valid(p.loops as ptr, p.loop_capacity, 16) + || !ir_span_valid(p.annotations as ptr, p.annotation_count, 56) + || !ir_span_valid(p.source_marks as ptr, p.annotation_count, 8) + || !ir_span_valid(p.type_sizes as ptr, p.core.type_capacity, 8) + || !ir_span_valid(p.declaration_map as ptr, p.core.name_count, 8) + || !ir_span_valid(p.field_slots as ptr, p.core.name_count, 8) + || !ir_span_valid(p.local_slots as ptr, p.core.name_count, 8) + || !ir_span_valid(p.global_slots as ptr, p.core.name_count, 8) + || !ir_span_valid(p.field_bindings as ptr, p.field_binding_capacity, 32) + || !ir_span_valid(p.constants as ptr, p.core.node_count, 72) + || !ir_span_valid(p.requests as ptr, p.request_capacity, 32)) { + return ir_lower_fail(p.core, 3, 0, 0, 0, 0); + } + if (p.mode == 1 && (!ir_span_valid(p.instructions as ptr, p.instruction_capacity, 104) + || !ir_span_valid(p.output_edges as ptr, p.output_edge_capacity, 8) + || !ir_span_valid(p.value_types as ptr, p.value_capacity, 8) + || !ir_span_valid(p.source_order as ptr, p.source_capacity, 8) + || !ir_span_valid(p.mapping_order as ptr, p.mapping_capacity, 8))) { + return ir_lower_fail(p.core, 3, 0, 0, 0, 0); + } + var at: u64 = 0; + while (at < p.core.name_count) { + if (!ir_lower_charge(p.core, 1, 0)) { return false; } + var name: ptr = &p.core.names[at]; + if (!ir_span_valid(name.data, name.length, 1)) { return ir_lower_fail(p.core, 3, 0, 0, 0, 0); } + p.declaration_map[at] = 18446744073709551615; p.field_slots[at] = 18446744073709551615; + p.local_slots[at] = 18446744073709551615; p.global_slots[at] = 18446744073709551615; at += 1; + } + at = 0; + while (at < p.core.type_capacity) { + if (!ir_lower_charge(p.core, 1, 0)) { return false; } + p.type_sizes[at] = 0; at += 1; + } + at = 0; + while (at < p.annotation_count) { + if (!ir_lower_charge(p.core, 1, 0)) { return false; } + p.source_marks[at] = 0; at += 1; + } + return true; +} + +export(c) fun whale_ir_lower_o0(p: ptr, root: u64) -> i32 { + if (p == null || p.core == null || p.core.result == null) { return 3; } + var success: bool = ir_lower_driver_initialize(p) && ir_lower_program(p, root); + p.core.result.work = p.core.work; + if (!success) { return p.core.result.status as i32; } + return 0; +} diff --git a/ir/lower_expression.wave b/ir/lower_expression.wave new file mode 100644 index 0000000..777daf5 --- /dev/null +++ b/ir/lower_expression.wave @@ -0,0 +1,356 @@ +// SPDX-License-Identifier: MPL-2.0 +// Scalar and preserved-constant expression lowering. Typed constexpr payloads +// stay independent from runtime instructions and are evaluated by the core +// constant engine after a successful lowering transaction. +fun ir_lower_mismatch(p: ptr, node: u64, expected: u64, actual: u64) -> bool { + ir_lower_fail(p.core, 6, node, expected, actual, 0); + if (node < p.core.node_count && p.core.nodes[node].tag == 0) { + p.core.result.annotation = p.core.nodes[node].a; + } + return false; +} + +fun ir_lower_literal(p: ptr, node: u64, value: ptr, + low: ptr, high: ptr, category: ptr) -> bool { + var n: ptr = &p.core.nodes[node]; + var ty: u64 = 0; + var width: u64 = 0; + var source: ptr = null; + var length: u64 = 0; + var cat: u64 = 0; + low[0] = 0; high[0] = 0; + if (n.tag == 16) { + if (n.a > 1) { return ir_lower_fail(p.core, 3, node, 0, 0, 0); } + ty = 1; low[0] = n.a; cat = 1; + } else { + width = n.a; + if (n.tag == 17) { + if (n.b > 1) { return ir_lower_fail(p.core, 3, node, 0, 0, 0); } + if (width == 1) { ty = 2; } + else if (width == 8) { ty = 4; } + else if (width == 16) { ty = 5; } + else if (width == 32) { ty = 6; } + else if (width == 64) { ty = 7; } + else if (width == 128) { ty = 8; } + else { return ir_lower_fail(p.core, 5, node, 0, 0, 0); } + cat = 2; + if (n.b == 0) { + cat = 3; + if (ty == 2) { ty = 3; } else { ty += 5; } + } + source = n.c as ptr; length = n.d; + } else if (n.tag == 18) { + if (width == 16) { ty = 14; } + else if (width == 32) { ty = 15; } + else if (width == 64) { ty = 16; } + else { return ir_lower_fail(p.core, 5, node, 0, 0, 0); } + cat = 4; source = n.b as ptr; length = n.c; + } else { return ir_lower_fail(p.core, 3, node, 0, 0, 0); } + var literal: IrLiteralResult; + var status: i32 = whale_ir_parse_literal(source, length, cat, width, + p.core.max_work - p.core.work, &literal); + if (status == 10) { return ir_lower_fail(p.core, 1, node, 0, 0, 0); } + if (!ir_lower_charge(p.core, literal.work, node)) { return false; } + if (status != 0) { return ir_lower_fail(p.core, 19, node, ty, 0, literal.status); } + low[0] = literal.low; high[0] = literal.high; + } + value.ty = ty; value.value = node; category[0] = cat; return true; +} + +fun ir_lower_binop(p: ptr, op: u64, ty: u64, node: u64, output: ptr) -> bool { + var code: u64 = 0; + if (ir_lower_float(ty)) { + if (op <= 2) { code = op + 7; } + else if (op == 6 || op == 7) { code = op + 4; } + else { return ir_lower_fail(p.core, 7, node, 0, 0, 0); } + } else if (ir_lower_integer(ty)) { + if (op <= 2) { code = op; } + else if (op >= 3 && op <= 5) { code = op + 9; } + else if (op == 6) { code = 3; if (ir_lower_signed(ty)) { code = 4; } } + else if (op == 7) { code = 5; if (ir_lower_signed(ty)) { code = 6; } } + else if (op == 8) { code = 15; } + else if (op == 9) { code = 16; if (ir_lower_signed(ty)) { code = 17; } } + else { return ir_lower_fail(p.core, 7, node, 0, 0, 0); } + } else { return ir_lower_fail(p.core, 7, node, 0, 0, 0); } + output[0] = code; return true; +} + +fun ir_lower_compare(p: ptr, op: u64, ty: u64, node: u64, output: ptr) -> bool { + if (op > 5) { return ir_lower_fail(p.core, 3, node, 0, 0, 0); } + if (ir_lower_float(ty)) { output[0] = op + 10; return true; } + if (ty == 1) { + if (op > 1) { return ir_lower_fail(p.core, 7, node, 0, 0, 0); } + output[0] = op; return true; + } + if (!ir_lower_integer(ty)) { return ir_lower_fail(p.core, 7, node, 0, 0, 0); } + if (op <= 1 || ir_lower_signed(ty)) { output[0] = op; } + else { output[0] = op + 4; } + return true; +} + +fun ir_lower_preserve_constant(p: ptr, node: u64, depth: u64, + output: ptr) -> bool { + if (!ir_lower_node(p.core, node, depth) + || !ir_lower_source_charge(p, 1, node)) { return false; } + var n: ptr = &p.core.nodes[node]; + if (n.tag == 0) { + var saved: u64 = p.core.annotation; p.core.annotation = n.a; + var success: bool = ir_lower_source(p, n.a, node) + && ir_lower_preserve_constant(p, n.b, depth + 1, output); + p.core.annotation = saved; return success; + } + var kind: u64 = 0; + var operation: u64 = 0; + var low: u64 = 0; + var high: u64 = 0; + var reference: u64 = 0; + var left: IrLowerValue; + var right: IrLowerValue; + left.value = 18446744073709551615; left.ty = 0; + right.value = 18446744073709551615; right.ty = 0; + var ty: u64 = 0; + if (n.tag >= 16 && n.tag <= 18) { + if (!ir_lower_literal(p, node, &left, &low, &high, &operation)) { return false; } + ty = left.ty; + } else if (n.tag == 15) { + var binding: IrLowerBinding; + if (!ir_lower_name(p.core, n.a, node) || !ir_lower_binding(p, n.a, node, false, &binding)) { return false; } + if (binding.kind == 0) { return ir_lower_fail(p.core, 17, node, 0, 0, 0); } + kind = binding.kind; reference = binding.value; ty = binding.ty; + } else if (n.tag == 9 || n.tag == 10) { + if (!ir_lower_preserve_constant(p, n.a, depth + 1, &left)) { return false; } + ty = left.ty; kind = 3; + if (n.tag == 9) { + if (!ir_lower_integer(ty)) { return ir_lower_fail(p.core, 7, node, 0, 0, 0); } + kind = 4; + } + } else if (n.tag == 19 || n.tag == 20) { + if (!ir_lower_preserve_constant(p, n.a, depth + 1, &left) + || !ir_lower_preserve_constant(p, n.c, depth + 1, &right)) { return false; } + if (left.ty != right.ty) { return ir_lower_fail(p.core, 6, node, left.ty, right.ty, 0); } + operation = n.b; ty = left.ty; + if (n.tag == 19) { + kind = 5; + if (operation == 10 || operation == 11) { + if (ty != 1) { return ir_lower_fail(p.core, 6, node, 1, ty, 0); } + } else { + var ignored: u64 = 0; + if (!ir_lower_binop(p, operation, ty, node, &ignored)) { return false; } + } + } else { kind = 6; ty = 1; } + } else { return ir_lower_fail(p.core, 17, node, 0, 0, 0); } + var type_size: u64 = 0; + if (!ir_lower_type_size(p, ty, node, 0, &type_size) + || !ir_lower_expand(p, 1 + type_size, node)) { return false; } + if (true) { + var record: ptr = &p.constants[node]; + record.kind = kind; record.operation = operation; record.ty = ty; + record.low = low; record.high = high; record.left = left.value; record.right = right.value; + record.reference = reference; record.annotation = p.core.annotation; + } + output.value = node; output.ty = ty; return true; +} + +fun ir_lower_immediate(p: ptr, ty: u64, low: u64, high: u64, + node: u64, output: ptr) -> bool { + var id: u64 = 0; + if (!ir_lower_value(p, ty, node, &id)) { return false; } + var category: u64 = 3; + if (ty == 1) { category = 1; } + else if (ir_lower_signed(ty)) { category = 2; } + else if (ir_lower_float(ty)) { category = 4; } + if (!ir_lower_emit(p, 4, id, ty, 2, low, high, category, 0, null, 0, false, node)) { return false; } + output[0] = id; return true; +} + +fun ir_lower_cast_value(p: ptr, op: u64, src_ty: u64, dst_ty: u64, + value: u64, node: u64, output: ptr) -> bool { + var id: u64 = 0; + if (!ir_lower_value(p, dst_ty, node, &id) + || !ir_lower_emit(p, 14, id, dst_ty, op, src_ty, value, 0, 0, null, 0, false, node)) { return false; } + output[0] = id; return true; +} + +fun ir_lower_call(p: ptr, node: u64, depth: u64, + output: ptr) -> bool { + var n: ptr = &p.core.nodes[node]; + var callee: u64 = n.b; + var signature: u64 = 0; + if (n.a == 0) { + if (!ir_lower_name(p.core, callee, node)) { return false; } + callee = p.declaration_map[callee]; + if (callee == 18446744073709551615) { return ir_lower_fail(p.core, 21, node, n.b, 0, 2); } + signature = p.declarations[callee].signature; + } else if (n.a == 1) { + var pointer: IrLowerValue; + if (!ir_lower_expression(p, callee, depth + 1, false, &pointer)) { return false; } + callee = pointer.value; signature = pointer.ty; + if (p.core.types[signature].kind != 18) { + return ir_lower_fail(p.core, 21, node, callee, 0, 3); + } + } else { return ir_lower_fail(p.core, 3, node, 0, 0, 0); } + if (!ir_lower_edges(p.core, n.c, n.d, node)) { return false; } + var saved: u64 = p.core.temporary_count; + if (n.d > (p.core.temporary_capacity - saved) / 2) { return ir_lower_fail(p.core, 4, node, 0, 0, 0); } + p.core.temporary_count += n.d * 2; + var at: u64 = 0; + var argument: IrLowerValue; + while (at < n.d) { + if (!ir_lower_expression(p, p.core.edges[n.c + at], depth + 1, false, &argument)) { return false; } + p.core.temporary[saved + at] = argument.value; + p.core.temporary[saved + n.d + at] = argument.ty; at += 1; + } + var sig: ptr = &p.core.types[signature]; + if (sig.count != n.d) { return ir_lower_fail(p.core, 21, node, sig.count, n.d, 4); } + at = 0; + while (at < n.d) { + var expected: u64 = p.core.type_edges[sig.first + at]; + var actual: u64 = p.core.temporary[saved + n.d + at]; + if (expected != actual) { + ir_lower_fail(p.core, 21, node, expected, actual, 5); + p.error_index = at; return false; + } + at += 1; + } + var value: u64 = 18446744073709551615; + if (sig.child != 0 && !ir_lower_value(p, sig.child, node, &value)) { return false; } + if (!ir_lower_emit(p, 29, value, sig.child, sig.auxiliary, n.a, callee, + signature, 0, &p.core.temporary[saved], n.d, false, node)) { return false; } + p.core.temporary_count = saved; output.value = value; output.ty = sig.child; return true; +} + +fun ir_lower_expression(p: ptr, node: u64, depth: u64, + allow_void: bool, output: ptr) -> bool { + if (!ir_lower_node(p.core, node, depth)) { return false; } + var n: ptr = &p.core.nodes[node]; + if (n.tag == 0) { + var saved_annotation: u64 = p.core.annotation; p.core.annotation = n.a; + var success: bool = ir_lower_expression(p, n.b, depth + 1, allow_void, output) + && ir_lower_complete_source(p, n.a, node); + p.core.annotation = saved_annotation; return success; + } + if (n.tag == 1 || n.tag == 2) { return ir_lower_aggregate_literal(p, node, depth, output); } + var left: IrLowerValue; + var right: IrLowerValue; + var ty: u64 = 0; + var value: u64 = 0; + if (n.tag == 3 || n.tag == 4 || n.tag == 6) { + if (!ir_lower_place(p, node, depth, &left)) { return false; } + return ir_lower_read(p, left.value, left.ty, node, output); + } + if (n.tag == 5) { + if (!ir_lower_place(p, n.a, depth + 1, &left) + || !ir_lower_pointer(p.core, left.ty, node, &ty)) { return false; } + output.value = left.value; output.ty = ty; return true; + } + if (n.tag == 7 || n.tag == 8) { + if (!ir_lower_expression(p, n.a, depth + 1, false, &left)) { return false; } + if (p.core.types[left.ty].kind != 17) { return ir_lower_fail(p.core, 7, node, 0, 0, 0); } + ty = p.core.types[left.ty].child; + if (n.tag == 7) { + if (!ir_lower_scalar(p.core, ty)) { return ir_lower_fail(p.core, 7, node, 0, 0, 0); } + if (!ir_lower_layout(p.core, ty, node) || !ir_lower_value(p, ty, node, &value) + || !ir_lower_emit(p, 19, value, ty, left.value, + p.core.layouts[ty].allocation_align, 0, 0, 0, null, 0, false, node)) { return false; } + } else { + if (!ir_lower_layout(p.core, ty, node) + || !ir_lower_expression(p, n.b, depth + 1, false, &right)) { return false; } + if (!ir_lower_integer(right.ty)) { return ir_lower_fail(p.core, 7, node, 0, 0, 0); } + ty = left.ty; + if (!ir_lower_value(p, ty, node, &value) + || !ir_lower_emit(p, 24, value, ty, left.value, 0, 0, 0, 0, + &right.value, 1, false, node)) { return false; } + } + } else if (n.tag == 9 || n.tag == 10) { + if (!ir_lower_expression(p, n.a, depth + 1, false, &left)) { return false; } + ty = left.ty; + if (!ir_lower_integer(ty) && (n.tag == 9 || !ir_lower_float(ty))) { + return ir_lower_fail(p.core, 7, node, 0, 0, 0); + } + var tag: u64 = 8; if (n.tag == 9) { tag = 9; } + if (!ir_lower_value(p, ty, node, &value) + || !ir_lower_emit(p, tag, value, ty, left.value, 0, 0, 0, 0, null, 0, false, node)) { return false; } + } else if (n.tag == 11) { + if (!ir_lower_type(p.core, n.b, 0, &ty)) { return false; } + if (!ir_lower_integer(ty)) { return ir_lower_fail(p.core, 7, node, 0, 0, 0); } + if (!ir_lower_expression(p, n.a, depth + 1, false, &left)) { return false; } + if (!ir_lower_integer(left.ty) || n.c > 1) { return ir_lower_fail(p.core, 7, node, 0, 0, 0); } + var cast: u64 = 0; + if (n.c == 0) { + var source_width: u64 = ir_lower_width(left.ty); + var destination_width: u64 = ir_lower_width(ty); + cast = 1; + if (source_width > destination_width) { cast = 3; } + else if (source_width == destination_width) { cast = 10; } + else if (ir_lower_signed(left.ty)) { cast = 2; } + } + if (!ir_lower_cast_value(p, cast, left.ty, ty, left.value, node, &value)) { return false; } + } else if (n.tag == 12 || n.tag == 13) { + var function: u64 = 0; + var tag: u64 = 27; + if (n.tag == 12) { + if (!ir_lower_name(p.core, n.a, node)) { return false; } + function = p.declaration_map[n.a]; + if (function == 18446744073709551615) { return ir_lower_fail(p.core, 21, node, n.a, 0, 2); } + ty = p.declarations[function].signature; tag = 28; + } else if (!ir_lower_type(p.core, n.a, 0, &ty)) { return false; } + if (p.core.types[ty].kind != 18) { return ir_lower_fail(p.core, 3, node, 0, 0, 0); } + if (!ir_lower_signature_validate(p, ty, 0, node)) { return false; } + if (!ir_lower_value(p, ty, node, &value) + || !ir_lower_emit(p, tag, value, ty, function, 0, 0, 0, 0, null, 0, false, node)) { return false; } + } else if (n.tag == 14) { + if (!ir_lower_call(p, node, depth, output)) { return false; } + if (!allow_void && output.ty == 0) { return ir_lower_fail(p.core, 16, node, 0, 0, 0); } + return true; + } else if (n.tag == 15) { + var binding: IrLowerBinding; + if (!ir_lower_binding(p, n.a, node, false, &binding)) { return false; } + ty = binding.ty; value = binding.value; + if (binding.kind == 0) { return ir_lower_read(p, value, ty, node, output); } + if (binding.kind == 2) { + if (!ir_lower_value(p, ty, node, &value) + || !ir_lower_emit(p, 4, value, ty, 1, binding.value, 0, 0, 0, null, 0, false, node)) { return false; } + } + } else if (n.tag >= 16 && n.tag <= 18) { + var low: u64 = 0; var high: u64 = 0; var category: u64 = 0; + if (!ir_lower_literal(p, node, &left, &low, &high, &category) + || !ir_lower_immediate(p, left.ty, low, high, node, &value)) { return false; } + ty = left.ty; + } else if (n.tag == 19 || n.tag == 20) { + if (!ir_lower_expression(p, n.a, depth + 1, false, &left)) { return false; } + if (n.tag == 19 && (n.b == 10 || n.b == 11)) { + if (left.ty != 1) { return ir_lower_fail(p.core, 6, node, 1, left.ty, 0); } + var left_exit: u64 = p.current_block; + var rhs: u64 = 0; var continuation: u64 = 0; + if (!ir_lower_block(p, 8, node, &rhs) || !ir_lower_block(p, 9, node, &continuation)) { return false; } + var true_block: u64 = rhs; var false_block: u64 = continuation; + if (n.b == 11) { true_block = continuation; false_block = rhs; } + if (!ir_lower_term(p, 2, 0, left.value, true_block, false_block, node)) { return false; } + p.current_block = rhs; + if (!ir_lower_expression(p, n.c, depth + 1, false, &right)) { return false; } + if (right.ty != 1) { return ir_lower_fail(p.core, 6, node, 1, right.ty, 0); } + var right_exit: u64 = p.current_block; + if (!ir_lower_term(p, 1, 0, continuation, 0, 0, node)) { return false; } + p.current_block = continuation; ty = 1; + var incoming: array; + incoming[0] = left.value; incoming[1] = left_exit; + incoming[2] = right.value; incoming[3] = right_exit; + if (!ir_lower_value(p, ty, node, &value) + || !ir_lower_emit(p, 15, value, ty, 0, 0, 0, 0, 0, &incoming[0], 4, false, node)) { return false; } + } else { + if (!ir_lower_expression(p, n.c, depth + 1, false, &right)) { return false; } + if (left.ty != right.ty) { return ir_lower_fail(p.core, 6, node, left.ty, right.ty, 0); } + ty = left.ty; var op: u64 = 0; var tag: u64 = 7; + if (n.tag == 20) { + if (!ir_lower_compare(p, n.b, ty, node, &op)) { return false; } + tag = 10; + } else if (!ir_lower_binop(p, n.b, ty, node, &op)) { return false; } + var result_type: u64 = ty; + if (n.tag == 20) { result_type = 1; } + if (!ir_lower_value(p, result_type, node, &value) + || !ir_lower_emit(p, tag, value, ty, op, left.value, right.value, 0, 0, null, 0, false, node)) { return false; } + ty = result_type; + } + } else { return ir_lower_fail(p.core, 7, node, 0, 0, 0); } + output.value = value; output.ty = ty; return true; +} diff --git a/ir/lower_hir.wave b/ir/lower_hir.wave new file mode 100644 index 0000000..e3aaa61 --- /dev/null +++ b/ir/lower_hir.wave @@ -0,0 +1,279 @@ +// SPDX-License-Identifier: MPL-2.0 +// Pinned Wave TypedProgram scalar adapter. Resolved numeric facts and stable +// expression identities cross this boundary explicitly; syntax never infers a +// type. All checks finish before the caller publishes a frontend Program. +struct IrHirNode { tag: u64; a: u64; b: u64; c: u64; d: u64; e: u64; f: u64; g: u64; } + +struct IrHirOutput { ty: u64; operation: u64; } + +struct IrHirBinding { name: u64; ty: u64; } + +struct IrHirIdentity { id: u64; occupied: u64; } + +struct IrHirResult { status: u64; node: u64; detail: u64; work: u64; } + +struct IrHirAdapter { + nodes: ptr; count: u64; edges: ptr; edge_count: u64; + output: ptr; bindings: ptr; binding_count: u64; + identities: ptr; identity_capacity: u64; + max_work: u64; work: u64; max_depth: u64; return_type: u64; + result: ptr; +} + +fun ir_hir_fail(p: ptr, status: u64, node: u64, detail: u64) -> bool { + p.result.status = status; p.result.node = node; p.result.detail = detail; return false; +} + +fun ir_hir_charge(p: ptr, amount: u64, node: u64) -> bool { + if (amount > p.max_work - p.work) { return ir_hir_fail(p, 1, node, 0); } + p.work += amount; return true; +} + +fun ir_hir_node(p: ptr, index: u64, depth: u64) -> bool { + if (depth > p.max_depth) { return ir_hir_fail(p, 2, index, 0); } + if (!ir_hir_charge(p, 1, index)) { return false; } + if (index >= p.count) { return ir_hir_fail(p, 3, index, 0); } + return true; +} + +fun ir_hir_type(p: ptr, index: u64, value: ptr) -> bool { + if (!ir_hir_node(p, index, 0)) { return false; } + var n: ptr = &p.nodes[index]; + if (n.tag != 2) { return ir_hir_fail(p, 3, index, 0); } + var ty: u64 = 0; + if (n.a == 1) { ty = 1; } + else if (n.a == 2) { + if (n.c > 1) { return ir_hir_fail(p, 4, index, 0); } + if (n.b == 1) { ty = 2; } + else if (n.b == 8) { ty = 4; } + else if (n.b == 16) { ty = 5; } + else if (n.b == 32) { ty = 6; } + else if (n.b == 64) { ty = 7; } + else if (n.b == 128) { ty = 8; } + else { return ir_hir_fail(p, 4, index, 0); } + if (n.c == 0) { + if (ty == 2) { ty = 3; } + else { ty += 5; } + } + } else if (n.a != 0) { return ir_hir_fail(p, 5, index, n.a); } + p.output[index].ty = ty; value[0] = ty; return true; +} + +fun ir_hir_identity(p: ptr, id: u64, node: u64) -> bool { + // A power-of-two open-addressed table bounds identity checking even when + // expressions are visited in a different order from their original IDs. + var slot: u64 = (id ^ (id >> 32)) & (p.identity_capacity - 1); + var visited: u64 = 0; + while (visited < p.identity_capacity) { + if (!ir_hir_charge(p, 1, node)) { return false; } + if (p.identities[slot].occupied == 0) { + p.identities[slot].occupied = 1; p.identities[slot].id = id; return true; + } + if (p.identities[slot].id == id) { return ir_hir_fail(p, 6, node, id); } + slot = (slot + 1) & (p.identity_capacity - 1); visited += 1; + } + return ir_hir_fail(p, 1, node, 0); +} + +fun ir_hir_integer(ty: u64) -> bool { return ty >= 2 && ty <= 13; } + +fun ir_hir_signed(ty: u64) -> bool { return ty == 2 || (ty >= 4 && ty <= 8); } + +fun ir_hir_width(ty: u64) -> u64 { + if (ty == 2 || ty == 3) { return 1; } + if (ty > 8) { ty -= 5; } + if (ty == 4) { return 8; } + if (ty == 5) { return 16; } + if (ty == 6) { return 32; } + if (ty == 7) { return 64; } + if (ty == 8) { return 128; } + return 0; +} + +fun ir_hir_find(p: ptr, name: u64, node: u64, ty: ptr) -> bool { + var index: u64 = p.binding_count; + while (index != 0) { + if (!ir_hir_charge(p, 1, node)) { return false; } + index -= 1; + if (p.bindings[index].name == name) { ty[0] = p.bindings[index].ty; return true; } + } + return ir_hir_fail(p, 7, node, name); +} + +fun ir_hir_bind(p: ptr, name: u64, ty: u64, node: u64) -> bool { + if (p.binding_count >= p.count) { return ir_hir_fail(p, 1, node, 0); } + p.bindings[p.binding_count].name = name; + p.bindings[p.binding_count].ty = ty; + p.binding_count += 1; return true; +} + +fun ir_hir_expression(p: ptr, index: u64, depth: u64, value: ptr) -> bool { + if (!ir_hir_node(p, index, depth)) { return false; } + var n: ptr = &p.nodes[index]; + if (n.tag == 12) { return ir_hir_fail(p, 5, index, n.a); } + if (n.tag < 3 || n.tag > 6) { return ir_hir_fail(p, 3, index, 0); } + if (!ir_hir_identity(p, n.a, index)) { return false; } + var ty: u64 = 0; + if (!ir_hir_type(p, n.b, &ty)) { return false; } + if (ty == 0) { return ir_hir_fail(p, 4, index, 0); } + var actual: u64 = 0; + var left: u64 = 0; + var right: u64 = 0; + if (n.tag == 3) { + if (!ir_hir_integer(ty)) { return ir_hir_fail(p, 4, index, 0); } + var literal: IrLiteralResult; + var category: u64 = 3; + if (ir_hir_signed(ty)) { category = 2; } + var status: i32 = whale_ir_parse_literal(n.c as ptr, n.d, category, + ir_hir_width(ty), p.max_work - p.work, &literal); + if (status == 10) { return ir_hir_fail(p, 1, index, 0); } + if (status != 0) { return ir_hir_fail(p, 8, index, literal.status); } + if (!ir_hir_charge(p, literal.work, index)) { return false; } + } else if (n.tag == 4) { + if (ty != 1 || n.c > 1) { return ir_hir_fail(p, 4, index, 0); } + } else if (n.tag == 5) { + if (!ir_hir_find(p, n.c, index, &actual)) { return false; } + if (actual != ty) { return ir_hir_fail(p, 4, index, actual); } + } else { + if (!ir_hir_expression(p, n.d, depth + 1, &left) + || !ir_hir_expression(p, n.e, depth + 1, &right)) { return false; } + if (left != right) { return ir_hir_fail(p, 4, index, right); } + var operation: u64 = n.c; + if (operation >= 12 && operation <= 17) { + if (ty != 1 || (!ir_hir_integer(left) && left != 1) + || (left == 1 && operation > 13)) { return ir_hir_fail(p, 4, index, left); } + operation = operation + 20; + } else if (operation == 10 || operation == 11) { + if (ty != 1 || left != 1) { return ir_hir_fail(p, 4, index, left); } + } else { + if (ty != left || !ir_hir_integer(ty) || operation > 9) { + return ir_hir_fail(p, 4, index, left); + } + if (operation == 3) { operation = 6; } + else if (operation == 4) { operation = 7; } + else if (operation >= 5 && operation <= 7) { operation -= 2; } + } + p.output[index].operation = operation; + } + p.output[index].ty = ty; value[0] = ty; return true; +} + +fun ir_hir_statements(p: ptr, first: u64, count: u64, depth: u64) -> bool { + if (first > p.edge_count || count > p.edge_count - first) { return ir_hir_fail(p, 3, first, 0); } + var item: u64 = 0; + var ty: u64 = 0; + var actual: u64 = 0; + while (item < count) { + var index: u64 = p.edges[first + item]; + if (!ir_hir_node(p, index, depth)) { return false; } + var n: ptr = &p.nodes[index]; + if (n.tag == 7) { + if (!ir_hir_type(p, n.b, &ty)) { return false; } + if (ty == 0) { return ir_hir_fail(p, 4, index, 0); } + if (n.c != 18446744073709551615) { + if (!ir_hir_expression(p, n.c, depth + 1, &actual)) { return false; } + if (actual != ty) { return ir_hir_fail(p, 4, index, actual); } + } + if (!ir_hir_bind(p, n.a, ty, index)) { return false; } + } else if (n.tag == 8) { + if (!ir_hir_find(p, n.a, index, &ty) + || !ir_hir_expression(p, n.b, depth + 1, &actual)) { return false; } + if (ty != actual) { return ir_hir_fail(p, 4, index, actual); } + } else if (n.tag == 9 || n.tag == 10) { + if (!ir_hir_expression(p, n.a, depth + 1, &ty)) { return false; } + if (ty != 1) { return ir_hir_fail(p, 4, index, ty); } + var saved: u64 = p.binding_count; + if (!ir_hir_statements(p, n.b, n.c, depth + 1)) { return false; } + p.binding_count = saved; + if (n.tag == 9) { + if (!ir_hir_statements(p, n.d, n.e, depth + 1)) { return false; } + p.binding_count = saved; + } + } else if (n.tag == 11) { + actual = 0; + if (n.a != 18446744073709551615 + && !ir_hir_expression(p, n.a, depth + 1, &actual)) { return false; } + if (actual != p.return_type) { return ir_hir_fail(p, 4, index, actual); } + } else if (n.tag == 13) { + if (!ir_hir_expression(p, n.a, depth + 1, &actual)) { return false; } + } else if (n.tag == 12) { return ir_hir_fail(p, 5, index, n.a); } + else { return ir_hir_fail(p, 3, index, 0); } + item += 1; + } + return true; +} + +export(c) fun whale_ir_adapt_wave_hir(nodes: ptr, node_count: u64, + edges: ptr, edge_count: u64, functions: u64, function_count: u64, + output: ptr, bindings: ptr, + identities: ptr, identity_capacity: u64, + max_depth: u64, max_work: u64, result: ptr) -> i32 { + if (result == null) { return 3; } + result.status = 0; result.node = 0; result.detail = 0; result.work = 0; + if (!ir_span_valid(nodes as ptr, node_count, 64) + || !ir_span_valid(edges as ptr, edge_count, 8) + || !ir_span_valid(output as ptr, node_count, 16) + || !ir_span_valid(bindings as ptr, node_count, 16) + || !ir_span_valid(identities as ptr, identity_capacity, 16) + || identity_capacity == 0 || !ir_power_two(identity_capacity) + || max_depth > 32 || functions > edge_count + || function_count > edge_count - functions) { result.status = 3; return 3; } + var p: IrHirAdapter; + p.nodes = nodes; p.count = node_count; p.edges = edges; p.edge_count = edge_count; + p.output = output; p.bindings = bindings; p.binding_count = 0; + p.identities = identities; p.identity_capacity = identity_capacity; + p.max_work = max_work; p.work = 0; p.max_depth = max_depth; p.return_type = 0; p.result = result; + var i: u64 = 0; + while (i < identity_capacity) { + if (!ir_hir_charge(&p, 1, 0)) { result.work = p.work; return result.status as i32; } + identities[i].occupied = 0; identities[i].id = 0; i += 1; + } + i = 0; + while (i < node_count) { + if (!ir_hir_charge(&p, 1, i)) { result.work = p.work; return result.status as i32; } + output[i].ty = 0; output[i].operation = 0; i += 1; + } + i = 0; + while (i < function_count) { + var index: u64 = edges[functions + i]; + if (!ir_hir_node(&p, index, 0)) { result.work = p.work; return result.status as i32; } + var n: ptr = &nodes[index]; + if (n.tag != 0) { result.status = 3; result.node = index; break; } + if (n.g != 0) { result.status = 5; result.node = index; result.detail = 3; break; } + if (n.b > edge_count || n.c > edge_count - n.b) { result.status = 3; result.node = index; break; } + var previous: u64 = 0; + while (previous < i) { + if (!ir_hir_charge(&p, 1, index)) { break; } + if (nodes[edges[functions + previous]].a == n.a) { + ir_hir_fail(&p, 9, index, n.a); break; + } + previous += 1; + } + if (result.status != 0) { break; } + if (!ir_hir_type(&p, n.d, &p.return_type)) { break; } + p.binding_count = 0; + var param: u64 = 0; + while (param < n.c) { + var parameter: u64 = edges[n.b + param]; + if (!ir_hir_node(&p, parameter, 0)) { break; } + if (nodes[parameter].tag != 1) { ir_hir_fail(&p, 3, parameter, 0); break; } + var ty: u64 = 0; + if (!ir_hir_type(&p, nodes[parameter].b, &ty)) { break; } + if (ty == 0) { ir_hir_fail(&p, 4, parameter, 0); break; } + previous = 0; + while (previous < p.binding_count) { + if (!ir_hir_charge(&p, 1, parameter)) { break; } + if (bindings[previous].name == nodes[parameter].a) { + ir_hir_fail(&p, 9, parameter, nodes[parameter].a); break; + } + previous += 1; + } + if (result.status != 0 || !ir_hir_bind(&p, nodes[parameter].a, ty, parameter)) { break; } + param += 1; + } + if (result.status != 0 || !ir_hir_statements(&p, n.e, n.f, 1)) { break; } + i += 1; + } + result.work = p.work; + return result.status as i32; +} diff --git a/ir/lower_limits.wave b/ir/lower_limits.wave new file mode 100644 index 0000000..3edb960 --- /dev/null +++ b/ir/lower_limits.wave @@ -0,0 +1,138 @@ +// SPDX-License-Identifier: MPL-2.0 +// Streaming AST admission, feature gates, numeric syntax and source identities. +struct IrAstInspectState { nodes: u64; strings: u64; features: u64; numbers: u64; sources: u64; work: u64; } + +struct IrAstInspectEvent { tag: u64; a: u64; b: u64; c: u64; d: u64; e: u64; f: u64; bytes: ptr; length: u64; } + +struct IrAstInspectSlot { id: u64; occupied: u64; } + +struct IrAstInspectResult { status: u64; } + +fun ir_ast_inspect_width(bits: u64) -> bool { + return bits == 1 || bits == 8 || bits == 16 || bits == 32 || bits == 64 || bits == 128; +} + +fun ir_ast_inspect_strings(state: ptr, length: u64, limit: u64) -> i32 { + if (state.strings > limit || length > limit - state.strings) { return 4; } + state.strings += length; return 0; +} + +fun ir_ast_inspect_probe(slots: ptr, capacity: u64, id: u64, + state: ptr, max_work: u64) -> u64 { + var at: u64 = ir_source_mix(id) & (capacity - 1); + while (true) { + if (!ir_cfg_charge(&state.work, max_work)) { return capacity; } + if (slots[at].occupied == 0 || slots[at].id == id) { return at; } + at = (at + 1) & (capacity - 1); + } + return capacity; +} + +export(c) fun whale_ir_ast_inspect_rehash(state: ptr, + old: ptr, old_capacity: u64, + slots: ptr, capacity: u64, max_work: u64, + result: ptr) -> i32 { + if (result == null) { return 8; } + result.status = 8; + if (state == null || state.work > max_work || capacity < 2 || !ir_power_two(capacity) + || old_capacity > capacity || state.sources > capacity / 2 + || !ir_span_valid(old as ptr, old_capacity, 16) + || !ir_span_valid(slots as ptr, capacity, 16)) { return 8; } + var i: u64 = 0; + while (i < capacity) { + if (!ir_cfg_charge(&state.work, max_work)) { result.status = 7; return 7; } + slots[i].occupied = 0; i += 1; + } + i = 0; var copied: u64 = 0; + while (i < old_capacity) { + if (old[i].occupied > 1) { return 8; } + if (old[i].occupied == 1) { + var at: u64 = ir_ast_inspect_probe(slots, capacity, old[i].id, state, max_work); + if (at == capacity) { result.status = 7; return 7; } + if (slots[at].occupied != 0) { return 8; } + slots[at].id = old[i].id; slots[at].occupied = 1; copied += 1; + } + i += 1; + } + if (copied != state.sources) { return 8; } + result.status = 0; return 0; +} + +export(c) fun whale_ir_ast_inspect_step(state: ptr, + event: ptr, max_depth: u64, max_nodes: u64, max_strings: u64, + max_source_work: u64, slots: ptr, capacity: u64, + result: ptr) -> i32 { + if (result == null) { return 8; } + result.status = 8; + if (state == null || event == null || state.features > 7 || state.numbers > 1 + || state.nodes > max_nodes || state.strings > max_strings + || state.work > max_source_work) { return 8; } + var status: i32 = 0; + if (event.tag <= 1) { + var depth: u64 = max_depth; if (depth > 32) { depth = 32; } + if (event.tag == 1 && event.a > depth) { status = 2; } + else if (state.nodes >= max_nodes) { status = 3; } + else { state.nodes += 1; } + } else if (event.tag == 2) { status = ir_ast_inspect_strings(state, event.length, max_strings); } + else if (event.tag == 3) { + // Source form: 1 struct type, 2 storage/expression, 3 store, 4 bit_not, 5 binary. + if (event.a >= 1 && event.a <= 3) { state.features = state.features | 4; } + else if (event.a == 4 || (event.a == 5 && event.b > 2 && event.b <= 11)) { state.features = state.features | 1; } + else if (event.a != 5 || event.b > 11) { status = 8; } + } else if (event.tag >= 4 && event.tag <= 7) { + var valid: bool = ir_ast_inspect_width(event.a); + if (event.tag == 5 || event.tag == 7) { valid = event.a == 16 || event.a == 32 || event.a == 64; } + if (event.tag >= 6) { + status = ir_ast_inspect_strings(state, event.length, max_strings); + if (status == 0) { + if (!ir_span_valid(event.bytes, event.length, 1)) { status = 8; } + else if (event.tag == 6) { + var at: u64 = 0; + if (event.length > 0 && event.bytes[0] == 45) { at = 1; } + if (at == event.length) { valid = false; } + while (at < event.length) { + if (event.bytes[at] < 48 || event.bytes[at] > 57) { valid = false; } + at += 1; + } + } else if (event.length != 2 + event.a / 4 || event.length < 2) { valid = false; } + else if (event.bytes[0] != 48 || event.bytes[1] != 120) { valid = false; } + else { + var at: u64 = 2; + while (at < event.length) { + var b: u8 = event.bytes[at]; + if (!((b >= 48 && b <= 57) || (b >= 65 && b <= 70) || (b >= 97 && b <= 102))) { valid = false; } + at += 1; + } + } + } + } + if (!valid) { state.numbers = 0; } + } else if (event.tag == 8) { + if (event.b > 1 || capacity < 2 || !ir_power_two(capacity) + || state.sources >= capacity / 2 + || !ir_span_valid(slots as ptr, capacity, 16)) { status = 8; } + else { + var at: u64 = ir_ast_inspect_probe(slots, capacity, event.a, state, max_source_work); + if (at == capacity) { status = 7; } + else if (slots[at].occupied != 0) { status = 1; } + else { + slots[at].id = event.a; slots[at].occupied = 1; state.sources += 1; state.features = state.features | 2; + if (event.b == 1) { + status = ir_ast_inspect_strings(state, event.length, max_strings); + if (status == 0) { + if (!ir_span_valid(event.bytes, event.length, 1)) { status = 8; } + else if (event.length == 0 || event.c == 0 || event.d == 0 || event.e == 0 || event.f == 0 + || event.c > event.e || (event.c == event.e && event.d > event.f)) { status = 1; } + else if (event.length > max_source_work - state.work) { status = 7; } + else { + state.work += event.length; + var i: u64 = 0; + while (i < event.length) { if (event.bytes[i] == 0) { status = 1; } i += 1; } + } + } + } + } + } + } else { status = 8; } + result.status = status as u64; return status; +} diff --git a/ir/lower_model.wave b/ir/lower_model.wave new file mode 100644 index 0000000..5522a98 --- /dev/null +++ b/ir/lower_model.wave @@ -0,0 +1,325 @@ +// SPDX-License-Identifier: MPL-2.0 +// Private flat frontend/output storage for O0 lowering. Types are canonical +// structural identities; field names remain source layout facts, not IR types. +struct IrLowerNode { tag: u64; a: u64; b: u64; c: u64; d: u64; e: u64; f: u64; g: u64; h: u64; i: u64; j: u64; k: u64; } + +struct IrLowerString { data: ptr; length: u64; } + +struct IrLowerType { kind: u64; child: u64; first: u64; count: u64; auxiliary: u64; } + +struct IrLowerValue { value: u64; ty: u64; } + +struct IrLowerBinding { name: u64; ty: u64; value: u64; kind: u64; constant: u64; } + +struct IrLowerResult { status: u64; node: u64; expected: u64; actual: u64; annotation: u64; detail: u64; work: u64; } + +struct IrLowerContext { + nodes: ptr; node_count: u64; + edges: ptr; edge_count: u64; + names: ptr; name_count: u64; + types: ptr; type_count: u64; type_capacity: u64; + type_edges: ptr; type_edge_count: u64; type_edge_capacity: u64; + type_table: ptr; type_table_capacity: u64; type_map: ptr; + temporary: ptr; temporary_count: u64; temporary_capacity: u64; + name_marks: ptr; marker: u64; + storage: ptr; layout_nodes: ptr; + layouts: ptr; layout_offsets: ptr; + annotation: u64; max_depth: u64; max_work: u64; work: u64; + result: ptr; +} + +fun ir_lower_fail(p: ptr, status: u64, node: u64, + expected: u64, actual: u64, detail: u64) -> bool { + p.result.status = status; p.result.node = node; + p.result.expected = expected; p.result.actual = actual; + p.result.detail = detail; p.result.annotation = p.annotation; + return false; +} + +fun ir_lower_charge(p: ptr, amount: u64, node: u64) -> bool { + if (amount > p.max_work - p.work) { return ir_lower_fail(p, 1, node, 0, 0, 0); } + p.work += amount; return true; +} + +fun ir_lower_node(p: ptr, node: u64, depth: u64) -> bool { + if (depth > p.max_depth) { return ir_lower_fail(p, 2, node, 0, 0, 0); } + if (!ir_lower_charge(p, 1, node)) { return false; } + if (node >= p.node_count) { return ir_lower_fail(p, 3, node, 0, 0, 0); } + return true; +} + +fun ir_lower_edges(p: ptr, first: u64, count: u64, node: u64) -> bool { + if (first > p.edge_count || count > p.edge_count - first) { + return ir_lower_fail(p, 3, node, 0, 0, 0); + } + return true; +} + +fun ir_lower_name(p: ptr, name: u64, node: u64) -> bool { + if (name >= p.name_count) { return ir_lower_fail(p, 3, node, 0, 0, 0); } + return true; +} + +fun ir_lower_integer(ty: u64) -> bool { return ty >= 2 && ty <= 13; } + +fun ir_lower_signed(ty: u64) -> bool { return ty == 2 || (ty >= 4 && ty <= 8); } + +fun ir_lower_float(ty: u64) -> bool { return ty >= 14 && ty <= 16; } + +fun ir_lower_scalar(p: ptr, ty: u64) -> bool { + return ty != 0 && ty < p.type_count && p.types[ty].kind <= 18; +} + +fun ir_lower_aggregate(p: ptr, ty: u64) -> bool { + return p.types[ty].kind == 19 || p.types[ty].kind == 20; +} + +fun ir_lower_width(ty: u64) -> u64 { + if (ty == 2 || ty == 3) { return 1; } + if (ty >= 9 && ty <= 13) { ty -= 5; } + if (ty == 4) { return 8; } + if (ty == 5) { return 16; } + if (ty == 6 || ty == 15) { return 32; } + if (ty == 7 || ty == 16) { return 64; } + if (ty == 8) { return 128; } + if (ty == 14) { return 16; } + return 0; +} + +fun ir_lower_layout_kind(kind: u64) -> u64 { + if (kind == 0) { return 0; } + if (kind <= 4 || kind == 9) { return 1; } + if (kind == 5 || kind == 10 || kind == 14) { return 2; } + if (kind == 6 || kind == 11 || kind == 15) { return 3; } + if (kind == 7 || kind == 12 || kind == 16) { return 4; } + if (kind == 8 || kind == 13) { return 5; } + if (kind == 17) { return 6; } + if (kind == 18) { return 7; } + if (kind == 19) { return 8; } + if (kind == 20) { return 9; } + return 10; +} + +fun ir_lower_mix(value: u64) -> u64 { + value = (value ^ (value >> 30)) * 13787848793156543929; + value = (value ^ (value >> 27)) * 10723151780598845931; + return value ^ (value >> 31); +} + +fun ir_lower_type_intern(p: ptr, kind: u64, child: u64, + children: ptr, count: u64, auxiliary: u64, node: u64, output: ptr) -> bool { + var hash: u64 = kind ^ (child << 7) ^ (child >> 57) ^ auxiliary ^ (count << 21); + var at: u64 = 0; + while (at < count) { + if (!ir_lower_charge(p, 1, node)) { return false; } + hash = (hash << 5) ^ (hash >> 59) ^ children[at]; at += 1; + } + var slot: u64 = ir_lower_mix(hash) & (p.type_table_capacity - 1); + var visited: u64 = 0; + while (visited < p.type_table_capacity) { + if (!ir_lower_charge(p, 1, node)) { return false; } + var entry: u64 = p.type_table[slot]; + if (entry == 0) { + if (p.type_count >= p.type_capacity + || count > p.type_edge_capacity - p.type_edge_count) { + return ir_lower_fail(p, 4, node, 0, 0, 0); + } + var id: u64 = p.type_count; + p.types[id].kind = kind; p.types[id].child = child; + p.types[id].first = p.type_edge_count; p.types[id].count = count; + p.types[id].auxiliary = auxiliary; + at = 0; + while (at < count) { + p.type_edges[p.type_edge_count + at] = children[at]; + p.layout_offsets[p.type_edge_count + at] = 0; + at += 1; + } + p.layout_nodes[id].kind = ir_lower_layout_kind(kind); + p.layout_nodes[id].child = child; + p.layout_nodes[id].first = p.type_edge_count; + p.layout_nodes[id].count = count; + if (kind == 19) { p.layout_nodes[id].count = auxiliary; } + if (kind == 17 || kind == 18) { p.layout_nodes[id].child = id; } + p.layouts[id].size = 0; p.layouts[id].align = 0; p.layouts[id].stride = 0; + p.layouts[id].allocation_align = 0; p.layouts[id].depth = 0; + p.type_edge_count += count; p.type_count += 1; + p.type_table[slot] = id + 1; output[0] = id; return true; + } + var id: u64 = entry - 1; + var same: bool = p.types[id].kind == kind && p.types[id].child == child + && p.types[id].count == count && p.types[id].auxiliary == auxiliary; + at = 0; + while (same && at < count) { + if (!ir_lower_charge(p, 1, node)) { return false; } + same = p.type_edges[p.types[id].first + at] == children[at]; at += 1; + } + if (same) { output[0] = id; return true; } + slot = (slot + 1) & (p.type_table_capacity - 1); visited += 1; + } + return ir_lower_fail(p, 4, node, 0, 0, 0); +} + +fun ir_lower_pointer(p: ptr, child: u64, node: u64, output: ptr) -> bool { + return ir_lower_type_intern(p, 17, child, null, 0, 0, node, output); +} + +fun ir_lower_type(p: ptr, node: u64, depth: u64, output: ptr) -> bool { + if (!ir_lower_node(p, node, depth)) { return false; } + if (p.type_map[node] != 18446744073709551615) { output[0] = p.type_map[node]; return true; } + var n: ptr = &p.nodes[node]; + var ty: u64 = 0; + var child: u64 = 0; + if (n.tag == 100) { ty = 0; } + else if (n.tag == 101) { ty = 1; } + else if (n.tag == 102) { + if (n.b > 1) { return ir_lower_fail(p, 3, node, 0, 0, 0); } + if (n.a == 1) { ty = 2; } + else if (n.a == 8) { ty = 4; } + else if (n.a == 16) { ty = 5; } + else if (n.a == 32) { ty = 6; } + else if (n.a == 64) { ty = 7; } + else if (n.a == 128) { ty = 8; } + else { return ir_lower_fail(p, 5, node, 0, 0, 0); } + if (n.b == 0) { if (ty == 2) { ty = 3; } else { ty += 5; } } + } else if (n.tag == 103) { + if (n.a == 16) { ty = 14; } + else if (n.a == 32) { ty = 15; } + else if (n.a == 64) { ty = 16; } + else { return ir_lower_fail(p, 5, node, 0, 0, 0); } + } else if (n.tag == 104 || n.tag == 106) { + if (!ir_lower_type(p, n.a, depth + 1, &child)) { return false; } + if (n.tag == 104) { + if (!ir_lower_pointer(p, child, node, &ty)) { return false; } + } else if (!ir_lower_type_intern(p, 19, child, null, 0, n.b, node, &ty)) { return false; } + } else if (n.tag == 105) { + if (!ir_lower_type(p, n.a, depth + 1, &ty)) { return false; } + if (p.types[ty].kind != 18) { return ir_lower_fail(p, 3, node, 0, 0, 0); } + } else if (n.tag == 107 || n.tag == 110) { + if (!ir_lower_edges(p, n.a, n.b, node)) { return false; } + var saved: u64 = p.temporary_count; + var at: u64 = 0; + var marker: u64 = p.marker; + p.marker += 1; + // Check all sibling names before recursively mapping child types; a + // nested struct may legitimately reuse the same interned field name. + if (n.tag == 107) { + while (at < n.b) { + var field: u64 = p.edges[n.a + at]; + if (!ir_lower_node(p, field, depth + 1)) { return false; } + if (p.nodes[field].tag != 108) { return ir_lower_fail(p, 3, field, 0, 0, 0); } + var field_name: u64 = p.nodes[field].a; + if (!ir_lower_name(p, field_name, field)) { return false; } + if (p.names[field_name].length == 0 || p.name_marks[field_name] == marker) { + return ir_lower_fail(p, 18, field, 0, 0, 1); + } + p.name_marks[field_name] = marker; + at += 1; + } + at = 0; + } + while (at < n.b) { + var source: u64 = p.edges[n.a + at]; + if (n.tag == 107) { + if (!ir_lower_node(p, source, depth + 1)) { return false; } + if (p.nodes[source].tag != 108) { return ir_lower_fail(p, 3, source, 0, 0, 0); } + source = p.nodes[source].b; + } + if (!ir_lower_type(p, source, depth + 1, &child)) { return false; } + if (n.tag == 107 && !ir_lower_scalar(p, child)) { + return ir_lower_fail(p, 18, source, 0, 0, 2); + } + if (n.tag == 110 && (child == 0 || (n.d == 1 && ir_lower_aggregate(p, child)))) { + return ir_lower_fail(p, 21, source, 0, 0, 1); + } + if (p.temporary_count >= p.temporary_capacity) { return ir_lower_fail(p, 4, node, 0, 0, 0); } + p.temporary[p.temporary_count] = child; p.temporary_count += 1; + at += 1; + } + var kind: u64 = 20; + var auxiliary: u64 = 0; + child = 0; + if (n.tag == 110) { + kind = 18; + if (n.d > 1 || n.e != 0) { return ir_lower_fail(p, 21, node, 0, 0, 1); } + auxiliary = n.d; + if (!ir_lower_type(p, n.c, depth + 1, &child)) { return false; } + } + if (!ir_lower_type_intern(p, kind, child, &p.temporary[saved], n.b, + auxiliary, node, &ty)) { return false; } + p.temporary_count = saved; + } else if (n.tag == 109) { return ir_lower_fail(p, 5, node, 0, 0, 1); } + else { return ir_lower_fail(p, 3, node, 0, 0, 0); } + p.type_map[node] = ty; output[0] = ty; return true; +} + +fun ir_lower_layout(p: ptr, ty: u64, node: u64) -> bool { + var remaining: u64 = p.max_work - p.work; + var status: i32 = ir_layout_node(ty, p.layout_nodes, p.type_count, + p.type_edges, p.type_edge_count, p.storage, p.max_depth, + p.layouts, p.layout_offsets, &remaining); + p.work = p.max_work - remaining; + if (status == 6) { return ir_lower_fail(p, 1, node, 0, 0, 0); } + if (status != 0) { return ir_lower_fail(p, 20, node, ty, 0, status as u64); } + return true; +} + +fun ir_lower_initialize(p: ptr) -> bool { + if (p == null || p.result == null) { return false; } + p.result.status = 0; p.result.node = 0; p.result.expected = 0; p.result.actual = 0; + p.result.annotation = 18446744073709551615; p.result.detail = 0; p.result.work = 0; + p.work = 0; p.annotation = 18446744073709551615; + if (!ir_span_valid(p.nodes as ptr, p.node_count, 96) + || !ir_span_valid(p.edges as ptr, p.edge_count, 8) + || !ir_span_valid(p.names as ptr, p.name_count, 16) + || !ir_span_valid(p.types as ptr, p.type_capacity, 40) + || !ir_span_valid(p.type_edges as ptr, p.type_edge_capacity, 8) + || !ir_span_valid(p.type_table as ptr, p.type_table_capacity, 8) + || !ir_span_valid(p.type_map as ptr, p.node_count, 8) + || !ir_span_valid(p.temporary as ptr, p.temporary_capacity, 8) + || !ir_span_valid(p.name_marks as ptr, p.name_count, 8) + || !ir_span_valid(p.layout_nodes as ptr, p.type_capacity, 32) + || !ir_span_valid(p.layouts as ptr, p.type_capacity, 40) + || !ir_span_valid(p.layout_offsets as ptr, p.type_edge_capacity, 8) + || !ir_storage_valid(p.storage) || !ir_power_two(p.type_table_capacity) + || p.type_capacity < 17 || p.max_depth > 32) { + return ir_lower_fail(p, 3, 0, 0, 0, 0); + } + p.type_count = 17; p.type_edge_count = 0; p.temporary_count = 0; p.marker = 1; + var at: u64 = 0; + while (at < 17) { + if (!ir_lower_charge(p, 1, 0)) { return false; } + p.types[at].kind = at; p.types[at].child = 0; p.types[at].first = 0; + p.types[at].count = 0; p.types[at].auxiliary = 0; + p.layout_nodes[at].kind = ir_lower_layout_kind(at); + p.layout_nodes[at].child = 0; p.layout_nodes[at].first = 0; p.layout_nodes[at].count = 0; + p.layouts[at].size = 0; p.layouts[at].align = 0; p.layouts[at].stride = 0; + p.layouts[at].allocation_align = 0; p.layouts[at].depth = 0; at += 1; + } + at = 0; + while (at < p.type_table_capacity) { + if (!ir_lower_charge(p, 1, 0)) { return false; } + p.type_table[at] = 0; at += 1; + } + at = 0; + while (at < p.node_count) { + if (!ir_lower_charge(p, 1, at)) { return false; } + p.type_map[at] = 18446744073709551615; at += 1; + } + at = 0; + while (at < p.name_count) { + if (!ir_lower_charge(p, 1, 0)) { return false; } + p.name_marks[at] = 0; at += 1; + } + return true; +} + +// Native conformance probe shares the same canonical model and Wave layout +// routines as the complete O0 lowering driver. The output ID is transactional. +export(c) fun whale_ir_lower_type(p: ptr, node: u64, output: ptr) -> i32 { + if (p == null || p.result == null || output == null) { return 3; } + if (!ir_lower_initialize(p)) { p.result.work = p.work; return p.result.status as i32; } + var ty: u64 = 0; + if (!ir_lower_type(p, node, 0, &ty)) { p.result.work = p.work; return p.result.status as i32; } + if (!ir_lower_layout(p, ty, node)) { p.result.work = p.work; return p.result.status as i32; } + output[0] = ty; p.result.work = p.work; return 0; +} diff --git a/ir/lower_output.wave b/ir/lower_output.wave new file mode 100644 index 0000000..f56cc51 --- /dev/null +++ b/ir/lower_output.wave @@ -0,0 +1,264 @@ +// SPDX-License-Identifier: MPL-2.0 +// Typed O0 output is a caller-owned flat model. Wave chooses every identity, +// body link, hoisted allocation position and source identity before Rust reads it. +struct IrLowerInstruction { + tag: u64; dst: u64; ty: u64; a: u64; b: u64; c: u64; d: u64; e: u64; + first: u64; count: u64; next: u64; annotation: u64; source: u64; +} + +struct IrLowerBlock { + id: u64; function: u64; name: u64; first: u64; last: u64; allocation_last: u64; + instruction_count: u64; term_kind: u64; term_a: u64; term_b: u64; term_c: u64; + term_ty: u64; term_annotation: u64; term_source: u64; +} + +struct IrLowerConstant { + kind: u64; operation: u64; ty: u64; low: u64; high: u64; + left: u64; right: u64; reference: u64; annotation: u64; +} + +struct IrLowerDeclaration { name: u64; signature: u64; linkage: u64; link_name: u64; defined: u64; source: u64; } + +struct IrLowerFunction { declaration: u64; first_param: u64; param_count: u64; first_block: u64; block_count: u64; entry: u64; source: u64; } + +struct IrLowerGlobal { name: u64; ty: u64; expression: u64; align: u64; annotation: u64; source: u64; } + +struct IrLowerFieldBinding { name: u64; ordinal: u64; previous: u64; used: u64; } + +struct IrLowerLoop { condition: u64; exit: u64; } + +struct IrLowerAnnotation { original: u64; has_source: u64; file: u64; line: u64; column: u64; end_line: u64; end_column: u64; } + +struct IrLowerOriginalSlot { id: u64; occupied: u64; } + +struct IrLowerEvalRequest { expression: u64; kind: u64; identity: u64; annotation: u64; } + +struct IrLowerDriver { + core: ptr; mode: u64; expansion: u64; max_expansion: u64; + instructions: ptr; instruction_count: u64; instruction_capacity: u64; + output_edges: ptr; output_edge_count: u64; output_edge_capacity: u64; + blocks: ptr; block_count: u64; block_capacity: u64; + constants: ptr; + declarations: ptr; declaration_count: u64; declaration_capacity: u64; + functions: ptr; function_count: u64; function_capacity: u64; + globals: ptr; global_count: u64; global_capacity: u64; + global_bindings: ptr; global_binding_count: u64; + bindings: ptr; binding_count: u64; binding_capacity: u64; + loops: ptr; loop_count: u64; loop_capacity: u64; + annotations: ptr; annotation_count: u64; + original_table: ptr; original_capacity: u64; + source_order: ptr; source_count: u64; source_capacity: u64; source_marks: ptr; + type_sizes: ptr; value_types: ptr; value_capacity: u64; next_value: u64; + declaration_map: ptr; + field_slots: ptr; field_bindings: ptr; + field_binding_count: u64; field_binding_capacity: u64; + current_function: u64; current_block: u64; entry: u64; return_type: u64; + local_slots: ptr; global_slots: ptr; + mapping_order: ptr; mapping_count: u64; mapping_capacity: u64; + source_work: u64; max_source_work: u64; error_index: u64; + requests: ptr; request_count: u64; request_capacity: u64; +} + +fun ir_lower_source_charge(p: ptr, amount: u64, node: u64) -> bool { + if (amount > p.max_source_work - p.source_work) { + return ir_lower_fail(p.core, 22, node, 0, 0, 0); + } + p.source_work += amount; return ir_lower_charge(p.core, amount, node); +} + +fun ir_lower_expand(p: ptr, amount: u64, node: u64) -> bool { + if (!ir_lower_charge(p.core, amount, node)) { return false; } + if (amount > p.max_expansion - p.expansion) { + return ir_lower_fail(p.core, 23, node, 0, 0, 0); + } + p.expansion += amount; return true; +} + +fun ir_lower_type_size(p: ptr, ty: u64, node: u64, depth: u64, size: ptr) -> bool { + if (ty >= p.core.type_count || depth > 32) { return ir_lower_fail(p.core, 3, node, 0, 0, 0); } + if (!ir_lower_charge(p.core, 1, node)) { return false; } + if (p.type_sizes[ty] != 0) { size[0] = p.type_sizes[ty]; return true; } + var count: u64 = 1; + var child: u64 = 0; + var t: ptr = &p.core.types[ty]; + if (t.kind == 17 || t.kind == 18 || t.kind == 19) { + if (!ir_lower_type_size(p, t.child, node, depth + 1, &child)) { return false; } + count += child; + } + var at: u64 = 0; + if (t.kind == 18 || t.kind == 20 || t.kind == 21) { + while (at < t.count) { + if (!ir_lower_type_size(p, p.core.type_edges[t.first + at], node, depth + 1, &child)) { return false; } + if (child > p.max_expansion - count) { return ir_lower_fail(p.core, 23, node, 0, 0, 0); } + count += child; at += 1; + } + } + p.type_sizes[ty] = count; size[0] = count; return true; +} + +fun ir_lower_value(p: ptr, ty: u64, node: u64, output: ptr) -> bool { + var size: u64 = 0; + if (!ir_lower_type_size(p, ty, node, 0, &size) || !ir_lower_expand(p, 1 + size, node)) { return false; } + if (p.next_value >= 4294967295) { return ir_lower_fail(p.core, 23, node, 0, 0, 0); } + if (p.mode == 1) { + if (p.next_value >= p.value_capacity) { return ir_lower_fail(p.core, 4, node, 0, 0, 0); } + p.value_types[p.next_value] = ty; + } + output[0] = p.next_value; p.next_value += 1; return true; +} + +fun ir_lower_block(p: ptr, name: u64, node: u64, output: ptr) -> bool { + if (!ir_lower_expand(p, 1, node)) { return false; } + if (p.block_count >= p.block_capacity || p.block_count >= 4294967295) { + return ir_lower_fail(p.core, 4, node, 0, 0, 0); + } + var id: u64 = p.block_count; + p.blocks[id].id = id; p.blocks[id].function = p.current_function; p.blocks[id].name = name; + p.blocks[id].first = 18446744073709551615; p.blocks[id].last = 18446744073709551615; + p.blocks[id].allocation_last = 18446744073709551615; + p.blocks[id].instruction_count = 0; p.blocks[id].term_kind = 0; + p.blocks[id].term_a = 0; p.blocks[id].term_b = 0; p.blocks[id].term_c = 0; + p.blocks[id].term_ty = 0; p.blocks[id].term_annotation = 18446744073709551615; + p.blocks[id].term_source = node; p.block_count += 1; output[0] = id; return true; +} + +fun ir_lower_emit(p: ptr, tag: u64, dst: u64, ty: u64, + a: u64, b: u64, c: u64, d: u64, e: u64, edges: ptr, count: u64, + hoisted: bool, node: u64) -> bool { + var type_size: u64 = 0; + if (ty != 18446744073709551615 + && !ir_lower_type_size(p, ty, node, 0, &type_size)) { return false; } + if (!ir_lower_expand(p, 1 + type_size, node) + || !ir_lower_charge(p.core, count, node)) { return false; } + if (p.core.annotation != 18446744073709551615 + && !ir_lower_source_charge(p, 1, node)) { return false; } + var block: u64 = p.current_block; + if (hoisted) { block = p.entry; } + if (block >= p.block_count || (p.blocks[block].term_kind != 0 && !hoisted)) { + return ir_lower_fail(p.core, 3, node, 0, 0, 0); + } + if (p.mode == 1) { + if (p.instruction_count >= p.instruction_capacity + || count > p.output_edge_capacity - p.output_edge_count) { + return ir_lower_fail(p.core, 4, node, 0, 0, 0); + } + var id: u64 = p.instruction_count; + var record: ptr = &p.instructions[id]; + record.tag = tag; record.dst = dst; record.ty = ty; record.a = a; record.b = b; record.c = c; + record.d = d; record.e = e; record.first = p.output_edge_count; record.count = count; + record.next = 18446744073709551615; record.annotation = p.core.annotation; record.source = node; + var at: u64 = 0; + while (at < count) { p.output_edges[p.output_edge_count + at] = edges[at]; at += 1; } + // Hoisting is Wave's linked-list operation, independent of when Rust + // later allocates the compatibility vectors for the completed module. + var last: u64 = p.blocks[block].last; + var allocation_last: u64 = p.blocks[block].allocation_last; + if (hoisted) { + if (allocation_last == 18446744073709551615) { + record.next = p.blocks[block].first; p.blocks[block].first = id; + } else { + record.next = p.instructions[allocation_last].next; + p.instructions[allocation_last].next = id; + } + p.blocks[block].allocation_last = id; + if (last == 18446744073709551615 || last == allocation_last) { p.blocks[block].last = id; } + } else { + if (last == 18446744073709551615) { p.blocks[block].first = id; } + else { p.instructions[last].next = id; } + p.blocks[block].last = id; + } + } + if (count > 18446744073709551615 - p.output_edge_count) { return ir_lower_fail(p.core, 23, node, 0, 0, 0); } + p.output_edge_count += count; p.instruction_count += 1; + p.blocks[block].instruction_count += 1; return true; +} + +fun ir_lower_term(p: ptr, kind: u64, ty: u64, a: u64, + b: u64, c: u64, node: u64) -> bool { + if (!ir_lower_expand(p, 1, node)) { return false; } + if (p.current_block >= p.block_count || p.blocks[p.current_block].term_kind != 0) { + return ir_lower_fail(p.core, 3, node, 0, 0, 0); + } + if (p.core.annotation != 18446744073709551615 + && !ir_lower_source_charge(p, 1, node)) { return false; } + var block: ptr = &p.blocks[p.current_block]; + block.term_kind = kind; block.term_ty = ty; block.term_a = a; block.term_b = b; + block.term_c = c; block.term_annotation = p.core.annotation; block.term_source = node; return true; +} + +fun ir_lower_source(p: ptr, annotation: u64, node: u64) -> bool { + if (annotation >= p.annotation_count) { return ir_lower_fail(p.core, 3, node, 0, 0, 0); } + if (!ir_lower_source_charge(p, 1, node)) { return false; } + if (p.source_marks[annotation] != 0) { return true; } + var source: ptr = &p.annotations[annotation]; + if (source.has_source != 0) { + if (!ir_lower_name(p.core, source.file, node) + || !ir_lower_source_charge(p, p.core.names[source.file].length, node)) { return false; } + } + if (p.mode == 1) { + if (p.source_count >= p.source_capacity) { return ir_lower_fail(p.core, 4, node, 0, 0, 0); } + p.source_order[p.source_count] = annotation; + } + p.source_count += 1; p.source_marks[annotation] = 1; return true; +} + +// Binding.constant stores the previous local slot. Typed constant payloads are +// separate records, so a scope restores names by popping only its own bindings. +fun ir_lower_binding(p: ptr, name: u64, node: u64, + global_only: bool, output: ptr) -> bool { + if (!ir_lower_charge(p.core, 1, node) || !ir_lower_name(p.core, name, node)) { return false; } + var slot: u64 = 18446744073709551615; + if (!global_only) { slot = p.local_slots[name]; } + if (slot != 18446744073709551615) { output[0] = p.bindings[slot]; return true; } + slot = p.global_slots[name]; + if (slot != 18446744073709551615) { output[0] = p.global_bindings[slot]; return true; } + return ir_lower_fail(p.core, 11, node, 0, 0, name); +} + +fun ir_lower_bind(p: ptr, name: u64, ty: u64, value: u64, + kind: u64, constant: u64, node: u64) -> bool { + if (!ir_lower_charge(p.core, 1, node) || !ir_lower_name(p.core, name, node)) { return false; } + if (p.binding_count >= p.binding_capacity) { return ir_lower_fail(p.core, 4, node, 0, 0, 0); } + var at: u64 = p.binding_count; + p.bindings[at].name = name; p.bindings[at].ty = ty; p.bindings[at].value = value; + p.bindings[at].kind = kind; p.bindings[at].constant = p.local_slots[name]; + p.local_slots[name] = at; p.binding_count += 1; return true; +} + +fun ir_lower_restore(p: ptr, saved: u64, node: u64) -> bool { + while (p.binding_count > saved) { + if (!ir_lower_charge(p.core, 1, node)) { return false; } + p.binding_count -= 1; + var binding: ptr = &p.bindings[p.binding_count]; + p.local_slots[binding.name] = binding.constant; + } + return true; +} + +fun ir_lower_local_binding(p: ptr, name: u64, node: u64, + output: ptr) -> bool { + if (!ir_lower_charge(p.core, 1, node) || !ir_lower_name(p.core, name, node)) { return false; } + var slot: u64 = p.local_slots[name]; + if (slot != 18446744073709551615) { output[0] = p.bindings[slot]; return true; } + return ir_lower_fail(p.core, 11, node, 0, 0, name); +} + +fun ir_lower_complete_source(p: ptr, annotation: u64, node: u64) -> bool { + if (!ir_lower_source(p, annotation, node)) { return false; } + if (p.mode == 1) { + if (p.mapping_count >= p.mapping_capacity) { return ir_lower_fail(p.core, 4, node, 0, 0, 0); } + p.mapping_order[p.mapping_count] = annotation; + } + p.mapping_count += 1; return true; +} + +// A completed constexpr is evaluated by the central numeric engine before a +// later AST error is reported. Partial preservation never publishes a request. +fun ir_lower_evaluate_request(p: ptr, expression: u64, kind: u64, + identity: u64, node: u64) -> bool { + if (p.request_count >= p.request_capacity) { return ir_lower_fail(p.core, 4, node, 0, 0, 0); } + var record: ptr = &p.requests[p.request_count]; + record.expression = expression; record.kind = kind; record.identity = identity; + record.annotation = p.core.annotation; p.request_count += 1; + return ir_lower_charge(p.core, 1, node); +} diff --git a/ir/lower_statement.wave b/ir/lower_statement.wave new file mode 100644 index 0000000..c923983 --- /dev/null +++ b/ir/lower_statement.wave @@ -0,0 +1,147 @@ +// SPDX-License-Identifier: MPL-2.0 +// Wave owns lexical scope restoration and all O0 control-flow construction. +fun ir_lower_statements(p: ptr, first: u64, count: u64, + depth: u64, node: u64) -> bool { + if (!ir_lower_edges(p.core, first, count, node)) { return false; } + var at: u64 = 0; + while (at < count) { + if (!ir_lower_statement(p, p.core.edges[first + at], depth, node)) { return false; } + at += 1; + } + return true; +} + +fun ir_lower_statement(p: ptr, node: u64, depth: u64, parent: u64) -> bool { + if (!ir_lower_node(p.core, node, depth)) { return false; } + if (p.blocks[p.current_block].term_kind != 0) { + var dead: u64 = 0; + if (!ir_lower_block(p, 1, node, &dead)) { return false; } + p.current_block = dead; + } + var n: ptr = &p.core.nodes[node]; + if (n.tag == 50) { + var saved_annotation: u64 = p.core.annotation; p.core.annotation = n.a; + var success: bool = ir_lower_statement(p, n.b, depth + 1, node) + && ir_lower_complete_source(p, n.a, node); + p.core.annotation = saved_annotation; return success; + } + var value: IrLowerValue; + var place: IrLowerValue; + var ty: u64 = 0; + var slot: u64 = 0; + if (n.tag == 51) { + if (p.return_type == 0) { + if (n.a != 18446744073709551615) { return ir_lower_fail(p.core, 15, node, 0, 0, 0); } + return ir_lower_term(p, 3, 0, 18446744073709551615, 0, 0, node); + } + if (n.a == 18446744073709551615) { return ir_lower_fail(p.core, 24, node, 0, 0, 0); } + if (!ir_lower_expression(p, n.a, depth + 1, false, &value)) { return false; } + if (value.ty != p.return_type) { return ir_lower_mismatch(p, n.a, p.return_type, value.ty); } + return ir_lower_term(p, 3, p.return_type, value.value, 0, 0, node); + } + if (n.tag == 52) { + if (!ir_lower_expression(p, n.a, depth + 1, false, &place)) { return false; } + if (p.core.types[place.ty].kind != 17) { return ir_lower_fail(p.core, 7, node, 0, 0, 0); } + ty = p.core.types[place.ty].child; + if (!ir_lower_scalar(p.core, ty)) { return ir_lower_fail(p.core, 7, node, 0, 0, 0); } + if (!ir_lower_expression(p, n.b, depth + 1, false, &value)) { return false; } + if (value.ty != ty) { return ir_lower_fail(p.core, 6, node, ty, value.ty, 0); } + if (!ir_lower_layout(p.core, ty, node)) { return false; } + return ir_lower_emit(p, 20, 18446744073709551615, ty, value.value, + place.value, p.core.layouts[ty].allocation_align, 0, 0, null, 0, false, node); + } + if (n.tag == 53) { + if (!ir_lower_place(p, n.a, depth + 1, &place) + || !ir_lower_expression(p, n.b, depth + 1, false, &value)) { return false; } + if (place.ty != value.ty) { return ir_lower_fail(p.core, 6, node, place.ty, value.ty, 0); } + return ir_lower_write(p, place.value, value.value, place.ty, node); + } + if (n.tag == 54) { + if (!ir_lower_name(p.core, n.a, node) || !ir_lower_type(p.core, n.b, 0, &ty) + || !ir_lower_preserve_constant(p, n.c, depth + 1, &value)) { return false; } + if (!ir_lower_evaluate_request(p, value.value, 1, p.next_value, node)) { return false; } + if (ty != value.ty) { return ir_lower_mismatch(p, n.c, ty, value.ty); } + if (!ir_lower_value(p, ty, node, &slot)) { return false; } + var saved: u64 = p.core.annotation; + if (p.core.nodes[n.c].tag == 0) { p.core.annotation = p.core.nodes[n.c].a; } + if (!ir_lower_emit(p, 3, slot, ty, n.a, value.value, 0, 0, 0, null, 0, false, node)) { return false; } + if (p.core.nodes[n.c].tag == 0 + && !ir_lower_complete_source(p, p.core.nodes[n.c].a, node)) { return false; } + p.core.annotation = saved; + return ir_lower_bind(p, n.a, ty, slot, 1, value.value, node); + } + if (n.tag == 55) { + if (!ir_lower_name(p.core, n.a, node) || !ir_lower_type(p.core, n.b, 0, &ty) + || !ir_lower_layout(p.core, ty, node)) { return false; } + var align: u64 = p.core.layouts[ty].allocation_align; + if (n.c != 18446744073709551615) { + if (!ir_lower_expression(p, n.c, depth + 1, false, &value)) { return false; } + if (value.ty != ty) { return ir_lower_mismatch(p, n.c, ty, value.ty); } + if (!ir_lower_alloca(p, ty, align, node, &slot) + || !ir_lower_write(p, slot, value.value, ty, node)) { return false; } + } else { + if (!ir_lower_alloca(p, ty, align, node, &slot) + || !ir_lower_emit(p, 22, 18446744073709551615, ty, + slot, align, 0, 0, 0, null, 0, false, node)) { return false; } + } + return ir_lower_bind(p, n.a, ty, slot, 0, 0, node); + } + if (n.tag == 56) { + if (!ir_lower_expression(p, n.b, depth + 1, false, &value)) { return false; } + var binding: IrLowerBinding; + if (!ir_lower_local_binding(p, n.a, node, &binding)) { return false; } + if (binding.kind != 0) { return ir_lower_fail(p.core, 12, node, 0, 0, n.a); } + if (binding.ty != value.ty) { return ir_lower_mismatch(p, n.b, binding.ty, value.ty); } + return ir_lower_write(p, binding.value, value.value, binding.ty, node); + } + if (n.tag == 57) { return ir_lower_expression(p, n.a, depth + 1, true, &value); } + if (n.tag == 58) { + if (!ir_lower_expression(p, n.a, depth + 1, false, &value)) { return false; } + if (value.ty != 1) { return ir_lower_mismatch(p, n.a, 1, value.ty); } + var then_block: u64 = 0; var else_block: u64 = 0; var continuation: u64 = 0; + if (!ir_lower_block(p, 2, node, &then_block) || !ir_lower_block(p, 3, node, &else_block) + || !ir_lower_block(p, 4, node, &continuation) + || !ir_lower_term(p, 2, 0, value.value, then_block, else_block, node)) { return false; } + var saved_bindings: u64 = p.binding_count; + p.current_block = then_block; + if (!ir_lower_statements(p, n.b, n.c, depth + 1, node)) { return false; } + if (p.blocks[p.current_block].term_kind == 0 + && !ir_lower_term(p, 1, 0, continuation, 0, 0, node)) { return false; } + if (!ir_lower_restore(p, saved_bindings, node)) { return false; } + p.current_block = else_block; + if (!ir_lower_statements(p, n.d, n.e, depth + 1, node)) { return false; } + if (p.blocks[p.current_block].term_kind == 0 + && !ir_lower_term(p, 1, 0, continuation, 0, 0, node)) { return false; } + if (!ir_lower_restore(p, saved_bindings, node)) { return false; } + p.current_block = continuation; return true; + } + if (n.tag == 59) { + var condition: u64 = 0; var body: u64 = 0; var exit: u64 = 0; + if (!ir_lower_block(p, 5, node, &condition) || !ir_lower_block(p, 6, node, &body) + || !ir_lower_block(p, 7, node, &exit) + || !ir_lower_term(p, 1, 0, condition, 0, 0, node)) { return false; } + p.current_block = condition; + if (!ir_lower_expression(p, n.a, depth + 1, false, &value)) { return false; } + if (value.ty != 1) { return ir_lower_mismatch(p, n.a, 1, value.ty); } + if (!ir_lower_term(p, 2, 0, value.value, body, exit, node)) { return false; } + p.current_block = body; + if (p.loop_count >= p.loop_capacity) { return ir_lower_fail(p.core, 4, node, 0, 0, 0); } + p.loops[p.loop_count].condition = condition; p.loops[p.loop_count].exit = exit; p.loop_count += 1; + var saved_bindings: u64 = p.binding_count; + if (!ir_lower_statements(p, n.b, n.c, depth + 1, node)) { return false; } + if (p.blocks[p.current_block].term_kind == 0 + && !ir_lower_term(p, 1, 0, condition, 0, 0, node)) { return false; } + if (!ir_lower_restore(p, saved_bindings, node)) { return false; } + p.loop_count -= 1; p.current_block = exit; return true; + } + if (n.tag == 60 || n.tag == 61) { + if (p.loop_count == 0) { + var error: u64 = 13; if (n.tag == 61) { error = 14; } + return ir_lower_fail(p.core, error, node, 0, 0, 0); + } + var destination: u64 = p.loops[p.loop_count - 1].exit; + if (n.tag == 61) { destination = p.loops[p.loop_count - 1].condition; } + return ir_lower_term(p, 1, 0, destination, 0, 0, node); + } + return ir_lower_fail(p.core, 24, node, 0, 0, 0); +} diff --git a/ir/lower_storage.wave b/ir/lower_storage.wave new file mode 100644 index 0000000..46a127f --- /dev/null +++ b/ir/lower_storage.wave @@ -0,0 +1,226 @@ +// SPDX-License-Identifier: MPL-2.0 +// Frontend aggregates denote addresses; scalar expressions denote SSA values. +// Copying an aggregate snapshots the RHS before touching a possibly aliasing LHS. +fun ir_lower_alloca(p: ptr, ty: u64, align: u64, node: u64, output: ptr) -> bool { + var pointer: u64 = 0; + var value: u64 = 0; + if (!ir_lower_pointer(p.core, ty, node, &pointer) + || !ir_lower_value(p, pointer, node, &value) + || !ir_lower_emit(p, 18, value, ty, align, 0, 0, 0, 0, null, 0, true, node)) { return false; } + output[0] = value; return true; +} + +fun ir_lower_read(p: ptr, pointer: u64, ty: u64, node: u64, + output: ptr) -> bool { + if (ir_lower_aggregate(p.core, ty)) { output.value = pointer; output.ty = ty; return true; } + if (!ir_lower_layout(p.core, ty, node)) { return false; } + var value: u64 = 0; + if (!ir_lower_value(p, ty, node, &value) + || !ir_lower_emit(p, 21, value, ty, pointer, p.core.layouts[ty].allocation_align, + 0, 0, 0, null, 0, false, node)) { return false; } + output.value = value; output.ty = ty; return true; +} + +fun ir_lower_write(p: ptr, pointer: u64, value: u64, ty: u64, node: u64) -> bool { + if (!ir_lower_layout(p.core, ty, node)) { return false; } + var align: u64 = p.core.layouts[ty].align; + if (!ir_lower_aggregate(p.core, ty)) { + return ir_lower_emit(p, 23, 18446744073709551615, ty, + value, pointer, align, 0, 0, null, 0, false, node); + } + if (pointer == value) { return true; } + var temporary: u64 = 0; + var byte_pointer: u64 = 0; + var aggregate_pointer: u64 = 0; + var destination: u64 = 0; + var source: u64 = 0; + var snapshot: u64 = 0; + var size: u64 = 0; + if (!ir_lower_alloca(p, ty, align, node, &temporary) + || !ir_lower_pointer(p.core, 9, node, &byte_pointer) + || !ir_lower_pointer(p.core, ty, node, &aggregate_pointer) + || !ir_lower_cast_value(p, 10, aggregate_pointer, byte_pointer, pointer, node, &destination) + || !ir_lower_cast_value(p, 10, aggregate_pointer, byte_pointer, value, node, &source) + || !ir_lower_cast_value(p, 10, aggregate_pointer, byte_pointer, temporary, node, &snapshot) + || !ir_lower_immediate(p, 12, p.core.layouts[ty].size, 0, node, &size) + || !ir_lower_emit(p, 25, 18446744073709551615, 18446744073709551615, + snapshot, source, size, align, 0, null, 0, false, node) + || !ir_lower_emit(p, 25, 18446744073709551615, 18446744073709551615, + destination, snapshot, size, align, 0, null, 0, false, node)) { return false; } + return true; +} + +fun ir_lower_field_pointer(p: ptr, base: u64, ordinal: u64, ty: u64, + node: u64, output: ptr) -> bool { + var zero: u64 = 0; + var index: u64 = 0; + var pointer: u64 = 0; + var destination: u64 = 0; + var indices: array; + if (!ir_lower_immediate(p, 12, 0, 0, node, &zero) + || !ir_lower_immediate(p, 12, ordinal, 0, node, &index) + || !ir_lower_pointer(p.core, ty, node, &pointer) + || !ir_lower_value(p, pointer, node, &destination)) { return false; } + indices[0] = zero; indices[1] = index; + if (!ir_lower_emit(p, 24, destination, pointer, base, 0, 0, 0, 0, + &indices[0], 2, false, node)) { return false; } + output[0] = destination; return true; +} + +fun ir_lower_place(p: ptr, node: u64, depth: u64, + output: ptr) -> bool { + if (!ir_lower_node(p.core, node, depth)) { return false; } + var n: ptr = &p.core.nodes[node]; + if (n.tag == 0) { + var saved: u64 = p.core.annotation; p.core.annotation = n.a; + var success: bool = ir_lower_place(p, n.b, depth + 1, output) + && ir_lower_complete_source(p, n.a, node); + p.core.annotation = saved; return success; + } + if (n.tag == 15) { + var binding: IrLowerBinding; + if (!ir_lower_name(p.core, n.a, node) || !ir_lower_local_binding(p, n.a, node, &binding)) { return false; } + if (binding.kind != 0) { return ir_lower_fail(p.core, 12, node, 0, 0, n.a); } + output.value = binding.value; output.ty = binding.ty; return true; + } + var base: IrLowerValue; + if (n.tag == 6) { + if (!ir_lower_expression(p, n.a, depth + 1, false, &base)) { return false; } + if (p.core.types[base.ty].kind != 17 || p.core.types[base.ty].child == 0) { + return ir_lower_fail(p.core, 7, node, 0, 0, 0); + } + output.value = base.value; output.ty = p.core.types[base.ty].child; return true; + } + if (n.tag == 3) { + var expected: u64 = 0; + if (!ir_lower_type(p.core, n.b, 0, &expected)) { return false; } + if (p.core.nodes[n.b].tag != 107 || !ir_lower_name(p.core, n.c, node)) { + return ir_lower_fail(p.core, 7, node, 0, 0, 0); + } + var layout: ptr = &p.core.nodes[n.b]; + var ordinal: u64 = 0; + while (ordinal < layout.b) { + if (!ir_lower_charge(p.core, 1, node)) { return false; } + if (p.core.nodes[p.core.edges[layout.a + ordinal]].a == n.c) { break; } + ordinal += 1; + } + if (ordinal == layout.b) { return ir_lower_fail(p.core, 18, node, 0, 0, 3); } + var ty: u64 = p.core.type_edges[p.core.types[expected].first + ordinal]; + if (!ir_lower_expression(p, n.a, depth + 1, false, &base)) { return false; } + if (base.ty != expected) { return ir_lower_fail(p.core, 6, node, expected, base.ty, 0); } + var pointer: u64 = 0; + if (!ir_lower_field_pointer(p, base.value, ordinal, ty, node, &pointer)) { return false; } + output.value = pointer; output.ty = ty; return true; + } + if (n.tag == 4) { + if (!ir_lower_expression(p, n.a, depth + 1, false, &base)) { return false; } + if (p.core.types[base.ty].kind != 19) { return ir_lower_fail(p.core, 7, node, 0, 0, 0); } + var element: u64 = p.core.types[base.ty].child; + var length: u64 = p.core.types[base.ty].auxiliary; + var index: IrLowerValue; + if (!ir_lower_expression(p, n.b, depth + 1, false, &index)) { return false; } + if (!ir_lower_integer(index.ty)) { return ir_lower_fail(p.core, 7, node, 0, 0, 0); } + var zero: u64 = 0; + var bad: u64 = 0; + if (ir_lower_signed(index.ty)) { + if (!ir_lower_immediate(p, index.ty, 0, 0, node, &zero) + || !ir_lower_value(p, 1, node, &bad) + || !ir_lower_emit(p, 11, bad, index.ty, 6, index.value, zero, 0, 0, null, 0, false, node) + || !ir_lower_emit(p, 30, 18446744073709551615, 1, + bad, 1, 0, 0, 0, null, 0, false, node)) { return false; } + } + var converted: u64 = 0; + var limit: u64 = 0; + if (!ir_lower_cast_value(p, 0, index.ty, 13, index.value, node, &converted) + || !ir_lower_immediate(p, 13, length, 0, node, &limit) + || !ir_lower_value(p, 1, node, &bad) + || !ir_lower_emit(p, 11, bad, 13, 5, converted, limit, 0, 0, null, 0, false, node) + || !ir_lower_emit(p, 30, 18446744073709551615, 1, + bad, 1, 0, 0, 0, null, 0, false, node) + || !ir_lower_immediate(p, 12, 0, 0, node, &zero)) { return false; } + var pointer: u64 = 0; + var destination: u64 = 0; + var indices: array; + if (!ir_lower_pointer(p.core, element, node, &pointer) + || !ir_lower_value(p, pointer, node, &destination)) { return false; } + indices[0] = zero; indices[1] = converted; + if (!ir_lower_emit(p, 24, destination, pointer, base.value, 0, 0, 0, 0, + &indices[0], 2, false, node)) { return false; } + output.value = destination; output.ty = element; return true; + } + return ir_lower_fail(p.core, 7, node, 0, 0, 0); +} + +fun ir_lower_field_map(p: ptr, layout: u64, node: u64) -> bool { + var t: ptr = &p.core.nodes[layout]; + var at: u64 = 0; + while (at < t.b) { + if (!ir_lower_charge(p.core, 1, node)) { return false; } + if (p.field_binding_count >= p.field_binding_capacity) { return ir_lower_fail(p.core, 4, node, 0, 0, 0); } + var name: u64 = p.core.nodes[p.core.edges[t.a + at]].a; + var id: u64 = p.field_binding_count; + p.field_bindings[id].name = name; p.field_bindings[id].ordinal = at; + p.field_bindings[id].previous = p.field_slots[name]; p.field_bindings[id].used = 0; + p.field_slots[name] = id; p.field_binding_count += 1; at += 1; + } + return true; +} + +fun ir_lower_aggregate_literal(p: ptr, node: u64, depth: u64, + output: ptr) -> bool { + var n: ptr = &p.core.nodes[node]; + var ty: u64 = 0; + if (!ir_lower_type(p.core, n.a, 0, &ty) || !ir_lower_layout(p.core, ty, node)) { return false; } + var align: u64 = p.core.layouts[ty].align; + var pointer: u64 = 0; + if (!ir_lower_alloca(p, ty, align, node, &pointer) + || !ir_lower_emit(p, 22, 18446744073709551615, ty, + pointer, align, 0, 0, 0, null, 0, false, node) + || !ir_lower_edges(p.core, n.b, n.c, node)) { return false; } + var at: u64 = 0; + var actual: IrLowerValue; + var destination: u64 = 0; + if (n.tag == 1 && p.core.types[ty].kind == 20 && p.core.nodes[n.a].tag == 107) { + if (n.c != p.core.types[ty].count) { return ir_lower_fail(p.core, 18, node, 0, 0, 4); } + var saved: u64 = p.field_binding_count; + if (!ir_lower_field_map(p, n.a, node)) { return false; } + while (at < n.c) { + var init: u64 = p.core.edges[n.b + at]; + if (!ir_lower_node(p.core, init, depth + 1) || p.core.nodes[init].tag != 24) { + return ir_lower_fail(p.core, 3, init, 0, 0, 0); + } + var name: u64 = p.core.nodes[init].a; + if (!ir_lower_name(p.core, name, init)) { return false; } + var binding: u64 = p.field_slots[name]; + if (binding == 18446744073709551615 || binding < saved) { + return ir_lower_fail(p.core, 18, init, 0, 0, 6); + } + if (p.field_bindings[binding].used != 0) { return ir_lower_fail(p.core, 18, init, 0, 0, 5); } + p.field_bindings[binding].used = 1; + var ordinal: u64 = p.field_bindings[binding].ordinal; + var expected: u64 = p.core.type_edges[p.core.types[ty].first + ordinal]; + if (!ir_lower_expression(p, p.core.nodes[init].b, depth + 1, false, &actual)) { return false; } + if (actual.ty != expected) { return ir_lower_fail(p.core, 6, init, expected, actual.ty, 0); } + if (!ir_lower_field_pointer(p, pointer, ordinal, expected, node, &destination) + || !ir_lower_write(p, destination, actual.value, expected, node)) { return false; } + at += 1; + } + while (p.field_binding_count > saved) { + p.field_binding_count -= 1; + var last: u64 = p.field_binding_count; + p.field_slots[p.field_bindings[last].name] = p.field_bindings[last].previous; + } + } else if (n.tag == 2 && p.core.types[ty].kind == 19) { + var element: u64 = p.core.types[ty].child; + if (!ir_lower_scalar(p.core, element)) { return ir_lower_fail(p.core, 18, node, 0, 0, 7); } + if (n.c != p.core.types[ty].auxiliary) { return ir_lower_fail(p.core, 18, node, 0, 0, 8); } + while (at < n.c) { + if (!ir_lower_expression(p, p.core.edges[n.b + at], depth + 1, false, &actual)) { return false; } + if (actual.ty != element) { return ir_lower_fail(p.core, 6, node, element, actual.ty, 0); } + if (!ir_lower_field_pointer(p, pointer, at, element, node, &destination) + || !ir_lower_write(p, destination, actual.value, element, node)) { return false; } + at += 1; + } + } else { return ir_lower_fail(p.core, 7, node, 0, 0, 0); } + output.value = pointer; output.ty = ty; return true; +} diff --git a/ir/meson.build b/ir/meson.build new file mode 100644 index 0000000..add61ac --- /dev/null +++ b/ir/meson.build @@ -0,0 +1,53 @@ +# SPDX-License-Identifier: MPL-2.0 +wave_ir_dependencies = [] +wave_ir_directory = get_option('wave-ir-dir') +if wave_ir_directory == '' and wave_source != '' + wave_ir_directory = meson.current_build_dir() + module_target = cargo_host_target + if module_target == '' + target_os = {'linux': 'unknown-linux-gnu', 'darwin': 'apple-darwin', 'windows': 'pc-windows-msvc'} + module_target = host_machine.cpu_family() + '-' + target_os[host_machine.system()] + endif + archive_name = module_target.contains('msvc') ? 'whale_wave_ir.lib' : 'libwhale_wave_ir.a' + arguments = ['--wave-source', wave_source, '--out-dir', '@OUTDIR@', + '--bootstrap-dir', wave_cache, '--target', module_target, + '--rust-toolchain', get_option('wave-rust-toolchain')] + if get_option('wave-allow-network') + arguments += ['--allow-network'] + endif + wave_ir_module = custom_target('wave-ir', + output: [archive_name, 'wave-ir.meta', 'provenance.json'], + command: [python, files('../tools/build_wave_ir.py'), arguments], + depend_files: files('model.wave', 'layout.wave', 'lexer.wave', 'header.wave', 'type_parser.wave', + 'literal.wave', 'expression_parser.wave', 'instruction_parser.wave', 'module_parser.wave', 'lower_hir.wave', + 'lower_model.wave', 'lower_output.wave', 'lower_expression.wave', 'lower_storage.wave', 'lower_statement.wave', 'lower_driver.wave', 'builder.wave', 'builder_namespace.wave', 'builder_body.wave', + 'verify.wave', 'verifier_index.wave', 'verifier_ssa.wave', 'printer.wave', + 'cfg.wave', 'shape.wave', 'source.wave', 'lower_limits.wave', 'entry.wave', + 'src/wave_layout.rs', 'src/source_wave.rs', 'src/lower_ast/wave_limits.rs', 'src/parser/wave_lexer.rs', 'src/parser/wave_header.rs', + 'src/parser/wave_text.rs', 'src/parser/wave_type.rs', + 'src/parser/wave_literal.rs', 'src/builder/wave.rs', + 'src/builder/namespace.rs', 'src/builder/body.rs', + 'src/parser/wave_expression.rs', + 'src/parser/wave_instruction.rs', + 'src/parser/wave_module.rs', + 'src/lower_ast/wave_hir.rs', 'src/lower_ast/wave_lower.rs', + 'src/verifier/wave_semantics.rs', + 'src/verifier/wave_index.rs', + 'src/verifier/wave_ssa.rs', + 'src/printer_wave.rs', + 'src/verifier/wave_cfg.rs', 'src/verifier/wave_shape.rs', + '../tools/build_wave_ir.py', + '../tools/wave_bootstrap.py'), + depends: wave_bootstrap, console: true) + wave_ir_dependencies += [wave_ir_module] +elif wave_ir_directory != '' + if not fs.is_absolute(wave_ir_directory) + error('-Dwave-ir-dir must be absolute.') + endif + archive_name = host_machine.system() == 'windows' ? 'whale_wave_ir.lib' : 'libwhale_wave_ir.a' + foreach artifact : [archive_name, 'wave-ir.meta', 'provenance.json'] + if not fs.is_file(wave_ir_directory / artifact) + error('Missing Wave IR module artifact: ' + (wave_ir_directory / artifact)) + endif + endforeach +endif diff --git a/ir/model.wave b/ir/model.wave new file mode 100644 index 0000000..6f4b343 --- /dev/null +++ b/ir/model.wave @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: MPL-2.0 +// Flat, caller-owned IR type graph. Aggregate children precede their parent; +// pointer and function-pointer pointees are deliberately not laid out. +// Kinds: void, 1/2/4/8/16-byte scalar, pointer, function pointer, array, +// struct, tuple. The Rust compatibility model maps its named scalar types to +// these storage classes at this internal boundary. +struct IrTypeNode { + kind: u64; + child: u64; + first: u64; + count: u64; +} + +struct IrStorage { + ptr_bits: u64; + pointer_align: u64; + scalar_align1: u64; + scalar_align2: u64; + scalar_align4: u64; + scalar_align8: u64; + scalar_align16: u64; + large_array_threshold: u64; + large_array_align: u64; + has_large_array: u64; +} + +struct IrTypeLayout { + size: u64; + align: u64; + stride: u64; + allocation_align: u64; + depth: u64; +} + +struct IrLayoutResult { + status: u64; + index: u64; +} + +fun ir_power_two(value: u64) -> bool { + return value != 0 && (value & (value - 1)) == 0; +} + +fun ir_storage_valid(storage: ptr) -> bool { + if (storage == null || (storage.ptr_bits != 32 && storage.ptr_bits != 64) + || !ir_power_two(storage.pointer_align) + || storage.pointer_align > storage.ptr_bits / 8 + || !ir_power_two(storage.scalar_align1) || storage.scalar_align1 > 1 + || !ir_power_two(storage.scalar_align2) || storage.scalar_align2 > 2 + || !ir_power_two(storage.scalar_align4) || storage.scalar_align4 > 4 + || !ir_power_two(storage.scalar_align8) || storage.scalar_align8 > 8 + || !ir_power_two(storage.scalar_align16) || storage.scalar_align16 > 16 + || storage.has_large_array > 1) { return false; } + return storage.has_large_array == 0 || ir_power_two(storage.large_array_align); +} + +fun ir_span_valid(data: ptr, count: u64, width: u64) -> bool { + return count <= 9223372036854775807 / width + && (count == 0 || data != null) + && count * width <= 18446744073709551615 - (data as u64); +} + +fun ir_align_up(size: u64, align: u64, result: ptr) -> bool { + var mask: u64 = align - 1; + if (size > 18446744073709551615 - mask) { return false; } + result[0] = (size + mask) & ~mask; + return true; +} diff --git a/ir/module_parser.wave b/ir/module_parser.wave new file mode 100644 index 0000000..98e71a4 --- /dev/null +++ b/ir/module_parser.wave @@ -0,0 +1,354 @@ +// SPDX-License-Identifier: MPL-2.0 +// Incremental versioned module grammar. Wave owns production selection and +// loop/ordering/version rules; callers construct values from typed events. +struct IrModuleState { + phase: u64; at: u64; format: u64; nodes: u64; work: u64; + a: u64; b: u64; c: u64; d: u64; e: u64; f: u64; g: u64; + name: u64; link: u64; terminated: u64; +} + +struct IrModuleEvent { + status: u64; reason: u64; at: u64; expected: u64; event: u64; role: u64; + a: u64; b: u64; c: u64; d: u64; e: u64; f: u64; g: u64; + name: u64; link: u64; next: u64; nodes: u64; work: u64; +} + +struct IrModuleParser { + tokens: ptr; count: u64; state: ptr; + max_nodes: u64; max_work: u64; result: ptr; +} + +fun ir_module_word(token: ptr, code: u64) -> bool { + var first: u64 = 0; var second: u64 = 0; var length: u64 = 0; + if (code == 0) { first = 125; second = 0; length = 1; } // } + else if (code == 1) { first = 58; second = 0; length = 1; } // : + else if (code == 2) { first = 61; second = 0; length = 1; } // = + else if (code == 3) { first = 500152823651; second = 0; length = 5; } // const + else if (code == 4) { first = 44; second = 0; length = 1; } // , + else if (code == 5) { first = 474181364833; second = 0; length = 5; } // align + else if (code == 6) { first = 8104338990102572649; second = 114; length = 9; } // init_expr + else if (code == 7) { first = 435761734006; second = 0; length = 5; } // value + else if (code == 8) { first = 7019269490406420085; second = 431199250796; length = 13; } // uninitialized + else if (code == 9) { first = 126939459445601; second = 0; length = 6; } // access + else if (code == 10) { first = 8749489600778560882; second = 0; length = 8; } // readonly + else if (code == 11) { first = 8388361638065038706; second = 101; length = 9; } // readwrite + else if (code == 12) { first = 28542640759662956; second = 0; length = 7; } // linkage + else if (code == 13) { first = 7809644666444607081; second = 0; length = 8; } // internal + else if (code == 14) { first = 7809644666444609637; second = 0; length = 8; } // external + else if (code == 15) { first = 7881702178978425196; second = 101; length = 9; } // link_name + else if (code == 16) { first = 435610019959; second = 0; length = 5; } // whale + else if (code == 17) { first = 57408520157555; second = 0; length = 6; } // sysv64 + else if (code == 18) { first = 40; second = 0; length = 1; } // ( + else if (code == 19) { first = 41; second = 0; length = 1; } // ) + else if (code == 20) { first = 15917; second = 0; length = 2; } // -> + else if (code == 21) { first = 521611275877; second = 0; length = 5; } // entry + else if (code == 22) { first = 123; second = 0; length = 1; } // { + else if (code == 23) { first = 7376726192452628339; second = 6646889; length = 11; } // source_file + else if (code == 24) { first = 7809644627822735983; second = 0; length = 8; } // original + else if (code == 25) { first = 1701736302; second = 0; length = 4; } // none + else if (code == 26) { first = 7881129350718123891; second = 28769; length = 10; } // source_map + else if (code == 27) { first = 8386676065534439017; second = 7237481; length = 11; } // instruction + else if (code == 28) { first = 8386105380227409268; second = 29295; length = 10; } // terminator + else if (code == 29) { first = 119165519096935; second = 0; length = 6; } // global + else if (code == 30) { first = 28542640877171827; second = 0; length = 7; } // storage + else if (code == 31) { first = 28554735403623780; second = 0; length = 7; } // declare + else if (code == 32) { first = 28262; second = 0; length = 2; } // fn + else if (code == 33) { first = 29282; second = 0; length = 2; } // br + else if (code == 34) { first = 7496291; second = 0; length = 3; } // cbr + else if (code == 35) { first = 114776364119923; second = 0; length = 6; } // switch + else if (code == 36) { first = 7628146; second = 0; length = 3; } // ret + else if (code == 37) { first = 1885434484; second = 0; length = 4; } // trap + else { return false; } + if (token.kind == 1 || token.kind == 3 || token.length != length) { return false; } + var i: u64 = 0; + while (i < length) { + var packed: u64 = first; if (i >= 8) { packed = second; } + if (token.data[i] as u64 != ((packed >> ((i & 7) * 8)) & 255)) { return false; } + i += 1; + } + return true; +} + +fun ir_module_fail(p: ptr, status: u64, reason: u64, at: u64, expected: u64) -> bool { + p.result.status = status; p.result.reason = reason; p.result.at = at; + p.result.expected = expected; return false; +} + +fun ir_module_charge(p: ptr, amount: u64) -> bool { + if (amount > p.max_work - p.state.work) { return ir_module_fail(p, 4, 0, p.state.at, 0); } + p.state.work += amount; return true; +} + +fun ir_module_read(p: ptr) -> bool { + if (p.state.at >= p.count) { return ir_module_fail(p, 6, 0, p.state.at, 0); } + var token: ptr = &p.tokens[p.state.at]; + if (token.kind > 3 || !ir_span_valid(token.data, token.length, 1)) { return ir_module_fail(p, 6, 0, p.state.at, 0); } + return ir_module_charge(p, 1 + token.length); +} + +fun ir_module_eat(p: ptr, code: u64) -> bool { + if (!ir_module_read(p)) { return false; } + if (!ir_module_word(&p.tokens[p.state.at], code)) { return false; } + p.state.at += 1; return true; +} + +fun ir_module_expect(p: ptr, code: u64) -> bool { + if (ir_module_eat(p, code)) { return true; } + if (p.result.status != 0) { return false; } + return ir_module_fail(p, 1, 1, p.state.at, code); +} + +fun ir_module_node(p: ptr) -> bool { + if (p.state.nodes >= p.max_nodes) { return ir_module_fail(p, 3, 0, p.state.at, 0); } + p.state.nodes += 1; return true; +} + +fun ir_module_number(p: ptr, maximum: u64, output: ptr) -> bool { + if (!ir_module_read(p)) { return false; } + var token: ptr = &p.tokens[p.state.at]; + if (token.kind != 0 || token.length == 0) { return ir_module_fail(p, 1, 2, p.state.at, 0); } + var value: u64 = 0; var i: u64 = 0; var overflow: bool = false; + while (i < token.length) { + var octet: u64 = token.data[i] as u64; + if (octet < 48 || octet > 57) { return ir_module_fail(p, 1, 2, p.state.at, 0); } + var digit: u64 = octet - 48; + if (value > (maximum - digit) / 10) { overflow = true; } + if (!overflow) { value = value * 10 + digit; } + i += 1; + } + if (overflow) { return ir_module_fail(p, 1, 3, p.state.at, 0); } + output[0] = value; p.state.at += 1; return true; +} + +fun ir_module_id(p: ptr, prefix: u64, output: ptr) -> bool { + if (!ir_module_read(p)) { return false; } + var token: ptr = &p.tokens[p.state.at]; + var first: u64 = 64; var second: u64 = 0; + if (prefix == 0) { first = 37; second = 118; } + else if (prefix == 1) { first = 37; second = 98; } + else if (prefix == 2) { second = 103; } + else if (prefix == 3) { second = 102; } + else if (prefix == 4) { second = 115; } + else { return ir_module_fail(p, 6, 0, p.state.at, 0); } + if (token.kind == 1 || token.kind == 3 || token.length < 2 + || token.data[0] as u64 != first || token.data[1] as u64 != second) { + return ir_module_fail(p, 1, 4, p.state.at, prefix); + } + if (token.length == 2) { return ir_module_fail(p, 1, 5, p.state.at, 0); } + var value: u64 = 0; var i: u64 = 2; var overflow: bool = false; + while (i < token.length) { + var octet: u64 = token.data[i] as u64; + if (octet < 48 || octet > 57) { return ir_module_fail(p, 1, 5, p.state.at, 0); } + var digit: u64 = octet - 48; + if (value > (4294967295 - digit) / 10) { overflow = true; } + if (!overflow) { value = value * 10 + digit; } + i += 1; + } + if (overflow) { return ir_module_fail(p, 1, 6, p.state.at, 0); } + output[0] = value; p.state.at += 1; return true; +} + +fun ir_module_string(p: ptr, output: ptr) -> bool { + if (!ir_module_read(p)) { return false; } + if (p.tokens[p.state.at].kind != 1) { return ir_module_fail(p, 1, 7, p.state.at, 0); } + output[0] = p.state.at; p.state.at += 1; return true; +} + +fun ir_module_choose(p: ptr, first: u64, second: u64, reason: u64, output: ptr) -> bool { + if (!ir_module_read(p)) { return false; } + var token: ptr = &p.tokens[p.state.at]; + if (token.kind != 0) { return ir_module_fail(p, 1, 8, p.state.at, 0); } + var choice: u64 = 0; + if (ir_module_word(token, first)) { choice = 0; } + else if (ir_module_word(token, second)) { choice = 1; } + else { return ir_module_fail(p, 1, reason, p.state.at, 0); } + output[0] = choice; p.state.at += 1; return true; +} + +fun ir_module_align(p: ptr) -> bool { + return ir_module_expect(p, 4) && ir_module_expect(p, 5) + && ir_module_number(p, 4294967295, &p.state.b); +} + +fun ir_module_link(p: ptr) -> bool { + if (!ir_module_expect(p, 4) || !ir_module_expect(p, 12) + || !ir_module_choose(p, 13, 14, 14, &p.state.d)) { return false; } + p.state.link = 18446744073709551615; + if (ir_module_eat(p, 4)) { + return ir_module_expect(p, 15) && ir_module_string(p, &p.state.link); + } + return p.result.status == 0; +} + +fun ir_module_event(p: ptr, event: u64, role: u64) -> bool { + p.result.event = event; p.result.role = role; + p.result.a = p.state.a; p.result.b = p.state.b; p.result.c = p.state.c; + p.result.d = p.state.d; p.result.e = p.state.e; p.result.f = p.state.f; p.result.g = p.state.g; + p.result.name = p.state.name; p.result.link = p.state.link; + return true; +} + +fun ir_module_request(p: ptr, event: u64, role: u64, phase: u64) -> bool { + p.state.phase = phase; return ir_module_event(p, event, role); +} + +fun ir_module_parameter(p: ptr) -> bool { + return ir_module_node(p) && ir_module_id(p, 0, &p.state.a) + && ir_module_string(p, &p.state.name) && ir_module_expect(p, 1) + && ir_module_request(p, 100, 7, 41); +} + +fun ir_module_function_return(p: ptr) -> bool { + return ir_module_expect(p, 20) && ir_module_request(p, 100, 8, 42); +} + +fun ir_module_step(p: ptr) -> bool { + var phase: u64 = p.state.phase; + if (phase == 0) { + if (ir_module_eat(p, 0)) { p.state.phase = 99; return ir_module_event(p, 14, 0); } + if (p.result.status != 0 || !ir_module_node(p) || !ir_module_read(p)) { return false; } + var token: ptr = &p.tokens[p.state.at]; + if (token.kind != 0) { return ir_module_fail(p, 1, 8, p.state.at, 0); } + var field: u64 = 23; + while (field <= 32 && !ir_module_word(token, field)) { field += 1; } + p.state.at += 1; + if (field == 23 || field == 24 || field == 26) { + if (p.state.format < 7) { return ir_module_fail(p, 1, 9, p.state.at, 0); } + } + if (field == 23) { + return ir_module_id(p, 4, &p.state.a) && ir_module_string(p, &p.state.name) + && ir_module_event(p, 1, 0); + } + if (field == 24) { + if (!ir_module_number(p, 18446744073709551615, &p.state.a)) { return false; } + if (ir_module_eat(p, 25)) { p.state.g = 0; return ir_module_event(p, 2, 0); } + p.state.g = 1; + return p.result.status == 0 && ir_module_id(p, 4, &p.state.b) + && ir_module_number(p, 4294967295, &p.state.c) + && ir_module_number(p, 4294967295, &p.state.d) + && ir_module_number(p, 4294967295, &p.state.e) + && ir_module_number(p, 4294967295, &p.state.f) + && ir_module_event(p, 2, 0); + } + if (field == 26) { + if (!ir_module_read(p)) { return false; } + token = &p.tokens[p.state.at]; + if (token.kind != 0) { return ir_module_fail(p, 1, 8, p.state.at, 0); } + if (ir_module_word(token, 27)) { p.state.a = 0; } + else if (ir_module_word(token, 28)) { p.state.a = 1; } + else if (ir_module_word(token, 29)) { p.state.a = 2; } + else { return ir_module_fail(p, 1, 11, p.state.at, 0); } + p.state.at += 1; + if (p.state.a == 2) { + if (!ir_module_id(p, 2, &p.state.b)) { return false; } + } else { + if (!ir_module_id(p, 3, &p.state.b) || !ir_module_id(p, 1, &p.state.c)) { return false; } + if (p.state.a == 0 && !ir_module_number(p, 18446744073709551615, &p.state.d)) { return false; } + } + return ir_module_number(p, 18446744073709551615, &p.state.e) && ir_module_event(p, 3, 0); + } + if (field == 29 || field == 30) { + if (field == 30 && p.state.format < 6) { return ir_module_fail(p, 1, 10, p.state.at - 1, 0); } + if (!ir_module_id(p, 2, &p.state.a) || !ir_module_string(p, &p.state.name) + || !ir_module_expect(p, 1)) { return false; } + if (field == 29) { return ir_module_request(p, 100, 1, 10); } + return ir_module_request(p, 100, 3, 20); + } + if (field == 31) { + if (!ir_module_id(p, 3, &p.state.a) || !ir_module_string(p, &p.state.name) + || !ir_module_expect(p, 1) || !ir_module_choose(p, 16, 17, 15, &p.state.c) + || !ir_module_expect(p, 18)) { return false; } + if (ir_module_eat(p, 19)) { + return ir_module_expect(p, 20) && ir_module_request(p, 100, 6, 32); + } + return p.result.status == 0 && ir_module_request(p, 100, 5, 31); + } + if (field == 32) { + if (!ir_module_id(p, 3, &p.state.a) || !ir_module_string(p, &p.state.name) + || !ir_module_expect(p, 18)) { return false; } + p.state.phase = 40; return ir_module_event(p, 7, 0); + } + return ir_module_fail(p, 1, 16, p.state.at - 1, 0); + } + if (phase == 10) { + return ir_module_expect(p, 2) && ir_module_expect(p, 3) && ir_module_request(p, 100, 2, 11); + } + if (phase == 11) { return ir_module_request(p, 101, 1, 12); } + if (phase == 12) { + return ir_module_align(p) && ir_module_expect(p, 4) && ir_module_expect(p, 6) + && ir_module_request(p, 102, 1, 13); + } + if (phase == 13) { p.state.phase = 0; return ir_module_event(p, 4, 0); } + if (phase == 20) { + if (!ir_module_expect(p, 2) || !ir_module_choose(p, 8, 7, 12, &p.state.e)) { return false; } + if (p.state.e != 0) { return ir_module_request(p, 100, 4, 21); } + p.state.phase = 22; return ir_module_step(p); + } + if (phase == 21) { return ir_module_request(p, 101, 2, 22); } + if (phase == 22) { + if (!ir_module_align(p) || !ir_module_expect(p, 4) || !ir_module_expect(p, 9) + || !ir_module_choose(p, 11, 10, 13, &p.state.c) || !ir_module_link(p)) { return false; } + p.state.phase = 0; return ir_module_event(p, 5, 0); + } + if (phase == 31) { + if (ir_module_eat(p, 19)) { return ir_module_expect(p, 20) && ir_module_request(p, 100, 6, 32); } + return p.result.status == 0 && ir_module_expect(p, 4) && ir_module_request(p, 100, 5, 31); + } + if (phase == 32) { + if (!ir_module_link(p)) { return false; } + p.state.phase = 0; return ir_module_event(p, 6, 0); + } + if (phase == 40) { + if (ir_module_eat(p, 19)) { return ir_module_function_return(p); } + return p.result.status == 0 && ir_module_parameter(p); + } + if (phase == 41) { p.state.phase = 46; return ir_module_event(p, 8, 0); } + if (phase == 46) { + if (ir_module_eat(p, 19)) { return ir_module_function_return(p); } + return p.result.status == 0 && ir_module_expect(p, 4) && ir_module_parameter(p); + } + if (phase == 42) { + if (!ir_module_expect(p, 4) || !ir_module_expect(p, 21) + || !ir_module_id(p, 1, &p.state.a) || !ir_module_expect(p, 22)) { return false; } + p.state.phase = 44; return ir_module_event(p, 9, 0); + } + if (phase == 44) { + if (ir_module_eat(p, 0)) { p.state.phase = 0; return ir_module_event(p, 13, 0); } + if (p.result.status != 0 || !ir_module_node(p) || !ir_module_id(p, 1, &p.state.a) + || !ir_module_string(p, &p.state.name) || !ir_module_expect(p, 1)) { return false; } + p.state.phase = 45; p.state.terminated = 0; return ir_module_event(p, 10, 0); + } + if (phase == 45) { + if (!ir_module_read(p)) { return false; } + var token: ptr = &p.tokens[p.state.at]; + var block_prefix: bool = token.kind != 1 && token.kind != 3 && token.length >= 2 + && token.data[0] == 37 && token.data[1] == 98; + if (block_prefix || ir_module_word(token, 0)) { p.state.phase = 44; return ir_module_event(p, 12, 0); } + if (p.state.terminated != 0) { return ir_module_fail(p, 1, 17, p.state.at, 0); } + if (!ir_module_node(p)) { return false; } + var word: u64 = 33; + while (word <= 37 && !ir_module_word(token, word)) { word += 1; } + if (word <= 37) { p.state.terminated = 1; return ir_module_event(p, 104, 0); } + return ir_module_event(p, 103, 0); + } + return ir_module_fail(p, 6, 0, p.state.at, 0); +} + +export(c) fun whale_ir_module_step(tokens: ptr, token_count: u64, + state: ptr, max_nodes: u64, max_work: u64, + result: ptr) -> i32 { + if (result == null) { return 6; } + result.status = 0; result.reason = 0; result.at = 0; result.expected = 0; + result.event = 0; result.role = 0; result.nodes = 0; result.work = 0; + if (state == null || !ir_span_valid(tokens as ptr, token_count, 24) + || state.at >= token_count || state.format < 3 || state.format > 8) { + result.status = 6; return 6; + } + state.nodes = 0; state.work = 0; + var parser: IrModuleParser; + parser.tokens = tokens; parser.count = token_count; parser.state = state; + parser.max_nodes = max_nodes; parser.max_work = max_work; parser.result = result; + if (!ir_module_step(&parser) && result.status == 0) { result.status = 6; } + result.next = state.at; result.nodes = state.nodes; result.work = state.work; + return result.status as i32; +} diff --git a/ir/printer.wave b/ir/printer.wave new file mode 100644 index 0000000..79907ad --- /dev/null +++ b/ir/printer.wave @@ -0,0 +1,2083 @@ +// SPDX-License-Identifier: MPL-2.0 +// Canonical IR grammar and byte escaping live here. Rust supplies a flat, +// borrowed model and drains bounded chunks; it does not choose print syntax. +// The caller owns the resumable task stack. No global strings or allocation. +struct IrPrintState { + nodes: ptr; node_count: u64; + edges: ptr; edge_count: u64; + stack: ptr; stack_capacity: u64; stack_len: u64; + output_limit: u64; total: u64; work: u64; depth_limit: u64; + status: u64; initialized: u64; +} + +fun irp_push(s: ptr, kind: u64, a: u64, b: u64, c: u64, + d: u64, e: u64, f: u64, g: u64, h: u64, depth: u64) -> bool { + if (s.status != 0) { return false; } + if (s.work == 0) { s.status = 4; return false; } + s.work -= 1; + if (s.stack_len >= s.stack_capacity) { s.status = 3; return false; } + var p: ptr = &s.stack[s.stack_len * 10]; + p[0] = kind; p[1] = a; p[2] = b; p[3] = c; p[4] = d; + p[5] = e; p[6] = f; p[7] = g; p[8] = h; p[9] = depth; + s.stack_len += 1; + return true; +} + +fun irp_list(s: ptr, first: u64, count: u64, separator: u64, + separator_len: u64, before: u64, before_len: u64, + after: u64, after_len: u64, depth: u64) -> bool { + if (first > s.edge_count || count > s.edge_count - first) { + s.status = 1; return false; + } + return irp_push(s, 8, first, count, separator, separator_len, + before, before_len, after, after_len, depth); +} + +fun irp_operator(s: ptr, family: u64, value: u64, depth: u64) -> bool { + if (family == 1) { + if (value == 0) { + // "add" + if (!irp_push(s, 1, 6579297, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 1) { + // "sub" + if (!irp_push(s, 1, 6452595, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 2) { + // "mul" + if (!irp_push(s, 1, 7107949, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 3) { + // "bit_and" + if (!irp_push(s, 1, 28268862163413346, 7, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 4) { + // "bit_or" + if (!irp_push(s, 1, 125822668400994, 6, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 5) { + // "bit_xor" + if (!irp_push(s, 1, 32210710133238114, 7, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 6) { + // "div" + if (!irp_push(s, 1, 7760228, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 7) { + // "rem" + if (!irp_push(s, 1, 7169394, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 8) { + // "ft" + if (!irp_push(s, 1, 29798, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "shift_le" + if (!irp_push(s, 1, 7308321248854501491, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 9) { + // "ght" + if (!irp_push(s, 1, 7628903, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "shift_ri" + if (!irp_push(s, 1, 7598240474866477171, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 10) { + // "and" + if (!irp_push(s, 1, 6581857, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "logical_" + if (!irp_push(s, 1, 6875977810685947756, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 11) { + // "or" + if (!irp_push(s, 1, 29295, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "logical_" + if (!irp_push(s, 1, 6875977810685947756, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + } + if (family == 2) { + if (value == 0) { + // "eq" + if (!irp_push(s, 1, 29029, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 1) { + // "ne" + if (!irp_push(s, 1, 25966, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 2) { + // "lt" + if (!irp_push(s, 1, 29804, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 3) { + // "le" + if (!irp_push(s, 1, 25964, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 4) { + // "gt" + if (!irp_push(s, 1, 29799, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 5) { + // "ge" + if (!irp_push(s, 1, 25959, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + } + if (family == 3) { + if (value == 0) { + // "add" + if (!irp_push(s, 1, 6579297, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 1) { + // "sub" + if (!irp_push(s, 1, 6452595, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 2) { + // "mul" + if (!irp_push(s, 1, 7107949, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 3) { + // "udiv" + if (!irp_push(s, 1, 1986618485, 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 4) { + // "sdiv" + if (!irp_push(s, 1, 1986618483, 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 5) { + // "urem" + if (!irp_push(s, 1, 1835364981, 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 6) { + // "srem" + if (!irp_push(s, 1, 1835364979, 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 7) { + // "fadd" + if (!irp_push(s, 1, 1684300134, 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 8) { + // "fsub" + if (!irp_push(s, 1, 1651864422, 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 9) { + // "fmul" + if (!irp_push(s, 1, 1819635046, 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 10) { + // "fdiv" + if (!irp_push(s, 1, 1986618470, 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 11) { + // "frem" + if (!irp_push(s, 1, 1835364966, 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 12) { + // "and" + if (!irp_push(s, 1, 6581857, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 13) { + // "or" + if (!irp_push(s, 1, 29295, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 14) { + // "xor" + if (!irp_push(s, 1, 7499640, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 15) { + // "shl" + if (!irp_push(s, 1, 7104627, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 16) { + // "lshr" + if (!irp_push(s, 1, 1919447916, 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 17) { + // "ashr" + if (!irp_push(s, 1, 1919447905, 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + } + if (family == 4) { + if (value == 0) { + // "eq" + if (!irp_push(s, 1, 29029, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 1) { + // "ne" + if (!irp_push(s, 1, 25966, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 2) { + // "slt" + if (!irp_push(s, 1, 7629939, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 3) { + // "sle" + if (!irp_push(s, 1, 6646899, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 4) { + // "sgt" + if (!irp_push(s, 1, 7628659, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 5) { + // "sge" + if (!irp_push(s, 1, 6645619, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 6) { + // "ult" + if (!irp_push(s, 1, 7629941, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 7) { + // "ule" + if (!irp_push(s, 1, 6646901, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 8) { + // "ugt" + if (!irp_push(s, 1, 7628661, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 9) { + // "uge" + if (!irp_push(s, 1, 6645621, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 10) { + // "feq" + if (!irp_push(s, 1, 7431526, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 11) { + // "fne" + if (!irp_push(s, 1, 6647398, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 12) { + // "flt" + if (!irp_push(s, 1, 7629926, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 13) { + // "fle" + if (!irp_push(s, 1, 6646886, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 14) { + // "fgt" + if (!irp_push(s, 1, 7628646, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 15) { + // "fge" + if (!irp_push(s, 1, 6645606, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + } + if (family == 5) { + if (value == 0) { + // "eq" + if (!irp_push(s, 1, 29029, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 1) { + // "ne" + if (!irp_push(s, 1, 25966, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 2) { + // "ult" + if (!irp_push(s, 1, 7629941, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 3) { + // "ule" + if (!irp_push(s, 1, 6646901, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 4) { + // "ugt" + if (!irp_push(s, 1, 7628661, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 5) { + // "uge" + if (!irp_push(s, 1, 6645621, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 6) { + // "slt" + if (!irp_push(s, 1, 7629939, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 7) { + // "sle" + if (!irp_push(s, 1, 6646899, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 8) { + // "sgt" + if (!irp_push(s, 1, 7628659, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 9) { + // "sge" + if (!irp_push(s, 1, 6645619, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + } + if (family == 6) { + if (value == 0) { + // "oeq" + if (!irp_push(s, 1, 7431535, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 1) { + // "one" + if (!irp_push(s, 1, 6647407, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 2) { + // "olt" + if (!irp_push(s, 1, 7629935, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 3) { + // "ole" + if (!irp_push(s, 1, 6646895, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 4) { + // "ogt" + if (!irp_push(s, 1, 7628655, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 5) { + // "oge" + if (!irp_push(s, 1, 6645615, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 6) { + // "ord" + if (!irp_push(s, 1, 6582895, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 7) { + // "uno" + if (!irp_push(s, 1, 7302773, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 8) { + // "ueq" + if (!irp_push(s, 1, 7431541, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 9) { + // "une" + if (!irp_push(s, 1, 6647413, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 10) { + // "ult" + if (!irp_push(s, 1, 7629941, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 11) { + // "ule" + if (!irp_push(s, 1, 6646901, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 12) { + // "ugt" + if (!irp_push(s, 1, 7628661, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 13) { + // "uge" + if (!irp_push(s, 1, 6645621, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + } + if (family == 7) { + if (value == 0) { + // "int" + if (!irp_push(s, 1, 7630441, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "checked_" + if (!irp_push(s, 1, 6873730443177715811, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 1) { + // "zext" + if (!irp_push(s, 1, 1954047354, 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 2) { + // "sext" + if (!irp_push(s, 1, 1954047347, 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 3) { + // "trunc" + if (!irp_push(s, 1, 427054953076, 5, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 4) { + // "fext" + if (!irp_push(s, 1, 1954047334, 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 5) { + // "ftrunc" + if (!irp_push(s, 1, 109326067987558, 6, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 6) { + // "itof_s" + if (!irp_push(s, 1, 126853577667689, 6, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 7) { + // "itof_u" + if (!irp_push(s, 1, 129052600923241, 6, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 8) { + // "ftoi_s" + if (!irp_push(s, 1, 126853627999334, 6, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 9) { + // "ftoi_u" + if (!irp_push(s, 1, 129052651254886, 6, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 10) { + // "bitcast" + if (!irp_push(s, 1, 32777959416031586, 7, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 11) { + // "ptrtoint" + if (!irp_push(s, 1, 8389759083253757040, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 12) { + // "inttoptr" + if (!irp_push(s, 1, 8247340441619689065, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + } + if (family == 8) { + if (value == 0) { + // "uadd" + if (!irp_push(s, 1, 1684300149, 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 1) { + // "usub" + if (!irp_push(s, 1, 1651864437, 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 2) { + // "umul" + if (!irp_push(s, 1, 1819635061, 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 3) { + // "sadd" + if (!irp_push(s, 1, 1684300147, 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 4) { + // "ssub" + if (!irp_push(s, 1, 1651864435, 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (value == 5) { + // "smul" + if (!irp_push(s, 1, 1819635059, 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + } + s.status = 1; return false; +} + +fun irp_expand(s: ptr, index: u64, depth: u64) -> bool { + if (index >= s.node_count) { s.status = 1; return false; } + if (depth > s.depth_limit) { s.status = 5; return false; } + var n: ptr = &s.nodes[index * 12]; + var tag: u64 = n[0]; + if (tag == 1) { + // "void" + if (!irp_push(s, 1, 1684631414, 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 2) { + // "bool" + if (!irp_push(s, 1, 1819242338, 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 3) { + // "i1" + if (!irp_push(s, 1, 12649, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 4) { + // "u1" + if (!irp_push(s, 1, 12661, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 5) { + // "i8" + if (!irp_push(s, 1, 14441, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 6) { + // "i16" + if (!irp_push(s, 1, 3551593, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 7) { + // "i32" + if (!irp_push(s, 1, 3289961, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 8) { + // "i64" + if (!irp_push(s, 1, 3421801, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 9) { + // "i128" + if (!irp_push(s, 1, 942813545, 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 10) { + // "u8" + if (!irp_push(s, 1, 14453, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 11) { + // "u16" + if (!irp_push(s, 1, 3551605, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 12) { + // "u32" + if (!irp_push(s, 1, 3289973, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 13) { + // "u64" + if (!irp_push(s, 1, 3421813, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 14) { + // "u128" + if (!irp_push(s, 1, 942813557, 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 15) { + // "f16" + if (!irp_push(s, 1, 3551590, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 16) { + // "f32" + if (!irp_push(s, 1, 3289958, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 17) { + // "f64" + if (!irp_push(s, 1, 3421798, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 18) { + // ">" + if (!irp_push(s, 1, 62, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[1], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // "ptr<" + if (!irp_push(s, 1, 1014133872, 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 19) { + // ">" + if (!irp_push(s, 1, 62, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[1], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // "fnptr<" + if (!irp_push(s, 1, 66462277463654, 6, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 20) { + // ">" + if (!irp_push(s, 1, 62, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[2], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", " + if (!irp_push(s, 1, 8236, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[1], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // "array<" + if (!irp_push(s, 1, 66492023599713, 6, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 21) { + // "}" + if (!irp_push(s, 1, 125, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_list(s, n[1], n[2], 8236, 2, 0, 0, 0, 0, depth)) { return false; } + // "struct{" + if (!irp_push(s, 1, 34749392656430195, 7, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 22) { + // ">" + if (!irp_push(s, 1, 62, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_list(s, n[1], n[2], 8236, 2, 0, 0, 0, 0, depth)) { return false; } + // "tuple<" + if (!irp_push(s, 1, 66406308672884, 6, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 23) { + if (n[1] > 1) { s.status = 1; return false; } + if (!irp_push(s, 2, n[4], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // ") -> " + if (!irp_push(s, 1, 138482098217, 5, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (n[5] != 0) { + // ", ..." + if (!irp_push(s, 1, 198343270444, 5, 0, 0, 0, 0, 0, 0, depth)) { return false; } + } + if (!irp_list(s, n[2], n[3], 8236, 2, 0, 0, 0, 0, depth)) { return false; } + // " (" + if (!irp_push(s, 1, 10272, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (n[1] == 0) { + // "whale" + if (!irp_push(s, 1, 435610019959, 5, 0, 0, 0, 0, 0, 0, depth)) { return false; } + } else { + // "sysv64" + if (!irp_push(s, 1, 57408520157555, 6, 0, 0, 0, 0, 0, 0, depth)) { return false; } + } + return true; + } + if (tag == 30) { + if (!irp_push(s, 7, n[1], n[2], 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 31) { + if (n[1] > 1) { s.status = 1; return false; } + if (n[1] != 0) { + // "true" + if (!irp_push(s, 1, 1702195828, 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + } else { + // "false" + if (!irp_push(s, 1, 435728179558, 5, 0, 0, 0, 0, 0, 0, depth)) { return false; } + } + return true; + } + if (tag == 32) { + if (!irp_push(s, 5, n[1], n[2], 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 33) { + if (!irp_push(s, 4, n[1], n[2], 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 34) { + if ((n[2] != 16 && n[2] != 32 && n[2] != 64) + || (n[2] == 16 && n[1] > 65535) || (n[2] == 32 && n[1] > 4294967295)) { s.status = 1; return false; } + if (!irp_push(s, 6, n[1], n[2] / 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "0x" + if (!irp_push(s, 1, 30768, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 35) { + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 36) { + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%b" + if (!irp_push(s, 1, 25125, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 37) { + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "@g" + if (!irp_push(s, 1, 26432, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 38) { + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "@f" + if (!irp_push(s, 1, 26176, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 40) { + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[1], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + return true; + } + if (tag == 41) { + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[1], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + return true; + } + if (tag == 42) { + // ")" + if (!irp_push(s, 1, 41, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[1], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // "neg(" + if (!irp_push(s, 1, 677864814, 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 43) { + // ")" + if (!irp_push(s, 1, 41, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[1], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // "bit_not(" + if (!irp_push(s, 1, 2915077378654103906, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 44) { + // ")" + if (!irp_push(s, 1, 41, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[3], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // ", " + if (!irp_push(s, 1, 8236, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // "(" + if (!irp_push(s, 1, 40, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_operator(s, 1, n[1], depth)) { return false; } + return true; + } + if (tag == 45) { + // ")" + if (!irp_push(s, 1, 41, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[3], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // ", " + if (!irp_push(s, 1, 8236, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // "(" + if (!irp_push(s, 1, 40, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_operator(s, 2, n[1], depth)) { return false; } + return true; + } + if (tag == 50) { + // "}\n" + if (!irp_push(s, 1, 2685, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[7], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + if (!irp_push(s, 2, n[6], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + if (!irp_push(s, 2, n[5], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + if (!irp_push(s, 2, n[4], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // " }\n\n" + if (!irp_push(s, 1, 168459552, 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (n[3] == 0) { + // "little" + if (!irp_push(s, 1, 111516484659564, 6, 0, 0, 0, 0, 0, 0, depth)) { return false; } + } else { + // "big" + if (!irp_push(s, 1, 6777186, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + } + // "=" + if (!irp_push(s, 1, 61, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", endian" + if (!irp_push(s, 1, 7953754296982773804, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[2], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "ptr=" + if (!irp_push(s, 1, 1030911088, 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "ayout { " + if (!irp_push(s, 1, 2340500115907639649, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "\n datal" + if (!irp_push(s, 1, 7809651190477627402, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[1], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // "t " + if (!irp_push(s, 1, 8308, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "\n targe" + if (!irp_push(s, 1, 7306934683317575690, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[9], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "sion " + if (!irp_push(s, 1, 139291748723, 5, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "tics_ver" + if (!irp_push(s, 1, 8243124845301426548, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "\n seman" + if (!irp_push(s, 1, 7953758699403616266, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[8], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "n " + if (!irp_push(s, 1, 8302, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "t_versio" + if (!irp_push(s, 1, 8028074745930342260, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "\n forma" + if (!irp_push(s, 1, 7020393216920789002, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "module {" + if (!irp_push(s, 1, 8872202782420266861, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 51) { + if (n[3] != 0 && n[2] != 0) { + // "\n" + if (!irp_push(s, 1, 10, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + } + if (!irp_list(s, n[1], n[2], 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 52) { + // "\n" + if (!irp_push(s, 1, 10, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "_file @s" + if (!irp_push(s, 1, 8304673332853827167, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " source" + if (!irp_push(s, 1, 7305808869231632416, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 53) { + // "\n" + if (!irp_push(s, 1, 10, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (n[2] != 18446744073709551615) { + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + } else { + // "none" + if (!irp_push(s, 1, 1701736302, 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "al " + if (!irp_push(s, 1, 2124897, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " origin" + if (!irp_push(s, 1, 7956003919315804192, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 54) { + if (!irp_push(s, 3, n[5], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[4], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[3], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[2], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "@s" + if (!irp_push(s, 1, 29504, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 55) { + // "\n" + if (!irp_push(s, 1, 10, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[4], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[3], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[2], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%b" + if (!irp_push(s, 1, 25125, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "@f" + if (!irp_push(s, 1, 26176, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "truction" + if (!irp_push(s, 1, 7957695015192719988, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "_map ins" + if (!irp_push(s, 1, 8317701149845187935, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " source" + if (!irp_push(s, 1, 7305808869231632416, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 56) { + // "\n" + if (!irp_push(s, 1, 10, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[3], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[2], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%b" + if (!irp_push(s, 1, 25125, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "@f" + if (!irp_push(s, 1, 26176, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "minator " + if (!irp_push(s, 1, 2338053702200224109, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "_map ter" + if (!irp_push(s, 1, 8243122375644769631, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " source" + if (!irp_push(s, 1, 7305808869231632416, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 57) { + // "\n" + if (!irp_push(s, 1, 10, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[2], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "@g" + if (!irp_push(s, 1, 26432, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "bal " + if (!irp_push(s, 1, 543973730, 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "_map glo" + if (!irp_push(s, 1, 8028905624716799327, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " source" + if (!irp_push(s, 1, 7305808869231632416, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 58) { + // "\n" + if (!irp_push(s, 1, 10, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[6], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // "xpr " + if (!irp_push(s, 1, 544370808, 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", init_e" + if (!irp_push(s, 1, 7304685116791005228, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[5], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", align " + if (!irp_push(s, 1, 2336918959139397676, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[4], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[3], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " = const" + if (!irp_push(s, 1, 8391171955404848416, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[3], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // ": " + if (!irp_push(s, 1, 8250, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "@g" + if (!irp_push(s, 1, 26432, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " global" + if (!irp_push(s, 1, 7809631459536740384, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 59) { + if (n[6] > 1 || n[7] > 1) { s.status = 1; return false; } + // "\n" + if (!irp_push(s, 1, 10, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (n[8] != 18446744073709551615) { + if (!irp_push(s, 2, n[8], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // "ame " + if (!irp_push(s, 1, 543518049, 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", link_n" + if (!irp_push(s, 1, 7953193588918853676, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + } + if (n[7] == 0) { + // "internal" + if (!irp_push(s, 1, 7809644666444607081, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + } else { + // "external" + if (!irp_push(s, 1, 7809644666444609637, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + } + // "e " + if (!irp_push(s, 1, 8293, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", linkag" + if (!irp_push(s, 1, 7449353380606779436, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (n[6] != 0) { + // "readonly" + if (!irp_push(s, 1, 8749489600778560882, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + } else { + // "e" + if (!irp_push(s, 1, 101, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "readwrit" + if (!irp_push(s, 1, 8388361638065038706, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", access" + if (!irp_push(s, 1, 8319104414226915372, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[5], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", align " + if (!irp_push(s, 1, 2336918959139397676, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (n[4] != 18446744073709551615) { + if (!irp_push(s, 2, n[4], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[3], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // "value " + if (!irp_push(s, 1, 35620133822838, 6, 0, 0, 0, 0, 0, 0, depth)) { return false; } + } else { + // "lized" + if (!irp_push(s, 1, 431199250796, 5, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "uninitia" + if (!irp_push(s, 1, 7019269490406420085, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + } + // " = " + if (!irp_push(s, 1, 2112800, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[3], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // ": " + if (!irp_push(s, 1, 8250, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "@g" + if (!irp_push(s, 1, 26432, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "e " + if (!irp_push(s, 1, 8293, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " storag" + if (!irp_push(s, 1, 7449361081668149280, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 60) { + if (n[4] > 1) { s.status = 1; return false; } + // "\n" + if (!irp_push(s, 1, 10, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (n[5] != 18446744073709551615) { + if (!irp_push(s, 2, n[5], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // "ame " + if (!irp_push(s, 1, 543518049, 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", link_n" + if (!irp_push(s, 1, 7953193588918853676, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + } + if (n[4] == 0) { + // "internal" + if (!irp_push(s, 1, 7809644666444607081, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + } else { + // "external" + if (!irp_push(s, 1, 7809644666444609637, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + } + // "e " + if (!irp_push(s, 1, 8293, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", linkag" + if (!irp_push(s, 1, 7449353380606779436, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[3], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // ": " + if (!irp_push(s, 1, 8250, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "@f" + if (!irp_push(s, 1, 26176, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "e " + if (!irp_push(s, 1, 8293, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " declar" + if (!irp_push(s, 1, 8241987967223341088, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 61) { + // " }\n\n" + if (!irp_push(s, 1, 43125645344, 5, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_list(s, n[7], n[8], 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " {\n" + if (!irp_push(s, 1, 686880, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[6], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%b" + if (!irp_push(s, 1, 25125, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", entry " + if (!irp_push(s, 1, 2340027325789577260, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[5], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // ") -> " + if (!irp_push(s, 1, 138482098217, 5, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_list(s, n[3], n[4], 8236, 2, 0, 0, 0, 0, depth)) { return false; } + // "(" + if (!irp_push(s, 1, 40, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "@f" + if (!irp_push(s, 1, 26176, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " fn " + if (!irp_push(s, 1, 139291140128, 5, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 62) { + if (!irp_push(s, 2, n[3], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // ": " + if (!irp_push(s, 1, 8250, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 63) { + if (n[5] != 18446744073709551615) { + // "\n" + if (!irp_push(s, 1, 10, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[5], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // " " + if (!irp_push(s, 1, 538976288, 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + } + if (!irp_list(s, n[3], n[4], 0, 0, 538976288, 4, 10, 1, depth)) { return false; } + // ":\n" + if (!irp_push(s, 1, 2618, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%b" + if (!irp_push(s, 1, 25125, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " " + if (!irp_push(s, 1, 8224, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 100) { + if (!irp_push(s, 3, n[2], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "@g" + if (!irp_push(s, 1, 26432, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "al_addr " + if (!irp_push(s, 1, 2338041538851859553, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "> = glob" + if (!irp_push(s, 1, 7093007128310128702, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[3], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // ": ptr<" + if (!irp_push(s, 1, 66462277443642, 6, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 101) { + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "_end " + if (!irp_push(s, 1, 139123909983, 5, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "lifetime" + if (!irp_push(s, 1, 7308613718930516332, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 102) { + if (!irp_push(s, 3, n[3], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", " + if (!irp_push(s, 1, 8236, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[2], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " ptrdiff" + if (!irp_push(s, 1, 7378700919631015968, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ": i128 =" + if (!irp_push(s, 1, 4404582223796838458, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 103) { + if (!irp_push(s, 2, n[4], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[5], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // "t " + if (!irp_push(s, 1, 8308, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " => cons" + if (!irp_push(s, 1, 8317708033333280032, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[3], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // "_decl " + if (!irp_push(s, 1, 35649896146015, 6, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " = const" + if (!irp_push(s, 1, 8391171955404848416, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[5], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // ": " + if (!irp_push(s, 1, 8250, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 104) { + if (!irp_push(s, 2, n[3], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " = const" + if (!irp_push(s, 1, 8391171955404848416, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // ": " + if (!irp_push(s, 1, 8250, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 105) { + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " = undef" + if (!irp_push(s, 1, 7378413990090652960, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // ": " + if (!irp_push(s, 1, 8250, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 106) { + if (!irp_push(s, 3, n[3], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // " = mov " + if (!irp_push(s, 1, 9137420199017760, 7, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // ": " + if (!irp_push(s, 1, 8250, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 107) { + if (!irp_push(s, 3, n[5], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", " + if (!irp_push(s, 1, 8236, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[4], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[3], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_operator(s, 3, n[2], depth)) { return false; } + // " = " + if (!irp_push(s, 1, 2112800, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[3], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // ": " + if (!irp_push(s, 1, 8250, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 108) { + if (!irp_push(s, 3, n[3], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // " = neg " + if (!irp_push(s, 1, 9120884591705376, 7, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // ": " + if (!irp_push(s, 1, 8250, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 109) { + if (!irp_push(s, 3, n[3], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // " = not " + if (!irp_push(s, 1, 9135221192539424, 7, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // ": " + if (!irp_push(s, 1, 8250, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 110) { + if (!irp_push(s, 3, n[5], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", " + if (!irp_push(s, 1, 8236, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[4], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[3], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_operator(s, 4, n[2], depth)) { return false; } + // " cmp " + if (!irp_push(s, 1, 139325170464, 5, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ": bool =" + if (!irp_push(s, 1, 4404639661434216506, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 111) { + if (!irp_push(s, 3, n[5], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", " + if (!irp_push(s, 1, 8236, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[4], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[3], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_operator(s, 5, n[2], depth)) { return false; } + // " icmp " + if (!irp_push(s, 1, 35667243657504, 6, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ": bool =" + if (!irp_push(s, 1, 4404639661434216506, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 112) { + if (!irp_push(s, 3, n[5], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", " + if (!irp_push(s, 1, 8236, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[4], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[3], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_operator(s, 6, n[2], depth)) { return false; } + // " fcmp " + if (!irp_push(s, 1, 35667243656736, 6, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ": bool =" + if (!irp_push(s, 1, 4404639661434216506, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 113) { + if (!irp_push(s, 3, n[5], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // ", " + if (!irp_push(s, 1, 8236, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[4], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // ", " + if (!irp_push(s, 1, 8236, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[3], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "t bool " + if (!irp_push(s, 1, 9126425120612468, 7, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " = selec" + if (!irp_push(s, 1, 7162249965381631264, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // ": " + if (!irp_push(s, 1, 8250, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 114) { + if (!irp_push(s, 2, n[3], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // " to " + if (!irp_push(s, 1, 544175136, 4, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[5], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[4], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_operator(s, 7, n[2], depth)) { return false; } + // " = " + if (!irp_push(s, 1, 2112800, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[3], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // ": " + if (!irp_push(s, 1, 8250, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 115) { + if (!irp_list(s, n[3], n[4], 8236, 2, 0, 0, 0, 0, depth)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // " = phi " + if (!irp_push(s, 1, 9123096533417248, 7, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // ": " + if (!irp_push(s, 1, 8250, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 116) { + if (!irp_push(s, 3, n[4], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", " + if (!irp_push(s, 1, 8236, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[3], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "ct " + if (!irp_push(s, 1, 2126947, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " = extra" + if (!irp_push(s, 1, 7021802829465533728, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // ": " + if (!irp_push(s, 1, 8250, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 117) { + if (!irp_push(s, 3, n[5], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", " + if (!irp_push(s, 1, 8236, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[4], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[3], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // "_chk " + if (!irp_push(s, 1, 139240956767, 5, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_operator(s, 8, n[2], depth)) { return false; } + // "= " + if (!irp_push(s, 1, 8253, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", bool> " + if (!irp_push(s, 1, 2323413683635626028, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[3], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // ": tuple<" + if (!irp_push(s, 1, 4352003845186134074, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 118) { + if (!irp_push(s, 3, n[3], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", align " + if (!irp_push(s, 1, 2336918959139397676, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // "ca " + if (!irp_push(s, 1, 2122083, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "> = allo" + if (!irp_push(s, 1, 8028911400103256126, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // ": ptr<" + if (!irp_push(s, 1, 66462277443642, 6, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 119) { + if (!irp_push(s, 3, n[4], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", align " + if (!irp_push(s, 1, 2336918959139397676, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[3], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "> " + if (!irp_push(s, 1, 8254, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // ", ptr<" + if (!irp_push(s, 1, 66462277443628, 6, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "ile_load" + if (!irp_push(s, 1, 7233184987781360745, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " = volat" + if (!irp_push(s, 1, 8386103207119568160, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // ": " + if (!irp_push(s, 1, 8250, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 121) { + if (!irp_push(s, 3, n[4], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", align " + if (!irp_push(s, 1, 2336918959139397676, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[3], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "> " + if (!irp_push(s, 1, 8254, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // ", ptr<" + if (!irp_push(s, 1, 66462277443628, 6, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // " = load " + if (!irp_push(s, 1, 2334097638068075808, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // ": " + if (!irp_push(s, 1, 8250, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 120) { + if (!irp_push(s, 3, n[4], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", align " + if (!irp_push(s, 1, 2336918959139397676, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[3], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "> " + if (!irp_push(s, 1, 8254, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[1], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // ", ptr<" + if (!irp_push(s, 1, 66462277443628, 6, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[2], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[1], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // "_store " + if (!irp_push(s, 1, 9118741425320799, 7, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "volatile" + if (!irp_push(s, 1, 7308332243887091574, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 123) { + if (!irp_push(s, 3, n[4], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", align " + if (!irp_push(s, 1, 2336918959139397676, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[3], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "> " + if (!irp_push(s, 1, 8254, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[1], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // ", ptr<" + if (!irp_push(s, 1, 66462277443628, 6, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[2], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[1], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // "store " + if (!irp_push(s, 1, 35620083692659, 6, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 122) { + if (!irp_push(s, 3, n[3], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", align " + if (!irp_push(s, 1, 2336918959139397676, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[2], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "> " + if (!irp_push(s, 1, 8254, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[1], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // ", ptr<" + if (!irp_push(s, 1, 66462277443628, 6, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[1], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // "uninit " + if (!irp_push(s, 1, 9135195427532405, 7, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 124) { + if (!irp_list(s, n[4], n[5], 0, 0, 8236, 2, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[3], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " = gep " + if (!irp_push(s, 1, 9130780078914848, 7, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // ": " + if (!irp_push(s, 1, 8250, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 125) { + if (!irp_push(s, 3, n[4], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", align " + if (!irp_push(s, 1, 2336918959139397676, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[3], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", u64 " + if (!irp_push(s, 1, 35408624033836, 6, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[2], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "> " + if (!irp_push(s, 1, 8254, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", ptr " + if (!irp_push(s, 1, 9075611460727412, 7, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "memcpy p" + if (!irp_push(s, 1, 8079591255114081645, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 126) { + if (!irp_push(s, 3, n[4], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", align " + if (!irp_push(s, 1, 2336918959139397676, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[3], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", u64 " + if (!irp_push(s, 1, 35408624033836, 6, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[2], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", u8 " + if (!irp_push(s, 1, 138386153516, 5, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "tr " + if (!irp_push(s, 1, 9075611460727412, 7, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "memset p" + if (!irp_push(s, 1, 8079585710579737965, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 127) { + // "n" + if (!irp_push(s, 1, 110, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "_functio" + if (!irp_push(s, 1, 8028075781168391775, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "> = null" + if (!irp_push(s, 1, 7812748569428697150, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // ": fnptr<" + if (!irp_push(s, 1, 4355671815858036794, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 128) { + if (!irp_push(s, 3, n[2], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "@f" + if (!irp_push(s, 1, 26176, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "r " + if (!irp_push(s, 1, 8306, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "tion_add" + if (!irp_push(s, 1, 7234013963966441844, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "> = func" + if (!irp_push(s, 1, 7164793138681028670, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[3], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // ": fnptr<" + if (!irp_push(s, 1, 4355671815858036794, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 129) { + if (n[1] > 1) { s.status = 1; return false; } + // ")" + if (!irp_push(s, 1, 41, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_list(s, n[5], n[6], 8236, 2, 0, 0, 0, 0, depth)) { return false; } + // "(" + if (!irp_push(s, 1, 40, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[4], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[3], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (n[1] == 0) { + // "whale" + if (!irp_push(s, 1, 435610019959, 5, 0, 0, 0, 0, 0, 0, depth)) { return false; } + } else { + // "sysv64" + if (!irp_push(s, 1, 57408520157555, 6, 0, 0, 0, 0, 0, 0, depth)) { return false; } + } + // "call " + if (!irp_push(s, 1, 139257995619, 5, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (n[2] != 18446744073709551615) { + // " = " + if (!irp_push(s, 1, 2112800, 3, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[3], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // ": " + if (!irp_push(s, 1, 8250, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[2], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + } + return true; + } + if (tag == 130) { + if (!irp_push(s, 2, n[2], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // "=" + if (!irp_push(s, 1, 61, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", reason" + if (!irp_push(s, 1, 7957705928737955884, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "bool " + if (!irp_push(s, 1, 139258195810, 5, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "trap_if " + if (!irp_push(s, 1, 2334669315466424948, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 140) { + // " ]" + if (!irp_push(s, 1, 23840, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[2], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%b" + if (!irp_push(s, 1, 25125, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", " + if (!irp_push(s, 1, 8236, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "[ " + if (!irp_push(s, 1, 8283, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 141) { + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "@f" + if (!irp_push(s, 1, 26176, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 142) { + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "indirect" + if (!irp_push(s, 1, 8386658473162862185, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 150) { + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%b" + if (!irp_push(s, 1, 25125, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "br label" + if (!irp_push(s, 1, 7810757299309408866, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 151) { + if (!irp_push(s, 3, n[3], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%b" + if (!irp_push(s, 1, 25125, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", label " + if (!irp_push(s, 1, 2336353779914121260, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[2], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%b" + if (!irp_push(s, 1, 25125, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", label " + if (!irp_push(s, 1, 2336353779914121260, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[1], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "cbr bool" + if (!irp_push(s, 1, 7813586345752945251, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 152) { + // " ]" + if (!irp_push(s, 1, 23840, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_list(s, n[4], n[5], 44, 1, 32, 1, 0, 0, depth)) { return false; } + // " [" + if (!irp_push(s, 1, 23328, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[3], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%b" + if (!irp_push(s, 1, 25125, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", label " + if (!irp_push(s, 1, 2336353779914121260, 8, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 3, n[2], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // " " + if (!irp_push(s, 1, 32, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + if (!irp_push(s, 2, n[1], 0, 0, 0, 0, 0, 0, 0, depth + 1)) { return false; } + // "switch " + if (!irp_push(s, 1, 9121975618860915, 7, 0, 0, 0, 0, 0, 0, depth)) { return false; } + return true; + } + if (tag == 153) { + if (n[1] >= s.node_count) { s.status = 1; return false; } + if (s.nodes[n[1] * 12] != 1) { + if (n[2] != 18446744073709551615) { + if (!irp_push(s, 3, n[2], 0, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // "%v" + if (!irp_push(s, 1, 30245, 2, 0, 0, 0, 0, 0, 0, depth)) { return false; } + } else { + // ">" + if (!irp_push(s, 1, 62, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + // ", low: u64, high: u64, signed_value: bool, + depth: u64) -> bool { + var negative: bool = signed_value && (high >> 63) != 0; + if (negative) { + high = ~high; + if (low == 0) { high += 1; } + else { low = ~low + 1; } + } + var remaining: bool = true; + while (remaining) { + var q_high: u64 = high / 10; + var rem: u64 = high % 10; + var q_low: u64 = 0; + var bit: u64 = 64; + while (bit != 0) { + bit -= 1; + rem = rem * 2 + ((low >> bit) & 1); + if (rem >= 10) { rem -= 10; q_low = q_low | ((1 as u64) << bit); } + } + if (!irp_push(s, 1, rem + 48, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + low = q_low; high = q_high; + remaining = low != 0 || high != 0; + } + if (negative) { return irp_push(s, 1, 45, 1, 0, 0, 0, 0, 0, 0, depth); } + return true; +} + +fun irp_hex(s: ptr, value: u64, digits: u64, depth: u64) -> bool { + if (digits > 16) { s.status = 1; return false; } + while (digits != 0) { + var digit: u64 = value & 15; + var octet: u64 = digit + 48; + if (digit >= 10) { octet = digit + 87; } + if (!irp_push(s, 1, octet, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + value = value >> 4; + digits -= 1; + } + return true; +} + +fun irp_string(s: ptr, data: ptr, length: u64, + at: u64, depth: u64) -> bool { + if (at == length) { return irp_push(s, 1, 34, 1, 0, 0, 0, 0, 0, 0, depth); } + var width: u64 = 0; + var cp: u64 = 0; + if (!ir_lex_utf8(data, length, at, &width, &cp)) { s.status = 1; return false; } + if (!irp_push(s, 9, data as u64, length, at + width, 0, 0, 0, 0, 0, depth)) { return false; } + if (cp == 92 || cp == 34) { + return irp_push(s, 1, 92 | (cp << 8), 2, 0, 0, 0, 0, 0, 0, depth); + } + if (cp == 10 || cp == 13 || cp == 9 || cp == 0) { + var code: u64 = 48; + if (cp == 10) { code = 110; } + else if (cp == 13) { code = 114; } + else if (cp == 9) { code = 116; } + return irp_push(s, 1, 92 | (code << 8), 2, 0, 0, 0, 0, 0, 0, depth); + } + if (cp < 32 || (cp >= 127 && cp <= 159) || cp == 8232 || cp == 8233) { + if (!irp_push(s, 1, 125, 1, 0, 0, 0, 0, 0, 0, depth)) { return false; } + var digits: u64 = 1; + var remaining: u64 = cp >> 4; + while (remaining != 0) { digits += 1; remaining = remaining >> 4; } + if (!irp_hex(s, cp, digits, depth)) { return false; } + return irp_push(s, 1, 8090972, 3, 0, 0, 0, 0, 0, 0, depth); + } + var packed: u64 = 0; + var i: u64 = 0; + while (i < width) { packed = packed | ((data[at + i] as u64) << (8 * i)); i += 1; } + return irp_push(s, 1, packed, width, 0, 0, 0, 0, 0, 0, depth); +} + +// Status: 0 complete, 1 malformed transport, 2 output limit, 3 stack, +// 4 work, 5 depth, 6 chunk ready. Each call advances the same state and +// publishes at most capacity bytes; all status/error paths respect the ceiling. +export(c) fun whale_ir_print_step(s: ptr, root: u64, + output: ptr, capacity: u64, written: ptr) -> i32 { + if (s == null || written == null) { return 1; } + written[0] = 0; + if (!ir_span_valid(output, capacity, 1) + || !ir_span_valid(s.nodes as ptr, s.node_count, 96) + || !ir_span_valid(s.edges as ptr, s.edge_count, 8) + || !ir_span_valid(s.stack as ptr, s.stack_capacity, 80) + || s.stack_len > s.stack_capacity || s.total > s.output_limit + || s.initialized > 1 || s.depth_limit > 1024) { s.status = 1; return 1; } + if (s.status != 0) { return s.status as i32; } + if (s.initialized == 0) { + if (s.stack_len != 0) { s.status = 1; return 1; } + s.initialized = 1; + if (!irp_push(s, 2, root, 0, 0, 0, 0, 0, 0, 0, 0)) { return s.status as i32; } + } + // Locals are scalar fields, never a loop-local aggregate alloca. + while (s.stack_len != 0 && s.status == 0) { + if (s.work == 0) { s.status = 4; break; } + s.work -= 1; + var p: ptr = &s.stack[(s.stack_len - 1) * 10]; + var kind: u64 = p[0]; + var a: u64 = p[1]; var b: u64 = p[2]; var c: u64 = p[3]; var d: u64 = p[4]; + var e: u64 = p[5]; var f: u64 = p[6]; var g: u64 = p[7]; var h: u64 = p[8]; + var depth: u64 = p[9]; + if (kind == 1) { + if (b > 8) { s.status = 1; break; } + if (b == 0) { s.stack_len -= 1; } + else { + if (s.total == s.output_limit) { s.status = 2; break; } + if (written[0] == capacity) { return 6; } + output[written[0]] = (a & 255) as u8; + written[0] += 1; s.total += 1; + p[1] = a >> 8; p[2] = b - 1; + } + } else { + s.stack_len -= 1; + if (kind == 2) { irp_expand(s, a, depth); } + else if (kind == 3) { irp_integer(s, a, 0, false, depth); } + else if (kind == 4) { irp_integer(s, a, b, false, depth); } + else if (kind == 5) { irp_integer(s, a, b, true, depth); } + else if (kind == 6) { irp_hex(s, a, b, depth); } + else if (kind == 7) { + if (!ir_span_valid(a as ptr, b, 1)) { s.status = 1; } + else if (irp_push(s, 9, a, b, 0, 0, 0, 0, 0, 0, depth)) { + irp_push(s, 1, 34, 1, 0, 0, 0, 0, 0, 0, depth); + } + } else if (kind == 8) { + if (a > s.edge_count || b > s.edge_count - a || d > 8 || f > 8 || h > 8) { s.status = 1; } + else if (b != 0) { + var child: u64 = s.edges[a]; + if (irp_push(s, 8, a + 1, b - 1, c, d, e, f, g, h, depth) + && irp_push(s, 1, c, 0, 0, 0, 0, 0, 0, 0, depth)) { + // The separator belongs before subsequent items, not after the last. + // Encode the continuation's prefix in its first-item flag below. + if (b > 1) { s.stack[(s.stack_len - 1) * 10 + 2] = d; } + // Move separator beneath the child and its suffix. + irp_push(s, 1, g, h, 0, 0, 0, 0, 0, 0, depth); + irp_push(s, 2, child, 0, 0, 0, 0, 0, 0, 0, depth + 1); + irp_push(s, 1, e, f, 0, 0, 0, 0, 0, 0, depth); + } + } + } else if (kind == 9) { irp_string(s, a as ptr, b, c, depth); } + else { s.status = 1; } + } + } + return s.status as i32; +} diff --git a/ir/shape.wave b/ir/shape.wave new file mode 100644 index 0000000..0910778 --- /dev/null +++ b/ir/shape.wave @@ -0,0 +1,151 @@ +// SPDX-License-Identifier: MPL-2.0 +// Bounded identity and branch-shape validation before SSA/type analysis. +struct IrShapeBlock { + id: u64; + terminated: u64; + first_edge: u64; + edge_count: u64; +} + +struct IrShapeValue { + id: u64; + void_parameter: u64; +} + +struct IrShapeResult { + status: u64; // 1 duplicate block, 2 entry, 3 duplicate value, + // 4 unterminated, 5 branch target, 6 transport, 7 work, + // 8 void parameter + index: u64; + detail: u64; + work: u64; +} + +fun ir_shape_hash(id: u64, mask: u64) -> u64 { + return (id ^ (id >> 16)) & mask; +} + +fun ir_shape_insert(table: ptr, capacity: u64, id: u64, + work: ptr, limit: u64) -> i32 { + var position: u64 = ir_shape_hash(id, capacity - 1); + while (true) { + if (!ir_cfg_charge(work, limit)) { return 2; } + if (table[position] == 18446744073709551615) { + table[position] = id; return 0; + } + if (table[position] == id) { return 1; } + position = (position + 1) & (capacity - 1); + } +} + +fun ir_shape_contains(table: ptr, capacity: u64, id: u64, + work: ptr, limit: u64) -> i32 { + var position: u64 = ir_shape_hash(id, capacity - 1); + while (true) { + if (!ir_cfg_charge(work, limit)) { return 2; } + if (table[position] == 18446744073709551615) { return 0; } + if (table[position] == id) { return 1; } + position = (position + 1) & (capacity - 1); + } +} + +export(c) fun whale_ir_shape_contains(table: ptr, capacity: u64, id: u64, + max_work: u64, result: ptr) -> i32 { + if (result == null) { return 6; } + result.status = 0; result.index = 0; result.detail = 0; result.work = 0; + if (capacity < 2 || !ir_power_two(capacity) + || !ir_span_valid(table as ptr, capacity, 8)) { result.status = 6; return 6; } + var work: u64 = 0; + var found: i32 = ir_shape_contains(table, capacity, id, &work, max_work); + result.work = work; + if (found == 2) { result.status = 7; return 7; } + result.detail = found as u64; + return 0; +} + +fun ir_shape_error(result: ptr, status: u64, index: u64, + detail: u64, work: u64) -> i32 { + result.status = status; result.index = index; + result.detail = detail; result.work = work; + return status as i32; +} + +export(c) fun whale_ir_verify_shape(blocks: ptr, block_count: u64, + entry: u64, values: ptr, value_count: u64, + edges: ptr, edge_count: u64, max_work: u64, + block_table: ptr, block_table_capacity: u64, + value_table: ptr, value_table_capacity: u64, + result: ptr) -> i32 { + if (result == null) { return 6; } + result.status = 0; result.index = 0; result.detail = 0; result.work = 0; + if (!ir_span_valid(blocks as ptr, block_count, 32) + || !ir_span_valid(values as ptr, value_count, 16) + || !ir_span_valid(edges as ptr, edge_count, 8) + || !ir_span_valid(block_table as ptr, block_table_capacity, 8) + || !ir_span_valid(value_table as ptr, value_table_capacity, 8) + || block_table_capacity < 2 || value_table_capacity < 2 + || !ir_power_two(block_table_capacity) || !ir_power_two(value_table_capacity) + || block_count > block_table_capacity / 2 + || value_count > value_table_capacity / 2) { + return ir_shape_error(result, 6, 0, 0, 0); + } + var work: u64 = 0; + var index: u64 = 0; + while (index < block_table_capacity) { + if (!ir_cfg_charge(&work, max_work)) { return ir_shape_error(result, 7, index, 0, work); } + block_table[index] = 18446744073709551615; + index += 1; + } + index = 0; + while (index < value_table_capacity) { + if (!ir_cfg_charge(&work, max_work)) { return ir_shape_error(result, 7, index, 0, work); } + value_table[index] = 18446744073709551615; + index += 1; + } + index = 0; + while (index < block_count) { + var block: ptr = &blocks[index]; + if (block.first_edge > edge_count || block.edge_count > edge_count - block.first_edge) { + return ir_shape_error(result, 6, index, 0, work); + } + var status: i32 = ir_shape_insert(block_table, block_table_capacity, + block.id, &work, max_work); + if (status == 1) { return ir_shape_error(result, 1, index, block.id, work); } + if (status == 2) { return ir_shape_error(result, 7, index, 0, work); } + index += 1; + } + var present: i32 = ir_shape_contains(block_table, block_table_capacity, + entry, &work, max_work); + if (present == 0) { return ir_shape_error(result, 2, 0, entry, work); } + if (present == 2) { return ir_shape_error(result, 7, 0, 0, work); } + index = 0; + while (index < value_count) { + if (values[index].void_parameter != 0) { + return ir_shape_error(result, 8, index, values[index].id, work); + } + var status: i32 = ir_shape_insert(value_table, value_table_capacity, + values[index].id, &work, max_work); + if (status == 1) { return ir_shape_error(result, 3, index, values[index].id, work); } + if (status == 2) { return ir_shape_error(result, 7, index, 0, work); } + index += 1; + } + index = 0; + while (index < block_count) { + var block: ptr = &blocks[index]; + if (block.terminated == 0) { + return ir_shape_error(result, 4, index, block.id, work); + } + var edge: u64 = 0; + while (edge < block.edge_count) { + var target: u64 = edges[block.first_edge + edge]; + var present: i32 = ir_shape_contains(block_table, block_table_capacity, + target, &work, max_work); + if (present == 0) { return ir_shape_error(result, 5, index, target, work); } + if (present == 2) { return ir_shape_error(result, 7, index, 0, work); } + edge += 1; + } + index += 1; + } + result.work = work; + return 0; +} diff --git a/ir/source.wave b/ir/source.wave new file mode 100644 index 0000000..338fbab --- /dev/null +++ b/ir/source.wave @@ -0,0 +1,154 @@ +// SPDX-License-Identifier: MPL-2.0 +// Source identities and mapping validation. Caller storage, Wave decisions. +struct IrSourceFile { id: u64; bytes: ptr; length: u64; } + +struct IrSourceOriginal { + id: u64; has_span: u64; file: u64; line: u64; column: u64; + end_line: u64; end_column: u64; +} + +struct IrSourceBlock { function: u64; block: u64; instructions: u64; terminated: u64; } + +struct IrSourceMapping { kind: u64; function: u64; block: u64; index: u64; original: u64; } + +struct IrSourceSlot { kind: u64; a: u64; b: u64; c: u64; value: u64; extra: u64; } + +struct IrSourceResult { status: u64; index: u64; work: u64; } + +fun ir_source_fail(result: ptr, status: u64, index: u64, work: u64) -> i32 { + result.status = status; result.index = index; result.work = work; return status as i32; +} + +// Return the matching slot or an empty slot. Probes always consume budget. +fun ir_source_mix(value: u64) -> u64 { + var x: u64 = value; + x = (x ^ (x >> 30)) * 13787848793156543929; + x = (x ^ (x >> 27)) * 10723151780598845931; + return x ^ (x >> 31); +} + +fun ir_source_slot(table: ptr, capacity: u64, kind: u64, + a: u64, b: u64, c: u64, work: ptr, limit: u64) -> u64 { + var hash: u64 = ir_source_mix(a ^ (kind * 16777619)); + hash = ir_source_mix(hash ^ b); + var at: u64 = ir_source_mix(hash ^ c) & (capacity - 1); + while (true) { + if (!ir_cfg_charge(work, limit)) { return capacity; } + var slot: ptr = &table[at]; + if (slot.kind == 0 || (slot.kind == kind && slot.a == a && slot.b == b && slot.c == c)) { return at; } + at = (at + 1) & (capacity - 1); + } + return capacity; +} + +fun ir_source_put(table: ptr, at: u64, kind: u64, a: u64, b: u64, c: u64, value: u64, extra: u64) { + table[at].kind = kind; table[at].a = a; table[at].b = b; table[at].c = c; + table[at].value = value; table[at].extra = extra; +} + +export(c) fun whale_ir_verify_sources(files: ptr, file_count: u64, + originals: ptr, original_count: u64, + blocks: ptr, block_count: u64, + globals: ptr, global_count: u64, + mappings: ptr, mapping_count: u64, + table: ptr, capacity: u64, max_work: u64, + result: ptr) -> i32 { + if (result == null) { return 6; } + result.status = 0; result.index = 0; result.work = 0; + if (!ir_span_valid(files as ptr, file_count, 24) + || !ir_span_valid(originals as ptr, original_count, 56) + || !ir_span_valid(blocks as ptr, block_count, 32) + || !ir_span_valid(globals as ptr, global_count, 8) + || !ir_span_valid(mappings as ptr, mapping_count, 40) + || !ir_span_valid(table as ptr, capacity, 48) + || capacity < 2 || !ir_power_two(capacity)) { return ir_source_fail(result, 6, 0, 0); } + if (file_count > capacity / 2) { return ir_source_fail(result, 6, 0, 0); } + var total: u64 = file_count; + if (original_count > capacity / 2 - total) { return ir_source_fail(result, 6, 0, 0); } + total += original_count; + if (block_count > capacity / 2 - total) { return ir_source_fail(result, 6, 0, 0); } + total += block_count; + if (global_count > capacity / 2 - total) { return ir_source_fail(result, 6, 0, 0); } + total += global_count; + if (mapping_count > capacity / 2 - total) { return ir_source_fail(result, 6, 0, 0); } + var work: u64 = 0; var i: u64 = 0; + while (i < capacity) { + if (!ir_cfg_charge(&work, max_work)) { return ir_source_fail(result, 7, i, work); } + table[i].kind = 0; i += 1; + } + i = 0; + while (i < file_count) { + var file: ptr = &files[i]; + if (!ir_span_valid(file.bytes, file.length, 1)) { return ir_source_fail(result, 6, i, work); } + if (file.length == 0) { return ir_source_fail(result, 1, i, work); } + var character: u64 = 0; + while (character < file.length) { + if (!ir_cfg_charge(&work, max_work)) { return ir_source_fail(result, 7, i, work); } + if (file.bytes[character] == 0) { return ir_source_fail(result, 1, i, work); } + character += 1; + } + var at: u64 = ir_source_slot(table, capacity, 1, file.id, 0, 0, &work, max_work); + if (at == capacity) { return ir_source_fail(result, 7, i, work); } + if (table[at].kind != 0) { return ir_source_fail(result, 1, i, work); } + ir_source_put(table, at, 1, file.id, 0, 0, 0, 0); i += 1; + } + i = 0; + while (i < original_count) { + var node: ptr = &originals[i]; + var at: u64 = ir_source_slot(table, capacity, 2, node.id, 0, 0, &work, max_work); + if (at == capacity) { return ir_source_fail(result, 7, i, work); } + if (table[at].kind != 0) { return ir_source_fail(result, 2, i, work); } + ir_source_put(table, at, 2, node.id, 0, 0, 0, 0); + if (node.has_span > 1) { return ir_source_fail(result, 6, i, work); } + if (node.has_span == 1) { + at = ir_source_slot(table, capacity, 1, node.file, 0, 0, &work, max_work); + if (at == capacity) { return ir_source_fail(result, 7, i, work); } + if (table[at].kind == 0 || node.line == 0 || node.column == 0 + || node.end_line == 0 || node.end_column == 0 || node.line > node.end_line + || (node.line == node.end_line && node.column > node.end_column)) { + return ir_source_fail(result, 3, i, work); + } + } + i += 1; + } + i = 0; + while (i < block_count) { + var block: ptr = &blocks[i]; + if (block.terminated > 1) { return ir_source_fail(result, 6, i, work); } + var at: u64 = ir_source_slot(table, capacity, 3, block.function, block.block, 0, &work, max_work); + if (at == capacity) { return ir_source_fail(result, 7, i, work); } + ir_source_put(table, at, 3, block.function, block.block, 0, block.instructions, block.terminated); + i += 1; + } + i = 0; + while (i < global_count) { + var at: u64 = ir_source_slot(table, capacity, 4, globals[i], 0, 0, &work, max_work); + if (at == capacity) { return ir_source_fail(result, 7, i, work); } + ir_source_put(table, at, 4, globals[i], 0, 0, 0, 0); i += 1; + } + i = 0; + while (i < mapping_count) { + var mapping: ptr = &mappings[i]; + if (mapping.kind > 2 || (mapping.kind == 1 && mapping.index != 0) + || (mapping.kind == 2 && (mapping.block != 0 || mapping.index != 0))) { return ir_source_fail(result, 6, i, work); } + var at: u64 = ir_source_slot(table, capacity, 2, mapping.original, 0, 0, &work, max_work); + if (at == capacity) { return ir_source_fail(result, 7, i, work); } + if (table[at].kind == 0) { return ir_source_fail(result, 4, i, work); } + at = ir_source_slot(table, capacity, 5 + mapping.kind, mapping.function, mapping.block, mapping.index, &work, max_work); + if (at == capacity) { return ir_source_fail(result, 7, i, work); } + if (table[at].kind != 0) { return ir_source_fail(result, 4, i, work); } + ir_source_put(table, at, 5 + mapping.kind, mapping.function, mapping.block, mapping.index, 0, 0); + if (mapping.kind == 2) { + at = ir_source_slot(table, capacity, 4, mapping.function, 0, 0, &work, max_work); + if (at == capacity) { return ir_source_fail(result, 7, i, work); } + if (table[at].kind == 0) { return ir_source_fail(result, 5, i, work); } + } else { + at = ir_source_slot(table, capacity, 3, mapping.function, mapping.block, 0, &work, max_work); + if (at == capacity) { return ir_source_fail(result, 7, i, work); } + if (table[at].kind == 0 || (mapping.kind == 0 && mapping.index >= table[at].value) + || (mapping.kind == 1 && table[at].extra == 0)) { return ir_source_fail(result, 5, i, work); } + } + i += 1; + } + result.work = work; return 0; +} diff --git a/ir/src/builder.rs b/ir/src/builder.rs index 0c0928c..5bcd137 100644 --- a/ir/src/builder.rs +++ b/ir/src/builder.rs @@ -5,6 +5,15 @@ use crate::{ ICmpPred, Instruction, Module, Param, Terminator, Type, ValueId, }; +#[cfg(whale_wave_ir)] +mod body; + +#[cfg(whale_wave_ir)] +mod namespace; + +#[cfg(whale_wave_ir)] +mod wave; + /// Construction-order errors returned by the `try_*` builder operations. #[derive(Clone, Debug, PartialEq, Eq)] pub enum BuilderError { @@ -15,11 +24,17 @@ pub enum BuilderError { InvalidPointerOperands, TerminatedBlock(BlockId), PhiAfterInstruction(BlockId), + ResourceLimit(crate::LimitError), + IdentityOverflow, + InvalidType, } impl std::fmt::Display for BuilderError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { + Self::ResourceLimit(error) => error.fmt(f), + Self::IdentityOverflow => f.write_str("builder identity space exhausted"), + Self::InvalidType => f.write_str("invalid typed builder model"), Self::UnknownBlock(id) => write!(f, "unknown builder block {id:?}"), Self::UnknownParameter { index, count } => { write!(f, "parameter {index} is outside 0..{count}") @@ -42,6 +57,10 @@ pub struct ModuleBuilder { next_value: u32, next_block: u32, next_global: u32, + #[cfg(not(whale_wave_ir))] + limits: crate::IrLimits, + #[cfg(whale_wave_ir)] + wave: wave::Builder, #[cfg(feature = "socket")] source_work: usize, #[cfg(feature = "socket")] @@ -68,39 +87,52 @@ impl FunctionBuilder<'_> { impl<'a> FunctionBuilder<'a> { pub fn try_global_addr(&mut self, global: crate::GlobalId) -> Result { self.ensure_insertable()?; - let ty = self + let ty = &self .mb .module .global_storage .iter() .find(|g| g.id == global) .ok_or(BuilderError::UnknownGlobal(global))? - .ty - .clone(); - let dst = self.define_value(Type::ptr_to(ty.clone())); - self.cur_block_mut().instructions.push(Instruction::GlobalAddr { dst, global, ty }); + .ty; + self.mb.preflight_type(ty)?; + let pointer = Type::ptr_to(ty.clone()); + self.preflight_value(&pointer, 0, 0)?; + let ty = ty.clone(); + let dst = self.define_value(&pointer); + self.push_instruction(Instruction::GlobalAddr { dst, global, ty }); Ok(dst) } pub fn try_lifetime_end(&mut self, ptr: ValueId) -> Result<(), BuilderError> { self.ensure_insertable()?; + #[cfg(whale_wave_ir)] + self.mb.wave.preflight_instruction(1, 0)?; self.ensure_values(&[ptr])?; + #[cfg(whale_wave_ir)] + self.mb.wave.pointer(self.first_value, ptr, None)?; + #[cfg(not(whale_wave_ir))] if !matches!(self.func.value_type(ptr), Some(Type::Ptr(_))) { return Err(BuilderError::InvalidPointerOperands); } - self.cur_block_mut().instructions.push(Instruction::LifetimeEnd { ptr }); + self.push_instruction(Instruction::LifetimeEnd { ptr }); Ok(()) } pub fn try_ptrdiff(&mut self, lhs: ValueId, rhs: ValueId) -> Result { self.ensure_insertable()?; + self.preflight_value(&Type::I128, 2, 0)?; self.ensure_values(&[lhs, rhs])?; + #[cfg(whale_wave_ir)] + self.mb.wave.pointer(self.first_value, lhs, Some(rhs))?; + #[cfg(not(whale_wave_ir))] let ty = self.func.value_type(lhs).unwrap(); + #[cfg(not(whale_wave_ir))] if !matches!(ty, Type::Ptr(_)) || self.func.value_type(rhs) != Some(ty) { return Err(BuilderError::InvalidPointerOperands); } - let dst = self.define_value(Type::I128); - self.cur_block_mut().instructions.push(Instruction::PtrDiff { dst, lhs, rhs }); + let dst = self.define_value(&Type::I128); + self.push_instruction(Instruction::PtrDiff { dst, lhs, rhs }); Ok(dst) } @@ -109,20 +141,22 @@ impl<'a> FunctionBuilder<'a> { } pub fn try_not(&mut self, ty: Type, src: ValueId) -> Result { + let ty = self.bound_type(ty)?; self.ensure_insertable()?; self.ensure_values(&[src])?; + self.preflight_value(&ty, 1, 0)?; Ok(self.not(ty, src)) } pub fn neg(&mut self, ty: Type, src: ValueId) -> ValueId { - let dst = self.define_value(ty.clone()); - self.cur_block_mut().instructions.push(Instruction::Neg { dst, ty, src }); + let dst = self.define_value(&ty); + self.push_instruction(Instruction::Neg { dst, ty, src }); dst } pub fn not(&mut self, ty: Type, src: ValueId) -> ValueId { - let dst = self.define_value(ty.clone()); - self.cur_block_mut().instructions.push(Instruction::Not { dst, ty, src }); + let dst = self.define_value(&ty); + self.push_instruction(Instruction::Not { dst, ty, src }); dst } @@ -133,16 +167,30 @@ impl<'a> FunctionBuilder<'a> { ty: Type, incomings: Vec<(ValueId, BlockId)>, ) -> Result { + let ty = self.bound_type(ty)?; self.ensure_insertable()?; for (value, block) in &incomings { self.ensure_values(&[*value])?; self.ensure_block(*block)?; } + #[cfg(whale_wave_ir)] + self.mb.wave.order( + self.first_block, + self.first_value, + self.insert_block, + 15, + &[], + &[], + true, + )?; + #[cfg(not(whale_wave_ir))] if self._cur_block().instructions.iter().any(|i| !matches!(i, Instruction::Phi { .. })) { return Err(BuilderError::PhiAfterInstruction(self.insert_block)); } - let dst = self.define_value(ty.clone()); - self.cur_block_mut().instructions.push(Instruction::Phi { dst, ty, incomings }); + self.mb.preflight_type(&ty)?; + self.preflight_value(&ty, incomings.len(), incomings.len())?; + let dst = self.define_value(&ty); + self.push_instruction(Instruction::Phi { dst, ty, incomings }); Ok(dst) } @@ -152,11 +200,12 @@ impl<'a> FunctionBuilder<'a> { /// Legacy diagnostic construction; verification rejects this instruction. pub fn undef(&mut self, ty: Type) -> ValueId { - let dst = self.define_value(ty.clone()); - self.cur_block_mut().instructions.push(Instruction::Undef { dst, ty }); + let dst = self.define_value(&ty); + self.push_instruction(Instruction::Undef { dst, ty }); dst } + #[cfg(not(whale_wave_ir))] fn _cur_block(&self) -> &BasicBlock { self.func.blocks.iter().find(|b| b.id == self.insert_block).expect("insert block not found") } @@ -171,19 +220,40 @@ impl<'a> FunctionBuilder<'a> { } pub fn alloca_in_entry(&mut self, ty: Type, align: u32) -> ValueId { - let dst = self.define_value(Type::Ptr(Box::new(ty.clone()))); + self.mb.preflight_type(&ty).expect("invalid builder type"); + let dst = self.define_value(&Type::Ptr(Box::new(ty.clone()))); let entry = self.func.entry; - + let instruction = Instruction::Alloca { dst, ty, align }; + #[cfg(whale_wave_ir)] + let pos = { + self.mb + .wave + .order(self.first_block, self.first_value, entry, 36, &[], &[], true) + .expect("invalid builder entry instruction"); + self.mb + .wave + .body + .instruction(entry, &instruction, true, false) + .expect("invalid Wave entry allocation body") + }; let entry_block = self.func.blocks.iter_mut().find(|b| b.id == entry).expect("entry block not found"); - + #[cfg(not(whale_wave_ir))] let pos = entry_block .instructions .iter() .position(|ins| !matches!(ins, Instruction::Alloca { .. })) .unwrap_or(entry_block.instructions.len()); - entry_block.instructions.insert(pos, Instruction::Alloca { dst, ty, align }); + #[cfg(not(whale_wave_ir))] + entry_block.instructions.insert(pos, instruction); + #[cfg(whale_wave_ir)] + entry_block.instructions.push(instruction); + #[cfg(whale_wave_ir)] + self.mb + .wave + .mark(self.first_block, self.first_value, entry, 36, &[], &[]) + .expect("invalid builder entry instruction"); if self.mb.source_mapped_functions.contains(&self.func.id) { self.mb @@ -199,8 +269,23 @@ impl<'a> FunctionBuilder<'a> { impl ModuleBuilder { pub fn new(target: impl Into, datalayout: DataLayout) -> Self { - Self { + Self::with_limits(target, datalayout, crate::IrLimits::default()) + .expect("valid builder limits") + } + + /// Construct with explicit limits for typed construction. + pub fn with_limits( + target: impl Into, + datalayout: DataLayout, + limits: crate::IrLimits, + ) -> Result { + limits.validate().map_err(BuilderError::ResourceLimit)?; + Ok(Self { module: Module::new(target, datalayout), + #[cfg(not(whale_wave_ir))] + limits, + #[cfg(whale_wave_ir)] + wave: wave::Builder::new(limits), next_value: 0, next_block: 0, next_global: 0, @@ -211,7 +296,7 @@ impl ModuleBuilder { .expect("valid defaults"), source_shifts: std::collections::HashMap::new(), source_mapped_functions: std::collections::HashSet::new(), - } + }) } pub fn add_global( @@ -231,11 +316,34 @@ impl ModuleBuilder { init: ConstValue, align: u32, ) -> crate::GlobalId { + let name = name.into(); + #[cfg(whale_wave_ir)] + let id = { + let id = crate::GlobalId( + u32::try_from(self.wave.state.next_global) + .expect("builder global identity overflow"), + ); + if let Err(error) = self.wave.body.global(id, &name, &expression, &init, align, true) { + body::discard_expression(expression); + panic!("invalid builder global payload: {error}"); + } + let admitted = self + .wave + .global_constant(&name, &expression.ty) + .expect("invalid builder global model"); + assert_eq!(id, admitted, "inconsistent Wave global identity"); + self.wave + .body + .global(id, &name, &expression, &init, align, false) + .expect("invalid builder global payload"); + id + }; + #[cfg(not(whale_wave_ir))] let id = crate::GlobalId(self.next_global); - self.next_global += 1; + self.next_global = id.0.checked_add(1).expect("builder global identity overflow"); self.module.globals.push(Global { id, - name: name.into(), + name, ty: expression.ty.clone(), init, init_expr: expression, @@ -250,24 +358,40 @@ impl ModuleBuilder { &mut self, mut storage: crate::GlobalStorage, ) -> Result { - if let Err(error) = storage.validate_with_limits(crate::IrLimits::default()) { - crate::limits::discard_type(storage.ty); - return Err(error); - } - if self.module.globals.iter().any(|g| g.name == storage.name) - || self.module.global_storage.iter().any(|g| g.name == storage.name) - { - return Err(crate::GlobalStorageError::DuplicateName); - } - if storage.link_name.as_ref().is_some_and(|link| { - self.module.declarations.iter().any(|d| d.link_name.as_ref() == Some(link)) - || self.module.global_storage.iter().any(|g| g.link_name.as_ref() == Some(link)) - }) { - return Err(crate::GlobalStorageError::LinkNameCollision); - } - let id = crate::GlobalId(self.next_global); + #[cfg(whale_wave_ir)] + let id = match self.wave.storage(&storage) { + Ok(id) => id, + Err(error) => { + crate::limits::discard_type(storage.ty); + return Err(error); + }, + }; + #[cfg(not(whale_wave_ir))] + let id = { + if let Err(error) = storage.validate_with_limits(crate::IrLimits::default()) { + crate::limits::discard_type(storage.ty); + return Err(error); + } + if self.module.globals.iter().any(|g| g.name == storage.name) + || self.module.global_storage.iter().any(|g| g.name == storage.name) + { + return Err(crate::GlobalStorageError::DuplicateName); + } + if storage.link_name.as_ref().is_some_and(|link| { + self.module.declarations.iter().any(|d| d.link_name.as_ref() == Some(link)) + || self.module.global_storage.iter().any(|g| g.link_name.as_ref() == Some(link)) + }) { + return Err(crate::GlobalStorageError::LinkNameCollision); + } + let id = crate::GlobalId(self.next_global); + self.next_global = self + .next_global + .checked_add(1) + .ok_or(crate::GlobalStorageError::DuplicateIdentity)?; + id + }; self.next_global = - self.next_global.checked_add(1).ok_or(crate::GlobalStorageError::DuplicateIdentity)?; + id.0.checked_add(1).ok_or(crate::GlobalStorageError::DuplicateIdentity)?; storage.id = id; self.module.global_storage.push(storage); Ok(id) @@ -298,45 +422,70 @@ impl ModuleBuilder { limits: crate::IrLimits, ) -> Result { let name = name.into(); - let candidate = crate::FunctionDecl { + let mut candidate = crate::FunctionDecl { id: crate::FunctionId(self.module.declarations.len() as u32), name, signature, linkage, link_name, }; - if let Err(error) = crate::function::validate_decl_with_limits(&candidate, limits) { - crate::limits::discard_signature(candidate.signature); - return Err(error); - } - if let Some(existing) = self.module.declarations.iter().find(|d| d.name == candidate.name) { - let mut same = candidate.clone(); - same.id = existing.id; - return if &same == existing { - Ok(existing.id) - } else { - Err(crate::CallError::ConflictingDeclaration(candidate.name)) - }; + #[cfg(whale_wave_ir)] + let id = match self.wave.declaration(&candidate, limits, false) { + Ok(id) => id, + Err(error) => { + crate::limits::discard_signature(candidate.signature); + return Err(error); + }, + }; + #[cfg(whale_wave_ir)] + if (id.0 as usize) < self.module.declarations.len() { + return Ok(id); } - if let Some(link) = &candidate.link_name { - if self.module.declarations.iter().any(|d| d.link_name.as_ref() == Some(link)) - || self.module.global_storage.iter().any(|g| g.link_name.as_ref() == Some(link)) + #[cfg(not(whale_wave_ir))] + let id = { + if let Err(error) = crate::function::validate_decl_with_limits(&candidate, limits) { + crate::limits::discard_signature(candidate.signature); + return Err(error); + } + if let Some(existing) = + self.module.declarations.iter().find(|d| d.name == candidate.name) { - return Err(crate::CallError::LinkNameCollision(link.clone())); + let mut same = candidate.clone(); + same.id = existing.id; + return if &same == existing { + Ok(existing.id) + } else { + Err(crate::CallError::ConflictingDeclaration(candidate.name)) + }; } - } - let id = candidate.id; + if let Some(link) = &candidate.link_name { + if self.module.declarations.iter().any(|d| d.link_name.as_ref() == Some(link)) + || self.module.global_storage.iter().any(|g| g.link_name.as_ref() == Some(link)) + { + return Err(crate::CallError::LinkNameCollision(link.clone())); + } + } + candidate.id + }; + candidate.id = id; self.module.declarations.push(candidate); Ok(id) } pub fn function_id(&self, name: &str) -> Result { - self.module - .declarations - .iter() - .find(|d| d.name == name) - .map(|d| d.id) - .ok_or_else(|| crate::CallError::UnknownFunctionName(name.into())) + #[cfg(whale_wave_ir)] + { + self.wave.lookup_function(name) + } + #[cfg(not(whale_wave_ir))] + { + self.module + .declarations + .iter() + .find(|d| d.name == name) + .map(|d| d.id) + .ok_or_else(|| crate::CallError::UnknownFunctionName(name.into())) + } } pub fn begin_declared_function( @@ -344,17 +493,24 @@ impl ModuleBuilder { id: crate::FunctionId, names: Vec, ) -> Result, crate::CallError> { + #[cfg(whale_wave_ir)] + self.wave.definition(id, names.len(), false)?; let decl = self .module .declarations .iter() .find(|d| d.id == id) .ok_or(crate::CallError::UnknownFunction(id))?; + #[cfg(not(whale_wave_ir))] crate::function::validate_signature(&decl.signature)?; + #[cfg(whale_wave_ir)] + self.wave.preflight_function(id)?; let decl = decl.clone(); + #[cfg(not(whale_wave_ir))] if self.module.functions.iter().any(|f| f.id == id) { return Err(crate::CallError::DuplicateDefinition(id)); } + #[cfg(not(whale_wave_ir))] if names.len() != decl.signature.params.len() { return Err(crate::CallError::DefinitionMismatch(id)); } @@ -369,10 +525,15 @@ impl ModuleBuilder { ret_ty: Type, ) -> FunctionBuilder<'_> { let name = name.into(); + self.preflight_type(&ret_ty).expect("invalid builder return type"); + for (_, ty) in ¶ms { + self.preflight_type(ty).expect("invalid builder parameter type"); + } // This legacy convenience API is intentionally infallible. The verifier // diagnoses duplicate names and invalid signatures, as before. let id = crate::FunctionId(self.module.declarations.len() as u32); - self.module.declarations.push(crate::FunctionDecl { + #[allow(unused_mut)] + let mut declaration = crate::FunctionDecl { id, name: name.clone(), signature: crate::FunctionSignature::whale( @@ -381,7 +542,16 @@ impl ModuleBuilder { ), linkage: crate::Linkage::Internal, link_name: None, - }); + }; + #[cfg(whale_wave_ir)] + { + declaration.id = self + .wave + .declaration(&declaration, self.wave.limits, true) + .expect("invalid builder function model"); + } + let id = declaration.id; + self.module.declarations.push(declaration); self.build_function(id, name, params, ret_ty) } @@ -392,11 +562,21 @@ impl ModuleBuilder { params: Vec<(String, Type)>, ret_ty: Type, ) -> FunctionBuilder<'_> { + #[cfg(whale_wave_ir)] + let first_value = self.wave.next_value(); + #[cfg(whale_wave_ir)] + let first_block = self.wave.next_block(); + #[cfg(not(whale_wave_ir))] + self.preflight_type(&ret_ty).expect("invalid builder return type"); + #[cfg(not(whale_wave_ir))] + for (_, ty) in ¶ms { + self.preflight_type(ty).expect("invalid builder parameter type"); + } let mut p = Vec::new(); let mut value_types = Vec::new(); for (nm, ty) in params { - let id = self.fresh_value(); + let id = self.fresh_value(&ty); value_types.push((id, ty.clone())); p.push(Param { name: nm, id, ty }); } @@ -407,23 +587,61 @@ impl ModuleBuilder { let func = Function { id, name, params: p, ret_ty, blocks: vec![entry_block], entry, value_types }; - FunctionBuilder { mb: self, func, insert_block: entry } + FunctionBuilder { + mb: self, + func, + insert_block: entry, + #[cfg(whale_wave_ir)] + first_value, + #[cfg(whale_wave_ir)] + first_block, + } + } + + fn preflight_type(&self, ty: &Type) -> Result<(), BuilderError> { + #[cfg(whale_wave_ir)] + { + self.wave.preflight(ty) + } + #[cfg(not(whale_wave_ir))] + { + crate::limits::Budget::new(self.limits) + .and_then(|mut budget| budget.ty(ty)) + .map_err(BuilderError::ResourceLimit) + } } - fn fresh_value(&mut self) -> ValueId { + fn fresh_value(&mut self, ty: &Type) -> ValueId { + #[cfg(not(whale_wave_ir))] + self.preflight_type(ty).expect("invalid builder value type"); + #[cfg(whale_wave_ir)] + let id = self.wave.value(ty).expect("invalid builder value allocation").0; + #[cfg(not(whale_wave_ir))] let id = self.next_value; - self.next_value += 1; + self.next_value = id.checked_add(1).expect("builder value identity overflow"); ValueId(id) } fn fresh_block(&mut self) -> BlockId { + #[cfg(whale_wave_ir)] + let id = self.wave.block().expect("invalid builder block allocation").0; + #[cfg(not(whale_wave_ir))] let id = self.next_block; - self.next_block += 1; + self.next_block = id.checked_add(1).expect("builder block identity overflow"); BlockId(id) } pub fn finish(self) -> Module { - self.module + #[cfg(whale_wave_ir)] + { + let mut module = self.module; + self.wave.body.restore_globals(&mut module.globals).expect("invalid Wave global model"); + module + } + #[cfg(not(whale_wave_ir))] + { + self.module + } } } @@ -433,6 +651,10 @@ pub struct FunctionBuilder<'a> { mb: &'a mut ModuleBuilder, func: Function, insert_block: BlockId, + #[cfg(whale_wave_ir)] + first_value: u32, + #[cfg(whale_wave_ir)] + first_block: u32, } #[cfg(feature = "socket")] @@ -471,15 +693,15 @@ impl FunctionBuilder<'_> { .blocks .iter() .map(|b| { - ( - b.id, - b.instructions.len(), - b.instructions - .iter() - .take_while(|i| matches!(i, Instruction::Alloca { .. })) - .count(), - b.terminator.is_some(), - ) + #[cfg(whale_wave_ir)] + let allocas = self.mb.wave.body.allocation_prefix(b.id); + #[cfg(not(whale_wave_ir))] + let allocas = b + .instructions + .iter() + .take_while(|i| matches!(i, Instruction::Alloca { .. })) + .count(); + (b.id, b.instructions.len(), allocas, b.terminator.is_some()) }) .collect(), )) @@ -510,6 +732,9 @@ impl FunctionBuilder<'_> { for b in &self.func.blocks { let (old_len, old_allocas, old_term) = before.get(&b.id).copied().unwrap_or((0, 0, false)); + #[cfg(whale_wave_ir)] + let allocas = self.mb.wave.body.allocation_prefix(b.id); + #[cfg(not(whale_wave_ir))] let allocas = b .instructions .iter() @@ -624,35 +849,104 @@ impl ModuleBuilder { } impl<'a> FunctionBuilder<'a> { + fn bound_type(&self, ty: Type) -> Result { + match self.mb.preflight_type(&ty) { + Ok(()) => { + #[cfg(whale_wave_ir)] + self.mb.wave.body.type_room(&ty, 0)?; + Ok(ty) + }, + Err(error) => { + crate::limits::discard_type(ty); + Err(error) + }, + } + } + + fn preflight_value( + &self, + ty: &Type, + operands: usize, + targets: usize, + ) -> Result<(), BuilderError> { + #[cfg(whale_wave_ir)] + { + self.mb.wave.preflight_value(ty, operands, targets) + } + #[cfg(not(whale_wave_ir))] + { + let _ = (operands, targets); + self.mb.preflight_type(ty) + } + } + fn ensure_block(&self, bb: BlockId) -> Result<(), BuilderError> { - if self.func.blocks.iter().any(|b| b.id == bb) { - Ok(()) - } else { - Err(BuilderError::UnknownBlock(bb)) + #[cfg(whale_wave_ir)] + { + self.mb.wave.order(self.first_block, self.first_value, bb, 34, &[], &[], true) + } + #[cfg(not(whale_wave_ir))] + { + if self.func.blocks.iter().any(|b| b.id == bb) { + Ok(()) + } else { + Err(BuilderError::UnknownBlock(bb)) + } } } fn ensure_insertable(&self) -> Result<(), BuilderError> { - let block = self - .func - .blocks - .iter() - .find(|b| b.id == self.insert_block) - .ok_or(BuilderError::UnknownBlock(self.insert_block))?; - if block.terminator.is_some() { - Err(BuilderError::TerminatedBlock(block.id)) - } else { - Ok(()) + #[cfg(whale_wave_ir)] + { + self.mb.wave.order( + self.first_block, + self.first_value, + self.insert_block, + 35, + &[], + &[], + true, + ) + } + #[cfg(not(whale_wave_ir))] + { + let block = self + .func + .blocks + .iter() + .find(|b| b.id == self.insert_block) + .ok_or(BuilderError::UnknownBlock(self.insert_block))?; + if block.terminator.is_some() { + Err(BuilderError::TerminatedBlock(block.id)) + } else { + Ok(()) + } } } fn ensure_values(&self, values: &[ValueId]) -> Result<(), BuilderError> { - for value in values { - if self.func.value_type(*value).is_none() { - return Err(BuilderError::UnknownValue(*value)); + #[cfg(whale_wave_ir)] + { + let ids: Vec = values.iter().map(|value| value.0.into()).collect(); + self.mb.wave.order( + self.first_block, + self.first_value, + self.insert_block, + 34, + &ids, + &[], + true, + ) + } + #[cfg(not(whale_wave_ir))] + { + for value in values { + if self.func.value_type(*value).is_none() { + return Err(BuilderError::UnknownValue(*value)); + } } + Ok(()) } - Ok(()) } pub fn try_param_value(&self, index: usize) -> Result { @@ -670,7 +964,9 @@ impl<'a> FunctionBuilder<'a> { } pub fn try_undef(&mut self, ty: Type) -> Result { + let ty = self.bound_type(ty)?; self.ensure_insertable()?; + self.preflight_value(&ty, 0, 0)?; Ok(self.undef(ty)) } @@ -680,17 +976,45 @@ impl<'a> FunctionBuilder<'a> { expression: crate::ConstExpr, value: ConstValue, ) -> Result { - self.ensure_insertable()?; - Ok(self.const_decl(name, expression, value)) + #[cfg(whale_wave_ir)] + { + let candidate = + Instruction::ConstDecl { dst: ValueId(0), name: name.into(), expression, value }; + let check = (|| { + self.ensure_insertable()?; + let Instruction::ConstDecl { expression, .. } = &candidate else { unreachable!() }; + self.mb.preflight_type(&expression.ty)?; + self.preflight_value(&expression.ty, 0, 0)?; + self.mb.wave.body.instruction(self.insert_block, &candidate, false, true)?; + Ok(()) + })(); + let Instruction::ConstDecl { name, expression, value, .. } = candidate else { + unreachable!() + }; + if let Err(error) = check { + body::discard_expression(expression); + return Err(error); + } + Ok(self.const_decl(name, expression, value)) + } + #[cfg(not(whale_wave_ir))] + { + self.ensure_insertable()?; + self.mb.preflight_type(&expression.ty)?; + self.preflight_value(&expression.ty, 0, 0)?; + Ok(self.const_decl(name, expression, value)) + } } pub fn try_const_bool(&mut self, v: bool) -> Result { self.ensure_insertable()?; + self.preflight_value(&Type::Bool, 0, 0)?; Ok(self.const_bool(v)) } pub fn try_const_i32(&mut self, v: i32) -> Result { self.ensure_insertable()?; + self.preflight_value(&Type::I32, 0, 0)?; Ok(self.const_i32(v)) } @@ -700,8 +1024,10 @@ impl<'a> FunctionBuilder<'a> { lhs: ValueId, rhs: ValueId, ) -> Result { + let ty = self.bound_type(ty)?; self.ensure_insertable()?; self.ensure_values(&[lhs, rhs])?; + self.preflight_value(&ty, 2, 0)?; Ok(self.add(ty, lhs, rhs)) } @@ -712,8 +1038,10 @@ impl<'a> FunctionBuilder<'a> { lhs: ValueId, rhs: ValueId, ) -> Result { + let ty = self.bound_type(ty)?; self.ensure_insertable()?; self.ensure_values(&[lhs, rhs])?; + self.preflight_value(&ty, 2, 0)?; Ok(self.bin(op, ty, lhs, rhs)) } @@ -724,8 +1052,11 @@ impl<'a> FunctionBuilder<'a> { lhs: ValueId, rhs: ValueId, ) -> Result { + let ty = self.bound_type(ty)?; self.ensure_insertable()?; self.ensure_values(&[lhs, rhs])?; + self.mb.preflight_type(&ty)?; + self.preflight_value(&Type::Bool, 2, 0)?; Ok(self.icmp(pred, ty, lhs, rhs)) } @@ -736,8 +1067,11 @@ impl<'a> FunctionBuilder<'a> { lhs: ValueId, rhs: ValueId, ) -> Result { + let ty = self.bound_type(ty)?; self.ensure_insertable()?; self.ensure_values(&[lhs, rhs])?; + self.mb.preflight_type(&ty)?; + self.preflight_value(&Type::Bool, 2, 0)?; Ok(self.cmp(op, ty, lhs, rhs)) } @@ -748,8 +1082,11 @@ impl<'a> FunctionBuilder<'a> { lhs: ValueId, rhs: ValueId, ) -> Result { + let ty = self.bound_type(ty)?; self.ensure_insertable()?; self.ensure_values(&[lhs, rhs])?; + self.mb.preflight_type(&ty)?; + self.preflight_value(&Type::Tuple(vec![ty.clone(), Type::Bool]), 2, 0)?; Ok(self.checked(op, ty, lhs, rhs)) } @@ -760,8 +1097,12 @@ impl<'a> FunctionBuilder<'a> { tuple: ValueId, index: u32, ) -> Result { + let dst_ty = self.bound_type(dst_ty)?; + crate::limits::discard_type(tuple_ty); + let tuple_ty = Type::Void; self.ensure_insertable()?; self.ensure_values(&[tuple])?; + self.preflight_value(&dst_ty, 1, 0)?; Ok(self.extract(tuple_ty, dst_ty, tuple, index)) } @@ -771,13 +1112,28 @@ impl<'a> FunctionBuilder<'a> { reason: impl Into, ) -> Result<(), BuilderError> { self.ensure_insertable()?; + #[cfg(whale_wave_ir)] + self.mb.wave.preflight_instruction(1, 0)?; self.ensure_values(&[cond])?; - self.trap_if(cond, reason); - Ok(()) + #[cfg(whale_wave_ir)] + { + let candidate = Instruction::TrapIf { cond, reason: reason.into() }; + self.mb.wave.body.instruction(self.insert_block, &candidate, false, true)?; + let Instruction::TrapIf { reason, .. } = candidate else { unreachable!() }; + self.trap_if(cond, reason); + Ok(()) + } + #[cfg(not(whale_wave_ir))] + { + self.trap_if(cond, reason); + Ok(()) + } } pub fn try_br(&mut self, target: BlockId) -> Result<(), BuilderError> { self.ensure_insertable()?; + #[cfg(whale_wave_ir)] + self.mb.wave.preflight_instruction(0, 1)?; self.ensure_block(target)?; self.br(target); Ok(()) @@ -790,6 +1146,8 @@ impl<'a> FunctionBuilder<'a> { else_bb: BlockId, ) -> Result<(), BuilderError> { self.ensure_insertable()?; + #[cfg(whale_wave_ir)] + self.mb.wave.preflight_instruction(1, 2)?; self.ensure_values(&[cond])?; self.ensure_block(then_bb)?; self.ensure_block(else_bb)?; @@ -799,22 +1157,37 @@ impl<'a> FunctionBuilder<'a> { pub fn try_trap(&mut self, reason: impl Into) -> Result<(), BuilderError> { self.ensure_insertable()?; + #[cfg(whale_wave_ir)] + self.mb.wave.preflight_instruction(0, 0)?; + #[cfg(whale_wave_ir)] + let reason = { + let candidate = Terminator::Trap { reason: reason.into() }; + self.mb.wave.body.terminator(self.insert_block, &candidate, true)?; + let Terminator::Trap { reason } = candidate else { unreachable!() }; + reason + }; self.trap(reason); Ok(()) } pub fn try_const_int(&mut self, ty: Type, v: i128) -> Result { + let ty = self.bound_type(ty)?; self.ensure_insertable()?; + self.preflight_value(&ty, 0, 0)?; Ok(self.const_int(ty, v)) } pub fn try_const_uint(&mut self, ty: Type, v: u128) -> Result { + let ty = self.bound_type(ty)?; self.ensure_insertable()?; + self.preflight_value(&ty, 0, 0)?; Ok(self.const_uint(ty, v)) } pub fn try_const_float(&mut self, ty: Type, v: f64) -> Result { + let ty = self.bound_type(ty)?; self.ensure_insertable()?; + self.preflight_value(&ty, 0, 0)?; Ok(self.const_float(ty, v)) } @@ -823,21 +1196,36 @@ impl<'a> FunctionBuilder<'a> { ty: Type, v: crate::FloatBits, ) -> Result { + let ty = self.bound_type(ty)?; self.ensure_insertable()?; + self.preflight_value(&ty, 0, 0)?; Ok(self.const_float_bits(ty, v)) } pub fn try_alloca(&mut self, ty: Type, align: u32) -> Result { + let ty = self.bound_type(ty)?; self.ensure_insertable()?; + self.mb.preflight_type(&ty)?; + self.preflight_value(&Type::Ptr(Box::new(ty.clone())), 0, 0)?; Ok(self.alloca(ty, align)) } pub fn try_alloca_in_entry(&mut self, ty: Type, align: u32) -> Result { + let ty = self.bound_type(ty)?; self.ensure_insertable()?; self.ensure_block(self.func.entry)?; if self.func.blocks.iter().find(|b| b.id == self.func.entry).unwrap().terminator.is_some() { return Err(BuilderError::TerminatedBlock(self.func.entry)); } + self.mb.preflight_type(&ty)?; + self.preflight_value(&Type::Ptr(Box::new(ty.clone())), 0, 0)?; + #[cfg(whale_wave_ir)] + self.mb.wave.body.instruction( + self.func.entry, + &Instruction::Alloca { dst: ValueId(0), ty: ty.clone(), align }, + true, + true, + )?; Ok(self.alloca_in_entry(ty, align)) } @@ -847,14 +1235,20 @@ impl<'a> FunctionBuilder<'a> { ptr: ValueId, align: u32, ) -> Result { + let ty = self.bound_type(ty)?; self.ensure_insertable()?; self.ensure_values(&[ptr])?; + self.preflight_value(&ty, 1, 0)?; Ok(self.load(ty, ptr, align)) } pub fn try_uninit(&mut self, ty: Type, ptr: ValueId, align: u32) -> Result<(), BuilderError> { + let ty = self.bound_type(ty)?; self.ensure_insertable()?; + #[cfg(whale_wave_ir)] + self.mb.wave.preflight_instruction(1, 0)?; self.ensure_values(&[ptr])?; + self.mb.preflight_type(&ty)?; self.uninit(ty, ptr, align); Ok(()) } @@ -866,17 +1260,29 @@ impl<'a> FunctionBuilder<'a> { ptr: ValueId, align: u32, ) -> Result<(), BuilderError> { + let ty = self.bound_type(ty)?; self.ensure_insertable()?; + #[cfg(whale_wave_ir)] + self.mb.wave.preflight_instruction(2, 0)?; self.ensure_values(&[value, ptr])?; + self.mb.preflight_type(&ty)?; self.store(ty, value, ptr, align); Ok(()) } pub fn try_ret(&mut self, value: Option) -> Result<(), BuilderError> { self.ensure_insertable()?; + #[cfg(whale_wave_ir)] + self.mb.wave.preflight_instruction(usize::from(value.is_some()), 0)?; if let Some(value) = value { self.ensure_values(&[value])?; } + #[cfg(whale_wave_ir)] + self.mb.wave.body.terminator( + self.insert_block, + &Terminator::Ret { ty: self.func.ret_ty.clone(), value }, + true, + )?; self.ret(value); Ok(()) } @@ -891,13 +1297,8 @@ impl<'a> FunctionBuilder<'a> { expression: crate::ConstExpr, value: ConstValue, ) -> ValueId { - let dst = self.define_value(expression.ty.clone()); - self.cur_block_mut().instructions.push(Instruction::ConstDecl { - dst, - name: name.into(), - expression, - value, - }); + let dst = self.define_value(&expression.ty); + self.push_instruction(Instruction::ConstDecl { dst, name: name.into(), expression, value }); dst } @@ -920,16 +1321,42 @@ impl<'a> FunctionBuilder<'a> { .expect("insert block not found") } - fn define_value(&mut self, ty: Type) -> ValueId { + fn push_instruction(&mut self, instruction: Instruction) { + #[cfg(whale_wave_ir)] + self.mb + .wave + .instruction(self.first_block, self.first_value, self.insert_block, &instruction, false) + .expect("invalid builder instruction order"); + self.cur_block_mut().instructions.push(instruction); + } + + fn mark_terminated(&mut self) { + #[cfg(whale_wave_ir)] + { + let term = self + .func + .blocks + .iter() + .find(|block| block.id == self.insert_block) + .and_then(|block| block.terminator.as_ref()) + .expect("builder terminator"); + self.mb + .wave + .terminator(self.first_block, self.first_value, self.insert_block, term, false) + .expect("invalid builder terminator order"); + } + } + + fn define_value(&mut self, ty: &Type) -> ValueId { self.ensure_insertable().expect("invalid builder insertion"); - let id = self.mb.fresh_value(); - self.func.value_types.push((id, ty)); + let id = self.mb.fresh_value(ty); + self.func.value_types.push((id, ty.clone())); id } pub fn const_bool(&mut self, v: bool) -> ValueId { - let dst = self.define_value(Type::Bool); - self.cur_block_mut().instructions.push(Instruction::Const { + let dst = self.define_value(&Type::Bool); + self.push_instruction(Instruction::Const { dst, ty: Type::Bool, value: ConstValue::Bool(v), @@ -938,8 +1365,8 @@ impl<'a> FunctionBuilder<'a> { } pub fn const_i32(&mut self, v: i32) -> ValueId { - let dst = self.define_value(Type::I32); - self.cur_block_mut().instructions.push(Instruction::Const { + let dst = self.define_value(&Type::I32); + self.push_instruction(Instruction::Const { dst, ty: Type::I32, value: ConstValue::I(v as i128), @@ -948,78 +1375,77 @@ impl<'a> FunctionBuilder<'a> { } pub fn add(&mut self, ty: Type, lhs: ValueId, rhs: ValueId) -> ValueId { - let dst = self.define_value(ty.clone()); - self.cur_block_mut().instructions.push(Instruction::Bin { - dst, - op: BinOp::Add, - ty, - lhs, - rhs, - }); + let dst = self.define_value(&ty); + self.push_instruction(Instruction::Bin { dst, op: BinOp::Add, ty, lhs, rhs }); dst } pub fn bin(&mut self, op: BinOp, ty: Type, lhs: ValueId, rhs: ValueId) -> ValueId { - let dst = self.define_value(ty.clone()); - self.cur_block_mut().instructions.push(Instruction::Bin { dst, op, ty, lhs, rhs }); + let dst = self.define_value(&ty); + self.push_instruction(Instruction::Bin { dst, op, ty, lhs, rhs }); dst } pub fn icmp(&mut self, pred: ICmpPred, ty: Type, lhs: ValueId, rhs: ValueId) -> ValueId { - let dst = self.define_value(Type::Bool); - self.cur_block_mut().instructions.push(Instruction::ICmp { dst, pred, ty, lhs, rhs }); + let dst = self.define_value(&Type::Bool); + self.push_instruction(Instruction::ICmp { dst, pred, ty, lhs, rhs }); dst } pub fn cmp(&mut self, op: CmpOp, ty: Type, lhs: ValueId, rhs: ValueId) -> ValueId { - let dst = self.define_value(Type::Bool); - self.cur_block_mut().instructions.push(Instruction::Cmp { dst, op, ty, lhs, rhs }); + let dst = self.define_value(&Type::Bool); + self.push_instruction(Instruction::Cmp { dst, op, ty, lhs, rhs }); dst } pub fn cast(&mut self, op: crate::CastOp, src_ty: Type, dst_ty: Type, src: ValueId) -> ValueId { - let dst = self.define_value(dst_ty.clone()); - self.cur_block_mut().instructions.push(Instruction::Cast { dst, op, dst_ty, src_ty, src }); + let dst = self.define_value(&dst_ty); + self.push_instruction(Instruction::Cast { dst, op, dst_ty, src_ty, src }); dst } pub fn checked(&mut self, op: CheckedOp, ty: Type, lhs: ValueId, rhs: ValueId) -> ValueId { + self.mb.preflight_type(&ty).expect("invalid builder type"); let dst_ty = Type::Tuple(vec![ty.clone(), Type::Bool]); - let dst = self.define_value(dst_ty); - self.cur_block_mut().instructions.push(Instruction::Checked { dst, op, ty, lhs, rhs }); + let dst = self.define_value(&dst_ty); + self.push_instruction(Instruction::Checked { dst, op, ty, lhs, rhs }); dst } pub fn extract(&mut self, tuple_ty: Type, dst_ty: Type, tuple: ValueId, index: u32) -> ValueId { - let dst = self.define_value(dst_ty.clone()); - self.cur_block_mut().instructions.push(Instruction::Extract { dst, dst_ty, tuple, index }); - let _ = tuple_ty; + let dst = self.define_value(&dst_ty); + self.push_instruction(Instruction::Extract { dst, dst_ty, tuple, index }); + crate::limits::discard_type(tuple_ty); dst } pub fn trap_if(&mut self, cond: ValueId, reason: impl Into) { - self.cur_block_mut().instructions.push(Instruction::TrapIf { cond, reason: reason.into() }); + self.push_instruction(Instruction::TrapIf { cond, reason: reason.into() }); } pub fn br(&mut self, target: BlockId) { let blk = self.cur_block_mut(); blk.terminator = Some(Terminator::Br { target }); + self.mark_terminated(); } pub fn cbr(&mut self, cond: ValueId, then_bb: BlockId, else_bb: BlockId) { let blk = self.cur_block_mut(); blk.terminator = Some(Terminator::CBr { cond, then_bb, else_bb }); + self.mark_terminated(); } pub fn ret(&mut self, value: Option) { let ty = self.func.ret_ty.clone(); let blk = self.cur_block_mut(); blk.terminator = Some(Terminator::Ret { ty, value }); + self.mark_terminated(); } pub fn trap(&mut self, reason: impl Into) { let blk = self.cur_block_mut(); blk.terminator = Some(Terminator::Trap { reason: reason.into() }); + self.mark_terminated(); } pub fn function_id(&self, name: &str) -> Result { @@ -1030,13 +1456,19 @@ impl<'a> FunctionBuilder<'a> { &mut self, signature: crate::FunctionSignature, ) -> Result { - if let Err(error) = crate::function::validate_signature(&signature) { + #[cfg(whale_wave_ir)] + let validity = self.mb.wave.signature(&signature); + #[cfg(not(whale_wave_ir))] + let validity = crate::function::validate_signature(&signature); + if let Err(error) = validity { crate::limits::discard_signature(signature); return Err(error); } self.ensure_insertable().map_err(crate::CallError::Builder)?; - let dst = self.define_value(Type::FnPtr(Box::new(signature.clone()))); - self.cur_block_mut().instructions.push(Instruction::NullFunction { dst, signature }); + let pointer = Type::FnPtr(Box::new(signature.clone())); + self.preflight_value(&pointer, 0, 0).map_err(crate::CallError::Builder)?; + let dst = self.define_value(&pointer); + self.push_instruction(Instruction::NullFunction { dst, signature }); Ok(dst) } @@ -1045,14 +1477,13 @@ impl<'a> FunctionBuilder<'a> { function: crate::FunctionId, ) -> Result { let signature = self.callee_signature(&Callee::Direct(function))?; + #[cfg(not(whale_wave_ir))] crate::function::validate_signature(&signature)?; self.ensure_insertable().map_err(crate::CallError::Builder)?; - let dst = self.define_value(Type::FnPtr(Box::new(signature.clone()))); - self.cur_block_mut().instructions.push(Instruction::FunctionAddr { - dst, - function, - signature, - }); + let pointer = Type::FnPtr(Box::new(signature.clone())); + self.preflight_value(&pointer, 0, 0).map_err(crate::CallError::Builder)?; + let dst = self.define_value(&pointer); + self.push_instruction(Instruction::FunctionAddr { dst, function, signature }); Ok(dst) } @@ -1060,6 +1491,8 @@ impl<'a> FunctionBuilder<'a> { &self, callee: &Callee, ) -> Result { + #[cfg(whale_wave_ir)] + self.mb.wave.check_call(self.first_value, callee, None, None, &self.func)?; let signature = match callee { Callee::Direct(id) => { &self @@ -1077,6 +1510,7 @@ impl<'a> FunctionBuilder<'a> { None => return Err(crate::CallError::UnknownValue(*value)), }, }; + #[cfg(not(whale_wave_ir))] crate::function::validate_signature(signature)?; Ok(signature.clone()) } @@ -1088,13 +1522,24 @@ impl<'a> FunctionBuilder<'a> { ) -> Result, crate::CallError> { self.ensure_insertable().map_err(crate::CallError::Builder)?; let signature = self.callee_signature(&callee)?; + #[cfg(not(whale_wave_ir))] crate::function::validate_signature(&signature)?; + #[cfg(whale_wave_ir)] + self.mb.wave.check_call( + self.first_value, + &callee, + Some(&args), + Some(&signature), + &self.func, + )?; + #[cfg(not(whale_wave_ir))] if args.len() != signature.params.len() { return Err(crate::CallError::ArgumentCount { expected: signature.params.len(), got: args.len(), }); } + #[cfg(not(whale_wave_ir))] for (index, (arg, expected)) in args.iter().zip(&signature.params).enumerate() { let got = self.func.value_type(*arg).ok_or(crate::CallError::UnknownValue(*arg))?; if got != expected { @@ -1107,8 +1552,21 @@ impl<'a> FunctionBuilder<'a> { } let ret_ty = signature.ret; - let dst = if ret_ty == Type::Void { None } else { Some(self.define_value(ret_ty.clone())) }; - self.cur_block_mut().instructions.push(Instruction::Call { + #[cfg(whale_wave_ir)] + { + let operands = + args.len().saturating_add(usize::from(matches!(callee, Callee::Indirect(_)))); + if ret_ty != Type::Void { + self.preflight_value(&ret_ty, operands, 0).map_err(crate::CallError::Builder)?; + } else { + self.mb + .wave + .preflight_instruction(operands, 0) + .map_err(crate::CallError::Builder)?; + } + } + let dst = if ret_ty == Type::Void { None } else { Some(self.define_value(&ret_ty)) }; + self.push_instruction(Instruction::Call { convention: signature.convention, dst, ret_ty, @@ -1119,27 +1577,26 @@ impl<'a> FunctionBuilder<'a> { } pub fn finish(mut self) { + #[cfg(whale_wave_ir)] + self.mb.wave.body.restore(&mut self.func).expect("invalid Wave builder body snapshot"); + #[cfg(whale_wave_ir)] + self.mb + .wave + .definition(self.func.id, self.func.params.len(), true) + .expect("invalid builder definition model"); self.flush_source_shifts(); self.mb.module.functions.push(self.func); } pub fn const_int(&mut self, ty: Type, v: i128) -> ValueId { - let dst = self.define_value(ty.clone()); - self.cur_block_mut().instructions.push(Instruction::Const { - dst, - ty, - value: ConstValue::I(v), - }); + let dst = self.define_value(&ty); + self.push_instruction(Instruction::Const { dst, ty, value: ConstValue::I(v) }); dst } pub fn const_uint(&mut self, ty: Type, v: u128) -> ValueId { - let dst = self.define_value(ty.clone()); - self.cur_block_mut().instructions.push(Instruction::Const { - dst, - ty, - value: ConstValue::U(v), - }); + let dst = self.define_value(&ty); + self.push_instruction(Instruction::Const { dst, ty, value: ConstValue::U(v) }); dst } @@ -1156,58 +1613,117 @@ impl<'a> FunctionBuilder<'a> { } pub fn const_float_bits(&mut self, ty: Type, v: crate::FloatBits) -> ValueId { - let dst = self.define_value(ty.clone()); - self.cur_block_mut().instructions.push(Instruction::Const { - dst, - ty, - value: ConstValue::F(v), - }); + let dst = self.define_value(&ty); + self.push_instruction(Instruction::Const { dst, ty, value: ConstValue::F(v) }); dst } pub fn alloca(&mut self, ty: Type, align: u32) -> ValueId { - let dst = self.define_value(Type::Ptr(Box::new(ty.clone()))); - self.cur_block_mut().instructions.push(Instruction::Alloca { dst, ty, align }); + self.mb.preflight_type(&ty).expect("invalid builder type"); + let dst = self.define_value(&Type::Ptr(Box::new(ty.clone()))); + self.push_instruction(Instruction::Alloca { dst, ty, align }); dst } pub fn gep(&mut self, base_ptr: ValueId, indices: Vec, dst_ty: Type) -> ValueId { - let dst = self.define_value(dst_ty.clone()); - self.cur_block_mut().instructions.push(Instruction::Gep { dst, dst_ty, base_ptr, indices }); + let dst = self.define_value(&dst_ty); + self.push_instruction(Instruction::Gep { dst, dst_ty, base_ptr, indices }); dst } pub fn memcpy(&mut self, dst: ValueId, src: ValueId, n: ValueId, align: u32) { - self.cur_block_mut().instructions.push(Instruction::Memcpy { dst, src, n, align }); + self.push_instruction(Instruction::Memcpy { dst, src, n, align }); } pub fn volatile_load(&mut self, ty: Type, ptr: ValueId, align: u32) -> ValueId { - let dst = self.define_value(ty.clone()); - self.cur_block_mut().instructions.push(Instruction::VolatileLoad { dst, ty, ptr, align }); + let dst = self.define_value(&ty); + self.push_instruction(Instruction::VolatileLoad { dst, ty, ptr, align }); dst } pub fn volatile_store(&mut self, ty: Type, value: ValueId, ptr: ValueId, align: u32) { - self.cur_block_mut().instructions.push(Instruction::VolatileStore { - ty, - value, - ptr, - align, - }); + self.push_instruction(Instruction::VolatileStore { ty, value, ptr, align }); } pub fn load(&mut self, ty: Type, ptr: ValueId, align: u32) -> ValueId { - let dst = self.define_value(ty.clone()); - self.cur_block_mut().instructions.push(Instruction::Load { dst, ty, ptr, align }); + let dst = self.define_value(&ty); + self.push_instruction(Instruction::Load { dst, ty, ptr, align }); dst } /// Revoke initialization at this program point without zeroing storage. pub fn uninit(&mut self, ty: Type, ptr: ValueId, align: u32) { - self.cur_block_mut().instructions.push(Instruction::Uninit { ty, ptr, align }); + self.push_instruction(Instruction::Uninit { ty, ptr, align }); } pub fn store(&mut self, ty: Type, value: ValueId, ptr: ValueId, align: u32) { - self.cur_block_mut().instructions.push(Instruction::Store { ty, value, ptr, align }); + self.push_instruction(Instruction::Store { ty, value, ptr, align }); + } +} + +#[cfg(all(test, whale_wave_ir))] +mod wave_model_tests { + use super::*; + + #[test] + fn finish_reads_complete_global_payloads_from_the_wave_model() { + let mut builder = ModuleBuilder::new("x86_64-whale-linux", DataLayout::default_64bit_le()); + let first = builder.add_global("base", Type::I32, ConstValue::I(40), 4); + builder + .try_add_global_storage(crate::GlobalStorage::internal( + "slot", + Type::I32, + crate::GlobalStorageInit::Uninitialized, + false, + 4, + )) + .unwrap(); + let second = builder.add_global_const( + "λ total", + crate::ConstExpr { + ty: Type::I32, + kind: crate::ConstExprKind::Binary { + op: crate::ConstBinaryOp::Add, + left: Box::new(crate::ConstExpr { + ty: Type::I32, + kind: crate::ConstExprKind::Reference(crate::ConstRef::Global(first)), + }), + right: Box::new(crate::ConstExpr::literal(Type::I32, ConstValue::I(2))), + }, + }, + ConstValue::I(42), + 16, + ); + assert_eq!(second, crate::GlobalId(2)); + let expected = builder.module.globals.clone(); + builder.module.globals.clear(); + let module = builder.finish(); + assert_eq!(module.globals, expected); + crate::verify_module(&module).unwrap(); + } + + #[test] + fn many_hoists_append_the_host_mirror_and_restore_canonical_body_order() { + let mut builder = ModuleBuilder::new("x86_64-whale-linux", DataLayout::default_64bit_le()); + let mut function = builder.begin_function("many", vec![], Type::Void); + for index in 0..10000 { + function.const_i32(index); + } + for _ in 0..10000 { + function.try_alloca_in_entry(Type::I32, 4).unwrap(); + } + // The compatibility mirror only appends. Its physical order must not + // impose a second quadratic insertion path beside Wave's indexed model. + assert!(matches!(function.func.blocks[0].instructions[0], Instruction::Const { .. })); + function.ret(None); + function.finish(); + let module = builder.finish(); + assert!(module.functions[0].blocks[0].instructions[..10000] + .iter() + .all(|i| matches!(i, Instruction::Alloca { .. }))); + assert!(module.functions[0].blocks[0].instructions[10000..] + .iter() + .all(|i| matches!(i, Instruction::Const { .. }))); + crate::verify_module(&module).unwrap(); } } diff --git a/ir/src/builder/body.rs b/ir/src/builder/body.rs new file mode 100644 index 0000000..f83cacf --- /dev/null +++ b/ir/src/builder/body.rs @@ -0,0 +1,1996 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Complete typed body transport for the authoritative Wave builder model. +use super::BuilderError; + +use crate::*; + +pub(super) fn discard_expression(root: ConstExpr) { + let mut pending = vec![root]; + while let Some(expression) = pending.pop() { + crate::limits::discard_type(expression.ty); + match expression.kind { + ConstExprKind::Not(child) | ConstExprKind::Neg(child) => pending.push(*child), + ConstExprKind::Binary { left, right, .. } + | ConstExprKind::Compare { left, right, .. } => { + pending.push(*left); + pending.push(*right); + }, + _ => {}, + } + } +} + +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct Atom { + kind: u64, + a: u64, + b: u64, + c: u64, +} + +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct Record { + op: u64, + block: u64, + first: u64, + count: u64, + byte_first: u64, + byte_count: u64, + next: u64, +} + +#[repr(C)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Block { + head: u64, + tail: u64, + count: u64, + terminator: u64, + prefix_tail: u64, + prefix_count: u64, +} + +impl Default for Block { + fn default() -> Self { + Self { + head: u64::MAX, + tail: u64::MAX, + count: 0, + terminator: u64::MAX, + prefix_tail: u64::MAX, + prefix_count: 0, + } + } +} + +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct State { + atoms: u64, + bytes: u64, + records: u64, + globals: u64, + work: u64, +} + +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct GlobalRecord { + id: u64, + first: u64, + count: u64, + byte_first: u64, + byte_count: u64, +} + +#[repr(C)] +#[derive(Default)] +struct RawResult { + status: u64, + detail: u64, + ordinal: u64, + work: u64, +} + +unsafe extern "C" { + fn whale_ir_builder_global( + state: *mut State, + id: u64, + globals: *mut GlobalRecord, + global_capacity: u64, + atoms: *const Atom, + atom_count: u64, + bytes: *const u8, + byte_count: u64, + depth: u64, + const_depth: u64, + node_limit: u64, + byte_limit: u64, + work_limit: u64, + mode: u64, + output_atoms: *mut Atom, + atom_capacity: u64, + output_bytes: *mut u8, + byte_capacity: u64, + result: *mut RawResult, + ) -> i32; + + fn whale_ir_builder_body( + state: *mut State, + blocks: *mut Block, + block_count: u64, + block: u64, + op: u64, + hoist: u64, + atoms: *const Atom, + atom_count: u64, + bytes: *const u8, + byte_count: u64, + depth: u64, + const_depth: u64, + node_limit: u64, + byte_limit: u64, + work_limit: u64, + mode: u64, + output_atoms: *mut Atom, + atom_capacity: u64, + output_bytes: *mut u8, + byte_capacity: u64, + records: *mut Record, + record_capacity: u64, + result: *mut RawResult, + ) -> i32; +} + +#[derive(Default)] +struct Input { + op: u64, + atoms: Vec, + bytes: Vec, + count_only: bool, + atom_count: usize, + byte_count: usize, +} + +impl Input { + fn atom(&mut self, atom: Atom) { + self.atom_count = self.atom_count.saturating_add(1); + if !self.count_only { + self.atoms.push(atom); + } + } + + fn uint(&mut self, value: u64) { + self.atom(Atom { kind: 0, a: value, b: 0, c: 0 }); + } + + fn id(&mut self, value: ValueId) { + self.uint(value.0.into()); + } + + fn constant(&mut self, value: &ConstValue) { + let (a, bits) = match value { + ConstValue::Bool(value) => (0, u128::from(*value)), + ConstValue::I(value) => (1, *value as u128), + ConstValue::U(value) => (2, *value), + ConstValue::F(FloatBits::F16(value)) => (3, u128::from(*value)), + ConstValue::F(FloatBits::F32(value)) => (4, u128::from(*value)), + ConstValue::F(FloatBits::F64(value)) => (5, u128::from(*value)), + }; + self.atom(Atom { kind: 1, a, b: bits as u64, c: (bits >> 64) as u64 }); + } + + fn string(&mut self, value: &str) { + self.atom(Atom { kind: 2, a: self.byte_count as u64, b: value.len() as u64, c: 0 }); + self.byte_count = self.byte_count.saturating_add(value.len()); + if !self.count_only { + self.bytes.extend_from_slice(value.as_bytes()); + } + } + + fn ty(&mut self, ty: &Type) { + let (kind, children, auxiliary) = match ty { + Type::Void => (0, 0, 0), + Type::Bool => (1, 0, 0), + Type::I1 => (2, 0, 0), + Type::U1 => (3, 0, 0), + Type::I8 => (4, 0, 0), + Type::I16 => (5, 0, 0), + Type::I32 => (6, 0, 0), + Type::I64 => (7, 0, 0), + Type::I128 => (8, 0, 0), + Type::U8 => (9, 0, 0), + Type::U16 => (10, 0, 0), + Type::U32 => (11, 0, 0), + Type::U64 => (12, 0, 0), + Type::U128 => (13, 0, 0), + Type::F16 => (14, 0, 0), + Type::F32 => (15, 0, 0), + Type::F64 => (16, 0, 0), + Type::Ptr(_) => (17, 1, 0), + Type::FnPtr(signature) => ( + 18, + signature.params.len() + 1, + u64::from(signature.variadic) * 2 + convention(&signature.convention), + ), + Type::Array(_, count) => (19, 1, *count), + Type::Struct(fields) => (20, fields.len(), 0), + Type::Tuple(fields) => (21, fields.len(), 0), + }; + self.atom(Atom { kind: 3, a: kind, b: children as u64, c: auxiliary }); + match ty { + Type::Ptr(child) | Type::Array(child, _) => self.ty(child), + Type::FnPtr(signature) => { + self.ty(&signature.ret); + for ty in &signature.params { + self.ty(ty); + } + }, + Type::Struct(fields) | Type::Tuple(fields) => { + for ty in fields { + self.ty(ty); + } + }, + _ => {}, + } + } + + fn expression(&mut self, expression: &ConstExpr) { + let (kind, op, children) = match &expression.kind { + ConstExprKind::Literal(_) => (0, 0, 0), + ConstExprKind::Reference(ConstRef::Global(_)) => (1, 0, 0), + ConstExprKind::Reference(ConstRef::Local(_)) => (2, 0, 0), + ConstExprKind::Not(_) => (3, 0, 1), + ConstExprKind::Neg(_) => (4, 0, 1), + ConstExprKind::Binary { op, .. } => (5, const_binary(op), 2), + ConstExprKind::Compare { op, .. } => (6, const_compare(op), 2), + }; + self.atom(Atom { kind: 4, a: kind, b: op, c: children }); + self.ty(&expression.ty); + match &expression.kind { + ConstExprKind::Literal(value) => self.constant(value), + ConstExprKind::Reference(ConstRef::Global(id)) => self.uint(id.0.into()), + ConstExprKind::Reference(ConstRef::Local(id)) => self.id(*id), + ConstExprKind::Not(child) | ConstExprKind::Neg(child) => self.expression(child), + ConstExprKind::Binary { left, right, .. } + | ConstExprKind::Compare { left, right, .. } => { + self.expression(left); + self.expression(right); + }, + } + } + + fn list(&mut self, kind: u64, count: usize) { + self.atom(Atom { kind: 5, a: kind, b: count as u64, c: 0 }); + } + + fn optional(&mut self, value: Option) { + self.uint(u64::from(value.is_some())); + if let Some(value) = value { + self.id(value); + } + } + + fn global( + name: &str, + expression: &ConstExpr, + init: &ConstValue, + align: u32, + count_only: bool, + ) -> Self { + let mut input = Self { count_only, ..Self::default() }; + input.string(name); + input.expression(expression); + input.constant(init); + input.uint(align.into()); + input + } + + fn instruction(instruction: &Instruction, count_only: bool) -> Self { + let mut input = Self { count_only, ..Self::default() }; + input.op = match instruction { + Instruction::GlobalAddr { dst, global, ty } => { + input.id(*dst); + input.uint(global.0.into()); + input.ty(ty); + 0 + }, + Instruction::LifetimeEnd { ptr } => { + input.id(*ptr); + 1 + }, + Instruction::PtrDiff { dst, lhs, rhs } => { + input.id(*dst); + input.id(*lhs); + input.id(*rhs); + 2 + }, + Instruction::ConstDecl { dst, name, expression, value } => { + input.id(*dst); + input.string(name); + input.expression(expression); + input.constant(value); + 3 + }, + Instruction::Const { dst, ty, value } => { + input.id(*dst); + input.ty(ty); + input.constant(value); + 4 + }, + Instruction::Undef { dst, ty } => { + input.id(*dst); + input.ty(ty); + 5 + }, + Instruction::Mov { dst, ty, src } => { + input.id(*dst); + input.ty(ty); + input.id(*src); + 6 + }, + Instruction::Bin { dst, op, ty, lhs, rhs } => { + input.id(*dst); + input.uint(bin(op)); + input.ty(ty); + input.id(*lhs); + input.id(*rhs); + 7 + }, + Instruction::Neg { dst, ty, src } => { + input.id(*dst); + input.ty(ty); + input.id(*src); + 8 + }, + Instruction::Not { dst, ty, src } => { + input.id(*dst); + input.ty(ty); + input.id(*src); + 9 + }, + Instruction::Cmp { dst, op, ty, lhs, rhs } => { + input.id(*dst); + input.uint(cmp(op)); + input.ty(ty); + input.id(*lhs); + input.id(*rhs); + 10 + }, + Instruction::ICmp { dst, pred, ty, lhs, rhs } => { + input.id(*dst); + input.uint(icmp(pred)); + input.ty(ty); + input.id(*lhs); + input.id(*rhs); + 11 + }, + Instruction::FCmp { dst, pred, ty, lhs, rhs } => { + input.id(*dst); + input.uint(fcmp(pred)); + input.ty(ty); + input.id(*lhs); + input.id(*rhs); + 12 + }, + Instruction::Select { dst, ty, cond, on_true, on_false } => { + input.id(*dst); + input.ty(ty); + input.id(*cond); + input.id(*on_true); + input.id(*on_false); + 13 + }, + Instruction::Cast { dst, op, src_ty, dst_ty, src } => { + input.id(*dst); + input.uint(cast(op)); + input.ty(src_ty); + input.ty(dst_ty); + input.id(*src); + 14 + }, + Instruction::Phi { dst, ty, incomings } => { + input.id(*dst); + input.ty(ty); + input.list(1, incomings.len()); + for (value, block) in incomings { + input.id(*value); + input.uint(block.0.into()); + } + 15 + }, + Instruction::Extract { dst, dst_ty, tuple, index } => { + input.id(*dst); + input.ty(dst_ty); + input.id(*tuple); + input.uint((*index).into()); + 16 + }, + Instruction::Checked { dst, op, ty, lhs, rhs } => { + input.id(*dst); + input.uint(checked(op)); + input.ty(ty); + input.id(*lhs); + input.id(*rhs); + 17 + }, + Instruction::Alloca { dst, ty, align } => { + input.id(*dst); + input.ty(ty); + input.uint((*align).into()); + 18 + }, + Instruction::VolatileLoad { dst, ty, ptr, align } => { + input.id(*dst); + input.ty(ty); + input.id(*ptr); + input.uint((*align).into()); + 19 + }, + Instruction::VolatileStore { ty, value, ptr, align } => { + input.ty(ty); + input.id(*value); + input.id(*ptr); + input.uint((*align).into()); + 20 + }, + Instruction::Load { dst, ty, ptr, align } => { + input.id(*dst); + input.ty(ty); + input.id(*ptr); + input.uint((*align).into()); + 21 + }, + Instruction::Uninit { ty, ptr, align } => { + input.ty(ty); + input.id(*ptr); + input.uint((*align).into()); + 22 + }, + Instruction::Store { ty, value, ptr, align } => { + input.ty(ty); + input.id(*value); + input.id(*ptr); + input.uint((*align).into()); + 23 + }, + Instruction::Gep { dst, dst_ty, base_ptr, indices } => { + input.id(*dst); + input.ty(dst_ty); + input.id(*base_ptr); + input.list(0, indices.len()); + for value in indices { + input.id(*value); + } + 24 + }, + Instruction::Memcpy { dst, src, n, align } => { + input.id(*dst); + input.id(*src); + input.id(*n); + input.uint((*align).into()); + 25 + }, + Instruction::Memset { dst, val, n, align } => { + input.id(*dst); + input.id(*val); + input.id(*n); + input.uint((*align).into()); + 26 + }, + Instruction::NullFunction { dst, signature } => { + input.id(*dst); + input.ty(&Type::FnPtr(Box::new(signature.clone()))); + 27 + }, + Instruction::FunctionAddr { dst, function, signature } => { + input.id(*dst); + input.uint(function.0.into()); + input.ty(&Type::FnPtr(Box::new(signature.clone()))); + 28 + }, + Instruction::Call { dst, ret_ty, convention: cc, callee, args } => { + input.optional(*dst); + input.ty(ret_ty); + input.uint(convention(cc)); + match callee { + Callee::Direct(id) => { + input.uint(0); + input.uint(id.0.into()); + }, + Callee::Indirect(value) => { + input.uint(1); + input.id(*value); + }, + } + input.list(0, args.len()); + for value in args { + input.id(*value); + } + 29 + }, + Instruction::TrapIf { cond, reason } => { + input.id(*cond); + input.string(reason); + 30 + }, + }; + input + } + + fn terminator(term: &Terminator, count_only: bool) -> Self { + let mut input = Self { count_only, ..Self::default() }; + input.op = match term { + Terminator::Br { target } => { + input.uint(target.0.into()); + 31 + }, + Terminator::CBr { cond, then_bb, else_bb } => { + input.id(*cond); + input.uint(then_bb.0.into()); + input.uint(else_bb.0.into()); + 32 + }, + Terminator::Switch { ty, value, default_bb, cases } => { + input.ty(ty); + input.id(*value); + input.uint(default_bb.0.into()); + input.list(2, cases.len()); + for (value, block) in cases { + input.constant(value); + input.uint(block.0.into()); + } + 33 + }, + Terminator::Ret { ty, value } => { + input.ty(ty); + input.optional(*value); + 34 + }, + Terminator::Trap { reason } => { + input.string(reason); + 35 + }, + }; + input + } +} + +fn bin(value: &BinOp) -> u64 { + match value { + BinOp::Add => 0, + BinOp::Sub => 1, + BinOp::Mul => 2, + BinOp::UDiv => 3, + BinOp::SDiv => 4, + BinOp::URem => 5, + BinOp::SRem => 6, + BinOp::FAdd => 7, + BinOp::FSub => 8, + BinOp::FMul => 9, + BinOp::FDiv => 10, + BinOp::FRem => 11, + BinOp::And => 12, + BinOp::Or => 13, + BinOp::Xor => 14, + BinOp::Shl => 15, + BinOp::LShr => 16, + BinOp::AShr => 17, + } +} + +fn decode_bin(value: u64) -> Option { + Some(match value { + 0 => BinOp::Add, + 1 => BinOp::Sub, + 2 => BinOp::Mul, + 3 => BinOp::UDiv, + 4 => BinOp::SDiv, + 5 => BinOp::URem, + 6 => BinOp::SRem, + 7 => BinOp::FAdd, + 8 => BinOp::FSub, + 9 => BinOp::FMul, + 10 => BinOp::FDiv, + 11 => BinOp::FRem, + 12 => BinOp::And, + 13 => BinOp::Or, + 14 => BinOp::Xor, + 15 => BinOp::Shl, + 16 => BinOp::LShr, + 17 => BinOp::AShr, + _ => return None, + }) +} + +fn cmp(value: &CmpOp) -> u64 { + match value { + CmpOp::Eq => 0, + CmpOp::Ne => 1, + CmpOp::SLt => 2, + CmpOp::SLe => 3, + CmpOp::SGt => 4, + CmpOp::SGe => 5, + CmpOp::ULt => 6, + CmpOp::ULe => 7, + CmpOp::UGt => 8, + CmpOp::UGe => 9, + CmpOp::FEq => 10, + CmpOp::FNe => 11, + CmpOp::FLt => 12, + CmpOp::FLe => 13, + CmpOp::FGt => 14, + CmpOp::FGe => 15, + } +} + +fn decode_cmp(value: u64) -> Option { + Some(match value { + 0 => CmpOp::Eq, + 1 => CmpOp::Ne, + 2 => CmpOp::SLt, + 3 => CmpOp::SLe, + 4 => CmpOp::SGt, + 5 => CmpOp::SGe, + 6 => CmpOp::ULt, + 7 => CmpOp::ULe, + 8 => CmpOp::UGt, + 9 => CmpOp::UGe, + 10 => CmpOp::FEq, + 11 => CmpOp::FNe, + 12 => CmpOp::FLt, + 13 => CmpOp::FLe, + 14 => CmpOp::FGt, + 15 => CmpOp::FGe, + _ => return None, + }) +} + +fn icmp(value: &ICmpPred) -> u64 { + match value { + ICmpPred::Eq => 0, + ICmpPred::Ne => 1, + ICmpPred::Ult => 2, + ICmpPred::Ule => 3, + ICmpPred::Ugt => 4, + ICmpPred::Uge => 5, + ICmpPred::Slt => 6, + ICmpPred::Sle => 7, + ICmpPred::Sgt => 8, + ICmpPred::Sge => 9, + } +} + +fn decode_icmp(value: u64) -> Option { + Some(match value { + 0 => ICmpPred::Eq, + 1 => ICmpPred::Ne, + 2 => ICmpPred::Ult, + 3 => ICmpPred::Ule, + 4 => ICmpPred::Ugt, + 5 => ICmpPred::Uge, + 6 => ICmpPred::Slt, + 7 => ICmpPred::Sle, + 8 => ICmpPred::Sgt, + 9 => ICmpPred::Sge, + _ => return None, + }) +} + +fn fcmp(value: &FCmpPred) -> u64 { + match value { + FCmpPred::Oeq => 0, + FCmpPred::One => 1, + FCmpPred::Olt => 2, + FCmpPred::Ole => 3, + FCmpPred::Ogt => 4, + FCmpPred::Oge => 5, + FCmpPred::Ord => 6, + FCmpPred::Uno => 7, + FCmpPred::Ueq => 8, + FCmpPred::Une => 9, + FCmpPred::Ult => 10, + FCmpPred::Ule => 11, + FCmpPred::Ugt => 12, + FCmpPred::Uge => 13, + } +} + +fn decode_fcmp(value: u64) -> Option { + Some(match value { + 0 => FCmpPred::Oeq, + 1 => FCmpPred::One, + 2 => FCmpPred::Olt, + 3 => FCmpPred::Ole, + 4 => FCmpPred::Ogt, + 5 => FCmpPred::Oge, + 6 => FCmpPred::Ord, + 7 => FCmpPred::Uno, + 8 => FCmpPred::Ueq, + 9 => FCmpPred::Une, + 10 => FCmpPred::Ult, + 11 => FCmpPred::Ule, + 12 => FCmpPred::Ugt, + 13 => FCmpPred::Uge, + _ => return None, + }) +} + +fn cast(value: &CastOp) -> u64 { + match value { + CastOp::CheckedInt => 0, + CastOp::ZExt => 1, + CastOp::SExt => 2, + CastOp::Trunc => 3, + CastOp::FExt => 4, + CastOp::FTrunc => 5, + CastOp::IToF_S => 6, + CastOp::IToF_U => 7, + CastOp::FToI_S => 8, + CastOp::FToI_U => 9, + CastOp::Bitcast => 10, + CastOp::PtrToInt => 11, + CastOp::IntToPtr => 12, + } +} + +fn decode_cast(value: u64) -> Option { + Some(match value { + 0 => CastOp::CheckedInt, + 1 => CastOp::ZExt, + 2 => CastOp::SExt, + 3 => CastOp::Trunc, + 4 => CastOp::FExt, + 5 => CastOp::FTrunc, + 6 => CastOp::IToF_S, + 7 => CastOp::IToF_U, + 8 => CastOp::FToI_S, + 9 => CastOp::FToI_U, + 10 => CastOp::Bitcast, + 11 => CastOp::PtrToInt, + 12 => CastOp::IntToPtr, + _ => return None, + }) +} + +fn checked(value: &CheckedOp) -> u64 { + match value { + CheckedOp::UAdd => 0, + CheckedOp::USub => 1, + CheckedOp::UMul => 2, + CheckedOp::SAdd => 3, + CheckedOp::SSub => 4, + CheckedOp::SMul => 5, + } +} + +fn decode_checked(value: u64) -> Option { + Some(match value { + 0 => CheckedOp::UAdd, + 1 => CheckedOp::USub, + 2 => CheckedOp::UMul, + 3 => CheckedOp::SAdd, + 4 => CheckedOp::SSub, + 5 => CheckedOp::SMul, + _ => return None, + }) +} + +fn const_binary(value: &ConstBinaryOp) -> u64 { + match value { + ConstBinaryOp::Add => 0, + ConstBinaryOp::Sub => 1, + ConstBinaryOp::Mul => 2, + ConstBinaryOp::BitAnd => 3, + ConstBinaryOp::BitOr => 4, + ConstBinaryOp::BitXor => 5, + ConstBinaryOp::Div => 6, + ConstBinaryOp::Rem => 7, + ConstBinaryOp::ShiftLeft => 8, + ConstBinaryOp::ShiftRight => 9, + ConstBinaryOp::LogicalAnd => 10, + ConstBinaryOp::LogicalOr => 11, + } +} + +fn decode_const_binary(value: u64) -> Option { + Some(match value { + 0 => ConstBinaryOp::Add, + 1 => ConstBinaryOp::Sub, + 2 => ConstBinaryOp::Mul, + 3 => ConstBinaryOp::BitAnd, + 4 => ConstBinaryOp::BitOr, + 5 => ConstBinaryOp::BitXor, + 6 => ConstBinaryOp::Div, + 7 => ConstBinaryOp::Rem, + 8 => ConstBinaryOp::ShiftLeft, + 9 => ConstBinaryOp::ShiftRight, + 10 => ConstBinaryOp::LogicalAnd, + 11 => ConstBinaryOp::LogicalOr, + _ => return None, + }) +} + +fn const_compare(value: &ConstCompareOp) -> u64 { + match value { + ConstCompareOp::Eq => 0, + ConstCompareOp::Ne => 1, + ConstCompareOp::Lt => 2, + ConstCompareOp::Le => 3, + ConstCompareOp::Gt => 4, + ConstCompareOp::Ge => 5, + } +} + +fn decode_const_compare(value: u64) -> Option { + Some(match value { + 0 => ConstCompareOp::Eq, + 1 => ConstCompareOp::Ne, + 2 => ConstCompareOp::Lt, + 3 => ConstCompareOp::Le, + 4 => ConstCompareOp::Gt, + 5 => ConstCompareOp::Ge, + _ => return None, + }) +} + +fn convention(value: &CallingConvention) -> u64 { + match value { + CallingConvention::Whale => 0, + CallingConvention::SysV64 => 1, + } +} + +fn decode_convention(value: u64) -> Option { + Some(match value { + 0 => CallingConvention::Whale, + 1 => CallingConvention::SysV64, + _ => return None, + }) +} + +struct Reader<'a> { + atoms: &'a [Atom], + bytes: &'a [u8], + at: usize, +} + +impl Reader<'_> { + fn atom(&mut self, kind: u64) -> Option { + let atom = *self.atoms.get(self.at)?; + if atom.kind != kind { + return None; + } + self.at += 1; + Some(atom) + } + + fn uint(&mut self) -> Option { + Some(self.atom(0)?.a) + } + + fn id(&mut self) -> Option { + Some(ValueId(self.uint()?.try_into().ok()?)) + } + + fn block(&mut self) -> Option { + Some(BlockId(self.uint()?.try_into().ok()?)) + } + + fn constant(&mut self) -> Option { + let a = self.atom(1)?; + let bits = u128::from(a.b) | (u128::from(a.c) << 64); + Some(match a.a { + 0 => ConstValue::Bool(a.b != 0), + 1 => ConstValue::I(bits as i128), + 2 => ConstValue::U(bits), + 3 => ConstValue::F(FloatBits::F16(a.b.try_into().ok()?)), + 4 => ConstValue::F(FloatBits::F32(a.b.try_into().ok()?)), + 5 => ConstValue::F(FloatBits::F64(a.b)), + _ => return None, + }) + } + + fn string(&mut self) -> Option { + let a = self.atom(2)?; + let first = usize::try_from(a.a).ok()?; + let end = first.checked_add(usize::try_from(a.b).ok()?)?; + Some(std::str::from_utf8(self.bytes.get(first..end)?).ok()?.into()) + } + + fn ty(&mut self) -> Option { + let a = self.atom(3)?; + Some(match a.a { + 0 => Type::Void, + 1 => Type::Bool, + 2 => Type::I1, + 3 => Type::U1, + 4 => Type::I8, + 5 => Type::I16, + 6 => Type::I32, + 7 => Type::I64, + 8 => Type::I128, + 9 => Type::U8, + 10 => Type::U16, + 11 => Type::U32, + 12 => Type::U64, + 13 => Type::U128, + 14 => Type::F16, + 15 => Type::F32, + 16 => Type::F64, + 17 => Type::ptr_to(self.ty()?), + 19 => Type::Array(Box::new(self.ty()?), a.c), + 18 => { + let ret = self.ty()?; + let mut params = Vec::new(); + for _ in 1..a.b { + params.push(self.ty()?); + } + Type::FnPtr(Box::new(FunctionSignature { + params, + ret, + convention: decode_convention(a.c & 1)?, + variadic: a.c & 2 != 0, + })) + }, + 20 | 21 => { + let mut fields = Vec::new(); + for _ in 0..a.b { + fields.push(self.ty()?); + } + if a.a == 20 { + Type::Struct(fields) + } else { + Type::Tuple(fields) + } + }, + _ => return None, + }) + } + + fn signature(&mut self) -> Option { + let Type::FnPtr(signature) = self.ty()? else { return None }; + Some(*signature) + } + + fn expression(&mut self) -> Option { + let a = self.atom(4)?; + let ty = self.ty()?; + let kind = match a.a { + 0 => ConstExprKind::Literal(self.constant()?), + 1 => { + ConstExprKind::Reference(ConstRef::Global(GlobalId(self.uint()?.try_into().ok()?))) + }, + 2 => ConstExprKind::Reference(ConstRef::Local(self.id()?)), + 3 => ConstExprKind::Not(Box::new(self.expression()?)), + 4 => ConstExprKind::Neg(Box::new(self.expression()?)), + 5 => ConstExprKind::Binary { + op: decode_const_binary(a.b)?, + left: Box::new(self.expression()?), + right: Box::new(self.expression()?), + }, + 6 => ConstExprKind::Compare { + op: decode_const_compare(a.b)?, + left: Box::new(self.expression()?), + right: Box::new(self.expression()?), + }, + _ => return None, + }; + Some(ConstExpr { ty, kind }) + } + + fn list(&mut self, kind: u64) -> Option { + let a = self.atom(5)?; + if a.a != kind { + return None; + } + a.b.try_into().ok() + } + + fn values(&mut self) -> Option> { + let count = self.list(0)?; + (0..count).map(|_| self.id()).collect() + } + + fn phi(&mut self) -> Option> { + let count = self.list(1)?; + (0..count).map(|_| Some((self.id()?, self.block()?))).collect() + } + + fn cases(&mut self) -> Option> { + let count = self.list(2)?; + (0..count).map(|_| Some((self.constant()?, self.block()?))).collect() + } + + fn optional(&mut self) -> Option> { + Some(if self.uint()? == 0 { None } else { Some(self.id()?) }) + } + + fn instruction(&mut self, op: u64) -> Option { + Some(match op { + 0 => Instruction::GlobalAddr { + dst: self.id()?, + global: GlobalId(self.uint()?.try_into().ok()?), + ty: self.ty()?, + }, + 1 => Instruction::LifetimeEnd { ptr: self.id()? }, + 2 => Instruction::PtrDiff { dst: self.id()?, lhs: self.id()?, rhs: self.id()? }, + 3 => Instruction::ConstDecl { + dst: self.id()?, + name: self.string()?, + expression: self.expression()?, + value: self.constant()?, + }, + 4 => Instruction::Const { dst: self.id()?, ty: self.ty()?, value: self.constant()? }, + 5 => Instruction::Undef { dst: self.id()?, ty: self.ty()? }, + 6 => Instruction::Mov { dst: self.id()?, ty: self.ty()?, src: self.id()? }, + 7 => Instruction::Bin { + dst: self.id()?, + op: decode_bin(self.uint()?)?, + ty: self.ty()?, + lhs: self.id()?, + rhs: self.id()?, + }, + 8 => Instruction::Neg { dst: self.id()?, ty: self.ty()?, src: self.id()? }, + 9 => Instruction::Not { dst: self.id()?, ty: self.ty()?, src: self.id()? }, + 10 => Instruction::Cmp { + dst: self.id()?, + op: decode_cmp(self.uint()?)?, + ty: self.ty()?, + lhs: self.id()?, + rhs: self.id()?, + }, + 11 => Instruction::ICmp { + dst: self.id()?, + pred: decode_icmp(self.uint()?)?, + ty: self.ty()?, + lhs: self.id()?, + rhs: self.id()?, + }, + 12 => Instruction::FCmp { + dst: self.id()?, + pred: decode_fcmp(self.uint()?)?, + ty: self.ty()?, + lhs: self.id()?, + rhs: self.id()?, + }, + 13 => Instruction::Select { + dst: self.id()?, + ty: self.ty()?, + cond: self.id()?, + on_true: self.id()?, + on_false: self.id()?, + }, + 14 => Instruction::Cast { + dst: self.id()?, + op: decode_cast(self.uint()?)?, + src_ty: self.ty()?, + dst_ty: self.ty()?, + src: self.id()?, + }, + 15 => Instruction::Phi { dst: self.id()?, ty: self.ty()?, incomings: self.phi()? }, + 16 => Instruction::Extract { + dst: self.id()?, + dst_ty: self.ty()?, + tuple: self.id()?, + index: self.uint()?.try_into().ok()?, + }, + 17 => Instruction::Checked { + dst: self.id()?, + op: decode_checked(self.uint()?)?, + ty: self.ty()?, + lhs: self.id()?, + rhs: self.id()?, + }, + 18 => Instruction::Alloca { + dst: self.id()?, + ty: self.ty()?, + align: self.uint()?.try_into().ok()?, + }, + 19 => Instruction::VolatileLoad { + dst: self.id()?, + ty: self.ty()?, + ptr: self.id()?, + align: self.uint()?.try_into().ok()?, + }, + 20 => Instruction::VolatileStore { + ty: self.ty()?, + value: self.id()?, + ptr: self.id()?, + align: self.uint()?.try_into().ok()?, + }, + 21 => Instruction::Load { + dst: self.id()?, + ty: self.ty()?, + ptr: self.id()?, + align: self.uint()?.try_into().ok()?, + }, + 22 => Instruction::Uninit { + ty: self.ty()?, + ptr: self.id()?, + align: self.uint()?.try_into().ok()?, + }, + 23 => Instruction::Store { + ty: self.ty()?, + value: self.id()?, + ptr: self.id()?, + align: self.uint()?.try_into().ok()?, + }, + 24 => Instruction::Gep { + dst: self.id()?, + dst_ty: self.ty()?, + base_ptr: self.id()?, + indices: self.values()?, + }, + 25 => Instruction::Memcpy { + dst: self.id()?, + src: self.id()?, + n: self.id()?, + align: self.uint()?.try_into().ok()?, + }, + 26 => Instruction::Memset { + dst: self.id()?, + val: self.id()?, + n: self.id()?, + align: self.uint()?.try_into().ok()?, + }, + 27 => Instruction::NullFunction { dst: self.id()?, signature: self.signature()? }, + 28 => Instruction::FunctionAddr { + dst: self.id()?, + function: FunctionId(self.uint()?.try_into().ok()?), + signature: self.signature()?, + }, + 29 => { + let dst = self.optional()?; + let ret_ty = self.ty()?; + let convention = decode_convention(self.uint()?)?; + let indirect = self.uint()?; + let target = self.uint()?.try_into().ok()?; + let callee = if indirect == 0 { + Callee::Direct(FunctionId(target)) + } else { + Callee::Indirect(ValueId(target)) + }; + Instruction::Call { dst, ret_ty, convention, callee, args: self.values()? } + }, + 30 => Instruction::TrapIf { cond: self.id()?, reason: self.string()? }, + _ => return None, + }) + } + + fn terminator(&mut self, op: u64) -> Option { + Some(match op { + 31 => Terminator::Br { target: self.block()? }, + 32 => { + Terminator::CBr { cond: self.id()?, then_bb: self.block()?, else_bb: self.block()? } + }, + 33 => Terminator::Switch { + ty: self.ty()?, + value: self.id()?, + default_bb: self.block()?, + cases: self.cases()?, + }, + 34 => Terminator::Ret { ty: self.ty()?, value: self.optional()? }, + 35 => Terminator::Trap { reason: self.string()? }, + _ => return None, + }) + } +} + +pub(super) struct Store { + state: State, + atoms: Vec, + bytes: Vec, + records: Vec, + globals: Vec, + blocks: Vec, + limits: IrLimits, +} + +impl Store { + fn validate_instruction(&self, instruction: &Instruction) -> Result<(), BuilderError> { + let mut budget = + crate::limits::Budget::new(self.limits).map_err(BuilderError::ResourceLimit)?; + let check = match instruction { + Instruction::ConstDecl { expression, .. } => budget.expression(expression), + Instruction::Cast { src_ty, dst_ty, .. } => { + budget.ty(src_ty).and_then(|_| budget.ty(dst_ty)) + }, + Instruction::Const { ty, .. } + | Instruction::Undef { ty, .. } + | Instruction::GlobalAddr { ty, .. } + | Instruction::Mov { ty, .. } + | Instruction::Bin { ty, .. } + | Instruction::Neg { ty, .. } + | Instruction::Not { ty, .. } + | Instruction::Cmp { ty, .. } + | Instruction::ICmp { ty, .. } + | Instruction::FCmp { ty, .. } + | Instruction::Select { ty, .. } + | Instruction::Checked { ty, .. } + | Instruction::Alloca { ty, .. } + | Instruction::VolatileLoad { ty, .. } + | Instruction::Load { ty, .. } + | Instruction::Uninit { ty, .. } + | Instruction::Store { ty, .. } + | Instruction::VolatileStore { ty, .. } => budget.ty(ty), + Instruction::Phi { ty, incomings, .. } => { + budget.ty(ty).and_then(|_| budget.nodes(incomings.len().saturating_mul(2))) + }, + Instruction::Extract { dst_ty, .. } => budget.ty(dst_ty), + Instruction::Gep { dst_ty, indices, .. } => { + budget.ty(dst_ty).and_then(|_| budget.nodes(indices.len())) + }, + Instruction::NullFunction { signature, .. } + | Instruction::FunctionAddr { signature, .. } => budget.signature(signature), + Instruction::Call { ret_ty, args, .. } => { + budget.ty(ret_ty).and_then(|_| budget.nodes(args.len())) + }, + _ => Ok(()), + }; + check.map_err(BuilderError::ResourceLimit) + } + + pub(super) fn new(limits: IrLimits) -> Self { + Self { + state: State::default(), + atoms: Vec::new(), + bytes: Vec::new(), + records: Vec::new(), + globals: Vec::new(), + blocks: Vec::new(), + limits, + } + } + + #[cfg(feature = "socket")] + pub(super) fn allocation_prefix(&self, id: BlockId) -> usize { + self.blocks[id.0 as usize].prefix_count as usize + } + + pub(super) fn block(&mut self, id: BlockId) { + assert_eq!(id.0 as usize, self.blocks.len()); + self.blocks.push(Block::default()); + } + + fn error(&self, status: i32) -> BuilderError { + match status { + 2 => BuilderError::ResourceLimit(LimitError { + resource: Resource::TypeDepth, + limit: self.limits.max_type_depth, + }), + 3 => BuilderError::ResourceLimit(LimitError { + resource: Resource::Nodes, + limit: self.limits.max_nodes, + }), + 4 => BuilderError::ResourceLimit(LimitError { + resource: Resource::AnalysisWork, + limit: self.limits.max_analysis_work, + }), + 10 => BuilderError::ResourceLimit(LimitError { + resource: Resource::InputBytes, + limit: self.limits.max_input_bytes, + }), + _ => BuilderError::InvalidType, + } + } + + // A logical IR node expands to a bounded number of typed wire atoms. This + // representation budget is separate from the source-model admission count. + fn node_limit(&self) -> u64 { + self.limits.max_nodes.saturating_mul(64) as u64 + } + + fn work_limit(&self) -> u64 { + self.limits.max_analysis_work.saturating_mul(64) as u64 + } + + pub(super) fn room(&self, atoms: usize, bytes: usize) -> Result<(), BuilderError> { + let atoms = atoms as u64; + let bytes = bytes as u64; + if atoms > self.node_limit().saturating_sub(self.state.atoms) { + return Err(self.error(3)); + } + if bytes > (self.limits.max_input_bytes as u64).saturating_sub(self.state.bytes) { + return Err(self.error(10)); + } + let cost = + atoms.saturating_mul(3).saturating_add(bytes.saturating_mul(3)).saturating_add(64); + if cost > self.work_limit().saturating_sub(self.state.work) { + return Err(self.error(4)); + } + Ok(()) + } + + pub(super) fn type_room(&self, ty: &Type, lists: usize) -> Result<(), BuilderError> { + let mut budget = + crate::limits::Budget::new(self.limits).map_err(BuilderError::ResourceLimit)?; + budget.ty(ty).map_err(BuilderError::ResourceLimit)?; + let mut input = Input { count_only: true, ..Input::default() }; + input.ty(ty); + self.room(input.atom_count.saturating_add(lists).saturating_add(64), 0) + } + + pub(super) fn instruction( + &mut self, + block: BlockId, + instruction: &Instruction, + hoist: bool, + probe: bool, + ) -> Result { + self.validate_instruction(instruction)?; + let count = Input::instruction(instruction, true); + self.room(count.atom_count, count.byte_count)?; + let input = Input::instruction(instruction, false); + self.apply(block, &input, hoist, probe) + } + + pub(super) fn terminator( + &mut self, + block: BlockId, + terminator: &Terminator, + probe: bool, + ) -> Result<(), BuilderError> { + match terminator { + Terminator::Switch { ty, cases, .. } => { + crate::limits::Budget::new(self.limits) + .and_then(|mut b| { + b.ty(ty)?; + b.nodes(cases.len()) + }) + .map_err(BuilderError::ResourceLimit)?; + }, + Terminator::Ret { ty, .. } => { + crate::limits::Budget::new(self.limits) + .and_then(|mut b| b.ty(ty)) + .map_err(BuilderError::ResourceLimit)?; + }, + _ => {}, + } + let count = Input::terminator(terminator, true); + self.room(count.atom_count, count.byte_count)?; + let input = Input::terminator(terminator, false); + self.apply(block, &input, false, probe).map(|_| ()) + } + + fn apply( + &mut self, + block: BlockId, + input: &Input, + hoist: bool, + probe: bool, + ) -> Result { + let before = self.state; + if before.atoms != self.atoms.len() as u64 + || before.bytes != self.bytes.len() as u64 + || before.records != self.records.len() as u64 + { + return Err(BuilderError::InvalidType); + } + let block_before = + *self.blocks.get(block.0 as usize).ok_or(BuilderError::UnknownBlock(block))?; + let run = |mode: u64, this: &mut Self| { + let mut result = RawResult::default(); + let node_limit = this.node_limit(); + let work_limit = this.work_limit(); + let status = unsafe { + whale_ir_builder_body( + &mut this.state, + this.blocks.as_mut_ptr(), + this.blocks.len() as u64, + block.0.into(), + input.op, + u64::from(hoist), + input.atoms.as_ptr(), + input.atoms.len() as u64, + input.bytes.as_ptr(), + input.bytes.len() as u64, + this.limits.max_type_depth as u64 + 1, + this.limits.max_const_depth as u64, + node_limit, + this.limits.max_input_bytes as u64, + work_limit, + mode, + this.atoms.as_mut_ptr(), + this.atoms.len() as u64, + this.bytes.as_mut_ptr(), + this.bytes.len() as u64, + this.records.as_mut_ptr(), + this.records.len() as u64, + &mut result, + ) + }; + (status, result) + }; + let (status, result) = run(0, self); + if status != result.status as i32 + || self.state != before + || self.blocks[block.0 as usize] != block_before + || result.work > self.work_limit().saturating_sub(before.work) + || result.ordinal > block_before.count + { + self.state = before; + self.blocks[block.0 as usize] = block_before; + return Err(BuilderError::InvalidType); + } + if status != 0 { + return Err(self.error(status)); + } + if probe { + return Ok(result.ordinal as usize); + } + let expected_atoms = + self.atoms.len().checked_add(input.atoms.len()).ok_or_else(|| self.error(3))?; + let expected_bytes = + self.bytes.len().checked_add(input.bytes.len()).ok_or_else(|| self.error(10))?; + let expected_records = self.records.len().checked_add(1).ok_or_else(|| self.error(3))?; + let expected_work = before.work.checked_add(result.work).ok_or_else(|| self.error(4))?; + let ordinal = result.ordinal; + let probe_work = result.work; + let mut previous = None; + let mut next = u64::MAX; + if input.op < 31 { + if hoist { + if ordinal != block_before.prefix_count { + return Err(BuilderError::InvalidType); + } + next = block_before.head; + if block_before.prefix_tail != u64::MAX { + let index = usize::try_from(block_before.prefix_tail) + .map_err(|_| BuilderError::InvalidType)?; + let record = *self.records.get(index).ok_or(BuilderError::InvalidType)?; + if record.block != u64::from(block.0) || record.op != 18 { + return Err(BuilderError::InvalidType); + } + previous = Some((index, record)); + next = record.next; + } + } else if block_before.tail != u64::MAX { + let index = + usize::try_from(block_before.tail).map_err(|_| BuilderError::InvalidType)?; + let record = *self.records.get(index).ok_or(BuilderError::InvalidType)?; + if record.block != u64::from(block.0) || record.op >= 31 || record.next != u64::MAX + { + return Err(BuilderError::InvalidType); + } + previous = Some((index, record)); + } + } + let new_index = before.records; + let mut expected_block = block_before; + if input.op < 31 { + if input.op == 18 && (hoist || block_before.prefix_count == block_before.count) { + expected_block.prefix_tail = new_index; + expected_block.prefix_count = + block_before.prefix_count.checked_add(1).ok_or(BuilderError::InvalidType)?; + } + expected_block.count = + expected_block.count.checked_add(1).ok_or(BuilderError::InvalidType)?; + if previous.is_none() { + expected_block.head = new_index; + } + if next == u64::MAX { + expected_block.tail = new_index; + } + } else { + expected_block.terminator = new_index; + } + let expected_record = Record { + op: input.op, + block: u64::from(block.0), + first: before.atoms, + count: input.atoms.len() as u64, + byte_first: before.bytes, + byte_count: input.bytes.len() as u64, + next, + }; + self.atoms.try_reserve(input.atoms.len()).map_err(|_| self.error(3))?; + self.bytes.try_reserve(input.bytes.len()).map_err(|_| self.error(10))?; + self.records.try_reserve(1).map_err(|_| self.error(3))?; + // Every slot is initialized before crossing FFI. Returned counters can + // never make Rust expose uninitialized memory, even on a bad backend. + self.atoms.resize(expected_atoms, Atom::default()); + self.bytes.resize(expected_bytes, 0); + self.records.resize(expected_records, Record::default()); + let (status, result) = run(1, self); + if status != 0 + || result.status != 0 + || result.ordinal != ordinal + || result.work != probe_work + || self.blocks[block.0 as usize] != expected_block + || self.records[before.records as usize] != expected_record + || previous.is_some_and(|(index, mut record)| { + record.next = new_index; + self.records[index] != record + }) + || self.state + != (State { + atoms: expected_atoms as u64, + bytes: expected_bytes as u64, + records: expected_records as u64, + globals: before.globals, + work: expected_work, + }) + { + self.atoms.truncate(before.atoms as usize); + self.bytes.truncate(before.bytes as usize); + self.records.truncate(before.records as usize); + if let Some((index, record)) = previous { + self.records[index] = record; + } + self.state = before; + self.blocks[block.0 as usize] = block_before; + return Err(BuilderError::InvalidType); + } + Ok(result.ordinal as usize) + } + + pub(super) fn global( + &mut self, + id: GlobalId, + name: &str, + expression: &ConstExpr, + init: &ConstValue, + align: u32, + probe: bool, + ) -> Result<(), BuilderError> { + crate::limits::Budget::new(self.limits) + .and_then(|mut budget| budget.expression(expression)) + .map_err(BuilderError::ResourceLimit)?; + let count = Input::global(name, expression, init, align, true); + self.room(count.atom_count, count.byte_count)?; + let input = Input::global(name, expression, init, align, false); + self.apply_global(id, &input, probe) + } + + fn apply_global( + &mut self, + id: GlobalId, + input: &Input, + probe: bool, + ) -> Result<(), BuilderError> { + let before = self.state; + if before.atoms != self.atoms.len() as u64 + || before.bytes != self.bytes.len() as u64 + || before.records != self.records.len() as u64 + || before.globals != self.globals.len() as u64 + { + return Err(BuilderError::InvalidType); + } + let run = |mode, this: &mut Self| { + let mut result = RawResult::default(); + let status = unsafe { + whale_ir_builder_global( + &mut this.state, + id.0.into(), + this.globals.as_mut_ptr(), + this.globals.len() as u64, + input.atoms.as_ptr(), + input.atoms.len() as u64, + input.bytes.as_ptr(), + input.bytes.len() as u64, + this.limits.max_type_depth as u64 + 1, + this.limits.max_const_depth as u64, + this.node_limit(), + this.limits.max_input_bytes as u64, + this.work_limit(), + mode, + this.atoms.as_mut_ptr(), + this.atoms.len() as u64, + this.bytes.as_mut_ptr(), + this.bytes.len() as u64, + &mut result, + ) + }; + (status, result) + }; + let (status, result) = run(0, self); + if status != result.status as i32 || self.state != before { + self.state = before; + return Err(BuilderError::InvalidType); + } + if status != 0 { + return Err(self.error(status)); + } + if result.ordinal != before.globals + || result.work > self.work_limit().saturating_sub(before.work) + { + return Err(BuilderError::InvalidType); + } + if probe { + return Ok(()); + } + let atoms = self.atoms.len().checked_add(input.atoms.len()).ok_or_else(|| self.error(3))?; + let bytes = + self.bytes.len().checked_add(input.bytes.len()).ok_or_else(|| self.error(10))?; + let globals = self.globals.len().checked_add(1).ok_or_else(|| self.error(3))?; + let work = before.work.checked_add(result.work).ok_or_else(|| self.error(4))?; + let expected = State { + atoms: atoms as u64, + bytes: bytes as u64, + globals: globals as u64, + work, + ..before + }; + let expected_record = GlobalRecord { + id: id.0.into(), + first: before.atoms, + count: input.atoms.len() as u64, + byte_first: before.bytes, + byte_count: input.bytes.len() as u64, + }; + self.atoms.try_reserve(input.atoms.len()).map_err(|_| self.error(3))?; + self.bytes.try_reserve(input.bytes.len()).map_err(|_| self.error(10))?; + self.globals.try_reserve(1).map_err(|_| self.error(3))?; + self.atoms.resize(atoms, Atom::default()); + self.bytes.resize(bytes, 0); + self.globals.resize(globals, GlobalRecord::default()); + let probe_work = result.work; + let (status, result) = run(1, self); + if status != 0 + || result.status != 0 + || result.ordinal != before.globals + || result.work != probe_work + || self.state != expected + || self.globals[before.globals as usize] != expected_record + { + self.atoms.truncate(before.atoms as usize); + self.bytes.truncate(before.bytes as usize); + self.globals.truncate(before.globals as usize); + self.state = before; + return Err(BuilderError::InvalidType); + } + Ok(()) + } + + pub(super) fn restore_globals(&self, globals: &mut Vec) -> Result<(), BuilderError> { + let mut restored = Vec::new(); + restored.try_reserve(self.globals.len()).map_err(|_| self.error(3))?; + for record in &self.globals { + let first = usize::try_from(record.first).map_err(|_| BuilderError::InvalidType)?; + let end = first + .checked_add(usize::try_from(record.count).map_err(|_| BuilderError::InvalidType)?) + .ok_or(BuilderError::InvalidType)?; + let mut reader = Reader { + atoms: self.atoms.get(first..end).ok_or(BuilderError::InvalidType)?, + bytes: &self.bytes, + at: 0, + }; + let name = reader.string().ok_or(BuilderError::InvalidType)?; + let expression = reader.expression().ok_or(BuilderError::InvalidType)?; + let init = reader.constant().ok_or(BuilderError::InvalidType)?; + let align = u32::try_from(reader.uint().ok_or(BuilderError::InvalidType)?) + .map_err(|_| BuilderError::InvalidType)?; + if reader.at != reader.atoms.len() { + return Err(BuilderError::InvalidType); + } + restored.push(Global { + id: GlobalId(u32::try_from(record.id).map_err(|_| BuilderError::InvalidType)?), + name, + ty: expression.ty.clone(), + init, + init_expr: expression, + align, + }); + } + *globals = restored; + Ok(()) + } + + fn reader(&self, index: u64) -> Option<(Reader<'_>, u64)> { + let record = self.records.get(usize::try_from(index).ok()?)?; + let first = usize::try_from(record.first).ok()?; + let end = first.checked_add(usize::try_from(record.count).ok()?)?; + Some((Reader { atoms: self.atoms.get(first..end)?, bytes: &self.bytes, at: 0 }, record.op)) + } + + pub(super) fn restore(&self, function: &mut Function) -> Result<(), BuilderError> { + for block in &mut function.blocks { + let model = self.blocks.get(block.id.0 as usize).ok_or(BuilderError::InvalidType)?; + let mut index = model.head; + if model.count > self.records.len() as u64 { + return Err(BuilderError::InvalidType); + } + let mut instructions = Vec::new(); + instructions.try_reserve(model.count as usize).map_err(|_| self.error(3))?; + while index != u64::MAX { + if instructions.len() >= model.count as usize { + return Err(BuilderError::InvalidType); + } + let (mut reader, op) = self.reader(index).ok_or(BuilderError::InvalidType)?; + let instruction = reader.instruction(op).ok_or(BuilderError::InvalidType)?; + if reader.at != reader.atoms.len() { + return Err(BuilderError::InvalidType); + } + instructions.push(instruction); + index = self.records[index as usize].next; + } + if instructions.len() != model.count as usize { + return Err(BuilderError::InvalidType); + } + let terminator = if model.terminator == u64::MAX { + None + } else { + let (mut reader, op) = + self.reader(model.terminator).ok_or(BuilderError::InvalidType)?; + let terminator = reader.terminator(op).ok_or(BuilderError::InvalidType)?; + if reader.at != reader.atoms.len() { + return Err(BuilderError::InvalidType); + } + Some(terminator) + }; + block.instructions = instructions; + block.terminator = terminator; + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn inventory() -> Vec { + let dst = ValueId(17); + let x = ValueId(3); + let y = ValueId(8); + let ty = Type::I128; + let signature = + FunctionSignature::whale(vec![Type::I128, Type::ptr_to(Type::Void)], Type::I128); + let expression = ConstExpr { + ty: ty.clone(), + kind: ConstExprKind::Binary { + op: ConstBinaryOp::Add, + left: Box::new(ConstExpr::literal(ty.clone(), ConstValue::I(i128::MIN))), + right: Box::new(ConstExpr { + ty: ty.clone(), + kind: ConstExprKind::Reference(ConstRef::Global(GlobalId(99))), + }), + }, + }; + vec![ + Instruction::GlobalAddr { dst, global: GlobalId(29), ty: ty.clone() }, + Instruction::LifetimeEnd { ptr: x }, + Instruction::PtrDiff { dst, lhs: x, rhs: y }, + Instruction::ConstDecl { + dst, + name: "λ🐋\0 declaration".into(), + expression, + value: ConstValue::I(i128::MIN + 7), + }, + Instruction::Const { + dst, + ty: Type::F64, + value: ConstValue::F(FloatBits::F64(0xfff8_0123_4567_89ab)), + }, + Instruction::Undef { dst, ty: Type::Tuple(vec![ty.clone(), Type::Bool]) }, + Instruction::Mov { dst, ty: ty.clone(), src: x }, + Instruction::Bin { dst, op: BinOp::AShr, ty: ty.clone(), lhs: x, rhs: y }, + Instruction::Neg { dst, ty: ty.clone(), src: x }, + Instruction::Not { dst, ty: ty.clone(), src: y }, + Instruction::Cmp { dst, op: CmpOp::FGe, ty: Type::F32, lhs: x, rhs: y }, + Instruction::ICmp { dst, pred: ICmpPred::Sge, ty: ty.clone(), lhs: x, rhs: y }, + Instruction::FCmp { dst, pred: FCmpPred::Uge, ty: Type::F16, lhs: x, rhs: y }, + Instruction::Select { dst, ty: ty.clone(), cond: x, on_true: x, on_false: y }, + Instruction::Cast { + dst, + op: CastOp::Bitcast, + src_ty: Type::F64, + dst_ty: Type::U64, + src: x, + }, + Instruction::Phi { + dst, + ty: ty.clone(), + incomings: vec![(x, BlockId(0)), (y, BlockId(4))], + }, + Instruction::Extract { dst, dst_ty: ty.clone(), tuple: x, index: u32::MAX }, + Instruction::Checked { dst, op: CheckedOp::SMul, ty: ty.clone(), lhs: x, rhs: y }, + Instruction::Alloca { + dst, + ty: Type::Struct(vec![ + Type::Array(Box::new(Type::U8), u64::MAX), + Type::FnPtr(Box::new(signature.clone())), + ]), + align: 64, + }, + Instruction::VolatileLoad { dst, ty: ty.clone(), ptr: x, align: 16 }, + Instruction::VolatileStore { ty: ty.clone(), value: y, ptr: x, align: 16 }, + Instruction::Load { dst, ty: ty.clone(), ptr: x, align: 16 }, + Instruction::Uninit { ty: ty.clone(), ptr: x, align: 16 }, + Instruction::Store { ty: ty.clone(), value: y, ptr: x, align: 16 }, + Instruction::Gep { + dst, + dst_ty: Type::ptr_to(Type::Array(Box::new(Type::U32), 5)), + base_ptr: x, + indices: vec![x, y], + }, + Instruction::Memcpy { dst: x, src: y, n: dst, align: 8 }, + Instruction::Memset { dst: x, val: y, n: dst, align: 8 }, + Instruction::NullFunction { dst, signature: signature.clone() }, + Instruction::FunctionAddr { dst, function: FunctionId(32), signature }, + Instruction::Call { + dst: Some(dst), + ret_ty: ty, + convention: CallingConvention::SysV64, + callee: Callee::Indirect(y), + args: vec![x, y], + }, + Instruction::TrapIf { cond: x, reason: "reason\0🐋\n\"".into() }, + ] + } + + fn function(blocks: usize) -> Function { + Function { + id: FunctionId(0), + name: "inventory".into(), + params: Vec::new(), + ret_ty: Type::Void, + entry: BlockId(0), + value_types: Vec::new(), + blocks: (0..blocks) + .map(|index| BasicBlock::new(BlockId(index as u32), format!("b{index}"))) + .collect(), + } + } + + #[test] + fn wave_global_records_preserve_exact_typed_literals_and_ids() { + let mut store = Store::new(IrLimits::default()); + let literals = [ + (Type::I128, ConstValue::I(i128::MIN)), + (Type::U128, ConstValue::U(u128::MAX)), + (Type::F16, ConstValue::F(FloatBits::F16(0xfe55))), + (Type::F32, ConstValue::F(FloatBits::F32(0xffc1_2345))), + (Type::F64, ConstValue::F(FloatBits::F64(0xfff8_0123_4567_89ab))), + (Type::Bool, ConstValue::Bool(true)), + ]; + let mut expected = Vec::new(); + for (index, (ty, value)) in literals.into_iter().enumerate() { + let id = GlobalId(index as u32 * 2); + let name = format!("λ\0 literal {index}"); + let expression = ConstExpr::literal(ty.clone(), value.clone()); + store.global(id, &name, &expression, &value, 16, false).unwrap(); + expected.push(Global { id, name, ty, init: value, init_expr: expression, align: 16 }); + } + let before = (store.state, store.atoms.clone(), store.bytes.clone(), store.globals.clone()); + let mut invalid = Input::global( + "bad", + &ConstExpr::literal(Type::I32, ConstValue::I(0)), + &ConstValue::I(0), + 4, + false, + ); + invalid.atoms.pop(); + assert!(store.apply_global(GlobalId(99), &invalid, false).is_err()); + assert_eq!( + (store.state, store.atoms.clone(), store.bytes.clone(), store.globals.clone()), + before + ); + let mut globals = Vec::new(); + store.restore_globals(&mut globals).unwrap(); + assert_eq!(globals, expected); + } + + #[test] + fn wave_body_is_authoritative_for_the_complete_instruction_and_terminator_inventory() { + let mut store = Store::new(IrLimits::default()); + for index in 0..5 { + store.block(BlockId(index)); + } + let instructions = inventory(); + for instruction in &instructions { + store.instruction(BlockId(0), instruction, false, false).unwrap(); + } + let terms = [ + Terminator::Br { target: BlockId(4) }, + Terminator::CBr { cond: ValueId(3), then_bb: BlockId(0), else_bb: BlockId(4) }, + Terminator::Switch { + ty: Type::U128, + value: ValueId(8), + default_bb: BlockId(0), + cases: vec![(ConstValue::U(u128::MAX), BlockId(4)), (ConstValue::U(0), BlockId(2))], + }, + Terminator::Ret { ty: Type::I128, value: Some(ValueId(17)) }, + Terminator::Trap { reason: "trap λ\0".into() }, + ]; + for (index, term) in terms.iter().enumerate() { + store.terminator(BlockId(index as u32), term, false).unwrap(); + } + let mut output = function(5); + // Poison the compatibility mirror: reconstruction must use the complete + // Wave model, including literals, names, expression/list/callee fields. + output.blocks[0].instructions.push(Instruction::LifetimeEnd { ptr: ValueId(999) }); + store.restore(&mut output).unwrap(); + assert_eq!(output.blocks[0].instructions, instructions); + for (index, term) in terms.into_iter().enumerate() { + assert_eq!(output.blocks[index].terminator, Some(term)); + } + } + + #[test] + fn wave_body_many_hoists_use_constant_work_and_preserve_payload_order() { + let count = 10000; + let mut store = + Store::new(IrLimits { max_analysis_work: count / 4, ..IrLimits::default() }); + store.block(BlockId(0)); + let literal = Instruction::Const { + dst: ValueId(count as u32), + ty: Type::I32, + value: ConstValue::I(42), + }; + store.instruction(BlockId(0), &literal, false, false).unwrap(); + store + .terminator(BlockId(0), &Terminator::Ret { ty: Type::Void, value: None }, false) + .unwrap(); + let mut cost = None; + for index in 0..count { + let before = store.state.work; + let allocation = + Instruction::Alloca { dst: ValueId(index as u32), ty: Type::I32, align: 4 }; + assert_eq!(store.instruction(BlockId(0), &allocation, true, false), Ok(index)); + let work = store.state.work - before; + assert_eq!(*cost.get_or_insert(work), work); + } + assert!(store.state.work <= count as u64 * 16); + let mut output = function(1); + store.restore(&mut output).unwrap(); + for (index, instruction) in output.blocks[0].instructions[..count].iter().enumerate() { + assert_eq!( + instruction, + &Instruction::Alloca { dst: ValueId(index as u32), ty: Type::I32, align: 4 } + ); + } + assert_eq!(output.blocks[0].instructions[count], literal); + assert_eq!( + output.blocks[0].terminator, + Some(Terminator::Ret { ty: Type::Void, value: None }) + ); + } + + #[test] + fn wave_body_hoisting_and_failed_appends_preserve_all_existing_payload() { + let mut store = Store::new(IrLimits::default()); + store.block(BlockId(0)); + let allocation = Instruction::Alloca { dst: ValueId(0), ty: Type::I32, align: 4 }; + let literal = + Instruction::Const { dst: ValueId(1), ty: Type::U128, value: ConstValue::U(u128::MAX) }; + store.instruction(BlockId(0), &allocation, false, false).unwrap(); + store.instruction(BlockId(0), &literal, false, false).unwrap(); + store + .terminator(BlockId(0), &Terminator::Ret { ty: Type::Void, value: None }, false) + .unwrap(); + let hoisted = Instruction::Alloca { dst: ValueId(2), ty: Type::Bool, align: 1 }; + assert_eq!(store.instruction(BlockId(0), &hoisted, true, false), Ok(1)); + let before = ( + store.state, + store.atoms.clone(), + store.bytes.clone(), + store.records.clone(), + store.blocks.clone(), + ); + assert!(store.instruction(BlockId(0), &literal, false, false).is_err()); + let mut malformed = Input::instruction(&allocation, false); + malformed.atoms.pop(); + assert!(store.apply(BlockId(0), &malformed, true, false).is_err()); + assert_eq!( + ( + store.state, + store.atoms.clone(), + store.bytes.clone(), + store.records.clone(), + store.blocks.clone() + ), + before + ); + let mut output = function(1); + store.restore(&mut output).unwrap(); + assert_eq!(output.blocks[0].instructions, vec![allocation, hoisted, literal]); + assert_eq!( + output.blocks[0].terminator, + Some(Terminator::Ret { ty: Type::Void, value: None }) + ); + } +} diff --git a/ir/src/builder/namespace.rs b/ir/src/builder/namespace.rs new file mode 100644 index 0000000..11082d4 --- /dev/null +++ b/ir/src/builder/namespace.rs @@ -0,0 +1,771 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Borrowed namespace transport; immutable payload allocations are retained for +//! the lifetime of the Wave-owned module namespace records. +use super::wave::{Builder, Node, ResultRecord, State, Value}; + +use crate::{ + CallError, FunctionDecl, FunctionId, GlobalId, GlobalStorage, GlobalStorageError, + GlobalStorageInit, IrLimits, LimitError, Linkage, Resource, Type, +}; + +#[repr(C)] +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) struct Record { + kind: u64, + id: u64, + flags: u64, + name: *const u8, + name_count: u64, + link: *const u8, + link_count: u64, + types: *const Node, + type_count: u64, + defined: u64, + align: u64, + initializer: u64, + low: u64, + high: u64, +} + +pub(super) struct Payload { + _name: String, + _link: Option, + _types: Vec, +} + +unsafe extern "C" { + fn whale_ir_builder_function_capacity( + state: *const State, + entries: *const Record, + count: u64, + id: u64, + nodes: u64, + work: u64, + result: *mut ResultRecord, + ) -> i32; + + fn whale_ir_builder_signature( + types: *const Node, + count: u64, + depth: u64, + nodes: u64, + work: u64, + result: *mut ResultRecord, + ) -> i32; + + fn whale_ir_builder_pointer( + types: *const Node, + type_count: u64, + values: *const Value, + value_count: u64, + first_value: u64, + lhs: u64, + rhs: u64, + pair: u64, + max_work: u64, + result: *mut ResultRecord, + ) -> i32; + + fn whale_ir_builder_call( + types: *const Node, + type_count: u64, + values: *const Value, + value_count: u64, + first_value: u64, + entries: *const Record, + entry_count: u64, + indirect: u64, + callee: u64, + arguments: *const u64, + argument_count: u64, + check_arguments: u64, + max_work: u64, + result: *mut ResultRecord, + ) -> i32; + + fn whale_ir_builder_namespace( + state: *mut State, + entries: *const Record, + entry_count: u64, + candidate: *const Record, + mode: u64, + legacy: u64, + depth: u64, + nodes: u64, + bytes: u64, + work: u64, + output: *mut Record, + capacity: u64, + result: *mut ResultRecord, + ) -> i32; + + fn whale_ir_builder_definition( + entries: *mut Record, + count: u64, + id: u64, + parameters: u64, + mode: u64, + work: u64, + result: *mut ResultRecord, + ) -> i32; + + fn whale_ir_builder_function_lookup( + entries: *const Record, + count: u64, + name: *const u8, + name_count: u64, + work: u64, + result: *mut ResultRecord, + ) -> i32; +} + +impl Builder { + fn namespace_error(&self, status: i32) -> LimitError { + match status { + 2 => LimitError { resource: Resource::TypeDepth, limit: self.limits.max_type_depth }, + 3 => LimitError { resource: Resource::Nodes, limit: self.limits.max_nodes }, + 19 => LimitError { resource: Resource::InputBytes, limit: self.limits.max_input_bytes }, + _ => LimitError { + resource: Resource::AnalysisWork, + limit: self.limits.max_analysis_work, + }, + } + } + + fn signature_nodes( + &self, + signature: &crate::FunctionSignature, + limits: IrLimits, + ) -> Result, CallError> { + // Only bound the borrowed transport here. Callable legality belongs to + // Wave's namespace/signature walk and does not use a Rust success path. + crate::limits::Budget::new(limits) + .and_then(|mut budget| budget.signature(signature)) + .map_err(CallError::ResourceLimit)?; + let mut nodes = vec![Node { + kind: 18, + depth: 0, + children: signature.params.len() as u64 + 1, + auxiliary: u64::from(signature.variadic) * 2 + + u64::from(signature.convention == crate::CallingConvention::SysV64), + }]; + for ty in std::iter::once(&signature.ret).chain(signature.params.iter()) { + let mut children = self.flatten(ty).map_err(|error| match error { + crate::BuilderError::ResourceLimit(error) => CallError::ResourceLimit(error), + error => CallError::Builder(error), + })?; + for node in &mut children { + node.depth += 1; + } + nodes.extend(children); + } + Ok(nodes) + } + + #[allow(clippy::too_many_arguments)] + fn namespace( + &mut self, + kind: u64, + flags: u64, + name: &str, + link: Option<&str>, + types: Vec, + legacy: bool, + limits: IrLimits, + align: u64, + initializer: u64, + low: u64, + high: u64, + ) -> Result { + let mut candidate = Record { + kind, + id: 0, + flags, + name: name.as_ptr(), + name_count: name.len() as u64, + link: link.map_or(std::ptr::null(), str::as_ptr), + link_count: link.map_or(0, str::len) as u64, + types: types.as_ptr(), + type_count: types.len() as u64, + defined: 0, + align, + initializer, + low, + high, + }; + let depth = + self.limits.max_type_depth.min(limits.max_type_depth) as u64 + u64::from(kind == 0); + let nodes = self.limits.max_nodes.min(limits.max_nodes) as u64; + let bytes = self.limits.max_input_bytes.min(limits.max_input_bytes) as u64; + let work = self.limits.max_analysis_work.min(limits.max_analysis_work) as u64; + let before = self.state; + let mut result = ResultRecord::default(); + let status = unsafe { + whale_ir_builder_namespace( + &mut self.state, + self.namespaces.as_ptr(), + self.namespaces.len() as u64, + &candidate, + 0, + u64::from(legacy), + depth, + nodes, + bytes, + work, + std::ptr::null_mut(), + 0, + &mut result, + ) + }; + if status != result.status as i32 || self.state != before { + self.state = before; + return Err(1); + } + if status != 0 { + return Err(status); + } + let admitted_value = result.value; + let admitted_work = result.work; + if admitted_work > work.saturating_sub(before.work) { + return Err(1); + } + if result.detail == 1 { + let status = unsafe { + whale_ir_builder_namespace( + &mut self.state, + self.namespaces.as_ptr(), + self.namespaces.len() as u64, + &candidate, + 1, + u64::from(legacy), + depth, + nodes, + bytes, + work, + std::ptr::null_mut(), + 0, + &mut result, + ) + }; + let mut expected = before; + expected.work = expected.work.checked_add(admitted_work).ok_or(1)?; + return if status == 0 + && result.status == 0 + && self.state == expected + && result.value == admitted_value + && result.work == admitted_work + && result.detail == 1 + { + Ok(result.value) + } else { + self.state = before; + Err(1) + }; + } + // Every string/type copy and Vec growth follows successful Wave admission. + let owned = |text: &str| -> Result { + let mut string = String::new(); + string.try_reserve_exact(text.len()).map_err(|_| 3)?; + string.push_str(text); + Ok(string) + }; + let payload = + Payload { _name: owned(name)?, _link: link.map(owned).transpose()?, _types: types }; + candidate.name = payload._name.as_ptr(); + candidate.link = payload._link.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()); + candidate.types = payload._types.as_ptr(); + self.namespaces.try_reserve(1).map_err(|_| 3)?; + self.namespace_payloads.try_reserve(1).map_err(|_| 3)?; + let count = self.namespaces.len(); + let mut expected = before; + if kind == 0 { + expected.next_function = expected.next_function.checked_add(1).ok_or(1)?; + } else { + expected.next_global = expected.next_global.checked_add(1).ok_or(1)?; + } + expected.namespace_nodes = expected + .namespace_nodes + .checked_add(candidate.type_count) + .and_then(|n| n.checked_add(1)) + .ok_or(1)?; + expected.namespace_bytes = expected + .namespace_bytes + .checked_add(candidate.name_count) + .and_then(|n| n.checked_add(candidate.link_count)) + .ok_or(1)?; + expected.work = expected.work.checked_add(admitted_work).ok_or(1)?; + let mut expected_record = candidate; + expected_record.id = admitted_value; + self.namespaces.push(candidate); + let status = unsafe { + whale_ir_builder_namespace( + &mut self.state, + self.namespaces.as_ptr(), + count as u64, + &candidate, + 1, + u64::from(legacy), + depth, + nodes, + bytes, + work, + self.namespaces.as_mut_ptr(), + self.namespaces.len() as u64, + &mut result, + ) + }; + if status != 0 + || result.status != 0 + || result.value != admitted_value + || result.work != admitted_work + || self.state != expected + || self.namespaces[count] != expected_record + { + self.namespaces.truncate(count); + self.state = before; + return Err(1); + } + self.namespace_payloads.push(payload); + Ok(result.value) + } + + pub(super) fn signature(&self, signature: &crate::FunctionSignature) -> Result<(), CallError> { + let nodes = self.signature_nodes(signature, self.limits)?; + let mut result = ResultRecord::default(); + let status = unsafe { + whale_ir_builder_signature( + nodes.as_ptr(), + nodes.len() as u64, + self.limits.max_type_depth as u64 + 1, + self.limits.max_nodes as u64, + self.limits.max_analysis_work.saturating_sub(self.state.work as usize) as u64, + &mut result, + ) + }; + match status { + 0 => Ok(()), + 17 => Err(CallError::InvalidSignature( + "void parameters, malformed types and variadic calls are unsupported".into(), + )), + 18 => Err(CallError::InvalidSignature( + "SysV64 aggregate signatures are unsupported".into(), + )), + status => Err(CallError::ResourceLimit(self.namespace_error(status))), + } + } + + pub(super) fn pointer( + &self, + first_value: u32, + lhs: crate::ValueId, + rhs: Option, + ) -> Result<(), crate::BuilderError> { + let mut result = ResultRecord::default(); + let status = unsafe { + whale_ir_builder_pointer( + self.types.as_ptr(), + self.types.len() as u64, + self.values.as_ptr(), + self.values.len() as u64, + first_value.into(), + lhs.0.into(), + rhs.map_or(0, |id| id.0).into(), + u64::from(rhs.is_some()), + self.limits.max_analysis_work.saturating_sub(self.state.work as usize) as u64, + &mut result, + ) + }; + if status == 0 { + Ok(()) + } else if status == 28 { + Err(crate::BuilderError::InvalidPointerOperands) + } else { + Err(self.error(status, result.detail)) + } + } + + pub(super) fn declaration( + &mut self, + declaration: &FunctionDecl, + limits: IrLimits, + legacy: bool, + ) -> Result { + let types = self.signature_nodes(&declaration.signature, limits)?; + let flags = u64::from(declaration.linkage == Linkage::External) + | (u64::from(declaration.link_name.is_some()) << 1); + self.namespace( + 0, + flags, + &declaration.name, + declaration.link_name.as_deref(), + types, + legacy, + limits, + 0, + 0, + 0, + 0, + ) + .map(|id| FunctionId(id as u32)) + .map_err(|status| match status { + 12 => CallError::ConflictingDeclaration(declaration.name.clone()), + 11 => CallError::LinkNameCollision(declaration.link_name.clone().unwrap_or_default()), + 16 => CallError::InvalidLinkName(declaration.name.clone()), + 17 => CallError::InvalidSignature( + "void parameters, malformed types and variadic calls are unsupported".into(), + ), + 18 => CallError::InvalidSignature("SysV64 aggregate signatures are unsupported".into()), + 2 | 3 | 4 | 19 => CallError::ResourceLimit(self.namespace_error(status)), + _ => CallError::Builder(self.error(status, 0)), + }) + } + + pub(super) fn global_constant( + &mut self, + name: &str, + ty: &Type, + ) -> Result { + let types = self.flatten(ty)?; + self.namespace(1, 0, name, None, types, true, self.limits, 0, 0, 0, 0) + .map(|id| GlobalId(id as u32)) + .map_err(|status| self.error(status, 0)) + } + + pub(super) fn storage( + &mut self, + storage: &GlobalStorage, + ) -> Result { + let types = self.flatten(&storage.ty).map_err(|error| match error { + crate::BuilderError::ResourceLimit(error) => GlobalStorageError::ResourceLimit(error), + _ => GlobalStorageError::InvalidType, + })?; + let (initializer, low, high) = match &storage.init { + GlobalStorageInit::Uninitialized => (0, 0, 0), + GlobalStorageInit::Value(crate::ConstValue::I(value)) => { + (1, *value as u64, (*value >> 64) as u64) + }, + GlobalStorageInit::Value(crate::ConstValue::U(value)) => { + (2, *value as u64, (*value >> 64) as u64) + }, + GlobalStorageInit::Value(crate::ConstValue::Bool(value)) => (3, u64::from(*value), 0), + GlobalStorageInit::Value(crate::ConstValue::F(value)) => (0, value.bits(), 0), + }; + let initializer = + if let GlobalStorageInit::Value(crate::ConstValue::F(value)) = &storage.init { + match value { + crate::FloatBits::F16(_) => 4, + crate::FloatBits::F32(_) => 5, + crate::FloatBits::F64(_) => 6, + } + } else { + initializer + }; + let flags = u64::from(storage.linkage == Linkage::External) + | (u64::from(storage.link_name.is_some()) << 1) + | (u64::from(storage.readonly) << 2); + self.namespace( + 2, + flags, + &storage.name, + storage.link_name.as_deref(), + types, + false, + self.limits, + storage.align.into(), + initializer, + low, + high, + ) + .map(|id| GlobalId(id as u32)) + .map_err(|status| match status { + 10 => GlobalStorageError::DuplicateName, + 11 => GlobalStorageError::LinkNameCollision, + 16 => GlobalStorageError::InvalidLinkName, + 25 => GlobalStorageError::InvalidAlignment, + 26 => GlobalStorageError::ReadOnlyUninitialized, + 27 => GlobalStorageError::InvalidInitializer, + 2 | 3 | 4 | 19 => GlobalStorageError::ResourceLimit(self.namespace_error(status)), + 5 => GlobalStorageError::DuplicateIdentity, + _ => GlobalStorageError::InvalidType, + }) + } + + pub(super) fn lookup_function(&self, name: &str) -> Result { + let mut result = ResultRecord::default(); + let status = unsafe { + whale_ir_builder_function_lookup( + self.namespaces.as_ptr(), + self.namespaces.len() as u64, + name.as_ptr(), + name.len() as u64, + self.limits.max_analysis_work as u64, + &mut result, + ) + }; + match status { + 0 => Ok(FunctionId(result.value as u32)), + 13 => Err(CallError::UnknownFunctionName(name.into())), + status => Err(CallError::ResourceLimit(self.namespace_error(status))), + } + } + + pub(super) fn check_call( + &self, + first_value: u32, + callee: &crate::Callee, + arguments: Option<&[crate::ValueId]>, + signature: Option<&crate::FunctionSignature>, + function: &crate::Function, + ) -> Result<(), CallError> { + let arguments_count = arguments.map_or(0, <[crate::ValueId]>::len); + if arguments_count > self.limits.max_analysis_work { + return Err(CallError::ResourceLimit(self.namespace_error(4))); + } + let arguments_raw: Vec = + arguments.unwrap_or(&[]).iter().map(|id| id.0.into()).collect(); + let (indirect, callee_id) = match callee { + crate::Callee::Direct(id) => (0, id.0), + crate::Callee::Indirect(id) => (1, id.0), + }; + let mut result = ResultRecord::default(); + let status = unsafe { + whale_ir_builder_call( + self.types.as_ptr(), + self.types.len() as u64, + self.values.as_ptr(), + self.values.len() as u64, + first_value.into(), + self.namespaces.as_ptr(), + self.namespaces.len() as u64, + indirect, + callee_id.into(), + arguments_raw.as_ptr(), + arguments_raw.len() as u64, + u64::from(arguments.is_some()), + self.limits.max_analysis_work.saturating_sub(self.state.work as usize) as u64, + &mut result, + ) + }; + match status { + 0 => Ok(()), + 8 => Err(CallError::UnknownValue(crate::ValueId(result.detail as u32))), + 13 => Err(CallError::UnknownFunction(FunctionId(callee_id))), + 21 => Err(CallError::NotFunctionPointer(crate::ValueId(callee_id))), + 22 => Err(CallError::ArgumentCount { + expected: result.detail as usize, + got: arguments_count, + }), + 23 => { + let index = result.detail as usize; + let expected = signature.and_then(|signature| signature.params.get(index)); + let got = arguments + .and_then(|args| args.get(index)) + .and_then(|id| function.value_type(*id)); + match (expected, got) { + (Some(expected), Some(got)) => Err(CallError::ArgumentType { + index, + expected: expected.clone(), + got: got.clone(), + }), + _ => Err(CallError::Builder(crate::BuilderError::InvalidType)), + } + }, + 17 => Err(CallError::InvalidSignature( + "void parameters, malformed types and variadic calls are unsupported".into(), + )), + 18 => Err(CallError::InvalidSignature( + "SysV64 aggregate signatures are unsupported".into(), + )), + status => Err(CallError::ResourceLimit(self.namespace_error(status))), + } + } + + pub(super) fn preflight_function(&self, id: FunctionId) -> Result<(), CallError> { + let mut result = ResultRecord::default(); + let status = unsafe { + whale_ir_builder_function_capacity( + &self.state, + self.namespaces.as_ptr(), + self.namespaces.len() as u64, + id.0.into(), + self.limits.max_nodes as u64, + self.limits.max_analysis_work as u64, + &mut result, + ) + }; + match status { + 0 => Ok(()), + 5 => Err(CallError::Builder(crate::BuilderError::IdentityOverflow)), + 13 => Err(CallError::UnknownFunction(id)), + status => Err(CallError::ResourceLimit(self.namespace_error(status))), + } + } + + pub(super) fn definition( + &mut self, + id: FunctionId, + parameters: usize, + commit: bool, + ) -> Result<(), CallError> { + let mut result = ResultRecord::default(); + let status = unsafe { + whale_ir_builder_definition( + self.namespaces.as_mut_ptr(), + self.namespaces.len() as u64, + id.0.into(), + parameters as u64, + u64::from(commit), + self.limits.max_analysis_work as u64, + &mut result, + ) + }; + match status { + 0 => Ok(()), + 13 => Err(CallError::UnknownFunction(id)), + 14 => Err(CallError::DuplicateDefinition(id)), + 15 => Err(CallError::DefinitionMismatch(id)), + 17 => Err(CallError::InvalidSignature( + "void parameters, malformed types and variadic calls are unsupported".into(), + )), + 18 => Err(CallError::InvalidSignature( + "SysV64 aggregate signatures are unsupported".into(), + )), + status => Err(CallError::ResourceLimit(self.namespace_error(status))), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn declaration(name: &str, link: Option<&str>, parameter: Type) -> FunctionDecl { + FunctionDecl { + id: FunctionId(999), + name: name.into(), + signature: crate::FunctionSignature::whale(vec![parameter], Type::Void), + linkage: if link.is_some() { Linkage::External } else { Linkage::Internal }, + link_name: link.map(str::to_owned), + } + } + + #[test] + fn namespace_duplicates_and_collisions_are_atomic_and_share_global_ids() { + let mut builder = Builder::new(IrLimits::default()); + let first = declaration("function", Some("export"), Type::I32); + assert_eq!(builder.declaration(&first, IrLimits::default(), false), Ok(FunctionId(0))); + assert_eq!(builder.declaration(&first, IrLimits::default(), false), Ok(FunctionId(0))); + let before = builder.state; + assert_eq!( + builder.declaration( + &declaration("function", Some("export"), Type::U32), + IrLimits::default(), + false + ), + Err(CallError::ConflictingDeclaration("function".into())) + ); + assert_eq!(builder.state, before); + let mut storage = GlobalStorage::internal( + "data", + Type::U32, + GlobalStorageInit::Value(crate::ConstValue::U(9)), + false, + 4, + ); + storage.linkage = Linkage::External; + storage.link_name = Some("export".into()); + assert_eq!(builder.storage(&storage), Err(GlobalStorageError::LinkNameCollision)); + assert_eq!(builder.state, before); + storage.link_name = Some("data_export".into()); + assert_eq!(builder.storage(&storage), Ok(GlobalId(0))); + assert_eq!(builder.global_constant("constant", &Type::U32), Ok(GlobalId(1))); + storage.name = "constant".into(); + storage.link_name = Some("third_export".into()); + let before = builder.state; + assert_eq!(builder.storage(&storage), Err(GlobalStorageError::DuplicateName)); + assert_eq!(builder.state, before); + assert_eq!(builder.lookup_function("function"), Ok(FunctionId(0))); + assert_eq!(builder.namespaces.len(), 3); + } + + #[test] + fn wave_callable_and_storage_validation_matches_the_reference_inventory() { + let types = [ + Type::Void, + Type::Bool, + Type::I1, + Type::U1, + Type::I8, + Type::U8, + Type::I32, + Type::U32, + Type::I128, + Type::U128, + Type::F16, + Type::F32, + Type::F64, + Type::ptr_to(Type::Void), + Type::ptr_to(Type::I32), + Type::Array(Box::new(Type::Void), 1), + Type::Tuple(vec![Type::Void]), + Type::Tuple(vec![Type::I32]), + Type::FnPtr(Box::new(crate::FunctionSignature::whale(vec![Type::Void], Type::Void))), + ]; + for ty in types { + let candidate = declaration("function", None, ty.clone()); + let reference = + crate::function::validate_decl_with_limits(&candidate, IrLimits::default()); + let result = Builder::new(IrLimits::default()).declaration( + &candidate, + IrLimits::default(), + false, + ); + assert_eq!(result.map(|_| ()), reference, "{ty:?}"); + for init in [ + GlobalStorageInit::Uninitialized, + GlobalStorageInit::Value(crate::ConstValue::I(-1)), + GlobalStorageInit::Value(crate::ConstValue::U(1)), + GlobalStorageInit::Value(crate::ConstValue::Bool(true)), + GlobalStorageInit::Value(crate::ConstValue::F(crate::FloatBits::F32(0x7fa00001))), + ] { + let storage = GlobalStorage::internal("data", ty.clone(), init, false, 4); + let reference = storage.validate_with_limits(IrLimits::default()); + let result = Builder::new(IrLimits::default()).storage(&storage).map(|_| ()); + assert_eq!(result, reference, "{storage:?}"); + } + } + } + + #[test] + fn definitions_publish_on_commit_and_rejected_names_do_not_copy_payloads() { + let mut builder = Builder::new(IrLimits::default()); + builder + .declaration(&declaration("callee", None, Type::I32), IrLimits::default(), false) + .unwrap(); + let before = builder.state; + assert_eq!( + builder.definition(FunctionId(0), 0, false), + Err(CallError::DefinitionMismatch(FunctionId(0))) + ); + builder.definition(FunctionId(0), 1, false).unwrap(); + builder.definition(FunctionId(0), 1, false).unwrap(); + assert_eq!(builder.state, before); + builder.definition(FunctionId(0), 1, true).unwrap(); + assert_eq!( + builder.definition(FunctionId(0), 1, false), + Err(CallError::DuplicateDefinition(FunctionId(0))) + ); + let mut tiny = Builder::new(IrLimits { max_input_bytes: 3, ..IrLimits::default() }); + let before = tiny.state; + let error = tiny + .declaration(&declaration("long", None, Type::I32), IrLimits::default(), false) + .unwrap_err(); + assert!(matches!( + error, + CallError::ResourceLimit(LimitError { resource: Resource::InputBytes, .. }) + )); + assert_eq!(tiny.state, before); + assert!(tiny.namespaces.is_empty()); + assert!(tiny.namespace_payloads.is_empty()); + } +} diff --git a/ir/src/builder/wave.rs b/ir/src/builder/wave.rs new file mode 100644 index 0000000..2e6ad5f --- /dev/null +++ b/ir/src/builder/wave.rs @@ -0,0 +1,737 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Caller-owned storage for the authoritative Wave construction model. +use super::BuilderError; + +use crate::{BlockId, IrLimits, LimitError, Resource, Type, ValueId}; + +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) struct Node { + pub(super) kind: u64, + pub(super) depth: u64, + pub(super) children: u64, + pub(super) auxiliary: u64, +} + +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) struct Value { + id: u64, + first_type: u64, + type_count: u64, +} + +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct Block { + id: u64, + terminated: u64, + non_phi: u64, +} + +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) struct State { + pub(super) next_value: u64, + pub(super) next_block: u64, + pub(super) type_count: u64, + pub(super) instruction_count: u64, + pub(super) namespace_nodes: u64, + pub(super) namespace_bytes: u64, + pub(super) next_function: u64, + pub(super) next_global: u64, + pub(super) work: u64, +} + +#[repr(C)] +#[derive(Default)] +pub(super) struct ResultRecord { + pub(super) status: u64, + pub(super) detail: u64, + pub(super) value: u64, + pub(super) work: u64, +} + +unsafe extern "C" { + fn whale_ir_builder_type( + nodes: *const Node, + count: u64, + depth: u64, + nodes_limit: u64, + work_limit: u64, + result: *mut ResultRecord, + ) -> i32; + + fn whale_ir_builder_allocate( + state: *mut State, + kind: u64, + types: *const Node, + count: u64, + depth_limit: u64, + node_limit: u64, + work_limit: u64, + mode: u64, + output_types: *mut Node, + type_capacity: u64, + output_values: *mut Value, + value_capacity: u64, + output_blocks: *mut Block, + block_capacity: u64, + result: *mut ResultRecord, + ) -> i32; + + fn whale_ir_builder_order( + state: *mut State, + node_limit: u64, + blocks: *mut Block, + count: u64, + first_block: u64, + first_value: u64, + value_end: u64, + block: u64, + op: u64, + operands: *const u64, + operand_count: u64, + targets: *const u64, + target_count: u64, + check_only: u64, + max_work: u64, + result: *mut ResultRecord, + ) -> i32; +} + +pub(super) struct Builder { + pub(super) body: super::body::Store, + pub(super) state: State, + pub(super) types: Vec, + pub(super) values: Vec, + blocks: Vec, + pub(super) limits: IrLimits, + pub(super) namespaces: Vec, + pub(super) namespace_payloads: Vec, +} + +// Raw namespace pointers reference only immutable allocations retained by this +// owner. Mutating Wave calls require &mut Builder; shared queries are read-only. +unsafe impl Send for Builder {} + +unsafe impl Sync for Builder {} + +impl Builder { + pub(super) fn new(limits: IrLimits) -> Self { + Self { + body: super::body::Store::new(limits), + state: State::default(), + types: Vec::new(), + values: Vec::new(), + blocks: Vec::new(), + limits, + namespaces: Vec::new(), + namespace_payloads: Vec::new(), + } + } + + pub(super) fn error(&self, status: i32, detail: u64) -> BuilderError { + match status { + 2 => self.limit(Resource::TypeDepth, self.limits.max_type_depth), + 3 => self.limit(Resource::Nodes, self.limits.max_nodes), + 4 => self.limit(Resource::AnalysisWork, self.limits.max_analysis_work), + 5 => BuilderError::IdentityOverflow, + 6 => BuilderError::UnknownBlock(BlockId(detail as u32)), + 7 => BuilderError::TerminatedBlock(BlockId(detail as u32)), + 8 => BuilderError::UnknownValue(ValueId(detail as u32)), + 9 => BuilderError::PhiAfterInstruction(BlockId(detail as u32)), + _ => BuilderError::InvalidType, + } + } + + fn limit(&self, resource: Resource, limit: usize) -> BuilderError { + BuilderError::ResourceLimit(LimitError { resource, limit }) + } + + pub(super) fn used_nodes(&self) -> usize { + self.types + .len() + .saturating_add(self.values.len()) + .saturating_add(self.blocks.len()) + .saturating_add(self.state.instruction_count as usize) + .saturating_add(self.state.namespace_nodes as usize) + } + + pub(super) fn flatten(&self, ty: &Type) -> Result, BuilderError> { + // This bounded borrowed transport walk precedes every recursive Rust + // clone. Wave checks the complete exact inventory and commits budgets. + let mut limits = self.limits; + limits.max_nodes = limits.max_nodes.saturating_sub(self.used_nodes()); + crate::limits::Budget::new(limits) + .and_then(|mut b| b.ty(ty)) + .map_err(BuilderError::ResourceLimit)?; + let mut nodes = Vec::new(); + let mut pending = vec![(ty, 0)]; + while let Some((ty, depth)) = pending.pop() { + let (kind, children, auxiliary) = match ty { + Type::Void => (0, 0, 0), + Type::Bool => (1, 0, 0), + Type::I1 => (2, 0, 0), + Type::U1 => (3, 0, 0), + Type::I8 => (4, 0, 0), + Type::I16 => (5, 0, 0), + Type::I32 => (6, 0, 0), + Type::I64 => (7, 0, 0), + Type::I128 => (8, 0, 0), + Type::U8 => (9, 0, 0), + Type::U16 => (10, 0, 0), + Type::U32 => (11, 0, 0), + Type::U64 => (12, 0, 0), + Type::U128 => (13, 0, 0), + Type::F16 => (14, 0, 0), + Type::F32 => (15, 0, 0), + Type::F64 => (16, 0, 0), + Type::Ptr(inner) => { + pending.push((inner, depth + 1)); + (17, 1, 0) + }, + Type::FnPtr(sig) => { + pending.extend(sig.params.iter().rev().map(|ty| (ty, depth + 1))); + pending.push((&sig.ret, depth + 1)); + ( + 18, + sig.params.len() + 1, + u64::from(sig.variadic) * 2 + + u64::from(sig.convention == crate::CallingConvention::SysV64), + ) + }, + Type::Array(inner, count) => { + pending.push((inner, depth + 1)); + (19, 1, *count) + }, + Type::Struct(fields) | Type::Tuple(fields) => { + pending.extend(fields.iter().rev().map(|ty| (ty, depth + 1))); + (if matches!(ty, Type::Struct(_)) { 20 } else { 21 }, fields.len(), 0) + }, + }; + nodes.push(Node { kind, depth, children: children as u64, auxiliary }); + } + Ok(nodes) + } + + pub(super) fn preflight(&self, ty: &Type) -> Result<(), BuilderError> { + self.preflight_value(ty, 0, 0) + } + + pub(super) fn preflight_value( + &self, + ty: &Type, + operands: usize, + targets: usize, + ) -> Result<(), BuilderError> { + self.body.type_room(ty, operands.saturating_add(targets))?; + let nodes = self.flatten(ty)?; + if nodes.len().saturating_add(2).saturating_add(operands).saturating_add(targets) + > self.limits.max_nodes.saturating_sub(self.used_nodes()) + { + return Err(self.limit(Resource::Nodes, self.limits.max_nodes)); + } + let mut result = ResultRecord::default(); + let status = unsafe { + whale_ir_builder_type( + nodes.as_ptr(), + nodes.len() as u64, + self.limits.max_type_depth as u64, + self.limits.max_nodes.saturating_sub(self.used_nodes()) as u64, + self.limits.max_analysis_work.saturating_sub(self.state.work as usize) as u64, + &mut result, + ) + }; + if status != 0 || result.status != 0 { + return Err(self.error(status, result.detail)); + } + // Allocation/copy and identity publication have their own reserved work. + if nodes + .len() + .saturating_mul(2) + .saturating_add(2) + .saturating_add(operands) + .saturating_add(targets) + > self.limits.max_analysis_work.saturating_sub(self.state.work as usize) + { + return Err(self.limit(Resource::AnalysisWork, self.limits.max_analysis_work)); + } + Ok(()) + } + + pub(super) fn value(&mut self, ty: &Type) -> Result { + let nodes = self.flatten(ty)?; + let result = self.allocate(0, &nodes)?; + Ok(ValueId(result as u32)) + } + + pub(super) fn block(&mut self) -> Result { + let id = BlockId(self.allocate(1, &[])? as u32); + self.body.block(id); + Ok(id) + } + + fn allocate(&mut self, kind: u64, nodes: &[Node]) -> Result { + let before = self.state; + if before.type_count != self.types.len() as u64 + || before.next_value != self.values.len() as u64 + || before.next_block != self.blocks.len() as u64 + { + return Err(BuilderError::InvalidType); + } + let mut result = ResultRecord::default(); + let status = unsafe { + whale_ir_builder_allocate( + &mut self.state, + kind, + nodes.as_ptr(), + nodes.len() as u64, + self.limits.max_type_depth as u64, + self.limits.max_nodes as u64, + self.limits.max_analysis_work as u64, + 0, + std::ptr::null_mut(), + 0, + std::ptr::null_mut(), + 0, + std::ptr::null_mut(), + 0, + &mut result, + ) + }; + if status != result.status as i32 || self.state != before { + self.state = before; + return Err(BuilderError::InvalidType); + } + if status != 0 { + return Err(self.error(status, result.detail)); + } + let value = if kind == 0 { before.next_value } else { before.next_block }; + let work = result.work; + if result.value != value + || work > (self.limits.max_analysis_work as u64).saturating_sub(before.work) + { + return Err(BuilderError::InvalidType); + } + let mut expected = before; + if kind == 0 { + expected.type_count = expected + .type_count + .checked_add(nodes.len() as u64) + .ok_or(BuilderError::InvalidType)?; + expected.next_value = + expected.next_value.checked_add(1).ok_or(BuilderError::IdentityOverflow)?; + self.types + .try_reserve(nodes.len()) + .map_err(|_| self.limit(Resource::Nodes, self.limits.max_nodes))?; + self.values + .try_reserve(1) + .map_err(|_| self.limit(Resource::Nodes, self.limits.max_nodes))?; + self.types.resize(expected.type_count as usize, Node::default()); + self.values.resize(expected.next_value as usize, Value::default()); + } else { + expected.next_block = + expected.next_block.checked_add(1).ok_or(BuilderError::IdentityOverflow)?; + self.blocks + .try_reserve(1) + .map_err(|_| self.limit(Resource::Nodes, self.limits.max_nodes))?; + self.blocks.resize(expected.next_block as usize, Block::default()); + } + expected.work = expected.work.checked_add(work).ok_or(BuilderError::InvalidType)?; + let status = unsafe { + whale_ir_builder_allocate( + &mut self.state, + kind, + nodes.as_ptr(), + nodes.len() as u64, + self.limits.max_type_depth as u64, + self.limits.max_nodes as u64, + self.limits.max_analysis_work as u64, + 1, + self.types.as_mut_ptr(), + self.types.len() as u64, + self.values.as_mut_ptr(), + self.values.len() as u64, + self.blocks.as_mut_ptr(), + self.blocks.len() as u64, + &mut result, + ) + }; + if status != 0 + || result.status != 0 + || self.state != expected + || result.value != value + || result.work != work + { + self.types.truncate(before.type_count as usize); + self.values.truncate(before.next_value as usize); + self.blocks.truncate(before.next_block as usize); + self.state = before; + return Err(BuilderError::InvalidType); + } + Ok(value) + } + + pub(super) fn next_value(&self) -> u32 { + self.state.next_value as u32 + } + + pub(super) fn next_block(&self) -> u32 { + self.state.next_block as u32 + } + + #[allow(clippy::too_many_arguments)] + pub(super) fn order( + &self, + first_block: u32, + first_value: u32, + block: BlockId, + op: u64, + operands: &[u64], + targets: &[u64], + check_only: bool, + ) -> Result<(), BuilderError> { + assert!(check_only); + let mut result = ResultRecord::default(); + // The checked query mode never writes state or block storage. + let status = unsafe { + whale_ir_builder_order( + (&self.state as *const State).cast_mut(), + self.limits.max_nodes as u64, + self.blocks.as_ptr().cast_mut(), + self.blocks.len() as u64, + first_block.into(), + first_value.into(), + self.state.next_value, + block.0.into(), + op, + operands.as_ptr(), + operands.len() as u64, + targets.as_ptr(), + targets.len() as u64, + 1, + self.limits.max_analysis_work as u64, + &mut result, + ) + }; + if status != 0 || result.status != 0 { + return Err(self.error(status, result.detail)); + } + Ok(()) + } + + #[allow(clippy::too_many_arguments)] + pub(super) fn mark( + &mut self, + first_block: u32, + first_value: u32, + block: BlockId, + op: u64, + operands: &[u64], + targets: &[u64], + ) -> Result<(), BuilderError> { + let mut result = ResultRecord::default(); + let value_end = self.state.next_value; + let status = unsafe { + whale_ir_builder_order( + &mut self.state, + self.limits.max_nodes as u64, + self.blocks.as_mut_ptr(), + self.blocks.len() as u64, + first_block.into(), + first_value.into(), + value_end, + block.0.into(), + op, + operands.as_ptr(), + operands.len() as u64, + targets.as_ptr(), + targets.len() as u64, + 0, + self.limits.max_analysis_work as u64, + &mut result, + ) + }; + if status != 0 || result.status != 0 { + return Err(self.error(status, result.detail)); + } + Ok(()) + } +} + +impl Builder { + pub(super) fn preflight_instruction( + &self, + operands: usize, + targets: usize, + ) -> Result<(), BuilderError> { + let cost = operands.saturating_add(targets).saturating_add(1); + self.body.room(cost.saturating_add(64), 0)?; + if cost > self.limits.max_nodes.saturating_sub(self.used_nodes()) { + return Err(self.limit(Resource::Nodes, self.limits.max_nodes)); + } + if cost > self.limits.max_analysis_work.saturating_sub(self.state.work as usize) { + return Err(self.limit(Resource::AnalysisWork, self.limits.max_analysis_work)); + } + Ok(()) + } + + pub(super) fn instruction( + &mut self, + first_block: u32, + first_value: u32, + block: BlockId, + instruction: &crate::Instruction, + check_only: bool, + ) -> Result<(), BuilderError> { + use crate::{Callee, Instruction as I}; + // Bound variable-length borrowed transports before allocating any list. + match instruction { + I::Phi { incomings, .. } => { + self.preflight_instruction(incomings.len(), incomings.len())? + }, + I::Gep { indices, .. } => { + self.preflight_instruction(indices.len().saturating_add(1), 0)? + }, + I::Call { args, callee, .. } => self.preflight_instruction( + args.len().saturating_add(usize::from(matches!(callee, Callee::Indirect(_)))), + 0, + )?, + _ => {}, + } + let mut targets = Vec::new(); + let (op, values): (u64, Vec) = match instruction { + I::GlobalAddr { .. } => (0, vec![]), + I::LifetimeEnd { ptr } => (1, vec![*ptr]), + I::PtrDiff { lhs, rhs, .. } => (2, vec![*lhs, *rhs]), + I::ConstDecl { .. } => (3, vec![]), + I::Const { .. } => (4, vec![]), + I::Undef { .. } => (5, vec![]), + I::Mov { src, .. } => (6, vec![*src]), + I::Bin { lhs, rhs, .. } => (7, vec![*lhs, *rhs]), + I::Neg { src, .. } => (8, vec![*src]), + I::Not { src, .. } => (9, vec![*src]), + I::Cmp { lhs, rhs, .. } => (10, vec![*lhs, *rhs]), + I::ICmp { lhs, rhs, .. } => (11, vec![*lhs, *rhs]), + I::FCmp { lhs, rhs, .. } => (12, vec![*lhs, *rhs]), + I::Select { cond, on_true, on_false, .. } => (13, vec![*cond, *on_true, *on_false]), + I::Cast { src, .. } => (14, vec![*src]), + I::Phi { incomings, .. } => { + targets.extend(incomings.iter().map(|(_, block)| u64::from(block.0))); + (15, incomings.iter().map(|(value, _)| *value).collect()) + }, + I::Extract { tuple, .. } => (16, vec![*tuple]), + I::Checked { lhs, rhs, .. } => (17, vec![*lhs, *rhs]), + I::Alloca { .. } => (18, vec![]), + I::VolatileLoad { ptr, .. } => (19, vec![*ptr]), + I::VolatileStore { value, ptr, .. } => (20, vec![*value, *ptr]), + I::Load { ptr, .. } => (21, vec![*ptr]), + I::Uninit { ptr, .. } => (22, vec![*ptr]), + I::Store { value, ptr, .. } => (23, vec![*value, *ptr]), + I::Gep { base_ptr, indices, .. } => { + let mut values = vec![*base_ptr]; + values.extend(indices); + (24, values) + }, + I::Memcpy { dst, src, n, .. } => (25, vec![*dst, *src, *n]), + I::Memset { dst, val, n, .. } => (26, vec![*dst, *val, *n]), + I::NullFunction { .. } => (27, vec![]), + I::FunctionAddr { .. } => (28, vec![]), + I::Call { callee, args, .. } => { + let mut values = Vec::new(); + if let Callee::Indirect(value) = callee { + values.push(*value); + } + values.extend(args); + (29, values) + }, + I::TrapIf { cond, .. } => (30, vec![*cond]), + }; + let values: Vec = values.into_iter().map(|id| id.0.into()).collect(); + if check_only { + self.body.instruction(block, instruction, false, true)?; + self.order(first_block, first_value, block, op, &values, &targets, true) + } else { + self.order(first_block, first_value, block, op, &values, &targets, true)?; + self.body.instruction(block, instruction, false, false)?; + self.mark(first_block, first_value, block, op, &values, &targets) + } + } + + pub(super) fn terminator( + &mut self, + first_block: u32, + first_value: u32, + block: BlockId, + term: &crate::Terminator, + check_only: bool, + ) -> Result<(), BuilderError> { + use crate::Terminator as T; + if let T::Switch { cases, .. } = term { + self.preflight_instruction(1, cases.len().saturating_add(1))?; + } + let (op, values, targets): (u64, Vec, Vec) = match term { + T::Br { target } => (31, vec![], vec![target.0.into()]), + T::CBr { cond, then_bb, else_bb } => { + (32, vec![cond.0.into()], vec![then_bb.0.into(), else_bb.0.into()]) + }, + T::Switch { value, default_bb, cases, .. } => { + let mut targets = vec![default_bb.0.into()]; + targets.extend(cases.iter().map(|(_, block)| u64::from(block.0))); + (32, vec![value.0.into()], targets) + }, + T::Ret { value, .. } => (33, value.iter().map(|id| u64::from(id.0)).collect(), vec![]), + T::Trap { .. } => (33, vec![], vec![]), + }; + if check_only { + self.body.terminator(block, term, true)?; + self.order(first_block, first_value, block, op, &values, &targets, true) + } else { + self.order(first_block, first_value, block, op, &values, &targets, true)?; + self.body.terminator(block, term, false)?; + self.mark(first_block, first_value, block, op, &values, &targets) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn snapshot(builder: &Builder) -> (State, Vec, Vec, Vec) { + (builder.state, builder.types.clone(), builder.values.clone(), builder.blocks.clone()) + } + + #[test] + fn exact_inventory_preserves_signed_and_aggregate_identity() { + let mut builder = Builder::new(IrLimits::default()); + let signature = crate::FunctionSignature { + ret: Type::I32, + params: vec![Type::U32, Type::ptr_to(Type::I32)], + convention: crate::CallingConvention::SysV64, + variadic: true, + }; + let types = [ + Type::Void, + Type::Bool, + Type::I1, + Type::U1, + Type::I8, + Type::I16, + Type::I32, + Type::I64, + Type::I128, + Type::U8, + Type::U16, + Type::U32, + Type::U64, + Type::U128, + Type::F16, + Type::F32, + Type::F64, + Type::ptr_to(Type::I32), + Type::FnPtr(Box::new(signature)), + Type::Array(Box::new(Type::I8), 23), + Type::Struct(vec![Type::I32, Type::U32]), + Type::Tuple(vec![Type::Bool, Type::I64]), + ]; + for (index, ty) in types.iter().enumerate() { + let id = builder.value(ty).unwrap(); + assert_eq!(id.0 as usize, index); + } + let kinds: Vec<_> = builder + .values + .iter() + .map(|value| builder.types[value.first_type as usize].kind) + .collect(); + assert_eq!(kinds, (0..=21).collect::>()); + let function = builder.values[18]; + let node = builder.types[function.first_type as usize]; + assert_eq!((node.kind, node.children, node.auxiliary), (18, 3, 3)); + assert_eq!(builder.types[function.first_type as usize + 1].kind, 6); + } + + #[test] + fn budgets_are_transactional_and_include_copied_nodes_and_operations() { + let mut builder = + Builder::new(IrLimits { max_nodes: 4, max_analysis_work: 5, ..IrLimits::default() }); + let block = builder.block().unwrap(); + builder.preflight_value(&Type::I32, 0, 0).unwrap(); + let value = builder.value(&Type::I32).unwrap(); + builder.mark(0, 0, block, 4, &[], &[]).unwrap(); + assert_eq!(value, ValueId(0)); + assert_eq!(builder.used_nodes(), 4); + assert_eq!(builder.state.work, 5); + let before = snapshot(&builder); + assert!(matches!(builder.value(&Type::I32), Err(BuilderError::ResourceLimit(_)))); + assert!(matches!(builder.block(), Err(BuilderError::ResourceLimit(_)))); + assert!(matches!( + builder.mark(0, 0, block, 4, &[], &[]), + Err(BuilderError::ResourceLimit(_)) + )); + builder.order(0, 0, block, 35, &[], &[], true).unwrap(); + assert_eq!(snapshot(&builder), before); + } + + #[test] + fn rejected_types_and_ordering_never_consume_an_identity_or_mutate_records() { + let mut builder = Builder::new(IrLimits { max_type_depth: 2, ..IrLimits::default() }); + let block = builder.block().unwrap(); + let value = builder.value(&Type::I32).unwrap(); + let before = snapshot(&builder); + let deep = Type::ptr_to(Type::ptr_to(Type::ptr_to(Type::I32))); + assert!(matches!(builder.value(&deep), Err(BuilderError::ResourceLimit(_)))); + assert_eq!( + builder.order(0, 0, block, 7, &[value.0.into(), 99], &[], true), + Err(BuilderError::UnknownValue(ValueId(99))) + ); + assert_eq!( + builder.order(0, 0, block, 31, &[], &[99], true), + Err(BuilderError::UnknownBlock(BlockId(99))) + ); + assert_eq!(snapshot(&builder), before); + builder.mark(0, 0, block, 15, &[value.0.into()], &[block.0.into()]).unwrap(); + builder.mark(0, 0, block, 4, &[], &[]).unwrap(); + let before = snapshot(&builder); + assert_eq!( + builder.mark(0, 0, block, 15, &[value.0.into()], &[block.0.into()]), + Err(BuilderError::PhiAfterInstruction(block)) + ); + assert_eq!(snapshot(&builder), before); + builder.mark(0, 0, block, 33, &[], &[]).unwrap(); + let before = snapshot(&builder); + assert_eq!( + builder.order(0, 0, block, 35, &[], &[], true), + Err(BuilderError::TerminatedBlock(block)) + ); + assert_eq!(snapshot(&builder), before); + } + + #[test] + fn identities_from_previous_functions_are_rejected() { + let mut builder = Builder::new(IrLimits::default()); + let old_block = builder.block().unwrap(); + let old_value = builder.value(&Type::I32).unwrap(); + let first_block = builder.next_block(); + let first_value = builder.next_value(); + let block = builder.block().unwrap(); + let value = builder.value(&Type::U32).unwrap(); + assert_eq!( + builder.order(first_block, first_value, old_block, 34, &[], &[], true), + Err(BuilderError::UnknownBlock(old_block)) + ); + assert_eq!( + builder.order( + first_block, + first_value, + block, + 7, + &[value.0.into(), old_value.0.into()], + &[], + true + ), + Err(BuilderError::UnknownValue(old_value)) + ); + } +} diff --git a/ir/src/diagnostic.rs b/ir/src/diagnostic.rs index 6fb1186..99cc4b9 100644 --- a/ir/src/diagnostic.rs +++ b/ir/src/diagnostic.rs @@ -180,6 +180,7 @@ impl ToDiagnostic for crate::lower_ast::LowerError { Self::InvalidLiteral { .. } => "ir.lower.invalid-literal", Self::AssignToConst(..) => "ir.lower.assign-to-const", Self::NonConstExpr => "ir.lower.non-const-expr", + Self::Backend(..) => "ir.lower.backend", }; let mut d = Diagnostic::new("ir", "lower", code, self.to_string()); if let Some(a) = self.annotation() { @@ -209,6 +210,12 @@ impl ToDiagnostic for crate::ParseError { Diagnostic::new("ir", "parse", "ir.parse.resource-limit", error.to_string()) }, crate::ParseErrorKind::Verification(error) => error.diagnostic(), + crate::ParseErrorKind::Backend(component) => Diagnostic::new( + "ir", + "parse", + "ir.parse.backend", + format!("IR Wave backend error: {component}"), + ), }; d.contexts.push(Context::Source(SourceLocation { source: "".into(), diff --git a/ir/src/function.rs b/ir/src/function.rs index 10543f4..8dd8c3b 100644 --- a/ir/src/function.rs +++ b/ir/src/function.rs @@ -162,6 +162,7 @@ pub fn validate_signature_with_limits( Ok(()) } +#[cfg(any(not(whale_wave_ir), test))] pub(crate) fn validate_decl_with_limits( decl: &FunctionDecl, limits: crate::IrLimits, diff --git a/ir/src/layout.rs b/ir/src/layout.rs index 2c3f4bf..4c910a7 100644 --- a/ir/src/layout.rs +++ b/ir/src/layout.rs @@ -61,9 +61,13 @@ pub fn layout_for_target( max_depth: usize, ) -> Result { target.validate().map_err(|_| LayoutError::InvalidTarget)?; + #[cfg(whale_wave_ir)] + return crate::wave_layout::layout(ty, &target.storage, max_depth).map(|(layout, _)| layout); + #[cfg(not(whale_wave_ir))] layout_storage(ty, &target.storage, max_depth.min(crate::MAX_IR_NESTING)) } +#[cfg(any(not(whale_wave_ir), test))] fn layout_storage( ty: &Type, storage: &target_spec::StorageLayout, @@ -114,6 +118,7 @@ fn layout_storage( Ok(result) } +#[cfg(any(not(whale_wave_ir), test))] fn align_up(size: u64, align: u32) -> Result { let mask = u64::from(align) - 1; let padding = size.wrapping_neg() & mask; @@ -130,13 +135,23 @@ pub fn allocation_align_for_target( ty: &Type, target: &target_spec::TargetSpec, ) -> Result { - let layout = layout_for_target(ty, target, 128)?; - Ok(match target.storage.large_array { - Some((threshold, align)) if matches!(ty, Type::Array(..)) && layout.size >= threshold => { - layout.align.max(align) - }, - _ => layout.align, - }) + #[cfg(whale_wave_ir)] + { + target.validate().map_err(|_| LayoutError::InvalidTarget)?; + crate::wave_layout::layout(ty, &target.storage, 128).map(|(_, align)| align) + } + #[cfg(not(whale_wave_ir))] + { + let layout = layout_for_target(ty, target, 128)?; + Ok(match target.storage.large_array { + Some((threshold, align)) + if matches!(ty, Type::Array(..)) && layout.size >= threshold => + { + layout.align.max(align) + }, + _ => layout.align, + }) + } } /// Scale for the first native GEP index; a zero-sized pointee cannot be stepped. @@ -148,3 +163,55 @@ pub fn pointer_stride(pointee: &Type, target: Target) -> Result u64 { + *state ^= *state << 13; + *state ^= *state >> 7; + *state ^= *state << 17; + *state + } + + fn ty(state: &mut u64, depth: u8) -> Type { + let choice = if depth == 0 { next(state) % 7 } else { next(state) % 12 }; + match choice { + 0 => Type::Void, + 1 => Type::U8, + 2 => Type::I16, + 3 => Type::F32, + 4 => Type::U64, + 5 => Type::I128, + 6 => Type::Ptr(Box::new(Type::Void)), + 7 => Type::Array(Box::new(ty(state, depth - 1)), next(state) % 8), + 8 => Type::Array(Box::new(ty(state, depth - 1)), u64::MAX), + 9 | 10 => { + let count = next(state) % 4; + let fields = (0..count).map(|_| ty(state, depth - 1)).collect(); + Type::Struct(fields) + }, + _ => Type::Tuple(vec![ty(state, depth - 1), ty(state, depth - 1)]), + } + } + + #[test] + fn wave_layout_agrees_with_reference_on_nested_types_and_limits() { + let target = Target::X86_64WhaleLinux.specification(); + let mut state = 0x149_350_256_u64; + for _ in 0..4000 { + let ty = ty(&mut state, 5); + let depth = (next(&mut state) % 8) as usize; + let reference = layout_storage(&ty, &target.storage, depth); + let wave = layout_for_target(&ty, &target, depth); + assert_eq!(wave, reference, "type {ty:?}, depth {depth}"); + } + let mut deep = Type::U8; + for _ in 0..20_000 { + deep = Type::Array(Box::new(deep), 1); + } + let first_error = Box::leak(Box::new(Type::Struct(vec![Type::Void, deep]))); + assert_eq!(layout_for_target(first_error, &target, 256), Err(LayoutError::Void)); + } +} diff --git a/ir/src/lib.rs b/ir/src/lib.rs index 17149c5..d382d26 100644 --- a/ir/src/lib.rs +++ b/ir/src/lib.rs @@ -24,6 +24,9 @@ mod interpreter; pub mod layout; +#[cfg(whale_wave_ir)] +mod wave_layout; + pub mod limits; pub mod module; @@ -32,6 +35,9 @@ pub mod printer; pub mod source; +#[cfg(whale_wave_ir)] +mod source_wave; + pub mod types; pub mod value; @@ -64,6 +70,9 @@ pub const IR_FORMAT_VERSION: u32 = 8; pub const SEMANTICS_VERSION: u32 = 1; +/// True when this IR crate is linked to the pinned Wave source module. +pub const IR_WAVE_ENABLED: bool = cfg!(whale_wave_ir); + pub use instr::*; pub use interpreter::*; diff --git a/ir/src/lower_ast/error.rs b/ir/src/lower_ast/error.rs index fabb823..ce4b343 100644 --- a/ir/src/lower_ast/error.rs +++ b/ir/src/lower_ast/error.rs @@ -8,6 +8,7 @@ use diagnostic::EscapedName; pub enum LowerError { Located { annotation: crate::SourceAnnotation, error: Box }, ResourceLimit(super::AstLimitError), + Backend(&'static str), Call(crate::CallError), VoidCallUsedAsValue, NumericLiteral(String), diff --git a/ir/src/lower_ast/limits.rs b/ir/src/lower_ast/limits.rs index a2dfb4c..9b00587 100644 --- a/ir/src/lower_ast/limits.rs +++ b/ir/src/lower_ast/limits.rs @@ -40,6 +40,7 @@ pub enum AstLimitError { Nodes, Strings, Output, + Backend, } impl std::fmt::Display for AstLimitError { @@ -52,12 +53,14 @@ impl std::fmt::Display for AstLimitError { Self::Nodes => "AST node limit exceeded", Self::Strings => "AST string byte limit exceeded", Self::Output => "AST JSON exceeds output byte limit", + Self::Backend => "invalid Wave AST inspection result", }) } } impl std::error::Error for AstLimitError {} +#[cfg(any(not(whale_wave_ir), test))] enum Node<'a> { Expr(&'a Expr), Stmt(&'a Stmt), @@ -65,6 +68,7 @@ enum Node<'a> { Signature(&'a SignatureRef), } +#[cfg(any(not(whale_wave_ir), test))] struct Inspect<'a> { limits: AstLimits, nodes: usize, @@ -75,6 +79,7 @@ struct Inspect<'a> { wire_numbers: bool, } +#[cfg(any(not(whale_wave_ir), test))] impl<'a> Inspect<'a> { fn source(&mut self, annotation: &crate::SourceAnnotation) -> Result<(), AstLimitError> { if !self.source_ids.insert(annotation.id) { @@ -146,9 +151,33 @@ pub(crate) fn inspect_program_wire(program: &Program, limits: AstLimits) -> Resu Ok(extended) } +/// Source identity admission work, shared with emitted source-map construction. +#[cfg(whale_wave_ir)] +pub(crate) fn inspect_program_source_work( + program: &Program, + limits: AstLimits, +) -> Result { + super::wave_limits::inspect_with_usage(program, limits).map(|(_, _, work)| work) +} + fn inspect_program_details( program: &Program, limits: AstLimits, +) -> Result<(u8, bool), AstLimitError> { + #[cfg(whale_wave_ir)] + { + super::wave_limits::inspect(program, limits) + } + #[cfg(not(whale_wave_ir))] + { + inspect_program_reference(program, limits) + } +} + +#[cfg(any(not(whale_wave_ir), test))] +fn inspect_program_reference( + program: &Program, + limits: AstLimits, ) -> Result<(u8, bool), AstLimitError> { let mut i = Inspect { limits, @@ -520,6 +549,143 @@ fn discard(root: Owned, pending: &mut Vec) { } } +#[cfg(any(not(whale_wave_ir), test))] fn valid_int_width(bits: u16) -> bool { matches!(bits, 1 | 8 | 16 | 32 | 64 | 128) } + +#[cfg(all(test, whale_wave_ir))] +mod wave_tests { + use super::*; + + fn program(expr: Expr) -> Program { + Program { + declarations: vec![], + globals: vec![], + functions: vec![Function { + convention: crate::CallingConvention::Whale, + linkage: crate::Linkage::Internal, + link_name: None, + name: "main".into(), + parameters: vec![], + return_type: TypeRef::Void, + body: vec![Stmt::ExprStmt(expr), Stmt::Return(None)], + }], + } + } + + fn compare(program: &Program) { + for limit in 0..48 { + for limits in [ + AstLimits { max_nodes: limit, ..Default::default() }, + AstLimits { max_string_bytes: limit, ..Default::default() }, + AstLimits { max_depth: limit, ..Default::default() }, + ] { + assert_eq!( + inspect_program_details(program, limits), + inspect_program_reference(program, limits), + "limits {limits:?}, program {program:?}" + ); + } + } + } + + #[test] + fn wave_inspection_preserves_counts_feature_gates_and_numeric_schema() { + for bits in [0, 1, 8, 16, 32, 64, 128, 256, u16::MAX] { + for value in [ + "", + "-", + "-0", + "+1", + "12", + "-12", + "000", + "0x1", + "١", + "340282366920938463463374607431768211456", + ] { + compare(&program(Expr::Lit(Lit::Int { bits, signed: true, value: value.into() }))); + } + for value in + ["", "0x0000", "0x80000000", "0X8000", "0x7ff8000000000000", "0xABCD", "0x12z4"] + { + compare(&program(Expr::Lit(Lit::Float { bits, value: value.into() }))); + } + } + let lit = || Expr::Lit(Lit::Bool(true)); + for op in [ + BinOpRef::Add, + BinOpRef::Sub, + BinOpRef::Mul, + BinOpRef::BitAnd, + BinOpRef::BitOr, + BinOpRef::BitXor, + BinOpRef::Div, + BinOpRef::Rem, + BinOpRef::ShiftLeft, + BinOpRef::ShiftRight, + BinOpRef::LogicalAnd, + BinOpRef::LogicalOr, + ] { + compare(&program(Expr::Binary { left: Box::new(lit()), op, right: Box::new(lit()) })); + } + compare(&program(Expr::Struct { + ty: TypeRef::Struct { + fields: vec![StructField { name: "field".into(), ty: TypeRef::Bool }], + }, + fields: vec![FieldInit { name: "field".into(), value: lit() }], + })); + for defect in 0..8 { + let mut annotation = crate::SourceAnnotation { + id: u64::MAX, + source: Some(crate::FrontendSource { + file: "경로/test.wave".into(), + line: 3, + column: 4, + end_line: 4, + end_column: 2, + }), + }; + match defect { + 1 => annotation.source.as_mut().unwrap().file.clear(), + 2 => annotation.source.as_mut().unwrap().file.push('\0'), + 3 => annotation.source.as_mut().unwrap().line = 0, + 4 => annotation.source.as_mut().unwrap().end_line = 2, + 5 => { + let s = annotation.source.as_mut().unwrap(); + s.end_line = 3; + s.end_column = 3; + }, + 6 => annotation.source = None, + _ => {}, + } + let expression = + Expr::Located { annotation: annotation.clone(), expression: Box::new(lit()) }; + let mut p = program(expression.clone()); + if defect == 7 { + p.functions[0].body.push(Stmt::ExprStmt(expression)); + } + compare(&p); + } + } + + #[test] + fn source_admission_has_a_separate_shared_work_ceiling() { + let p = program(Expr::Located { + annotation: crate::SourceAnnotation { id: 1, source: None }, + expression: Box::new(Expr::Lit(Lit::Bool(true))), + }); + assert_eq!( + inspect_program(&p, AstLimits { max_source_work: 0, ..Default::default() }), + Err(AstLimitError::SourceWork) + ); + assert_eq!( + inspect_program( + &program(Expr::Lit(Lit::Bool(true))), + AstLimits { max_source_work: 0, ..Default::default() } + ), + Ok(()) + ); + } +} diff --git a/ir/src/lower_ast/mod.rs b/ir/src/lower_ast/mod.rs index 542c936..4954e2c 100644 --- a/ir/src/lower_ast/mod.rs +++ b/ir/src/lower_ast/mod.rs @@ -9,18 +9,52 @@ pub mod interchange; pub mod frontend; +pub mod wave_hir; + mod binding; mod error; pub mod limits; +#[cfg(whale_wave_ir)] +mod wave_limits; + mod o0; +#[cfg(whale_wave_ir)] +mod wave_lower; + mod support; pub use error::LowerError; pub use limits::{AstLimitError, AstLimits, MAX_AST_DEPTH}; +#[cfg(not(whale_wave_ir))] pub use o0::{lower_o0, lower_o0_with_limits}; + +#[cfg(whale_wave_ir)] +pub fn lower_o0( + program: &frontend::Program, + target: &str, + datalayout: crate::DataLayout, +) -> Result { + lower_o0_with_limits(program, target, datalayout, AstLimits::default()) +} + +#[cfg(whale_wave_ir)] +pub fn lower_o0_with_limits( + program: &frontend::Program, + target: &str, + datalayout: crate::DataLayout, + limits: AstLimits, +) -> Result { + wave_lower::lower(program, target, datalayout, limits) +} + +// Explicit conformance oracle; production Wave lowering never falls back here. +#[doc(hidden)] +pub use o0::{ + lower_o0 as lower_o0_reference, lower_o0_with_limits as lower_o0_reference_with_limits, +}; diff --git a/ir/src/lower_ast/wave_hir.rs b/ir/src/lower_ast/wave_hir.rs new file mode 100644 index 0000000..420f29a --- /dev/null +++ b/ir/src/lower_ast/wave_hir.rs @@ -0,0 +1,635 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Adapter for the pinned Wave frontend's post-import, post-monomorphization +//! TypedProgram facts. The bounded scalar test surface uses resolved types and +//! ExpressionId values; it does not depend on Wave backend-owned structures. +use super::{frontend as f, AstLimits, LowerError}; + +pub const WAVE_HIR_REVISION: &str = "e0952ed65d07e14c6ed0aa64f3c9a5532dd7533b"; + +#[cfg_attr(feature = "socket", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "socket", serde(deny_unknown_fields))] +#[derive(Clone, Debug)] +pub struct Program { + pub wave_revision: String, + pub functions: Vec, +} + +#[cfg_attr(feature = "socket", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "socket", serde(deny_unknown_fields))] +#[derive(Clone, Debug)] +pub struct Function { + pub name: String, + pub parameters: Vec, + pub return_type: ResolvedType, + pub body: Vec, + pub is_async: bool, +} + +#[cfg_attr(feature = "socket", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "socket", serde(deny_unknown_fields))] +#[derive(Clone, Debug)] +pub struct Parameter { + pub name: String, + pub ty: ResolvedType, +} + +#[cfg_attr(feature = "socket", derive(serde::Serialize, serde::Deserialize))] +#[derive(Clone, Debug)] +pub enum ResolvedType { + Void, + Bool, + Integer { bits: u16, signed: bool }, + Unsupported(String), +} + +#[cfg_attr(feature = "socket", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "socket", serde(deny_unknown_fields))] +#[derive(Clone, Debug)] +pub struct Expression { + pub id: u64, + /// Use NumericExpressionInfo.result_type for contextual integer literals; + /// use HirExpressionType::Resolved for already-resolved named expressions. + pub resolved_type: ResolvedType, + pub kind: ExpressionKind, +} + +#[cfg_attr(feature = "socket", derive(serde::Serialize, serde::Deserialize))] +#[derive(Clone, Debug)] +pub enum ExpressionKind { + Integer(String), + Bool(bool), + Local(String), + Binary { left: Box, operator: Operator, right: Box }, + Unsupported(Unsupported), +} + +#[cfg_attr(feature = "socket", derive(serde::Serialize, serde::Deserialize))] +#[derive(Clone, Copy, Debug)] +#[repr(u64)] +pub enum Operator { + Add, + Subtract, + Multiply, + Divide, + Remainder, + BitwiseAnd, + BitwiseOr, + BitwiseXor, + ShiftLeft, + ShiftRight, + LogicalAnd, + LogicalOr, + Equal, + NotEqual, + Less, + LessEqual, + Greater, + GreaterEqual, +} + +#[cfg_attr(feature = "socket", derive(serde::Serialize, serde::Deserialize))] +#[derive(Clone, Copy, Debug)] +#[repr(u64)] +pub enum Unsupported { + Call = 1, + Aggregate = 2, + Async = 3, + InlineAssembly = 4, + Other = 5, +} + +#[cfg_attr(feature = "socket", derive(serde::Serialize, serde::Deserialize))] +#[derive(Clone, Debug)] +pub enum Statement { + Variable { name: String, ty: ResolvedType, init: Option }, + Assign { name: String, value: Expression }, + If { condition: Expression, body: Vec, else_body: Vec }, + While { condition: Expression, body: Vec }, + Return(Option), + Expression(Expression), + Unsupported(Unsupported), +} + +#[derive(Debug)] +pub enum AdapterError { + Revision, + Unavailable, + Resource, + InvalidTransport, + ResolvedType { node: usize }, + Unsupported { node: usize, category: u64 }, + DuplicateExpression { id: u64 }, + UnknownBinding { node: usize }, + NumericLiteral { node: usize }, + DuplicateName { node: usize }, +} + +impl std::fmt::Display for AdapterError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "Wave typed-HIR adapter: {self:?}") + } +} + +impl std::error::Error for AdapterError {} + +/// Validate the entire typed surface in Wave before publishing any frontend AST. +/// Unsupported calls, aggregate/async/asm nodes and inconsistent facts are errors. +pub fn adapt(program: &Program, limits: AstLimits) -> Result { + if program.wave_revision != WAVE_HIR_REVISION { + return Err(AdapterError::Revision); + } + #[cfg(whale_wave_ir)] + { + native::adapt(program, limits) + } + #[cfg(not(whale_wave_ir))] + { + let _ = limits; + Err(AdapterError::Unavailable) + } +} + +/// Direct checked path from resolved Wave facts into the frontend-independent IR. +pub fn lower( + program: &Program, + target: &str, + datalayout: crate::DataLayout, + limits: AstLimits, +) -> Result { + let program = adapt(program, limits).map_err(HirLowerError::Adapter)?; + super::lower_o0_with_limits(&program, target, datalayout, limits).map_err(HirLowerError::Lower) +} + +#[derive(Debug)] +pub enum HirLowerError { + Adapter(AdapterError), + Lower(LowerError), +} + +impl std::fmt::Display for HirLowerError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Adapter(error) => error.fmt(f), + Self::Lower(error) => error.fmt(f), + } + } +} + +impl std::error::Error for HirLowerError {} + +#[cfg(whale_wave_ir)] +mod native { + use super::*; + + use std::collections::HashMap; + + const NONE: u64 = u64::MAX; + + #[repr(C)] + #[derive(Clone, Copy, Default)] + struct Node([u64; 8]); + + #[repr(C)] + #[derive(Clone, Copy, Default)] + struct Output { + ty: u64, + operation: u64, + } + + #[repr(C)] + #[derive(Clone, Copy, Default)] + struct Pair([u64; 2]); + + #[repr(C)] + #[derive(Default)] + struct ResultRecord { + status: u64, + node: u64, + detail: u64, + work: u64, + } + + unsafe extern "C" { + fn whale_ir_adapt_wave_hir( + nodes: *const Node, + node_count: u64, + edges: *const u64, + edge_count: u64, + functions: u64, + function_count: u64, + output: *mut Output, + bindings: *mut Pair, + identities: *mut Pair, + identity_capacity: u64, + max_depth: u64, + max_work: u64, + result: *mut ResultRecord, + ) -> i32; + } + + macro_rules! node { + ($this:ident,$tag:expr $(,$field:expr)* $(,)?) => {{ + let fields = [$($field),*]; + $this.node($tag, &fields) + }}; + } + + struct Transport<'a> { + nodes: Vec, + edges: Vec, + names: HashMap<&'a str, u64>, + expressions: HashMap, + types: HashMap, + limits: AstLimits, + strings: usize, + depth: usize, + } + + impl<'a> Transport<'a> { + fn node(&mut self, tag: u64, fields: &[u64]) -> Result { + if self.nodes.len() >= self.limits.max_nodes { + return Err(AdapterError::Resource); + } + self.nodes.try_reserve(1).map_err(|_| AdapterError::Resource)?; + let mut node = Node::default(); + node.0[0] = tag; + node.0[1..1 + fields.len()].copy_from_slice(fields); + let index = self.nodes.len() as u64; + self.nodes.push(node); + Ok(index) + } + + fn string(&mut self, text: &str) -> Result<(), AdapterError> { + self.strings = self + .strings + .checked_add(text.len()) + .filter(|n| *n <= self.limits.max_string_bytes) + .ok_or(AdapterError::Resource)?; + Ok(()) + } + + fn name(&mut self, text: &'a str) -> Result { + self.string(text)?; + let next = self.names.len() as u64; + Ok(*self.names.entry(text).or_insert(next)) + } + + fn list( + &mut self, + values: &'a [T], + mut visit: impl FnMut(&mut Self, &'a T) -> Result, + ) -> Result<(u64, u64), AdapterError> { + if values.len() > self.limits.max_nodes.saturating_sub(self.nodes.len()) { + return Err(AdapterError::Resource); + } + let mut list = Vec::new(); + list.try_reserve(values.len()).map_err(|_| AdapterError::Resource)?; + for value in values { + list.push(visit(self, value)?); + } + if list.len() > self.limits.max_nodes.saturating_sub(self.edges.len()) { + return Err(AdapterError::Resource); + } + self.edges.try_reserve(list.len()).map_err(|_| AdapterError::Resource)?; + let first = self.edges.len() as u64; + self.edges.extend(list); + Ok((first, values.len() as u64)) + } + + fn enter(&mut self) -> Result<(), AdapterError> { + if self.depth >= self.limits.max_depth.min(super::super::MAX_AST_DEPTH) { + return Err(AdapterError::Resource); + } + self.depth += 1; + Ok(()) + } + + fn ty(&mut self, ty: &'a ResolvedType) -> Result { + let id = match ty { + ResolvedType::Void => node!(self, 2, 0)?, + ResolvedType::Bool => node!(self, 2, 1)?, + ResolvedType::Integer { bits, signed } => { + node!(self, 2, 2, u64::from(*bits), u64::from(*signed))? + }, + ResolvedType::Unsupported(name) => { + self.string(name)?; + node!(self, 2, 3)? + }, + }; + self.types.insert(ty as *const _ as usize, id as usize); + Ok(id) + } + + fn expression(&mut self, expression: &'a Expression) -> Result { + self.enter()?; + let ty = self.ty(&expression.resolved_type)?; + let id = match &expression.kind { + ExpressionKind::Integer(text) => { + self.string(text)?; + node!(self, 3, expression.id, ty, text.as_ptr() as u64, text.len() as u64)? + }, + ExpressionKind::Bool(value) => { + node!(self, 4, expression.id, ty, u64::from(*value))? + }, + ExpressionKind::Local(name) => node!(self, 5, expression.id, ty, self.name(name)?)?, + ExpressionKind::Binary { left, operator, right } => node!( + self, + 6, + expression.id, + ty, + *operator as u64, + self.expression(left)?, + self.expression(right)? + )?, + ExpressionKind::Unsupported(kind) => node!(self, 12, *kind as u64)?, + }; + self.expressions.insert(expression as *const _ as usize, id as usize); + self.depth -= 1; + Ok(id) + } + + fn statement(&mut self, statement: &'a Statement) -> Result { + self.enter()?; + let id = match statement { + Statement::Variable { name, ty, init } => node!( + self, + 7, + self.name(name)?, + self.ty(ty)?, + match init { + Some(expression) => self.expression(expression)?, + None => NONE, + } + )?, + Statement::Assign { name, value } => { + node!(self, 8, self.name(name)?, self.expression(value)?)? + }, + Statement::If { condition, body, else_body } => { + let condition = self.expression(condition)?; + let (first, count) = self.list(body, Self::statement)?; + let (other, other_count) = self.list(else_body, Self::statement)?; + node!(self, 9, condition, first, count, other, other_count)? + }, + Statement::While { condition, body } => { + let condition = self.expression(condition)?; + let (first, count) = self.list(body, Self::statement)?; + node!(self, 10, condition, first, count)? + }, + Statement::Return(value) => node!( + self, + 11, + match value { + Some(expression) => self.expression(expression)?, + None => NONE, + } + )?, + Statement::Expression(expression) => node!(self, 13, self.expression(expression)?)?, + Statement::Unsupported(kind) => node!(self, 12, *kind as u64)?, + }; + self.depth -= 1; + Ok(id) + } + + fn function(&mut self, function: &'a Function) -> Result { + let (params, count) = self.list(&function.parameters, |this, param| { + node!(this, 1, this.name(¶m.name)?, this.ty(¶m.ty)?) + })?; + let (body, body_count) = self.list(&function.body, Self::statement)?; + node!( + self, + 0, + self.name(&function.name)?, + params, + count, + self.ty(&function.return_type)?, + body, + body_count, + u64::from(function.is_async) + ) + } + + fn type_ref( + &self, + ty: &ResolvedType, + output: &[Output], + ) -> Result { + let index = *self + .types + .get(&(ty as *const _ as usize)) + .ok_or(AdapterError::InvalidTransport)?; + match output[index].ty { + 0 => Ok(f::TypeRef::Void), + 1 => Ok(f::TypeRef::Bool), + value @ 2..=13 => { + let (bits, signed) = match value { + 2 => (1, true), + 3 => (1, false), + 4 => (8, true), + 5 => (16, true), + 6 => (32, true), + 7 => (64, true), + 8 => (128, true), + 9 => (8, false), + 10 => (16, false), + 11 => (32, false), + 12 => (64, false), + 13 => (128, false), + _ => unreachable!(), + }; + Ok(f::TypeRef::Int { bits, signed }) + }, + _ => Err(AdapterError::InvalidTransport), + } + } + + fn materialize_expr( + &self, + expression: &Expression, + output: &[Output], + ) -> Result { + let index = *self + .expressions + .get(&(expression as *const _ as usize)) + .ok_or(AdapterError::InvalidTransport)?; + let mapped = match &expression.kind { + ExpressionKind::Integer(value) => { + let f::TypeRef::Int { bits, signed } = + self.type_ref(&expression.resolved_type, output)? + else { + return Err(AdapterError::InvalidTransport); + }; + f::Expr::Lit(f::Lit::Int { bits, signed, value: value.clone() }) + }, + ExpressionKind::Bool(value) => f::Expr::Lit(f::Lit::Bool(*value)), + ExpressionKind::Local(name) => f::Expr::Var(name.clone()), + ExpressionKind::Binary { left, right, .. } => { + let left = Box::new(self.materialize_expr(left, output)?); + let right = Box::new(self.materialize_expr(right, output)?); + let op = output[index].operation; + if op >= 32 { + let op = match op { + 32 => f::CmpOpRef::Eq, + 33 => f::CmpOpRef::Ne, + 34 => f::CmpOpRef::Lt, + 35 => f::CmpOpRef::Le, + 36 => f::CmpOpRef::Gt, + 37 => f::CmpOpRef::Ge, + _ => return Err(AdapterError::InvalidTransport), + }; + f::Expr::Cmp { left, op, right } + } else { + let op = match op { + 0 => f::BinOpRef::Add, + 1 => f::BinOpRef::Sub, + 2 => f::BinOpRef::Mul, + 3 => f::BinOpRef::BitAnd, + 4 => f::BinOpRef::BitOr, + 5 => f::BinOpRef::BitXor, + 6 => f::BinOpRef::Div, + 7 => f::BinOpRef::Rem, + 8 => f::BinOpRef::ShiftLeft, + 9 => f::BinOpRef::ShiftRight, + 10 => f::BinOpRef::LogicalAnd, + 11 => f::BinOpRef::LogicalOr, + _ => return Err(AdapterError::InvalidTransport), + }; + f::Expr::Binary { left, op, right } + } + }, + ExpressionKind::Unsupported(_) => return Err(AdapterError::InvalidTransport), + }; + Ok(f::Expr::Located { + annotation: crate::SourceAnnotation { id: expression.id, source: None }, + expression: Box::new(mapped), + }) + } + + fn materialize_statements( + &self, + statements: &[Statement], + output: &[Output], + ) -> Result, AdapterError> { + statements + .iter() + .map(|statement| { + Ok(match statement { + Statement::Variable { name, ty, init } => f::Stmt::VarDecl { + name: name.clone(), + ty: self.type_ref(ty, output)?, + init: init + .as_ref() + .map(|expression| self.materialize_expr(expression, output)) + .transpose()?, + }, + Statement::Assign { name, value } => f::Stmt::Assign { + name: name.clone(), + value: self.materialize_expr(value, output)?, + }, + Statement::If { condition, body, else_body } => f::Stmt::If { + cond: self.materialize_expr(condition, output)?, + then_body: self.materialize_statements(body, output)?, + else_body: self.materialize_statements(else_body, output)?, + }, + Statement::While { condition, body } => f::Stmt::While { + cond: self.materialize_expr(condition, output)?, + body: self.materialize_statements(body, output)?, + }, + Statement::Return(value) => f::Stmt::Return( + value + .as_ref() + .map(|expression| self.materialize_expr(expression, output)) + .transpose()?, + ), + Statement::Expression(expression) => { + f::Stmt::ExprStmt(self.materialize_expr(expression, output)?) + }, + Statement::Unsupported(_) => return Err(AdapterError::InvalidTransport), + }) + }) + .collect() + } + } + + pub(super) fn adapt(program: &Program, limits: AstLimits) -> Result { + let mut model = Transport { + nodes: Vec::new(), + edges: Vec::new(), + names: HashMap::new(), + expressions: HashMap::new(), + types: HashMap::new(), + limits, + strings: 0, + depth: 0, + }; + let (first, count) = model.list(&program.functions, Transport::function)?; + let capacity = model + .nodes + .len() + .checked_mul(2) + .and_then(usize::checked_next_power_of_two) + .ok_or(AdapterError::Resource)? + .max(1); + let mut output = vec![Output::default(); model.nodes.len()]; + let mut bindings = vec![Pair::default(); model.nodes.len()]; + let mut identities = vec![Pair::default(); capacity]; + let mut result = ResultRecord::default(); + let status = unsafe { + whale_ir_adapt_wave_hir( + model.nodes.as_ptr(), + model.nodes.len() as u64, + model.edges.as_ptr(), + model.edges.len() as u64, + first, + count, + output.as_mut_ptr(), + bindings.as_mut_ptr(), + identities.as_mut_ptr(), + capacity as u64, + limits.max_depth.min(super::super::MAX_AST_DEPTH) as u64, + limits.max_source_work as u64, + &mut result, + ) + }; + if status != 0 || result.status != 0 { + let node = result.node as usize; + return Err(match status { + 1 | 2 => AdapterError::Resource, + 4 => AdapterError::ResolvedType { node }, + 5 => AdapterError::Unsupported { node, category: result.detail }, + 6 => AdapterError::DuplicateExpression { id: result.detail }, + 7 => AdapterError::UnknownBinding { node }, + 8 => AdapterError::NumericLiteral { node }, + 9 => AdapterError::DuplicateName { node }, + _ => AdapterError::InvalidTransport, + }); + } + if result.work > limits.max_source_work as u64 { + return Err(AdapterError::InvalidTransport); + } + let functions = program + .functions + .iter() + .map(|function| { + Ok(f::Function { + convention: crate::CallingConvention::Whale, + linkage: crate::Linkage::Internal, + link_name: None, + name: function.name.clone(), + parameters: function + .parameters + .iter() + .map(|parameter| { + Ok(f::Parameter { + name: parameter.name.clone(), + ty: model.type_ref(¶meter.ty, &output)?, + }) + }) + .collect::>()?, + return_type: model.type_ref(&function.return_type, &output)?, + body: model.materialize_statements(&function.body, &output)?, + }) + }) + .collect::>()?; + Ok(f::Program { declarations: vec![], globals: vec![], functions }) + } +} diff --git a/ir/src/lower_ast/wave_limits.rs b/ir/src/lower_ast/wave_limits.rs new file mode 100644 index 0000000..925e437 --- /dev/null +++ b/ir/src/lower_ast/wave_limits.rs @@ -0,0 +1,426 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Bounded borrowed AST admission events. Wave owns feature/schema/source rules. +use super::{ + frontend::*, + limits::{AstLimitError, AstLimits}, +}; + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct State { + nodes: u64, + strings: u64, + features: u64, + numbers: u64, + sources: u64, + work: u64, +} + +#[repr(C)] +struct Event { + tag: u64, + a: u64, + b: u64, + c: u64, + d: u64, + e: u64, + f: u64, + bytes: *const u8, + length: u64, +} + +impl Default for Event { + fn default() -> Self { + Self { tag: 0, a: 0, b: 0, c: 0, d: 0, e: 0, f: 0, bytes: std::ptr::null(), length: 0 } + } +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct Slot { + id: u64, + occupied: u64, +} + +#[repr(C)] +#[derive(Default)] +struct RawResult { + status: u64, +} + +unsafe extern "C" { + fn whale_ir_ast_inspect_step( + state: *mut State, + event: *const Event, + max_depth: u64, + max_nodes: u64, + max_strings: u64, + max_source_work: u64, + slots: *mut Slot, + capacity: u64, + result: *mut RawResult, + ) -> i32; + + fn whale_ir_ast_inspect_rehash( + state: *mut State, + old: *const Slot, + old_capacity: u64, + slots: *mut Slot, + capacity: u64, + max_work: u64, + result: *mut RawResult, + ) -> i32; +} + +fn result(status: i32, record: &RawResult) -> Result<(), AstLimitError> { + if i32::try_from(record.status).ok() != Some(status) { + return Err(AstLimitError::Backend); + } + match status { + 0 => Ok(()), + 1 => Err(AstLimitError::Source), + 2 => Err(AstLimitError::Depth), + 3 => Err(AstLimitError::Nodes), + 4 => Err(AstLimitError::Strings), + 7 => Err(AstLimitError::SourceWork), + _ => Err(AstLimitError::Backend), + } +} + +enum Node<'a> { + Expr(&'a Expr), + Stmt(&'a Stmt), + Type(&'a TypeRef), + Signature(&'a SignatureRef), +} + +struct Inspect<'a> { + limits: AstLimits, + state: State, + slots: Vec, + pending: Vec<(Node<'a>, usize)>, +} + +impl<'a> Inspect<'a> { + fn new(limits: AstLimits) -> Self { + Self { + limits, + state: State { numbers: 1, ..State::default() }, + slots: Vec::new(), + pending: Vec::new(), + } + } + + fn step(&mut self, event: Event) -> Result<(), AstLimitError> { + let mut record = RawResult::default(); + let before = self.state; + let status = unsafe { + whale_ir_ast_inspect_step( + &mut self.state, + &event, + self.limits.max_depth as u64, + self.limits.max_nodes as u64, + self.limits.max_string_bytes as u64, + self.limits.max_source_work as u64, + self.slots.as_mut_ptr(), + self.slots.len() as u64, + &mut record, + ) + }; + result(status, &record)?; + if self.state.nodes < before.nodes + || self.state.nodes > self.limits.max_nodes as u64 + || self.state.strings < before.strings + || self.state.strings > self.limits.max_string_bytes as u64 + || self.state.features > 7 + || self.state.numbers > 1 + || self.state.sources < before.sources + || self.state.sources > self.state.nodes + || self.state.work < before.work + || self.state.work > self.limits.max_source_work as u64 + { + return Err(AstLimitError::Backend); + } + Ok(()) + } + + fn count(&mut self) -> Result<(), AstLimitError> { + self.step(Event::default()) + } + + fn push(&mut self, node: Node<'a>, depth: usize) -> Result<(), AstLimitError> { + self.step(Event { tag: 1, a: depth as u64, ..Event::default() })?; + self.pending.try_reserve(1).map_err(|_| AstLimitError::Nodes)?; + self.pending.push((node, depth)); + Ok(()) + } + + fn string(&mut self, value: &str) -> Result<(), AstLimitError> { + self.step(Event { + tag: 2, + bytes: value.as_ptr(), + length: value.len() as u64, + ..Event::default() + }) + } + + fn form(&mut self, form: u64, op: u64) -> Result<(), AstLimitError> { + self.step(Event { tag: 3, a: form, b: op, ..Event::default() }) + } + + fn number(&mut self, tag: u64, bits: u16, value: &str) -> Result<(), AstLimitError> { + self.step(Event { + tag, + a: bits.into(), + bytes: value.as_ptr(), + length: value.len() as u64, + ..Event::default() + }) + } + + fn source(&mut self, source: &crate::SourceAnnotation) -> Result<(), AstLimitError> { + let needed = (self.state.sources as usize) + .checked_add(1) + .and_then(|n| n.checked_mul(2)) + .and_then(usize::checked_next_power_of_two) + .ok_or(AstLimitError::Nodes)?; + if needed > self.slots.len() { + if needed > self.limits.max_source_work.saturating_sub(self.state.work as usize) { + return Err(AstLimitError::SourceWork); + } + let mut slots = Vec::new(); + slots.try_reserve_exact(needed).map_err(|_| AstLimitError::Nodes)?; + slots.resize(needed, Slot::default()); + let mut record = RawResult::default(); + let status = unsafe { + whale_ir_ast_inspect_rehash( + &mut self.state, + self.slots.as_ptr(), + self.slots.len() as u64, + slots.as_mut_ptr(), + slots.len() as u64, + self.limits.max_source_work as u64, + &mut record, + ) + }; + result(status, &record)?; + self.slots = slots; + } + let mut event = Event { tag: 8, a: source.id, ..Event::default() }; + if let Some(span) = &source.source { + event.b = 1; + event.c = span.line.into(); + event.d = span.column.into(); + event.e = span.end_line.into(); + event.f = span.end_column.into(); + event.bytes = span.file.as_ptr(); + event.length = span.file.len() as u64; + } + self.step(event) + } +} + +pub(super) fn inspect(program: &Program, limits: AstLimits) -> Result<(u8, bool), AstLimitError> { + inspect_with_usage(program, limits).map(|(features, numbers, _)| (features, numbers)) +} + +pub(super) fn inspect_with_usage( + program: &Program, + limits: AstLimits, +) -> Result<(u8, bool, usize), AstLimitError> { + let mut i = Inspect::new(limits); + i.count()?; // program + for d in &program.declarations { + i.count()?; + i.string(&d.name)?; + if let Some(s) = &d.link_name { + i.string(s)?; + } + i.push(Node::Signature(&d.signature), 1)?; + } + for g in &program.globals { + i.count()?; + i.string(&g.name)?; + i.push(Node::Type(&g.ty), 1)?; + i.push(Node::Expr(&g.init), 1)?; + } + for f in &program.functions { + i.count()?; + i.string(&f.name)?; + if let Some(s) = &f.link_name { + i.string(s)?; + } + i.push(Node::Type(&f.return_type), 1)?; + for p in &f.parameters { + i.count()?; + i.string(&p.name)?; + i.push(Node::Type(&p.ty), 1)?; + } + for s in &f.body { + i.push(Node::Stmt(s), 1)?; + } + } + while let Some((node, depth)) = i.pending.pop() { + let next = depth + 1; + match node { + Node::Signature(s) => { + i.push(Node::Type(&s.ret), next)?; + for t in &s.params { + i.push(Node::Type(t), next)?; + } + }, + Node::Type(t) => match t { + TypeRef::Int { bits, .. } => i.number(4, *bits, "")?, + TypeRef::Float { bits } => i.number(5, *bits, "")?, + TypeRef::Ptr(t) | TypeRef::Array { elem: t, .. } => i.push(Node::Type(t), next)?, + TypeRef::FnPtr(s) => i.push(Node::Signature(s), next)?, + TypeRef::Struct { fields } => { + i.form(2, 0)?; + for f in fields { + i.count()?; + i.string(&f.name)?; + i.push(Node::Type(&f.ty), next)?; + } + }, + TypeRef::Opaque(s) => i.string(s)?, + _ => {}, + }, + Node::Expr(e) => match e { + Expr::Struct { ty, fields } => { + i.form(2, 0)?; + i.push(Node::Type(ty), next)?; + for f in fields { + i.count()?; + i.string(&f.name)?; + i.push(Node::Expr(&f.value), next)?; + } + }, + Expr::Array { ty, elements } => { + i.form(2, 0)?; + i.push(Node::Type(ty), next)?; + for e in elements { + i.push(Node::Expr(e), next)?; + } + }, + Expr::Field { base, layout, name } => { + i.form(2, 0)?; + i.string(name)?; + i.push(Node::Expr(base), next)?; + i.push(Node::Type(layout), next)?; + }, + Expr::Index { base, index } | Expr::PointerOffset { base, index } => { + i.form(2, 0)?; + i.push(Node::Expr(base), next)?; + i.push(Node::Expr(index), next)?; + }, + Expr::VolatileLoad(value) | Expr::Deref(value) | Expr::AddressOf(value) => { + i.form(2, 0)?; + i.push(Node::Expr(value), next)?; + }, + Expr::Located { annotation, expression } => { + i.source(annotation)?; + i.push(Node::Expr(expression), next)?; + }, + Expr::Neg(value) => { + i.form(2, 0)?; + i.push(Node::Expr(value), next)?; + }, + Expr::Cast { value, ty, .. } => { + i.form(2, 0)?; + i.push(Node::Expr(value), next)?; + i.push(Node::Type(ty), next)?; + }, + Expr::BitNot(value) => { + i.form(4, 0)?; + i.push(Node::Expr(value), next)?; + }, + Expr::FunctionRef(s) | Expr::Var(s) => i.string(s)?, + Expr::NullFunction(s) => i.push(Node::Signature(s), next)?, + Expr::Call { callee, args } => { + match callee { + CalleeRef::Direct(s) => i.string(s)?, + CalleeRef::Indirect(e) => i.push(Node::Expr(e), next)?, + } + for e in args { + i.push(Node::Expr(e), next)?; + } + }, + Expr::Lit(Lit::Int { bits, value, .. }) => i.number(6, *bits, value)?, + Expr::Lit(Lit::Float { bits, value }) => i.number(7, *bits, value)?, + Expr::Lit(Lit::Bool(_)) => {}, + Expr::Binary { left, op, right } => { + i.form( + 5, + match op { + BinOpRef::Add => 0, + BinOpRef::Sub => 1, + BinOpRef::Mul => 2, + BinOpRef::BitAnd => 3, + BinOpRef::BitOr => 4, + BinOpRef::BitXor => 5, + BinOpRef::Div => 6, + BinOpRef::Rem => 7, + BinOpRef::ShiftLeft => 8, + BinOpRef::ShiftRight => 9, + BinOpRef::LogicalAnd => 10, + BinOpRef::LogicalOr => 11, + }, + )?; + i.push(Node::Expr(left), next)?; + i.push(Node::Expr(right), next)?; + }, + Expr::Cmp { left, right, .. } => { + i.push(Node::Expr(left), next)?; + i.push(Node::Expr(right), next)?; + }, + }, + Node::Stmt(s) => match s { + Stmt::Located { annotation, statement } => { + i.source(annotation)?; + i.push(Node::Stmt(statement), next)?; + }, + Stmt::VolatileStore { pointer: place, value } | Stmt::Store { place, value } => { + i.form(2, 0)?; + i.push(Node::Expr(place), next)?; + i.push(Node::Expr(value), next)?; + }, + Stmt::Return(e) => { + if let Some(e) = e { + i.push(Node::Expr(e), next)?; + } + }, + Stmt::ConstDecl { name, ty, init } => { + i.string(name)?; + i.push(Node::Type(ty), next)?; + i.push(Node::Expr(init), next)?; + }, + Stmt::VarDecl { name, ty, init } => { + i.string(name)?; + i.push(Node::Type(ty), next)?; + if let Some(e) = init { + i.push(Node::Expr(e), next)?; + } + }, + Stmt::Assign { name, value } => { + i.string(name)?; + i.push(Node::Expr(value), next)?; + }, + Stmt::ExprStmt(e) => i.push(Node::Expr(e), next)?, + Stmt::If { cond, then_body, else_body } => { + i.push(Node::Expr(cond), next)?; + for s in then_body.iter().chain(else_body) { + i.push(Node::Stmt(s), next)?; + } + }, + Stmt::While { cond, body } => { + i.push(Node::Expr(cond), next)?; + for s in body { + i.push(Node::Stmt(s), next)?; + } + }, + Stmt::Break | Stmt::Continue => {}, + }, + } + } + Ok((i.state.features as u8, i.state.numbers != 0, i.state.work as usize)) +} diff --git a/ir/src/lower_ast/wave_lower.rs b/ir/src/lower_ast/wave_lower.rs new file mode 100644 index 0000000..db4de9f --- /dev/null +++ b/ir/src/lower_ast/wave_lower.rs @@ -0,0 +1,1931 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Borrowed frontend transport and checked materialization of Wave's O0 model. +//! AST/control-flow/type decisions belong to lower_*.wave. This bridge copies +//! shape-only input records and reads a completed, caller-owned typed result. +use super::{frontend as ast, AstLimitError, AstLimits, LowerError}; + +use crate::*; + +use std::collections::HashMap; + +const NONE: u64 = u64::MAX; + +fn backend() -> LowerError { + LowerError::Backend("AST lowering transport") +} + +fn expansion() -> LowerError { + LowerError::ResourceLimit(AstLimitError::Expansion) +} + +fn zeroed(count: usize) -> Result, LowerError> { + let mut out = Vec::new(); + out.try_reserve_exact(count).map_err(|_| expansion())?; + out.resize(count, T::default()); + Ok(out) +} + +fn filled(count: usize, value: u64) -> Result, LowerError> { + let mut out = zeroed(count)?; + out.fill(value); + Ok(out) +} + +// Raw pointers do not implement Default on the supported Rust 1.86 MSRV. +// Restrict transport defaults to the actual scalar and pointer field kinds. +trait TransportDefault { + fn transport_default() -> Self; +} + +impl TransportDefault for u64 { + fn transport_default() -> Self { + 0 + } +} + +impl TransportDefault for *const T { + fn transport_default() -> Self { + std::ptr::null() + } +} + +impl TransportDefault for *mut T { + fn transport_default() -> Self { + std::ptr::null_mut() + } +} + +macro_rules! record { ($name:ident { $($field:ident : $ty:ty),* $(,)? }) => { + #[repr(C)] #[derive(Clone, Copy)] struct $name { $($field: $ty),* } + impl Default for $name { + fn default() -> Self { Self { $($field: <$ty as TransportDefault>::transport_default()),* } } + } +} } + +record!(Node { + tag: u64, + a: u64, + b: u64, + c: u64, + d: u64, + e: u64, + f: u64, + g: u64, + h: u64, + i: u64, + j: u64, + k: u64 +}); +record!(RawString {data:*const u8,length:u64}); +record!(RawType { kind: u64, child: u64, first: u64, count: u64, auxiliary: u64 }); +record!(Binding { name: u64, ty: u64, value: u64, kind: u64, constant: u64 }); +record!(ResultRecord { + status: u64, + node: u64, + expected: u64, + actual: u64, + annotation: u64, + detail: u64, + work: u64 +}); +record!(Storage { + ptr_bits: u64, + pointer_align: u64, + scalar_align1: u64, + scalar_align2: u64, + scalar_align4: u64, + scalar_align8: u64, + scalar_align16: u64, + large_array_threshold: u64, + large_array_align: u64, + has_large_array: u64 +}); +record!(LayoutNode { kind: u64, child: u64, first: u64, count: u64 }); +record!(Layout { size: u64, align: u64, stride: u64, allocation_align: u64, depth: u64 }); +record!(Context { + nodes:*const Node,node_count:u64,edges:*const u64,edge_count:u64,names:*const RawString,name_count:u64, + types:*mut RawType,type_count:u64,type_capacity:u64,type_edges:*mut u64,type_edge_count:u64,type_edge_capacity:u64, + type_table:*mut u64,type_table_capacity:u64,type_map:*mut u64,temporary:*mut u64,temporary_count:u64,temporary_capacity:u64, + name_marks:*mut u64,marker:u64,storage:*const Storage,layout_nodes:*mut LayoutNode,layouts:*mut Layout,layout_offsets:*mut u64, + annotation:u64,max_depth:u64,max_work:u64,work:u64,result:*mut ResultRecord +}); +record!(RawInstruction { + tag: u64, + dst: u64, + ty: u64, + a: u64, + b: u64, + c: u64, + d: u64, + e: u64, + first: u64, + count: u64, + next: u64, + annotation: u64, + source: u64 +}); +record!(RawBlock { + id: u64, + function: u64, + name: u64, + first: u64, + last: u64, + allocation_last: u64, + instruction_count: u64, + term_kind: u64, + term_a: u64, + term_b: u64, + term_c: u64, + term_ty: u64, + term_annotation: u64, + term_source: u64 +}); +record!(RawConstant { + kind: u64, + operation: u64, + ty: u64, + low: u64, + high: u64, + left: u64, + right: u64, + reference: u64, + annotation: u64 +}); +record!(RawDeclaration { + name: u64, + signature: u64, + linkage: u64, + link_name: u64, + defined: u64, + source: u64 +}); +record!(RawFunction { + declaration: u64, + first_param: u64, + param_count: u64, + first_block: u64, + block_count: u64, + entry: u64, + source: u64 +}); +record!(RawGlobal { + name: u64, + ty: u64, + expression: u64, + align: u64, + annotation: u64, + source: u64 +}); +record!(FieldBinding { name: u64, ordinal: u64, previous: u64, used: u64 }); +record!(RawLoop { condition: u64, exit: u64 }); +record!(Annotation { + original: u64, + has_source: u64, + file: u64, + line: u64, + column: u64, + end_line: u64, + end_column: u64 +}); +record!(OriginalSlot { id: u64, occupied: u64 }); +record!(EvalRequest { expression: u64, kind: u64, identity: u64, annotation: u64 }); +record!(Driver { + core:*mut Context,mode:u64,expansion:u64,max_expansion:u64, + instructions:*mut RawInstruction,instruction_count:u64,instruction_capacity:u64, + output_edges:*mut u64,output_edge_count:u64,output_edge_capacity:u64, + blocks:*mut RawBlock,block_count:u64,block_capacity:u64,constants:*mut RawConstant, + declarations:*mut RawDeclaration,declaration_count:u64,declaration_capacity:u64, + functions:*mut RawFunction,function_count:u64,function_capacity:u64, + globals:*mut RawGlobal,global_count:u64,global_capacity:u64, + global_bindings:*mut Binding,global_binding_count:u64,bindings:*mut Binding,binding_count:u64,binding_capacity:u64, + loops:*mut RawLoop,loop_count:u64,loop_capacity:u64,annotations:*const Annotation,annotation_count:u64, + original_table:*mut OriginalSlot,original_capacity:u64, + source_order:*mut u64,source_count:u64,source_capacity:u64,source_marks:*mut u64, + type_sizes:*mut u64,value_types:*mut u64,value_capacity:u64,next_value:u64,declaration_map:*mut u64, + field_slots:*mut u64,field_bindings:*mut FieldBinding,field_binding_count:u64,field_binding_capacity:u64, + current_function:u64,current_block:u64,entry:u64,return_type:u64,local_slots:*mut u64,global_slots:*mut u64, + mapping_order:*mut u64,mapping_count:u64,mapping_capacity:u64,source_work:u64,max_source_work:u64,error_index:u64,requests:*mut EvalRequest,request_count:u64,request_capacity:u64 +}); +unsafe extern "C" { + fn whale_ir_lower_o0(driver: *mut Driver, root: u64) -> i32; +} + +struct Wire<'a> { + nodes: Vec, + edges: Vec, + names: Vec<&'a str>, + name_ids: HashMap<&'a str, u64>, + annotations: Vec<&'a SourceAnnotation>, + raw_annotations: Vec, + literals: HashMap, +} + +impl<'a> Wire<'a> { + fn new() -> Self { + Self { + nodes: Vec::new(), + edges: Vec::new(), + names: Vec::new(), + name_ids: HashMap::new(), + annotations: Vec::new(), + raw_annotations: Vec::new(), + literals: HashMap::new(), + } + } + + fn push(&mut self, node: Node) -> Result { + self.nodes.try_reserve(1).map_err(|_| expansion())?; + let id = self.nodes.len() as u64; + self.nodes.push(node); + Ok(id) + } + + fn list(&mut self, items: Vec) -> Result<(u64, u64), LowerError> { + self.edges.try_reserve(items.len()).map_err(|_| expansion())?; + let first = self.edges.len() as u64; + let count = items.len() as u64; + self.edges.extend(items); + Ok((first, count)) + } + + fn name(&mut self, name: &'a str) -> Result { + if let Some(id) = self.name_ids.get(name) { + return Ok(*id); + } + self.names.try_reserve(1).map_err(|_| expansion())?; + self.name_ids.try_reserve(1).map_err(|_| expansion())?; + let id = self.names.len() as u64; + self.names.push(name); + self.name_ids.insert(name, id); + Ok(id) + } + + fn annotation(&mut self, a: &'a SourceAnnotation) -> Result { + let mut raw = Annotation { original: a.id, ..Annotation::default() }; + if let Some(s) = &a.source { + raw.has_source = 1; + raw.file = self.name(&s.file)?; + raw.line = s.line.into(); + raw.column = s.column.into(); + raw.end_line = s.end_line.into(); + raw.end_column = s.end_column.into(); + } + self.annotations.try_reserve(1).map_err(|_| expansion())?; + self.raw_annotations.try_reserve(1).map_err(|_| expansion())?; + let id = self.annotations.len() as u64; + self.annotations.push(a); + self.raw_annotations.push(raw); + Ok(id) + } + + fn ty(&mut self, ty: &'a ast::TypeRef) -> Result { + use ast::TypeRef::*; + let mut n = Node::default(); + match ty { + Void => n.tag = 100, + Bool => n.tag = 101, + Int { bits, signed } => { + n.tag = 102; + n.a = (*bits).into(); + n.b = u64::from(*signed) + }, + Float { bits } => { + n.tag = 103; + n.a = (*bits).into() + }, + Ptr(child) => { + n.tag = 104; + n.a = self.ty(child)? + }, + FnPtr(sig) => { + n.tag = 105; + n.a = self.signature(sig)? + }, + Array { elem, len } => { + n.tag = 106; + n.a = self.ty(elem)?; + n.b = *len + }, + Struct { fields } => { + n.tag = 107; + let mut ids = Vec::new(); + ids.try_reserve(fields.len()).map_err(|_| expansion())?; + for f in fields { + let a = self.name(&f.name)?; + let b = self.ty(&f.ty)?; + ids.push(self.push(Node { tag: 108, a, b, ..Node::default() })?) + } + (n.a, n.b) = self.list(ids)? + }, + Opaque(name) => { + n.tag = 109; + n.a = self.name(name)? + }, + } + self.push(n) + } + + fn signature(&mut self, sig: &'a ast::SignatureRef) -> Result { + let mut ids = Vec::new(); + ids.try_reserve(sig.params.len()).map_err(|_| expansion())?; + for t in &sig.params { + ids.push(self.ty(t)?) + } + let (a, b) = self.list(ids)?; + let c = self.ty(&sig.ret)?; + self.push(Node { + tag: 110, + a, + b, + c, + d: convention(sig.convention), + e: u64::from(sig.variadic), + ..Node::default() + }) + } + + fn exprs(&mut self, values: &'a [ast::Expr]) -> Result<(u64, u64), LowerError> { + let mut ids = Vec::new(); + ids.try_reserve(values.len()).map_err(|_| expansion())?; + for e in values { + ids.push(self.expr(e)?) + } + self.list(ids) + } + + fn stmts(&mut self, values: &'a [ast::Stmt]) -> Result<(u64, u64), LowerError> { + let mut ids = Vec::new(); + ids.try_reserve(values.len()).map_err(|_| expansion())?; + for s in values { + ids.push(self.stmt(s)?) + } + self.list(ids) + } + + fn expr(&mut self, e: &'a ast::Expr) -> Result { + use ast::Expr::*; + let mut n = Node::default(); + match e { + Located { annotation, expression } => { + n.tag = 0; + n.a = self.annotation(annotation)?; + n.b = self.expr(expression)? + }, + Struct { ty, fields } => { + n.tag = 1; + n.a = self.ty(ty)?; + let mut ids = Vec::new(); + ids.try_reserve(fields.len()).map_err(|_| expansion())?; + for f in fields { + let a = self.name(&f.name)?; + let b = self.expr(&f.value)?; + ids.push(self.push(Node { tag: 24, a, b, ..Node::default() })?) + } + (n.b, n.c) = self.list(ids)? + }, + Array { ty, elements } => { + n.tag = 2; + n.a = self.ty(ty)?; + (n.b, n.c) = self.exprs(elements)? + }, + Field { base, layout, name } => { + n.tag = 3; + n.a = self.expr(base)?; + n.b = self.ty(layout)?; + n.c = self.name(name)? + }, + Index { base, index } => { + n.tag = 4; + n.a = self.expr(base)?; + n.b = self.expr(index)? + }, + AddressOf(value) => { + n.tag = 5; + n.a = self.expr(value)? + }, + Deref(value) => { + n.tag = 6; + n.a = self.expr(value)? + }, + VolatileLoad(value) => { + n.tag = 7; + n.a = self.expr(value)? + }, + PointerOffset { base, index } => { + n.tag = 8; + n.a = self.expr(base)?; + n.b = self.expr(index)? + }, + BitNot(value) => { + n.tag = 9; + n.a = self.expr(value)? + }, + Neg(value) => { + n.tag = 10; + n.a = self.expr(value)? + }, + Cast { value, ty, kind } => { + n.tag = 11; + n.a = self.expr(value)?; + n.b = self.ty(ty)?; + n.c = match kind { + ast::IntegerCast::Numeric => 0, + ast::IntegerCast::Checked => 1, + } + }, + FunctionRef(name) => { + n.tag = 12; + n.a = self.name(name)? + }, + NullFunction(sig) => { + n.tag = 13; + n.a = self.signature(sig)? + }, + Call { callee, args } => { + n.tag = 14; + match callee { + ast::CalleeRef::Direct(name) => { + n.a = 0; + n.b = self.name(name)? + }, + ast::CalleeRef::Indirect(value) => { + n.a = 1; + n.b = self.expr(value)? + }, + } + (n.c, n.d) = self.exprs(args)? + }, + Var(name) => { + n.tag = 15; + n.a = self.name(name)? + }, + Lit(ast::Lit::Bool(b)) => { + n.tag = 16; + n.a = u64::from(*b) + }, + Lit(ast::Lit::Int { bits, signed, value }) => { + n.tag = 17; + n.a = (*bits).into(); + n.b = u64::from(*signed); + n.c = value.as_ptr() as u64; + n.d = value.len() as u64 + }, + Lit(ast::Lit::Float { bits, value }) => { + n.tag = 18; + n.a = (*bits).into(); + n.b = value.as_ptr() as u64; + n.c = value.len() as u64 + }, + Binary { left, op, right } => { + n.tag = 19; + n.a = self.expr(left)?; + n.b = binop(*op); + n.c = self.expr(right)? + }, + Cmp { left, op, right } => { + n.tag = 20; + n.a = self.expr(left)?; + n.b = cmpop(*op); + n.c = self.expr(right)? + }, + } + let id = self.push(n)?; + if let Lit(lit) = e { + self.literals.try_reserve(1).map_err(|_| expansion())?; + self.literals.insert(id, lit); + } + Ok(id) + } + + fn stmt(&mut self, s: &'a ast::Stmt) -> Result { + use ast::Stmt::*; + let mut n = Node::default(); + match s { + Located { annotation, statement } => { + n.tag = 50; + n.a = self.annotation(annotation)?; + n.b = self.stmt(statement)? + }, + Return(e) => { + n.tag = 51; + n.a = match e { + Some(e) => self.expr(e)?, + None => NONE, + } + }, + VolatileStore { pointer, value } => { + n.tag = 52; + n.a = self.expr(pointer)?; + n.b = self.expr(value)? + }, + Store { place, value } => { + n.tag = 53; + n.a = self.expr(place)?; + n.b = self.expr(value)? + }, + ConstDecl { name, ty, init } => { + n.tag = 54; + n.a = self.name(name)?; + n.b = self.ty(ty)?; + n.c = self.expr(init)? + }, + VarDecl { name, ty, init } => { + n.tag = 55; + n.a = self.name(name)?; + n.b = self.ty(ty)?; + n.c = match init { + Some(e) => self.expr(e)?, + None => NONE, + } + }, + Assign { name, value } => { + n.tag = 56; + n.a = self.name(name)?; + n.b = self.expr(value)? + }, + ExprStmt(e) => { + n.tag = 57; + n.a = self.expr(e)? + }, + If { cond, then_body, else_body } => { + n.tag = 58; + n.a = self.expr(cond)?; + (n.b, n.c) = self.stmts(then_body)?; + (n.d, n.e) = self.stmts(else_body)? + }, + While { cond, body } => { + n.tag = 59; + n.a = self.expr(cond)?; + (n.b, n.c) = self.stmts(body)? + }, + Break => n.tag = 60, + Continue => n.tag = 61, + } + self.push(n) + } + + fn program(&mut self, p: &'a ast::Program) -> Result { + let mut ids = Vec::new(); + ids.try_reserve(p.declarations.len()).map_err(|_| expansion())?; + for d in &p.declarations { + let a = self.name(&d.name)?; + let b = self.signature(&d.signature)?; + let link = match &d.link_name { + Some(s) => self.name(s)?, + None => NONE, + }; + ids.push(self.push(Node { + tag: 201, + a, + b, + c: linkage(d.linkage), + d: link, + ..Node::default() + })?) + } + let (a, b) = self.list(ids)?; + let mut ids = Vec::new(); + ids.try_reserve(p.globals.len()).map_err(|_| expansion())?; + for g in &p.globals { + let a = self.name(&g.name)?; + let b = self.ty(&g.ty)?; + let c = self.expr(&g.init)?; + ids.push(self.push(Node { tag: 202, a, b, c, ..Node::default() })?) + } + let (c, d) = self.list(ids)?; + let mut ids = Vec::new(); + ids.try_reserve(p.functions.len()).map_err(|_| expansion())?; + for f in &p.functions { + let name = self.name(&f.name)?; + let mut params = Vec::new(); + params.try_reserve(f.parameters.len()).map_err(|_| expansion())?; + for p in &f.parameters { + let a = self.name(&p.name)?; + let b = self.ty(&p.ty)?; + params.push(self.push(Node { tag: 204, a, b, ..Node::default() })?) + } + let (first, count) = self.list(params)?; + let ret = self.ty(&f.return_type)?; + let (body, body_count) = self.stmts(&f.body)?; + let link = match &f.link_name { + Some(s) => self.name(s)?, + None => NONE, + }; + ids.push(self.push(Node { + tag: 203, + a: name, + b: first, + c: count, + d: ret, + e: body, + f: body_count, + g: convention(f.convention), + h: linkage(f.linkage), + i: link, + ..Node::default() + })?); + } + let (e, f) = self.list(ids)?; + self.push(Node { tag: 200, a, b, c, d, e, f, ..Node::default() }) + } +} + +fn convention(c: CallingConvention) -> u64 { + match c { + CallingConvention::Whale => 0, + CallingConvention::SysV64 => 1, + } +} + +fn linkage(l: Linkage) -> u64 { + match l { + Linkage::Internal => 0, + Linkage::External => 1, + } +} + +fn binop(op: ast::BinOpRef) -> u64 { + use ast::BinOpRef::*; + match op { + Add => 0, + Sub => 1, + Mul => 2, + BitAnd => 3, + BitOr => 4, + BitXor => 5, + Div => 6, + Rem => 7, + ShiftLeft => 8, + ShiftRight => 9, + LogicalAnd => 10, + LogicalOr => 11, + } +} + +fn cmpop(op: ast::CmpOpRef) -> u64 { + use ast::CmpOpRef::*; + match op { + Eq => 0, + Ne => 1, + Lt => 2, + Le => 3, + Gt => 4, + Ge => 5, + } +} + +#[derive(Clone)] +struct Output { + result: ResultRecord, + requests: Vec, + types: Vec, + type_edges: Vec, + instructions: Vec, + output_edges: Vec, + blocks: Vec, + constants: Vec, + declarations: Vec, + functions: Vec, + globals: Vec, + source_order: Vec, + mapping_order: Vec, + value_types: Vec, + error_index: u64, + instruction_count: usize, + edge_count: usize, + value_count: usize, +} + +fn execute( + w: &Wire<'_>, + root: u64, + target: Target, + limits: AstLimits, + counts: Option<(usize, usize, usize)>, +) -> Result { + let n = w.nodes.len(); + let names = w.names.len(); + let annotations = w.annotations.len(); + let four = n.checked_mul(4).ok_or_else(expansion)?; + let type_cap = four.checked_add(17).ok_or_else(expansion)?; + let edge_cap = four.checked_add(64).ok_or_else(expansion)?; + let block_cap = four.checked_add(8).ok_or_else(expansion)?; + let binding_cap = n.checked_add(8).ok_or_else(expansion)?; + let table_cap = + type_cap.checked_mul(2).and_then(usize::checked_next_power_of_two).ok_or_else(expansion)?; + let original_cap = annotations + .checked_mul(2) + .and_then(|n| n.max(2).checked_next_power_of_two()) + .ok_or_else(expansion)?; + let mut types = zeroed::(type_cap)?; + let mut type_edges = zeroed::(edge_cap)?; + let mut type_table = zeroed::(table_cap)?; + let mut type_map = filled(n, NONE)?; + let mut temporary = zeroed::(edge_cap)?; + let mut name_marks = zeroed::(names)?; + let mut layout_nodes = zeroed::(type_cap)?; + let mut layouts = zeroed::(type_cap)?; + let mut offsets = zeroed::(edge_cap)?; + let mut type_sizes = zeroed::(type_cap)?; + let mut blocks = zeroed::(block_cap)?; + let mut declarations = zeroed::(n)?; + let mut functions = zeroed::(n)?; + let mut globals = zeroed::(n)?; + let mut global_bindings = zeroed::(n)?; + let mut bindings = zeroed::(binding_cap)?; + let mut loops = zeroed::(binding_cap)?; + let mut original_table = zeroed::(original_cap)?; + let mut source_marks = zeroed::(annotations)?; + let mut declaration_map = filled(names, NONE)?; + let mut field_slots = filled(names, NONE)?; + let mut field_bindings = zeroed::(binding_cap)?; + let mut local_slots = filled(names, NONE)?; + let mut global_slots = filled(names, NONE)?; + let (instruction_cap, output_edge_cap, value_cap) = counts.unwrap_or((0, 0, 0)); + let publish = counts.is_some(); + let mut instructions = zeroed::(instruction_cap)?; + let mut output_edges = zeroed::(output_edge_cap)?; + let mut value_types = zeroed::(value_cap)?; + let mut constants = zeroed::(n)?; + let mut requests = zeroed::(n)?; + let mut source_order = zeroed::(if publish { annotations } else { 0 })?; + let mut mapping_order = zeroed::(if publish { annotations } else { 0 })?; + let raw_names = w + .names + .iter() + .map(|s| RawString { data: s.as_ptr(), length: s.len() as u64 }) + .collect::>(); + let storage = target.specification().storage; + let (large_array_threshold, large_array_align) = storage.large_array.unwrap_or((0, 0)); + let storage = Storage { + ptr_bits: storage.data.ptr_bits.into(), + pointer_align: storage.pointer_align.into(), + scalar_align1: storage.scalar_align[0].into(), + scalar_align2: storage.scalar_align[1].into(), + scalar_align4: storage.scalar_align[2].into(), + scalar_align8: storage.scalar_align[3].into(), + scalar_align16: storage.scalar_align[4].into(), + large_array_threshold, + large_array_align: large_array_align.into(), + has_large_array: u64::from(storage.large_array.is_some()), + }; + let mut result = ResultRecord::default(); + let mut core = Context { + nodes: w.nodes.as_ptr(), + node_count: n as u64, + edges: w.edges.as_ptr(), + edge_count: w.edges.len() as u64, + names: raw_names.as_ptr(), + name_count: names as u64, + types: types.as_mut_ptr(), + type_capacity: type_cap as u64, + type_edges: type_edges.as_mut_ptr(), + type_edge_capacity: edge_cap as u64, + type_table: type_table.as_mut_ptr(), + type_table_capacity: table_cap as u64, + type_map: type_map.as_mut_ptr(), + temporary: temporary.as_mut_ptr(), + temporary_capacity: edge_cap as u64, + name_marks: name_marks.as_mut_ptr(), + storage: &storage, + layout_nodes: layout_nodes.as_mut_ptr(), + layouts: layouts.as_mut_ptr(), + layout_offsets: offsets.as_mut_ptr(), + max_depth: limits.max_depth.min(super::MAX_AST_DEPTH) as u64, + max_work: limits.max_nodes.saturating_mul(256).saturating_add(1024) as u64, + result: &mut result, + ..Context::default() + }; + let mut d = Driver { + core: &mut core, + mode: u64::from(publish), + max_expansion: IrLimits::default().max_nodes as u64, + instructions: if publish { instructions.as_mut_ptr() } else { std::ptr::null_mut() }, + instruction_capacity: instruction_cap as u64, + output_edges: if publish { output_edges.as_mut_ptr() } else { std::ptr::null_mut() }, + output_edge_capacity: output_edge_cap as u64, + blocks: blocks.as_mut_ptr(), + block_capacity: block_cap as u64, + constants: constants.as_mut_ptr(), + declarations: declarations.as_mut_ptr(), + declaration_capacity: n as u64, + functions: functions.as_mut_ptr(), + function_capacity: n as u64, + globals: globals.as_mut_ptr(), + global_capacity: n as u64, + global_bindings: global_bindings.as_mut_ptr(), + bindings: bindings.as_mut_ptr(), + binding_capacity: binding_cap as u64, + loops: loops.as_mut_ptr(), + loop_capacity: binding_cap as u64, + annotations: w.raw_annotations.as_ptr(), + annotation_count: annotations as u64, + original_table: original_table.as_mut_ptr(), + original_capacity: original_cap as u64, + source_order: if publish { source_order.as_mut_ptr() } else { std::ptr::null_mut() }, + source_capacity: annotations as u64, + source_marks: source_marks.as_mut_ptr(), + type_sizes: type_sizes.as_mut_ptr(), + value_types: if publish { value_types.as_mut_ptr() } else { std::ptr::null_mut() }, + value_capacity: value_cap as u64, + declaration_map: declaration_map.as_mut_ptr(), + field_slots: field_slots.as_mut_ptr(), + field_bindings: field_bindings.as_mut_ptr(), + field_binding_capacity: binding_cap as u64, + local_slots: local_slots.as_mut_ptr(), + global_slots: global_slots.as_mut_ptr(), + mapping_order: if publish { mapping_order.as_mut_ptr() } else { std::ptr::null_mut() }, + mapping_capacity: annotations as u64, + max_source_work: limits.max_source_work as u64, + requests: requests.as_mut_ptr(), + request_capacity: n as u64, + ..Driver::default() + }; + // Every pointee is caller-owned and remains alive throughout this synchronous + // call. Wave receives exact capacities and only publishes into the second pass. + let status = unsafe { whale_ir_lower_o0(&mut d, root) }; + if status < 0 + || result.status != status as u64 + || core.work > core.max_work + || result.work != core.work + || core.type_count > core.type_capacity + || core.type_edge_count > core.type_edge_capacity + || d.block_count > d.block_capacity + || d.declaration_count > d.declaration_capacity + || d.function_count > d.function_capacity + || d.global_count > d.global_capacity + || d.source_count > d.source_capacity + || d.mapping_count > d.mapping_capacity + || d.source_work > d.max_source_work + || d.expansion > d.max_expansion + || d.request_count > d.request_capacity + || (publish + && (d.instruction_count > d.instruction_capacity + || d.output_edge_count > d.output_edge_capacity + || d.next_value > d.value_capacity)) + { + return Err(backend()); + } + requests.truncate(d.request_count as usize); + types.truncate(core.type_count as usize); + type_edges.truncate(core.type_edge_count as usize); + blocks.truncate(d.block_count as usize); + declarations.truncate(d.declaration_count as usize); + functions.truncate(d.function_count as usize); + globals.truncate(d.global_count as usize); + if publish { + source_order.truncate(d.source_count as usize); + mapping_order.truncate(d.mapping_count as usize); + } + Ok(Output { + result, + requests, + error_index: d.error_index, + types, + type_edges, + instructions, + output_edges, + blocks, + constants, + declarations, + functions, + globals, + source_order, + mapping_order, + value_types, + instruction_count: usize::try_from(d.instruction_count).map_err(|_| backend())?, + edge_count: usize::try_from(d.output_edge_count).map_err(|_| backend())?, + value_count: usize::try_from(d.next_value).map_err(|_| backend())?, + }) +} + +fn index(v: u64) -> Result { + usize::try_from(v).map_err(|_| backend()) +} + +fn id(v: u64) -> Result { + u32::try_from(v).map_err(|_| backend()) +} + +fn slice(values: &[T], first: u64, count: u64) -> Result<&[T], LowerError> { + let first = index(first)?; + let count = index(count)?; + values.get(first..first.checked_add(count).ok_or_else(backend)?).ok_or_else(backend) +} + +fn name<'a>(w: &'a Wire<'_>, v: u64) -> Result<&'a str, LowerError> { + w.names.get(index(v)?).copied().ok_or_else(backend) +} + +fn annotation<'a>(w: &'a Wire<'_>, v: u64) -> Result, LowerError> { + if v == NONE { + Ok(None) + } else { + w.annotations.get(index(v)?).copied().map(Some).ok_or_else(backend) + } +} + +fn located(w: &Wire<'_>, v: u64, error: LowerError) -> Result { + Ok(match annotation(w, v)? { + Some(a) => error.at(a), + None => error, + }) +} + +fn calling(v: u64) -> Result { + match v { + 0 => Ok(CallingConvention::Whale), + 1 => Ok(CallingConvention::SysV64), + _ => Err(backend()), + } +} + +fn link(v: u64) -> Result { + match v { + 0 => Ok(Linkage::Internal), + 1 => Ok(Linkage::External), + _ => Err(backend()), + } +} + +fn decode_type(o: &Output, root: u64, depth: usize) -> Result { + decode_type_inner(o, root, depth, &mut IrLimits::default().max_nodes) +} + +fn decode_type_inner( + o: &Output, + root: u64, + depth: usize, + remaining: &mut usize, +) -> Result { + *remaining = remaining.checked_sub(1).ok_or_else(backend)?; + if depth > super::MAX_AST_DEPTH { + return Err(backend()); + } + let t = o.types.get(index(root)?).ok_or_else(backend)?; + Ok(match t.kind { + 0 => Type::Void, + 1 => Type::Bool, + 2 => Type::I1, + 3 => Type::U1, + 4 => Type::I8, + 5 => Type::I16, + 6 => Type::I32, + 7 => Type::I64, + 8 => Type::I128, + 9 => Type::U8, + 10 => Type::U16, + 11 => Type::U32, + 12 => Type::U64, + 13 => Type::U128, + 14 => Type::F16, + 15 => Type::F32, + 16 => Type::F64, + 17 => Type::Ptr(Box::new(decode_type_inner(o, t.child, depth + 1, remaining)?)), + 18 => Type::FnPtr(Box::new(FunctionSignature { + params: slice(&o.type_edges, t.first, t.count)? + .iter() + .map(|id| decode_type_inner(o, *id, depth + 1, remaining)) + .collect::>()?, + ret: decode_type_inner(o, t.child, depth + 1, remaining)?, + convention: calling(t.auxiliary)?, + variadic: false, + })), + 19 => { + Type::Array(Box::new(decode_type_inner(o, t.child, depth + 1, remaining)?), t.auxiliary) + }, + 20 | 21 => { + let fields = slice(&o.type_edges, t.first, t.count)? + .iter() + .map(|id| decode_type_inner(o, *id, depth + 1, remaining)) + .collect::>()?; + if t.kind == 20 { + Type::Struct(fields) + } else { + Type::Tuple(fields) + } + }, + _ => return Err(backend()), + }) +} + +fn signature(o: &Output, ty: u64) -> Result { + match decode_type(o, ty, 0)? { + Type::FnPtr(sig) => Ok(*sig), + _ => Err(backend()), + } +} + +fn payload(category: u64, low: u64, high: u64, ty: &Type) -> Result { + let bits = u128::from(low) | (u128::from(high) << 64); + Ok(match category { + 1 if low <= 1 && high == 0 => ConstValue::Bool(low != 0), + 2 => ConstValue::I(bits as i128), + 3 => ConstValue::U(bits), + 4 if high == 0 => ConstValue::F(match ty { + Type::F16 if low <= u16::MAX.into() => FloatBits::F16(low as u16), + Type::F32 if low <= u32::MAX.into() => FloatBits::F32(low as u32), + Type::F64 => FloatBits::F64(low), + _ => return Err(backend()), + }), + _ => return Err(backend()), + }) +} + +fn const_binary(op: u64) -> Result { + use ConstBinaryOp::*; + Ok(match op { + 0 => Add, + 1 => Sub, + 2 => Mul, + 3 => BitAnd, + 4 => BitOr, + 5 => BitXor, + 6 => Div, + 7 => Rem, + 8 => ShiftLeft, + 9 => ShiftRight, + 10 => LogicalAnd, + 11 => LogicalOr, + _ => return Err(backend()), + }) +} + +fn const_compare(op: u64) -> Result { + use ConstCompareOp::*; + Ok(match op { + 0 => Eq, + 1 => Ne, + 2 => Lt, + 3 => Le, + 4 => Gt, + 5 => Ge, + _ => return Err(backend()), + }) +} + +fn decode_constant(o: &Output, root: u64, depth: usize) -> Result { + decode_constant_inner(o, root, depth, &mut IrLimits::default().max_nodes) +} + +fn decode_constant_inner( + o: &Output, + root: u64, + depth: usize, + remaining: &mut usize, +) -> Result { + *remaining = remaining.checked_sub(1).ok_or_else(backend)?; + if depth > super::MAX_AST_DEPTH { + return Err(backend()); + } + let c = o.constants.get(index(root)?).ok_or_else(backend)?; + let ty = decode_type(o, c.ty, 0)?; + let kind = match c.kind { + 0 => ConstExprKind::Literal(payload(c.operation, c.low, c.high, &ty)?), + 1 => ConstExprKind::Reference(ConstRef::Local(ValueId(id(c.reference)?))), + 2 => ConstExprKind::Reference(ConstRef::Global(GlobalId(id(c.reference)?))), + 3 => ConstExprKind::Neg(Box::new(decode_constant_inner(o, c.left, depth + 1, remaining)?)), + 4 => ConstExprKind::Not(Box::new(decode_constant_inner(o, c.left, depth + 1, remaining)?)), + 5 => ConstExprKind::Binary { + op: const_binary(c.operation)?, + left: Box::new(decode_constant_inner(o, c.left, depth + 1, remaining)?), + right: Box::new(decode_constant_inner(o, c.right, depth + 1, remaining)?), + }, + 6 => ConstExprKind::Compare { + op: const_compare(c.operation)?, + left: Box::new(decode_constant_inner(o, c.left, depth + 1, remaining)?), + right: Box::new(decode_constant_inner(o, c.right, depth + 1, remaining)?), + }, + _ => return Err(backend()), + }; + Ok(ConstExpr { ty, kind }) +} + +struct Evaluated { + root: u64, + expression: ConstExpr, + value: ConstValue, +} + +type ConstantResults = HashMap; + +fn evaluate_requests(w: &Wire<'_>, o: &Output) -> Result { + let mut values = ConstantResults::new(); + values.try_reserve(o.requests.len()).map_err(|_| expansion())?; + for request in &o.requests { + let key = match request.kind { + 0 => ConstRef::Global(GlobalId(id(request.identity)?)), + 1 => ConstRef::Local(ValueId(id(request.identity)?)), + _ => return Err(backend()), + }; + let expression = decode_constant(o, request.expression, 0)?; + let value = expression + .evaluate_with_error_site( + &|reference| { + values + .get(&reference) + .map(|entry| (entry.expression.ty.clone(), entry.value.clone())) + }, + IrLimits::default(), + ) + .map_err(|(error, failed)| { + constant_error( + w, + o, + request.expression, + &expression, + failed, + error, + request.annotation, + ) + })?; + if values.insert(key, Evaluated { root: request.expression, expression, value }).is_some() { + return Err(backend()); + } + } + Ok(values) +} + +fn constant_error( + w: &Wire<'_>, + o: &Output, + root: u64, + expression: &ConstExpr, + failed: &ConstExpr, + error: ConstEvalError, + fallback: u64, +) -> LowerError { + let mut pending = vec![(root, expression)]; + while let Some((raw, typed)) = pending.pop() { + let Some(c) = index(raw).ok().and_then(|i| o.constants.get(i)) else { return backend() }; + if std::ptr::eq(typed, failed) { + return located( + w, + if c.annotation == NONE { fallback } else { c.annotation }, + LowerError::ConstantEvaluation(error), + ) + .unwrap_or_else(|e| e); + } + match &typed.kind { + ConstExprKind::Neg(v) | ConstExprKind::Not(v) => pending.push((c.left, v)), + ConstExprKind::Binary { left, right, .. } + | ConstExprKind::Compare { left, right, .. } => { + pending.push((c.right, right)); + pending.push((c.left, left)); + }, + _ => {}, + } + } + backend() +} + +fn kernel_error(w: &Wire<'_>, o: &Output) -> Result { + let r = &o.result; + let raw = w.nodes.get(index(r.node)?).ok_or_else(backend)?; + let err = match r.status { + 1 => LowerError::ResourceLimit(AstLimitError::SourceWork), + 2 => LowerError::ResourceLimit(AstLimitError::Depth), + 3 | 4 => return Err(backend()), + 5 => LowerError::UnsupportedType(match raw.tag { + 102 | 17 => format!("int bits={} signed={}", raw.a, raw.b != 0), + 103 | 18 => format!("float bits={}", raw.a), + 109 => format!("opaque {}", name(w, raw.a)?), + _ => return Err(backend()), + }), + 6 => LowerError::TypeMismatch { + expected: decode_type(o, r.expected, 0)?, + got: decode_type(o, r.actual, 0)?, + }, + 7 => LowerError::UnsupportedExpr, + 8 => LowerError::DuplicateFunction(name(w, r.detail)?.to_owned()), + 9 => LowerError::DuplicateParameter { + func: name(w, raw.a)?.to_owned(), + param: name(w, r.detail)?.to_owned(), + }, + 10 => LowerError::DuplicateGlobal(name(w, r.detail)?.to_owned()), + 11 => LowerError::UnknownVariable(name(w, r.detail)?.to_owned()), + 12 => LowerError::AssignToConst(name(w, r.detail)?.to_owned()), + 13 => LowerError::BreakOutsideLoop, + 14 => LowerError::ContinueOutsideLoop, + 15 => LowerError::ValueReturnedFromVoid, + 16 => LowerError::VoidCallUsedAsValue, + 17 => LowerError::NonConstExpr, + 18 => LowerError::Aggregate(match r.detail { + 1 => "duplicate or empty struct field".into(), + 2 => "initial structs require scalar fields".into(), + 3 => format!("unknown field {:?}", name(w, raw.c)?), + 4 => "struct initializer field count mismatch".into(), + 5 => "duplicate field initializer".into(), + 6 => format!("unknown initializer field {:?}", name(w, raw.a)?), + 7 => "initial array literals require scalar elements".into(), + 8 => "array literal length mismatch".into(), + 9 => "aggregate by-value signatures are unsupported".into(), + _ => return Err(backend()), + }), + 19 => { + let lit = w.literals.get(&r.node).ok_or_else(backend)?; + match lit { + ast::Lit::Int { signed, value, .. } => match r.detail { + 2 | 4 => LowerError::NumericLiteral( + "expected decimal digits with an optional signed minus".into(), + ), + 3 if value.parse::().is_err() => { + LowerError::NumericLiteral("integer exceeds i128 range".into()) + }, + 5 if value.parse::().is_err() => { + LowerError::NumericLiteral("integer exceeds u128 range".into()) + }, + 3 | 5 | 9 => LowerError::InvalidLiteral { + ty: decode_type(o, r.expected, 0)?, + value: if *signed { + ConstValue::I(value.parse().map_err(|_| backend())?) + } else { + ConstValue::U(value.parse().map_err(|_| backend())?) + }, + }, + _ => return Err(backend()), + }, + ast::Lit::Float { bits, value } => LowerError::NumericLiteral( + FloatBits::parse(*bits, value).err().ok_or_else(backend)?, + ), + _ => return Err(backend()), + } + }, + 20 => LowerError::Layout(match r.detail { + 1 => LayoutError::Void, + 2 => LayoutError::DepthLimit, + 3 => LayoutError::Overflow, + 4 | 5 => return Err(backend()), + _ => return Err(backend()), + }), + 21 => LowerError::Call(match r.detail { + 1 => CallError::InvalidSignature( + "void parameters, malformed types and variadic calls are unsupported".into(), + ), + 2 => CallError::UnknownFunctionName(name(w, r.expected)?.to_owned()), + 3 => CallError::NotFunctionPointer(ValueId(id(r.expected)?)), + 4 => CallError::ArgumentCount { expected: index(r.expected)?, got: index(r.actual)? }, + 5 => CallError::ArgumentType { + index: index(o.error_index)?, + expected: decode_type(o, r.expected, 0)?, + got: decode_type(o, r.actual, 0)?, + }, + 6 => CallError::ConflictingDeclaration(name(w, r.expected)?.to_owned()), + 7 => CallError::MissingDefinition(FunctionId(id(r.expected)?)), + 8 => CallError::DuplicateDefinition(FunctionId(id(r.expected)?)), + 9 => CallError::InvalidLinkName(name(w, r.expected)?.to_owned()), + 10 => CallError::LinkNameCollision(name(w, r.expected)?.to_owned()), + _ => return Err(backend()), + }), + 22 => LowerError::ResourceLimit(AstLimitError::SourceWork), + 23 => LowerError::ResourceLimit(AstLimitError::Expansion), + 24 => LowerError::UnsupportedStmt, + _ => return Err(backend()), + }; + if r.status == 22 { + Ok(err) + } else { + located(w, r.annotation, err) + } +} + +fn runtime_bin(op: u64) -> Result { + use BinOp::*; + Ok(match op { + 0 => Add, + 1 => Sub, + 2 => Mul, + 3 => UDiv, + 4 => SDiv, + 5 => URem, + 6 => SRem, + 7 => FAdd, + 8 => FSub, + 9 => FMul, + 10 => FDiv, + 11 => FRem, + 12 => And, + 13 => Or, + 14 => Xor, + 15 => Shl, + 16 => LShr, + 17 => AShr, + _ => return Err(backend()), + }) +} + +fn runtime_cmp(op: u64) -> Result { + use CmpOp::*; + Ok(match op { + 0 => Eq, + 1 => Ne, + 2 => SLt, + 3 => SLe, + 4 => SGt, + 5 => SGe, + 6 => ULt, + 7 => ULe, + 8 => UGt, + 9 => UGe, + 10 => FEq, + 11 => FNe, + 12 => FLt, + 13 => FLe, + 14 => FGt, + 15 => FGe, + _ => return Err(backend()), + }) +} + +fn runtime_cast(op: u64) -> Result { + use CastOp::*; + Ok(match op { + 0 => CheckedInt, + 1 => ZExt, + 2 => SExt, + 3 => Trunc, + 4 => FExt, + 5 => FTrunc, + 6 => IToF_S, + 7 => IToF_U, + 8 => FToI_S, + 9 => FToI_U, + 10 => Bitcast, + 11 => PtrToInt, + 12 => IntToPtr, + _ => return Err(backend()), + }) +} + +struct FunctionRange { + values: u64, + end_values: u64, + blocks: u64, + end_blocks: u64, +} + +impl FunctionRange { + fn value(&self, v: u64) -> Result { + if v < self.values || v >= self.end_values { + return Err(backend()); + } + Ok(ValueId(id(v)?)) + } + + fn block(&self, v: u64) -> Result { + if v < self.blocks || v >= self.end_blocks { + return Err(backend()); + } + Ok(BlockId(id(v)?)) + } +} + +fn instruction( + w: &Wire<'_>, + o: &Output, + r: &RawInstruction, + range: &FunctionRange, + global_values: &[(Type, ConstValue)], + constants: &mut ConstantResults, +) -> Result { + let ty = || decode_type(o, r.ty, 0); + let value = |v| range.value(v); + let dst = || value(r.dst); + let align = |v| id(v); + Ok(match r.tag { + 3 => { + let dst = dst()?; + let evaluated = constants.remove(&ConstRef::Local(dst)).ok_or_else(backend)?; + if evaluated.root != r.b { + return Err(backend()); + } + Instruction::ConstDecl { + dst, + name: name(w, r.a)?.to_owned(), + expression: evaluated.expression, + value: evaluated.value, + } + }, + 4 => Instruction::Const { + dst: dst()?, + ty: ty()?, + value: match r.a { + 1 => global_values.get(index(r.b)?).map(|(_, v)| v.clone()).ok_or_else(backend)?, + 2 => payload(r.d, r.b, r.c, &ty()?)?, + _ => return Err(backend()), + }, + }, + 7 => Instruction::Bin { + dst: dst()?, + op: runtime_bin(r.a)?, + ty: ty()?, + lhs: value(r.b)?, + rhs: value(r.c)?, + }, + 8 => Instruction::Neg { dst: dst()?, ty: ty()?, src: value(r.a)? }, + 9 => Instruction::Not { dst: dst()?, ty: ty()?, src: value(r.a)? }, + 10 => Instruction::Cmp { + dst: dst()?, + op: runtime_cmp(r.a)?, + ty: ty()?, + lhs: value(r.b)?, + rhs: value(r.c)?, + }, + 11 => Instruction::ICmp { + dst: dst()?, + pred: match r.a { + 0 => ICmpPred::Eq, + 1 => ICmpPred::Ne, + 2 => ICmpPred::Ult, + 3 => ICmpPred::Ule, + 4 => ICmpPred::Ugt, + 5 => ICmpPred::Uge, + 6 => ICmpPred::Slt, + 7 => ICmpPred::Sle, + 8 => ICmpPred::Sgt, + 9 => ICmpPred::Sge, + _ => return Err(backend()), + }, + ty: ty()?, + lhs: value(r.b)?, + rhs: value(r.c)?, + }, + 14 => Instruction::Cast { + dst: dst()?, + op: runtime_cast(r.a)?, + dst_ty: ty()?, + src_ty: decode_type(o, r.b, 0)?, + src: value(r.c)?, + }, + 15 => { + let edges = slice(&o.output_edges, r.first, r.count)?; + if edges.len() % 2 != 0 { + return Err(backend()); + } + Instruction::Phi { + dst: dst()?, + ty: ty()?, + incomings: edges + .chunks_exact(2) + .map(|p| Ok((value(p[0])?, range.block(p[1])?))) + .collect::>()?, + } + }, + 18 => Instruction::Alloca { dst: dst()?, ty: ty()?, align: align(r.a)? }, + 19 => Instruction::VolatileLoad { + dst: dst()?, + ty: ty()?, + ptr: value(r.a)?, + align: align(r.b)?, + }, + 20 => Instruction::VolatileStore { + ty: ty()?, + value: value(r.a)?, + ptr: value(r.b)?, + align: align(r.c)?, + }, + 21 => Instruction::Load { dst: dst()?, ty: ty()?, ptr: value(r.a)?, align: align(r.b)? }, + 22 => Instruction::Uninit { ty: ty()?, ptr: value(r.a)?, align: align(r.b)? }, + 23 => Instruction::Store { + ty: ty()?, + value: value(r.a)?, + ptr: value(r.b)?, + align: align(r.c)?, + }, + 24 => Instruction::Gep { + dst: dst()?, + dst_ty: ty()?, + base_ptr: value(r.a)?, + indices: slice(&o.output_edges, r.first, r.count)? + .iter() + .map(|v| value(*v)) + .collect::>()?, + }, + 25 => Instruction::Memcpy { + dst: value(r.a)?, + src: value(r.b)?, + n: value(r.c)?, + align: align(r.d)?, + }, + 27 => Instruction::NullFunction { dst: dst()?, signature: signature(o, r.ty)? }, + 28 => Instruction::FunctionAddr { + dst: dst()?, + function: FunctionId(id(r.a)?), + signature: signature(o, r.ty)?, + }, + 29 => Instruction::Call { + convention: calling(r.a)?, + dst: if r.dst == NONE { None } else { Some(dst()?) }, + ret_ty: ty()?, + callee: match r.b { + 0 => Callee::Direct(FunctionId(id(r.c)?)), + 1 => Callee::Indirect(value(r.c)?), + _ => return Err(backend()), + }, + args: slice(&o.output_edges, r.first, r.count)? + .iter() + .map(|v| value(*v)) + .collect::>()?, + }, + 30 => Instruction::TrapIf { + cond: value(r.a)?, + reason: match r.b { + 1 => "array index out of bounds", + _ => return Err(backend()), + } + .into(), + }, + _ => return Err(backend()), + }) +} + +fn terminator(o: &Output, r: &RawBlock, range: &FunctionRange) -> Result { + Ok(match r.term_kind { + 1 => Terminator::Br { target: range.block(r.term_a)? }, + 2 => Terminator::CBr { + cond: range.value(r.term_a)?, + then_bb: range.block(r.term_b)?, + else_bb: range.block(r.term_c)?, + }, + 3 => Terminator::Ret { + ty: decode_type(o, r.term_ty, 0)?, + value: if r.term_a == NONE { None } else { Some(range.value(r.term_a)?) }, + }, + 4 => Terminator::Trap { + reason: match r.term_a { + 0 => "missing return", + _ => return Err(backend()), + } + .into(), + }, + _ => return Err(backend()), + }) +} + +fn materialize( + w: &Wire<'_>, + o: &Output, + target: Target, + datalayout: DataLayout, + mut constants: ConstantResults, +) -> Result { + let mut module = Module::new(target.name(), datalayout); + module.declarations.try_reserve_exact(o.declarations.len()).map_err(|_| expansion())?; + for (ordinal, d) in o.declarations.iter().enumerate() { + module.declarations.push(FunctionDecl { + id: FunctionId(u32::try_from(ordinal).map_err(|_| backend())?), + name: name(w, d.name)?.to_owned(), + signature: signature(o, d.signature)?, + linkage: link(d.linkage)?, + link_name: if d.link_name == NONE { + None + } else { + Some(name(w, d.link_name)?.to_owned()) + }, + }); + } + let mut mappings = zeroed::>(w.annotations.len())?; + let mut globals = Vec::new(); + globals.try_reserve_exact(o.globals.len()).map_err(|_| expansion())?; + for (ordinal, g) in o.globals.iter().enumerate() { + let ty = decode_type(o, g.ty, 0)?; + let gid = GlobalId(u32::try_from(ordinal).map_err(|_| backend())?); + let evaluated = constants.remove(&ConstRef::Global(gid)).ok_or_else(backend)?; + if evaluated.root != g.expression { + return Err(backend()); + } + let init_expr = evaluated.expression; + let init = evaluated.value; + module.globals.push(Global { + id: gid, + name: name(w, g.name)?.to_owned(), + ty: ty.clone(), + init: init.clone(), + init_expr, + align: id(g.align)?, + }); + globals.push((ty, init)); + if g.annotation != NONE { + mappings + .get_mut(index(g.annotation)?) + .ok_or_else(backend)? + .push(SourceTarget::Global(gid)); + } + } + let mut visited = zeroed::(o.instructions.len())?; + for (ordinal, f) in o.functions.iter().enumerate() { + let decl = module.declarations.get(index(f.declaration)?).ok_or_else(backend)?; + let raw = w.nodes.get(index(f.source)?).ok_or_else(backend)?; + if raw.tag != 203 || f.param_count != raw.c { + return Err(backend()); + } + let end_values = + o.functions.get(ordinal + 1).map_or(o.value_count as u64, |f| f.first_param); + let end_blocks = f.first_block.checked_add(f.block_count).ok_or_else(backend)?; + let range = + FunctionRange { values: f.first_param, end_values, blocks: f.first_block, end_blocks }; + if end_values < f.first_param + || end_values > o.value_count as u64 + || end_blocks > o.blocks.len() as u64 + { + return Err(backend()); + } + let mut params = Vec::new(); + params.try_reserve_exact(index(f.param_count)?).map_err(|_| expansion())?; + for (ordinal, param) in slice(&w.edges, raw.b, raw.c)?.iter().enumerate() { + let p = w.nodes.get(index(*param)?).ok_or_else(backend)?; + if p.tag != 204 { + return Err(backend()); + } + let v = f.first_param.checked_add(ordinal as u64).ok_or_else(backend)?; + let ty = *o.value_types.get(index(v)?).ok_or_else(backend)?; + params.push(Param { + name: name(w, p.a)?.to_owned(), + id: range.value(v)?, + ty: decode_type(o, ty, 0)?, + }); + } + let mut blocks = Vec::new(); + blocks.try_reserve_exact(index(f.block_count)?).map_err(|_| expansion())?; + for (block_offset, b) in slice(&o.blocks, f.first_block, f.block_count)?.iter().enumerate() + { + let block_id = f.first_block + block_offset as u64; + if b.id != block_id || b.function != ordinal as u64 { + return Err(backend()); + } + let bid = range.block(b.id)?; + let mut instructions = Vec::new(); + instructions.try_reserve_exact(index(b.instruction_count)?).map_err(|_| expansion())?; + let mut next = b.first; + let mut last = NONE; + for instruction_index in 0..index(b.instruction_count)? { + let raw_index = index(next)?; + let record = o.instructions.get(raw_index).ok_or_else(backend)?; + let seen = visited.get_mut(raw_index).ok_or_else(backend)?; + if *seen { + return Err(backend()); + } + *seen = true; + instructions.push(instruction(w, o, record, &range, &globals, &mut constants)?); + if record.annotation != NONE { + mappings.get_mut(index(record.annotation)?).ok_or_else(backend)?.push( + SourceTarget::Instruction { + function: decl.id, + block: bid, + index: instruction_index, + }, + ); + } + last = next; + next = record.next; + } + if next != NONE || last != b.last { + return Err(backend()); + } + let terminator = terminator(o, b, &range)?; + if b.term_annotation != NONE { + mappings + .get_mut(index(b.term_annotation)?) + .ok_or_else(backend)? + .push(SourceTarget::Terminator { function: decl.id, block: bid }); + } + let block_name = match b.name { + 0 => "entry", + 1 => "unreachable.cont", + 2 => "if.then", + 3 => "if.else", + 4 => "if.cont", + 5 => "while.cond", + 6 => "while.body", + 7 => "while.exit", + 8 => "logical.rhs", + 9 => "logical.cont", + _ => return Err(backend()), + }; + blocks.push(BasicBlock { + id: bid, + name: block_name.into(), + instructions, + terminator: Some(terminator), + }); + } + let value_types = slice(&o.value_types, f.first_param, end_values - f.first_param)? + .iter() + .enumerate() + .map(|(offset, ty)| { + Ok((range.value(f.first_param + offset as u64)?, decode_type(o, *ty, 0)?)) + }) + .collect::>()?; + module.functions.push(Function { + id: decl.id, + name: decl.name.clone(), + params, + ret_ty: decl.signature.ret.clone(), + blocks, + entry: range.block(f.entry)?, + value_types, + }); + } + if !constants.is_empty() || visited.iter().any(|seen| !*seen) { + return Err(backend()); + } + let mut files = HashMap::<&str, u32>::new(); + let mut originals = zeroed::(w.annotations.len())?; + for a in &o.source_order { + let index = index(*a)?; + let seen = originals.get_mut(index).ok_or_else(backend)?; + if *seen { + return Err(backend()); + } + *seen = true; + let annotation = w.annotations.get(index).ok_or_else(backend)?; + let span = if let Some(source) = &annotation.source { + let file = if let Some(id) = files.get(source.file.as_str()) { + *id + } else { + let id = u32::try_from(module.sources.files.len()).map_err(|_| backend())?; + module.sources.files.push(SourceFile { id, name: source.file.clone() }); + files.insert(&source.file, id); + id + }; + Some(SourceSpan { + file, + line: source.line, + column: source.column, + end_line: source.end_line, + end_column: source.end_column, + }) + } else { + None + }; + module.sources.originals.push(OriginalNode { id: annotation.id, span }); + } + let mut completed = zeroed::(w.annotations.len())?; + for a in &o.mapping_order { + let at = index(*a)?; + let seen = completed.get_mut(at).ok_or_else(backend)?; + if *seen || !originals.get(at).copied().unwrap_or(false) { + return Err(backend()); + } + *seen = true; + let annotation = w.annotations.get(at).ok_or_else(backend)?; + for target in std::mem::take(mappings.get_mut(at).ok_or_else(backend)?) { + module.sources.mappings.push(SourceMapping { target, original: annotation.id }); + } + } + if mappings.iter().any(|bucket| !bucket.is_empty()) { + return Err(backend()); + } + Ok(module) +} + +// Internal ABI/capacity faults take priority over user arithmetic. For genuine +// later AST failures, completed constant requests retain source evaluation order. +fn check_kernel_status(w: &Wire<'_>, o: &Output) -> Result<(), LowerError> { + if o.result.status == 0 { + return Ok(()); + } + let error = kernel_error(w, o).unwrap_or_else(|error| error); + if matches!(error.root_cause(), LowerError::Backend(_)) { + return Err(error); + } + evaluate_requests(w, o)?; + Err(error) +} + +pub(super) fn lower( + program: &ast::Program, + target: &str, + datalayout: DataLayout, + limits: AstLimits, +) -> Result { + let source_work = super::limits::inspect_program_source_work(program, limits) + .map_err(LowerError::ResourceLimit)?; + let limits = AstLimits { + max_source_work: limits + .max_source_work + .checked_sub(source_work) + .ok_or(LowerError::ResourceLimit(AstLimitError::SourceWork))?, + ..limits + }; + let target = Target::lookup(target).map_err(LowerError::Target)?; + target.validate_layout(datalayout).map_err(LowerError::Target)?; + let mut wire = Wire::new(); + let root = wire.program(program)?; + let counted = execute(&wire, root, target, limits, None)?; + check_kernel_status(&wire, &counted)?; + let counts = (counted.instruction_count, counted.edge_count, counted.value_count); + drop(counted); + let output = execute(&wire, root, target, limits, Some(counts))?; + check_kernel_status(&wire, &output)?; + if (output.instruction_count, output.edge_count, output.value_count) != counts { + return Err(backend()); + } + let constants = evaluate_requests(&wire, &output)?; + materialize(&wire, &output, target, datalayout, constants) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn malformed_backend_records_are_errors_before_any_module_is_returned() { + let program = + ast::Program { + declarations: vec![], + globals: vec![], + functions: vec![ast::Function { + name: "transport".into(), + convention: CallingConvention::Whale, + linkage: Linkage::Internal, + link_name: None, + parameters: vec![], + return_type: ast::TypeRef::Int { bits: 32, signed: true }, + body: vec![ast::Stmt::Located { + annotation: SourceAnnotation { id: 1, source: None }, + statement: Box::new(ast::Stmt::Return(Some(ast::Expr::Lit( + ast::Lit::Int { bits: 32, signed: true, value: "42".into() }, + )))), + }], + }], + }; + let mut wire = Wire::new(); + let root = wire.program(&program).unwrap(); + let target = Target::X86_64WhaleLinux; + let limits = AstLimits::default(); + let probe = execute(&wire, root, target, limits, None).unwrap(); + assert_eq!(probe.result.status, 0); + let output = execute( + &wire, + root, + target, + limits, + Some((probe.instruction_count, probe.edge_count, probe.value_count)), + ) + .unwrap(); + let render = |o: &Output| -> Result { + materialize(&wire, o, target, target.data_layout(), evaluate_requests(&wire, o)?) + }; + assert!(render(&output).is_ok()); + let mut invalid = output.clone(); + invalid.instructions[0].next = 0; + assert!(matches!(render(&invalid), Err(LowerError::Backend(_)))); + let mut invalid = output.clone(); + invalid.instructions[0].ty = NONE; + assert!(matches!(render(&invalid), Err(LowerError::Backend(_)))); + let mut invalid = output.clone(); + invalid.mapping_order.push(invalid.mapping_order[0]); + assert!(matches!(render(&invalid), Err(LowerError::Backend(_)))); + let mut invalid = output.clone(); + let cycle = invalid.types.len() as u64; + invalid.types.push(RawType { kind: 17, child: cycle, ..RawType::default() }); + invalid.instructions[0].ty = cycle; + assert!(matches!(render(&invalid), Err(LowerError::Backend(_)))); + + // A completed user arithmetic prefix cannot disguise a backend fault. + // Real later AST errors still preserve that prefix's evaluation order. + let mut arithmetic = program.clone(); + let integer = |value: &str| { + ast::Expr::Lit(ast::Lit::Int { bits: 32, signed: true, value: value.into() }) + }; + arithmetic.globals.push(ast::GlobalConst { + name: "bad".into(), + ty: ast::TypeRef::Int { bits: 32, signed: true }, + init: ast::Expr::Binary { + left: Box::new(integer("1")), + op: ast::BinOpRef::Div, + right: Box::new(integer("0")), + }, + }); + let mut wire = Wire::new(); + let root = wire.program(&arithmetic).unwrap(); + let complete = execute(&wire, root, target, limits, None).unwrap(); + assert_eq!(complete.result.status, 0); + assert!(matches!( + evaluate_requests(&wire, &complete), + Err(LowerError::ConstantEvaluation(ConstEvalError::DivisionByZero)) + )); + for status in [3, 4, 255] { + let mut invalid = complete.clone(); + invalid.result.status = status; + assert!(matches!(check_kernel_status(&wire, &invalid), Err(LowerError::Backend(_)))); + } + let mut invalid = complete.clone(); + invalid.result.status = 7; + invalid.result.node = NONE; + assert!(matches!(check_kernel_status(&wire, &invalid), Err(LowerError::Backend(_)))); + let mut invalid = complete.clone(); + invalid.result.status = 6; + invalid.result.expected = NONE; + assert!(matches!(check_kernel_status(&wire, &invalid), Err(LowerError::Backend(_)))); + for status in [7, 22] { + let mut later = complete.clone(); + later.result.status = status; + assert!(matches!( + check_kernel_status(&wire, &later), + Err(LowerError::ConstantEvaluation(ConstEvalError::DivisionByZero)) + )); + } + } +} diff --git a/ir/src/parser/instruction.rs b/ir/src/parser/instruction.rs index 9a4c36c..7d49e9b 100644 --- a/ir/src/parser/instruction.rs +++ b/ir/src/parser/instruction.rs @@ -3,10 +3,26 @@ use super::{syntax::Parser, ParseError}; use crate::*; -type ParsedInstruction = (Instruction, Option<(ValueId, Type)>); +pub(super) type ParsedInstruction = (Instruction, Option<(ValueId, Type)>); impl Parser<'_> { pub(super) fn instruction(&mut self) -> Result { + #[cfg(all(test, whale_wave_ir))] + if self.reference_types { + return self.instruction_reference(); + } + #[cfg(whale_wave_ir)] + { + self.instruction_wave() + } + #[cfg(not(whale_wave_ir))] + { + self.instruction_reference() + } + } + + #[cfg(any(not(whale_wave_ir), test))] + fn instruction_reference(&mut self) -> Result { let result = if self.peek().starts_with("%v") { let id = self.value()?; self.expect(":")?; @@ -450,6 +466,22 @@ impl Parser<'_> { } pub(super) fn terminator(&mut self) -> Result { + #[cfg(all(test, whale_wave_ir))] + if self.reference_types { + return self.terminator_reference(); + } + #[cfg(whale_wave_ir)] + { + self.terminator_wave() + } + #[cfg(not(whale_wave_ir))] + { + self.terminator_reference() + } + } + + #[cfg(any(not(whale_wave_ir), test))] + fn terminator_reference(&mut self) -> Result { Ok(match self.word()? { "br" => { self.expect("label")?; diff --git a/ir/src/parser/lexer.rs b/ir/src/parser/lexer.rs index f3f40ba..4da7b0f 100644 --- a/ir/src/parser/lexer.rs +++ b/ir/src/parser/lexer.rs @@ -3,19 +3,78 @@ use super::{ParseError, ParseErrorKind, SourceLocation}; use crate::{IrLimits, LimitError, Resource}; -#[derive(Debug)] +#[derive(Debug, PartialEq, Eq)] pub(super) enum Kind<'a> { Word(&'a str), String(String), Mark(&'a str), } -#[derive(Debug)] +#[derive(Debug, PartialEq, Eq)] pub(super) struct Token<'a> { pub kind: Kind<'a>, pub location: SourceLocation, } +#[cfg(all(test, whale_wave_ir))] +mod wave_tests { + use super::*; + + #[test] + fn wave_lexer_matches_reference_on_unicode_escapes_and_generated_tokens() { + let seeds = [ + "module { // comment\n target \"🐋\\u{1f600}\\n\"\n}", + " α β\u{2003}γ\u{0085}δ -> => \"\" ", + "\"escaped \\\" \\\\ \\0 \\t \\r\"", + "a->b a=>b : < > [ ] ( ) { } , =", + ]; + for seed in seeds { + assert_eq!( + lex(seed, IrLimits::default()).unwrap(), + lex_reference(seed, IrLimits::default()).unwrap() + ); + } + for malformed in [ + "\"unterminated", + "\"\\", + "\"\\q\"", + "\"\\u123\"", + "\"\\u{}\"", + "\"\\u{1234567}\"", + "\"\\u{d800}\"", + "\"\\u{110000}\"", + "\"\n\"", + ] { + let wave = lex(malformed, IrLimits::default()).unwrap_err(); + let reference = lex_reference(malformed, IrLimits::default()).unwrap_err(); + assert_eq!(wave.location, reference.location, "{malformed:?}"); + assert_eq!(wave.to_string(), reference.to_string(), "{malformed:?}"); + } + let pieces = + ["a", "b", "=>", "->", "{", "}", "\"a\\u{1F40B}\"", "// note\n", " ", "\n", "\u{2009}"]; + let mut state = 0x4839_0ab3_d541_u64; + for _ in 0..4000 { + let mut text = String::new(); + for _ in 0..40 { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + text.push_str(pieces[(state as usize) % pieces.len()]); + } + let wave = lex(&text, IrLimits::default()); + let reference = lex_reference(&text, IrLimits::default()); + match (wave, reference) { + (Ok(a), Ok(b)) => assert_eq!(a, b, "{text:?}"), + (Err(a), Err(b)) => { + assert_eq!(a.location, b.location, "{text:?}"); + assert_eq!(a.to_string(), b.to_string(), "{text:?}"); + }, + (a, b) => panic!("Wave/reference lexer divergence on {text:?}: {a:?} vs {b:?}"), + } + } + } +} + fn error(location: SourceLocation, message: &str) -> ParseError { ParseError { location, kind: ParseErrorKind::Syntax(message.into()) } } @@ -30,7 +89,18 @@ fn advance(location: &mut SourceLocation, c: char) { } } +#[cfg(whale_wave_ir)] pub(super) fn lex(source: &str, limits: IrLimits) -> Result>, ParseError> { + super::wave_lexer::lex(source, limits) +} + +#[cfg(not(whale_wave_ir))] +pub(super) fn lex(source: &str, limits: IrLimits) -> Result>, ParseError> { + lex_reference(source, limits) +} + +#[cfg_attr(whale_wave_ir, allow(dead_code))] +pub(super) fn lex_reference(source: &str, limits: IrLimits) -> Result>, ParseError> { let mut pos = SourceLocation { byte_offset: 0, line: 1, column: 1 }; if source.len() > limits.max_input_bytes { return Err(ParseError { diff --git a/ir/src/parser/mod.rs b/ir/src/parser/mod.rs index 09a89d4..e4bcb06 100644 --- a/ir/src/parser/mod.rs +++ b/ir/src/parser/mod.rs @@ -4,6 +4,30 @@ mod instruction; mod lexer; +#[cfg(whale_wave_ir)] +mod wave_lexer; + +#[cfg(whale_wave_ir)] +mod wave_header; + +#[cfg(whale_wave_ir)] +mod wave_text; + +#[cfg(whale_wave_ir)] +mod wave_type; + +#[cfg(whale_wave_ir)] +mod wave_literal; + +#[cfg(whale_wave_ir)] +mod wave_expression; + +#[cfg(whale_wave_ir)] +mod wave_module; + +#[cfg(whale_wave_ir)] +mod wave_instruction; + mod syntax; use crate::{IrLimits, LimitError, Module, VerifyError}; @@ -20,6 +44,7 @@ pub enum ParseErrorKind { Syntax(String), ResourceLimit(LimitError), Verification(Box), + Backend(&'static str), } #[derive(Debug)] @@ -35,6 +60,7 @@ impl std::fmt::Display for ParseError { ParseErrorKind::Syntax(s) => f.write_str(s), ParseErrorKind::ResourceLimit(e) => e.fmt(f), ParseErrorKind::Verification(e) => write!(f, "invalid IR: {e:?}"), + ParseErrorKind::Backend(component) => write!(f, "IR Wave backend error: {component}"), } } } diff --git a/ir/src/parser/syntax.rs b/ir/src/parser/syntax.rs index 5c5191c..d9ec294 100644 --- a/ir/src/parser/syntax.rs +++ b/ir/src/parser/syntax.rs @@ -7,21 +7,36 @@ use super::{ use crate::*; pub(super) struct Parser<'a> { - tokens: Vec>, - at: usize, + pub(super) tokens: Vec>, + #[cfg(whale_wave_ir)] + pub(super) raw_tokens: Vec, + #[cfg(whale_wave_ir)] + pub(super) grammar_work: usize, + #[cfg(all(test, whale_wave_ir))] + pub(super) reference_types: bool, + pub(super) at: usize, pub limits: IrLimits, - nodes: usize, + pub(super) nodes: usize, pub(super) format_version: u32, - function_locations: std::collections::HashMap, - declaration_locations: std::collections::HashMap, - global_locations: std::collections::HashMap, - global_constant_locations: std::collections::HashMap, + pub(super) function_locations: std::collections::HashMap, + pub(super) declaration_locations: std::collections::HashMap, + pub(super) global_locations: std::collections::HashMap, + pub(super) global_constant_locations: + std::collections::HashMap, } impl<'a> Parser<'a> { pub fn new(tokens: Vec>, limits: IrLimits) -> Self { + #[cfg(whale_wave_ir)] + let raw_tokens = tokens.iter().map(super::wave_text::RawToken::from).collect(); Self { tokens, + #[cfg(whale_wave_ir)] + raw_tokens, + #[cfg(whale_wave_ir)] + grammar_work: 0, + #[cfg(all(test, whale_wave_ir))] + reference_types: false, at: 0, limits, nodes: 0, @@ -92,6 +107,12 @@ impl<'a> Parser<'a> { } } + #[cfg(whale_wave_ir)] + pub(super) fn backend(&self, component: &'static str) -> ParseError { + ParseError { location: self.location(), kind: ParseErrorKind::Backend(component) } + } + + #[cfg(any(not(whale_wave_ir), test))] pub fn previous_error(&self, message: &str) -> ParseError { ParseError { location: self.tokens[self.at.saturating_sub(1)].location, @@ -110,6 +131,7 @@ impl<'a> Parser<'a> { } } + #[cfg(any(not(whale_wave_ir), test))] pub fn node(&mut self) -> Result<(), ParseError> { if self.nodes >= self.limits.max_nodes { return Err(self.limit(Resource::Nodes, self.limits.max_nodes)); @@ -129,6 +151,7 @@ impl<'a> Parser<'a> { self.peek() == "" } + #[cfg(any(not(whale_wave_ir), test))] pub fn eat(&mut self, s: &str) -> bool { if self.peek() == s { self.at += 1; @@ -138,6 +161,7 @@ impl<'a> Parser<'a> { } } + #[cfg(any(not(whale_wave_ir), test))] pub fn expect(&mut self, s: &str) -> Result<(), ParseError> { if self.eat(s) { Ok(()) @@ -146,6 +170,7 @@ impl<'a> Parser<'a> { } } + #[cfg(any(not(whale_wave_ir), test))] pub fn word(&mut self) -> Result<&'a str, ParseError> { match self.tokens[self.at].kind { Kind::Word(s) => { @@ -156,6 +181,7 @@ impl<'a> Parser<'a> { } } + #[cfg(any(not(whale_wave_ir), test))] pub fn string(&mut self) -> Result { match &mut self.tokens[self.at].kind { Kind::String(s) => { @@ -167,6 +193,7 @@ impl<'a> Parser<'a> { } } + #[cfg(any(not(whale_wave_ir), test))] pub fn number(&mut self) -> Result { let s = self.peek(); if s.is_empty() || !s.bytes().all(|b| b.is_ascii_digit()) { @@ -177,6 +204,7 @@ impl<'a> Parser<'a> { Ok(value) } + #[cfg(any(not(whale_wave_ir), test))] pub fn id(&mut self, prefix: &str) -> Result { let s = self .peek() @@ -190,24 +218,29 @@ impl<'a> Parser<'a> { Ok(id) } + #[cfg(any(not(whale_wave_ir), test))] pub fn value(&mut self) -> Result { self.id("%v").map(ValueId) } + #[cfg(any(not(whale_wave_ir), test))] pub fn block_id(&mut self) -> Result { self.id("%b").map(BlockId) } + #[cfg(any(not(whale_wave_ir), test))] pub fn comma(&mut self) -> Result<(), ParseError> { self.expect(",") } + #[cfg(any(not(whale_wave_ir), test))] pub fn align(&mut self) -> Result { self.comma()?; self.expect("align")?; self.number() } + #[cfg(any(not(whale_wave_ir), test))] pub fn convention(&mut self) -> Result { match self.word()? { "whale" => Ok(CallingConvention::Whale), @@ -216,6 +249,7 @@ impl<'a> Parser<'a> { } } + #[cfg(any(not(whale_wave_ir), test))] pub fn signature(&mut self, depth: usize) -> Result { let convention = self.convention()?; self.expect("(")?; @@ -225,6 +259,7 @@ impl<'a> Parser<'a> { Ok(FunctionSignature { params, ret, convention, variadic: false }) } + #[cfg(any(not(whale_wave_ir), test))] fn types(&mut self, end: &str, depth: usize) -> Result, ParseError> { let mut types = Vec::new(); if !self.eat(end) { @@ -240,6 +275,34 @@ impl<'a> Parser<'a> { } pub fn ty(&mut self, depth: usize) -> Result { + #[cfg(all(test, whale_wave_ir))] + if self.reference_types { + return self.ty_reference(depth); + } + #[cfg(whale_wave_ir)] + { + let parsed = super::wave_type::parse( + &self.tokens, + &self.raw_tokens, + super::wave_type::Options { + start: self.at, + depth, + limits: self.limits, + remaining_nodes: self.limits.max_nodes.saturating_sub(self.nodes), + remaining_work: self.limits.max_analysis_work.saturating_sub(self.grammar_work), + }, + )?; + self.at = parsed.next; + self.nodes += parsed.nodes; + self.grammar_work += parsed.work; + Ok(parsed.ty) + } + #[cfg(not(whale_wave_ir))] + self.ty_reference(depth) + } + + #[cfg(any(not(whale_wave_ir), test))] + fn ty_reference(&mut self, depth: usize) -> Result { if depth > self.limits.max_type_depth { return Err(self.limit(Resource::TypeDepth, self.limits.max_type_depth)); } @@ -295,6 +358,29 @@ impl<'a> Parser<'a> { } pub fn literal(&mut self, ty: &Type) -> Result { + #[cfg(whale_wave_ir)] + { + #[cfg(test)] + if self.reference_types { + return self.literal_reference(ty); + } + let (value, work) = super::wave_literal::parse( + self.peek(), + ty, + self.limits.max_analysis_work.saturating_sub(self.grammar_work), + self.limits.max_analysis_work, + ) + .map_err(|kind| ParseError { location: self.location(), kind })?; + self.grammar_work += work; + self.at += 1; + Ok(value) + } + #[cfg(not(whale_wave_ir))] + self.literal_reference(ty) + } + + #[cfg(any(not(whale_wave_ir), test))] + fn literal_reference(&mut self, ty: &Type) -> Result { let s = self.peek(); let value = match ty { Type::Bool => match s { @@ -335,8 +421,29 @@ impl<'a> Parser<'a> { Ok(value) } - pub fn equal_type(&self, left: &Type, right: &Type) -> Result<(), ParseError> { - if left == right { + pub fn equal_type(&mut self, left: &Type, right: &Type) -> Result<(), ParseError> { + #[cfg(whale_wave_ir)] + let equal = { + #[cfg(test)] + if self.reference_types { + return if left == right { + Ok(()) + } else { + Err(self.error("conflicting type annotations")) + }; + } + let (equal, work) = crate::verifier::wave_types_equal( + left, + right, + self.limits.max_analysis_work.saturating_sub(self.grammar_work), + ) + .map_err(|_| self.limit(Resource::AnalysisWork, self.limits.max_analysis_work))?; + self.grammar_work += work; + equal + }; + #[cfg(not(whale_wave_ir))] + let equal = left == right; + if equal { Ok(()) } else { Err(self.error("conflicting type annotations")) @@ -344,6 +451,35 @@ impl<'a> Parser<'a> { } pub fn expression(&mut self, depth: usize) -> Result { + #[cfg(whale_wave_ir)] + { + #[cfg(test)] + if self.reference_types { + return self.expression_reference(depth); + } + let parsed = super::wave_expression::parse( + &self.tokens, + &self.raw_tokens, + super::wave_expression::Options { + start: self.at, + depth, + format: self.format_version, + limits: self.limits, + remaining_nodes: self.limits.max_nodes.saturating_sub(self.nodes), + remaining_work: self.limits.max_analysis_work.saturating_sub(self.grammar_work), + }, + )?; + self.at = parsed.next; + self.nodes += parsed.nodes; + self.grammar_work += parsed.work; + Ok(parsed.expression) + } + #[cfg(not(whale_wave_ir))] + self.expression_reference(depth) + } + + #[cfg(any(not(whale_wave_ir), test))] + fn expression_reference(&mut self, depth: usize) -> Result { if depth > self.limits.max_const_depth { return Err(self.limit(Resource::ConstantDepth, self.limits.max_const_depth)); } @@ -458,36 +594,63 @@ impl<'a> Parser<'a> { } pub fn module(&mut self) -> Result { - self.expect("module")?; - self.expect("{")?; - self.expect("format_version")?; - let version: u32 = self.number()?; - if !(3..=IR_FORMAT_VERSION).contains(&version) { - return Err(self.previous_error("unsupported IR format version")); + #[cfg(all(test, whale_wave_ir))] + if self.reference_types { + return self.module_reference(); } - self.format_version = version; - self.expect("semantics_version")?; - let semantics: u32 = self.number()?; - if semantics != SEMANTICS_VERSION { - return Err(self.previous_error("unsupported semantics version")); + #[cfg(whale_wave_ir)] + { + self.module_wave() } - self.expect("target")?; - let target = self.string()?; - self.expect("datalayout")?; - self.expect("{")?; - self.expect("ptr")?; - self.expect("=")?; - let ptr_bits = self.number()?; - self.comma()?; - self.expect("endian")?; - self.expect("=")?; - let endian = match self.word()? { - "little" => Endian::Little, - "big" => Endian::Big, - _ => return Err(self.previous_error("unknown byte order")), + #[cfg(not(whale_wave_ir))] + { + self.module_reference() + } + } + + #[cfg(any(not(whale_wave_ir), test))] + fn module_reference(&mut self) -> Result { + #[cfg(whale_wave_ir)] + let (target, datalayout) = { + let (target, layout, version, next) = super::wave_header::parse(&self.tokens)?; + self.format_version = version; + self.at = next; + (target, layout) + }; + #[cfg(not(whale_wave_ir))] + let (target, datalayout) = { + self.expect("module")?; + self.expect("{")?; + self.expect("format_version")?; + let version: u32 = self.number()?; + if !(3..=IR_FORMAT_VERSION).contains(&version) { + return Err(self.previous_error("unsupported IR format version")); + } + self.format_version = version; + self.expect("semantics_version")?; + let semantics: u32 = self.number()?; + if semantics != SEMANTICS_VERSION { + return Err(self.previous_error("unsupported semantics version")); + } + self.expect("target")?; + let target = self.string()?; + self.expect("datalayout")?; + self.expect("{")?; + self.expect("ptr")?; + self.expect("=")?; + let ptr_bits = self.number()?; + self.comma()?; + self.expect("endian")?; + self.expect("=")?; + let endian = match self.word()? { + "little" => Endian::Little, + "big" => Endian::Big, + _ => return Err(self.previous_error("unknown byte order")), + }; + self.expect("}")?; + (target, DataLayout { ptr_bits, endian }) }; - self.expect("}")?; - let mut module = Module::new(target, DataLayout { ptr_bits, endian }); + let mut module = Module::new(target, datalayout); while !self.eat("}") { self.node()?; match self.word()? { @@ -648,6 +811,7 @@ impl<'a> Parser<'a> { Ok(module) } + #[cfg(any(not(whale_wave_ir), test))] fn function(&mut self) -> Result { let id = FunctionId(self.id("@f")?); let location = self.tokens[self.at].location; diff --git a/ir/src/parser/wave_expression.rs b/ir/src/parser/wave_expression.rs new file mode 100644 index 0000000..ddb89e5 --- /dev/null +++ b/ir/src/parser/wave_expression.rs @@ -0,0 +1,470 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Internal postorder transport for Wave-owned constant-expression parsing. + +use super::{ + lexer::{Kind, Token}, + wave_text::RawToken, + wave_type, ParseError, ParseErrorKind, +}; + +use crate::{ + ConstBinaryOp, ConstCompareOp, ConstExpr, ConstExprKind, ConstRef, ConstValue, FloatBits, + GlobalId, IrLimits, LimitError, Resource, Type, ValueId, +}; + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct Node { + kind: u64, + op: u64, + type_first: u64, + type_count: u64, + low: u64, + high: u64, +} + +#[repr(C)] +#[derive(Default)] +struct RawResult { + status: u64, + reason: u64, + at: u64, + expected: u64, + detail: u64, + next: u64, + expressions: u64, + types: u64, + spent: u64, + work: u64, +} + +unsafe extern "C" { + fn whale_ir_parse_expression( + tokens: *const RawToken, + token_count: u64, + start: u64, + depth: u64, + format: u64, + max_depth: u64, + max_type_depth: u64, + max_nodes: u64, + max_work: u64, + mode: u64, + type_scratch: *mut wave_type::Node, + type_capacity: u64, + expression_scratch: *mut Node, + expression_capacity: u64, + output_types: *mut wave_type::Node, + output_type_capacity: u64, + output_expressions: *mut Node, + output_expression_capacity: u64, + result: *mut RawResult, + ) -> i32; +} + +pub(super) struct Options { + pub start: usize, + pub depth: usize, + pub format: u32, + pub limits: IrLimits, + pub remaining_nodes: usize, + pub remaining_work: usize, +} + +pub(super) struct Parsed { + pub expression: ConstExpr, + pub next: usize, + pub nodes: usize, + pub work: usize, +} + +fn error(tokens: &[Token<'_>], r: &RawResult, options: &Options) -> ParseError { + let index = usize::try_from(r.at).unwrap_or(usize::MAX).min(tokens.len() - 1); + let resource = |resource, limit| ParseErrorKind::ResourceLimit(LimitError { resource, limit }); + let syntax = |message: &str| ParseErrorKind::Syntax(message.into()); + let found = match &tokens[index].kind { + Kind::Word(s) | Kind::Mark(s) => *s, + Kind::String(_) => "", + }; + let expected_token = + |expected: &str| ParseErrorKind::Syntax(format!("expected '{expected}', found '{found}'")); + let kind = match r.status { + 1 if (1..=5).contains(&r.reason) && (r.reason != 1 || (20..=22).contains(&r.expected)) => { + match r.reason { + 1 => expected_token(match r.expected { + 20 => "(", + 21 => ")", + 22 => ",", + _ => "?", + }), + 2 => syntax("extended constant operators require typed IR format 5"), + 3 => syntax("constant neg requires typed IR format 8"), + 4 => syntax("invalid numeric ID"), + 5 => syntax("ID out of range"), + _ => ParseErrorKind::Backend("expression parser transport"), + } + }, + 2 => resource(Resource::ConstantDepth, options.limits.max_const_depth), + 3 => resource(Resource::Nodes, options.limits.max_nodes), + 4 => resource(Resource::AnalysisWork, options.limits.max_analysis_work), + 7 => match r.reason { + 1 if (1..=6).contains(&r.expected) + && (r.expected != 1 || (24..=31).contains(&r.detail)) => + { + match r.expected { + 1 => expected_token(match r.detail { + 24 => "<", + 25 => ">", + 26 => "{", + 27 => "}", + 28 => "(", + 29 => ")", + 30 => "->", + 31 => ",", + _ => "?", + }), + 2 => syntax("expected unsigned decimal integer"), + 3 => syntax("integer out of range"), + 4 => syntax("expected word"), + 5 => syntax("unknown type"), + 6 => syntax("unknown calling convention"), + _ => ParseErrorKind::Backend("expression parser transport"), + } + }, + 2 => resource(Resource::TypeDepth, options.limits.max_type_depth), + 3 => resource(Resource::Nodes, options.limits.max_nodes), + 4 => resource(Resource::AnalysisWork, options.limits.max_analysis_work), + _ => ParseErrorKind::Backend("expression parser transport"), + }, + 8 => match r.reason { + 1 => syntax("expected boolean literal"), + 2 => syntax("expected signed decimal literal"), + 3 => syntax("signed literal out of range"), + 4 => syntax("expected unsigned decimal literal"), + 5 => syntax("unsigned literal out of range"), + 6 => syntax("float value must start with 0x"), + 7 if matches!(r.expected, 16 | 32 | 64) => syntax(&format!( + "f{} requires exactly {} hexadecimal digits", + r.expected, + r.expected / 4 + )), + 8 => syntax("type has no scalar literal"), + 9 => syntax("literal outside type range"), + 10 => resource(Resource::AnalysisWork, options.limits.max_analysis_work), + _ => ParseErrorKind::Backend("expression parser transport"), + }, + _ => ParseErrorKind::Backend("expression parser transport"), + }; + ParseError { location: tokens[index].location, kind } +} + +fn decode(types: &[wave_type::Node], nodes: &[Node]) -> Option { + let mut stack: Vec = Vec::new(); + stack.try_reserve_exact(nodes.len()).ok()?; + for n in nodes { + let first = usize::try_from(n.type_first).ok()?; + let count = usize::try_from(n.type_count).ok()?; + let ty = wave_type::decode(types.get(first..first.checked_add(count)?)?)?; + let kind = match n.kind { + 0 => { + let bits = (u128::from(n.high) << 64) | u128::from(n.low); + ConstExprKind::Literal(match &ty { + Type::Bool if n.low <= 1 && n.high == 0 => ConstValue::Bool(n.low != 0), + Type::I1 | Type::I8 | Type::I16 | Type::I32 | Type::I64 | Type::I128 => { + ConstValue::I(bits as i128) + }, + Type::U1 | Type::U8 | Type::U16 | Type::U32 | Type::U64 | Type::U128 => { + ConstValue::U(bits) + }, + Type::F16 if n.low <= u16::MAX.into() && n.high == 0 => { + ConstValue::F(FloatBits::F16(n.low as u16)) + }, + Type::F32 if n.low <= u32::MAX.into() && n.high == 0 => { + ConstValue::F(FloatBits::F32(n.low as u32)) + }, + Type::F64 if n.high == 0 => ConstValue::F(FloatBits::F64(n.low)), + _ => return None, + }) + }, + 1 | 2 => { + let id = u32::try_from(n.op).ok()?; + ConstExprKind::Reference(if n.kind == 1 { + ConstRef::Global(GlobalId(id)) + } else { + ConstRef::Local(ValueId(id)) + }) + }, + 3 => ConstExprKind::Not(Box::new(stack.pop()?)), + 4 => ConstExprKind::Neg(Box::new(stack.pop()?)), + 5 => { + let right = Box::new(stack.pop()?); + let left = Box::new(stack.pop()?); + let op = match n.op { + 0 => ConstBinaryOp::Add, + 1 => ConstBinaryOp::Sub, + 2 => ConstBinaryOp::Mul, + 3 => ConstBinaryOp::BitAnd, + 4 => ConstBinaryOp::BitOr, + 5 => ConstBinaryOp::BitXor, + 6 => ConstBinaryOp::Div, + 7 => ConstBinaryOp::Rem, + 8 => ConstBinaryOp::ShiftLeft, + 9 => ConstBinaryOp::ShiftRight, + 10 => ConstBinaryOp::LogicalAnd, + 11 => ConstBinaryOp::LogicalOr, + _ => return None, + }; + ConstExprKind::Binary { op, left, right } + }, + 6 => { + let right = Box::new(stack.pop()?); + let left = Box::new(stack.pop()?); + let op = match n.op { + 0 => ConstCompareOp::Eq, + 1 => ConstCompareOp::Ne, + 2 => ConstCompareOp::Lt, + 3 => ConstCompareOp::Le, + 4 => ConstCompareOp::Gt, + 5 => ConstCompareOp::Ge, + _ => return None, + }; + ConstExprKind::Compare { op, left, right } + }, + _ => return None, + }; + stack.push(ConstExpr { ty, kind }); + } + if stack.len() != 1 { + return None; + } + stack.pop() +} + +pub(super) fn parse( + tokens: &[Token<'_>], + raw: &[RawToken], + options: Options, +) -> Result { + let mut result = RawResult::default(); + let invoke = |mode, + type_scratch: &mut [wave_type::Node], + expression_scratch: &mut [Node], + output_types: &mut [wave_type::Node], + output_expressions: &mut [Node], + result: &mut RawResult| unsafe { + whale_ir_parse_expression( + raw.as_ptr(), + raw.len() as u64, + options.start as u64, + options.depth as u64, + options.format.into(), + options.limits.max_const_depth as u64, + options.limits.max_type_depth as u64, + options.remaining_nodes as u64, + options.remaining_work as u64, + mode, + type_scratch.as_mut_ptr(), + type_scratch.len() as u64, + expression_scratch.as_mut_ptr(), + expression_scratch.len() as u64, + output_types.as_mut_ptr(), + output_types.len() as u64, + output_expressions.as_mut_ptr(), + output_expressions.len() as u64, + result, + ) + }; + let status = invoke(0, &mut [], &mut [], &mut [], &mut [], &mut result); + if status != 0 || result.status != 0 { + return Err(error(tokens, &result, &options)); + } + let expr_count = + usize::try_from(result.expressions).map_err(|_| error(tokens, &result, &options))?; + let type_count = usize::try_from(result.types).map_err(|_| error(tokens, &result, &options))?; + let next = usize::try_from(result.next).map_err(|_| error(tokens, &result, &options))?; + let nodes = usize::try_from(result.spent).map_err(|_| error(tokens, &result, &options))?; + let work = usize::try_from(result.work).map_err(|_| error(tokens, &result, &options))?; + if expr_count == 0 + || type_count == 0 + || expr_count > raw.len() + || type_count > raw.len() + || next <= options.start + || next >= raw.len() + || nodes > options.remaining_nodes + || work > options.remaining_work + { + return Err(error(tokens, &result, &options)); + } + let allocate_types = || -> Result, ParseError> { + let mut v = Vec::new(); + v.try_reserve_exact(type_count).map_err(|_| error(tokens, &result, &options))?; + v.resize(type_count, wave_type::Node::default()); + Ok(v) + }; + let allocate_expressions = || -> Result, ParseError> { + let mut v = Vec::new(); + v.try_reserve_exact(expr_count).map_err(|_| error(tokens, &result, &options))?; + v.resize(expr_count, Node::default()); + Ok(v) + }; + let mut type_scratch = allocate_types()?; + let mut types = allocate_types()?; + let mut expr_scratch = allocate_expressions()?; + let mut expressions = allocate_expressions()?; + let status = + invoke(1, &mut type_scratch, &mut expr_scratch, &mut types, &mut expressions, &mut result); + if status != 0 + || result.status != 0 + || result.expressions != expr_count as u64 + || result.types != type_count as u64 + || result.next != next as u64 + || result.spent != nodes as u64 + || result.work != work as u64 + { + return Err(error(tokens, &result, &options)); + } + let expression = + decode(&types, &expressions).ok_or_else(|| error(tokens, &result, &options))?; + Ok(Parsed { expression, next, nodes, work }) +} + +#[cfg(test)] +mod tests { + use super::*; + + use crate::parser::{lexer, syntax::Parser}; + + fn run( + source: &str, + version: u32, + limits: IrLimits, + reference: bool, + ) -> Result<(ConstExpr, String), ParseError> { + let tokens = if reference { + lexer::lex_reference(source, limits)? + } else { + lexer::lex(source, limits)? + }; + let mut parser = Parser::new(tokens, limits); + parser.reference_types = reference; + parser.format_version = version; + let expression = parser.expression(0)?; + Ok((expression, parser.peek().into())) + } + + fn compare(source: &str, version: u32, limits: IrLimits) { + match (run(source, version, limits, false), run(source, version, limits, true)) { + (Ok(a), Ok(b)) => assert_eq!(a, b, "v{version} {source:?}"), + (Err(a), Err(b)) => { + assert_eq!(a.location, b.location, "v{version} {source:?}"); + assert_eq!(a.to_string(), b.to_string(), "v{version} {source:?}"); + }, + (a, b) => { + panic!("Wave/reference expression divergence v{version} {source:?}: {a:?} / {b:?}") + }, + } + } + + fn random(state: &mut u64) -> u64 { + *state ^= *state << 13; + *state ^= *state >> 7; + *state ^= *state << 17; + *state + } + + fn generated(state: &mut u64, depth: usize) -> String { + let choice = random(state) % if depth == 0 { 8 } else { 28 }; + match choice { + 0 => format!("i128 {}", random(state) as i64), + 1 => format!("u128 {}", random(state)), + 2 => format!("i32 @g{}", random(state) as u32), + 3 => format!("tuple> %v{}", random(state) as u32), + 4 => format!("f64 0x{:016x}", random(state)), + 5 => format!("f32 0x{:08x}", random(state) as u32), + 6 => format!("f16 0x{:04x}", random(state) as u16), + 7 => if random(state) & 1 == 0 { "bool true" } else { "bool false" }.into(), + 8 | 9 => format!( + "{}({})", + if choice == 8 { "bit_not" } else { "neg" }, + generated(state, depth - 1) + ), + _ => { + const OPS: [&str; 18] = [ + "add", + "sub", + "mul", + "bit_and", + "bit_or", + "bit_xor", + "div", + "rem", + "shift_left", + "shift_right", + "logical_and", + "logical_or", + "eq", + "ne", + "lt", + "le", + "gt", + "ge", + ]; + format!( + "{}({}, {})", + OPS[(choice - 10) as usize], + generated(state, depth - 1), + generated(state, depth - 1) + ) + }, + } + } + + #[test] + fn wave_expression_grammar_matches_reference_and_preserves_diagnostics() { + for seed in [ + "add(i32 1, i32 2)", + "neg(bit_not(i128 -170141183460469231731687303715884105728))", + "logical_and(eq(u8 1, u8 1), bool false)", + "ptr @g12", + "fnptr void> %v2", + "i32 @g4294967296", + "i32 @g4294967296x", + "i32 @g", + "i32 %v", + "i32 %v-1", + "array @g0", + "i128 170141183460469231731687303715884105728", + "u128 340282366920938463463374607431768211456x", + "f32 0xGGGGGGGG", + "bool \"true\"", + "i32 \"1\"", + "struct{} 0", + "bit_not(i32 1", + "add(i32 1 i32 2)", + "neg(i32)", + "", + "🐋", + ] { + for version in 3..=8 { + compare(seed, version, IrLimits::default()); + } + for (end, _) in seed.char_indices() { + compare(&seed[..end], 8, IrLimits::default()); + } + for max_nodes in 0..12 { + compare(seed, 8, IrLimits { max_nodes, ..IrLimits::default() }); + } + for max_const_depth in 0..4 { + compare(seed, 8, IrLimits { max_const_depth, ..IrLimits::default() }); + } + } + let mut state = 0x349_351_u64; + for _ in 0..10000 { + let source = generated(&mut state, 5); + compare(&source, 8, IrLimits::default()); + compare(&source, 3 + (random(&mut state) % 6) as u32, IrLimits::default()); + let end = random(&mut state) as usize % source.len(); + compare(&source[..end], 8, IrLimits::default()); + } + } +} diff --git a/ir/src/parser/wave_header.rs b/ir/src/parser/wave_header.rs new file mode 100644 index 0000000..dd61edf --- /dev/null +++ b/ir/src/parser/wave_header.rs @@ -0,0 +1,232 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Borrowed bridge for the Wave-owned versioned IR header parser. + +use super::{lexer::Kind, lexer::Token, wave_text::RawToken, ParseError, ParseErrorKind}; + +use crate::{DataLayout, Endian, IR_FORMAT_VERSION, SEMANTICS_VERSION}; + +#[repr(C)] +#[derive(Default)] +struct RawResult { + status: u64, + at: u64, + expected: u64, + version: u64, + ptr_bits: u64, + endian: u64, + target_index: u64, + next: u64, +} + +unsafe extern "C" { + fn whale_ir_header( + tokens: *const RawToken, + count: u64, + max_format: u64, + semantics: u64, + result: *mut RawResult, + ) -> i32; +} + +const EXPECTED: [&str; 18] = [ + "module", + "{", + "format_version", + "", + "semantics_version", + "", + "target", + "", + "datalayout", + "{", + "ptr", + "=", + "", + ",", + "endian", + "=", + "", + "}", +]; + +pub(super) fn parse(tokens: &[Token<'_>]) -> Result<(String, DataLayout, u32, usize), ParseError> { + let raw: Vec<_> = tokens.iter().take(18).map(RawToken::from).collect(); + let mut result = RawResult::default(); + let status = unsafe { + whale_ir_header( + raw.as_ptr(), + raw.len() as u64, + IR_FORMAT_VERSION.into(), + SEMANTICS_VERSION.into(), + &mut result, + ) + }; + if status != 0 || result.status != 0 { + let index = usize::try_from(result.at).unwrap_or(usize::MAX).min(tokens.len() - 1); + if !matches!(result.status, 1..=7 | 9) + || (result.status == 1 + && EXPECTED.get(result.expected as usize).is_none_or(|word| word.is_empty())) + { + return Err(ParseError { + location: tokens[index].location, + kind: ParseErrorKind::Backend("header transport"), + }); + } + let found = match &tokens[index].kind { + Kind::Word(s) | Kind::Mark(s) => *s, + Kind::String(_) => "", + }; + let message = match result.status { + 1 => { + let expected = EXPECTED.get(result.expected as usize).copied().unwrap_or("?"); + format!("expected '{expected}', found '{found}'") + }, + 2 => "expected unsigned decimal integer".into(), + 3 => "integer out of range".into(), + 4 => "unsupported IR format version".into(), + 5 => "unsupported semantics version".into(), + 6 => "expected quoted string".into(), + 7 => "unknown byte order".into(), + 9 => "expected word".into(), + _ => "invalid Wave IR header result".into(), + }; + return Err(ParseError { + location: tokens[index].location, + kind: ParseErrorKind::Syntax(message), + }); + } + let target_index = usize::try_from(result.target_index).map_err(|_| ParseError { + location: tokens[0].location, + kind: ParseErrorKind::Backend("header transport"), + })?; + let next = usize::try_from(result.next).map_err(|_| ParseError { + location: tokens[0].location, + kind: ParseErrorKind::Backend("header transport"), + })?; + let Some(Token { kind: Kind::String(target), .. }) = tokens.get(target_index) else { + return Err(ParseError { + location: tokens[0].location, + kind: ParseErrorKind::Backend("header transport"), + }); + }; + if next != 18 + || target_index != 7 + || !(3..=u64::from(IR_FORMAT_VERSION)).contains(&result.version) + || result.ptr_bits > u32::MAX.into() + || result.endian > 1 + { + return Err(ParseError { + location: tokens[0].location, + kind: ParseErrorKind::Backend("header transport"), + }); + } + Ok(( + target.clone(), + DataLayout { + ptr_bits: result.ptr_bits as u32, + endian: if result.endian == 0 { Endian::Little } else { Endian::Big }, + }, + result.version as u32, + next, + )) +} + +#[cfg(test)] +mod tests { + use super::*; + + use crate::IrLimits; + + fn reference(tokens: Vec>) -> Result<(String, DataLayout, u32, usize), ParseError> { + let mut p = super::super::syntax::Parser::new(tokens, IrLimits::default()); + p.expect("module")?; + p.expect("{")?; + p.expect("format_version")?; + let version: u32 = p.number()?; + if !(3..=IR_FORMAT_VERSION).contains(&version) { + return Err(p.previous_error("unsupported IR format version")); + } + p.expect("semantics_version")?; + let semantics: u32 = p.number()?; + if semantics != SEMANTICS_VERSION { + return Err(p.previous_error("unsupported semantics version")); + } + p.expect("target")?; + let target = p.string()?; + p.expect("datalayout")?; + p.expect("{")?; + p.expect("ptr")?; + p.expect("=")?; + let ptr_bits = p.number()?; + p.comma()?; + p.expect("endian")?; + p.expect("=")?; + let endian = match p.word()? { + "little" => Endian::Little, + "big" => Endian::Big, + _ => return Err(p.previous_error("unknown byte order")), + }; + p.expect("}")?; + Ok((target, DataLayout { ptr_bits, endian }, version, 18)) + } + + #[test] + fn wave_header_matches_reference_for_versions_errors_and_truncation() { + let canonical = [ + "module", + "{", + "format_version", + "8", + "semantics_version", + "1", + "target", + "\"🐋\"", + "datalayout", + "{", + "ptr", + "=", + "64", + ",", + "endian", + "=", + "little", + "}", + ]; + let mut cases = Vec::new(); + cases.push(canonical.to_vec()); + for end in 0..canonical.len() { + cases.push(canonical[..end].to_vec()); + } + for index in 0..canonical.len() { + for replacement in ["unexpected", "\"quoted\"", "0", "-1", "4294967296", "4294967296x"] + { + let mut words = canonical.to_vec(); + words[index] = replacement; + cases.push(words); + } + } + for (index, replacement) in + [(3, "2"), (3, "3"), (3, "9"), (5, "2"), (12, "32"), (16, "big")] + { + let mut words = canonical.to_vec(); + words[index] = replacement; + cases.push(words); + } + for words in cases { + let source = words.join(" "); + let wave_tokens = super::super::lexer::lex(&source, IrLimits::default()).unwrap(); + let reference_tokens = + super::super::lexer::lex_reference(&source, IrLimits::default()).unwrap(); + match (parse(&wave_tokens), reference(reference_tokens)) { + (Ok(actual), Ok(expected)) => assert_eq!(actual, expected, "{source:?}"), + (Err(actual), Err(expected)) => { + assert_eq!(actual.location, expected.location, "{source:?}"); + assert_eq!(actual.to_string(), expected.to_string(), "{source:?}"); + }, + (actual, expected) => { + panic!("Wave/reference header divergence for {source:?}: {actual:?} / {expected:?}") + }, + } + } + } +} diff --git a/ir/src/parser/wave_instruction.rs b/ir/src/parser/wave_instruction.rs new file mode 100644 index 0000000..71c1251 --- /dev/null +++ b/ir/src/parser/wave_instruction.rs @@ -0,0 +1,990 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Rust materialization of events from the Wave instruction grammar. Production +//! choice, primitive parsing, loops, version gates and result rules stay in Wave. +use super::{ + instruction::ParsedInstruction, + lexer::{Kind, Token}, + syntax::Parser, + wave_text::RawToken, + ParseError, ParseErrorKind, +}; + +use crate::*; + +#[repr(C)] +#[derive(Default)] +struct State { + phase: u64, + at: u64, + format: u64, + mode: u64, + op: u64, + sub: u64, + op_at: u64, + has_dst: u64, + dst: u64, + annotation_kind: u64, + type_kind: u64, + a: u64, + b: u64, + c: u64, + d: u64, + e: u64, + name: u64, + aux: u64, + nodes: u64, + work: u64, +} + +#[repr(C)] +#[derive(Default)] +struct Event { + status: u64, + reason: u64, + at: u64, + expected: u64, + event: u64, + role: u64, + op: u64, + sub: u64, + has_dst: u64, + dst: u64, + a: u64, + b: u64, + c: u64, + d: u64, + e: u64, + name: u64, + aux: u64, + next: u64, + nodes: u64, + work: u64, +} + +unsafe extern "C" { + fn whale_ir_instruction_step( + tokens: *const RawToken, + count: u64, + state: *mut State, + max_nodes: u64, + max_work: u64, + result: *mut Event, + ) -> i32; +} + +const WORDS: &[&str] = &[ + ":", + "=", + ",", + "[", + "]", + "(", + ")", + "<", + ">", + "bool", + "ptr", + "u8", + "u64", + "align", + "label", + "reason", + "to", + "=>", + "indirect", + "whale", + "sysv64", + "global_addr", + "lifetime_end", + "ptrdiff", + "const_decl", + "const", + "undef", + "mov", + "neg", + "not", + "cmp", + "icmp", + "fcmp", + "select", + "phi", + "extract", + "alloca", + "volatile_load", + "volatile_store", + "load", + "uninit", + "store", + "gep", + "memcpy", + "memset", + "null_function", + "function_addr", + "call", + "trap_if", + "br", + "cbr", + "switch", + "ret", + "trap", + "add", + "sub", + "mul", + "udiv", + "sdiv", + "urem", + "srem", + "fadd", + "fsub", + "fmul", + "fdiv", + "frem", + "and", + "or", + "xor", + "shl", + "lshr", + "ashr", + "checked_int", + "zext", + "sext", + "trunc", + "fext", + "ftrunc", + "itof_s", + "itof_u", + "ftoi_s", + "ftoi_u", + "bitcast", + "ptrtoint", + "inttoptr", + "uadd_chk", + "usub_chk", + "umul_chk", + "sadd_chk", + "ssub_chk", + "smul_chk", + "eq", + "ne", + "slt", + "sle", + "sgt", + "sge", + "ult", + "ule", + "ugt", + "uge", + "feq", + "fne", + "flt", + "fle", + "fgt", + "fge", + "oeq", + "one", + "olt", + "ole", + "ogt", + "oge", + "ord", + "uno", + "ueq", + "une", +]; + +fn type_kind(ty: &Type) -> u64 { + match ty { + Type::Void => 0, + Type::Bool => 1, + Type::I1 => 2, + Type::U1 => 3, + Type::I8 => 4, + Type::I16 => 5, + Type::I32 => 6, + Type::I64 => 7, + Type::I128 => 8, + Type::U8 => 9, + Type::U16 => 10, + Type::U32 => 11, + Type::U64 => 12, + Type::U128 => 13, + Type::F16 => 14, + Type::F32 => 15, + Type::F64 => 16, + Type::Ptr(_) => 17, + Type::FnPtr(_) => 18, + Type::Array(..) => 19, + Type::Struct(_) => 20, + Type::Tuple(_) => 21, + } +} + +fn error(tokens: &[Token<'_>], event: &Event, limits: IrLimits) -> ParseError { + let index = (event.at as usize).min(tokens.len() - 1); + let found = match &tokens[index].kind { + Kind::Word(s) | Kind::Mark(s) => *s, + Kind::String(_) => "", + }; + if event.at as usize >= tokens.len() + || (event.status == 1 && event.reason == 1 && event.expected as usize >= WORDS.len()) + || (event.status == 1 && event.reason == 6 && event.expected >= 4) + { + return ParseError { + location: tokens[index].location, + kind: ParseErrorKind::Backend("instruction parser"), + }; + } + let kind = match event.status { + 3 => ParseErrorKind::ResourceLimit(LimitError { + resource: Resource::Nodes, + limit: limits.max_nodes, + }), + 4 => ParseErrorKind::ResourceLimit(LimitError { + resource: Resource::AnalysisWork, + limit: limits.max_analysis_work, + }), + 1 if (1..=25).contains(&event.reason) => ParseErrorKind::Syntax(match event.reason { + 1 => format!( + "expected '{}', found '{found}'", + WORDS.get(event.expected as usize).unwrap_or(&"?") + ), + 2 => "expected word".into(), + 3 => "expected quoted string".into(), + 4 => "expected unsigned decimal integer".into(), + 5 => "integer out of range".into(), + 6 => format!( + "expected {} ID", + ["%v", "%b", "@g", "@f"].get(event.expected as usize).unwrap_or(&"?") + ), + 7 => "invalid numeric ID".into(), + 8 => "ID out of range".into(), + 9 => "instruction requires a result".into(), + 10 => "global_addr requires a data-pointer result".into(), + 11 => "global/lifetime/pointer operations require typed IR format 6".into(), + 12 => "neg requires typed IR format 8".into(), + 13 => "pointer ordering requires typed IR format 6".into(), + 14 => "unknown comparison predicate".into(), + 15 => "unknown integer predicate".into(), + 16 => "unknown float predicate".into(), + 17 => "checked_int requires typed IR format 8".into(), + 18 => "uninit requires typed IR format 4".into(), + 19 => "volatile accesses require typed IR format 8".into(), + 20 => "load requires a result".into(), + 21 => "function address requires fnptr type".into(), + 22 => "unknown calling convention".into(), + 23 => "unknown instruction".into(), + 24 => "incorrect result presence".into(), + 25 => "unknown terminator".into(), + _ => "invalid Wave IR instruction result".into(), + }), + _ => ParseErrorKind::Backend("instruction parser"), + }; + ParseError { location: tokens[index].location, kind } +} + +fn bin(sub: u64) -> Option { + Some(match sub { + 0 => BinOp::Add, + 1 => BinOp::Sub, + 2 => BinOp::Mul, + 3 => BinOp::UDiv, + 4 => BinOp::SDiv, + 5 => BinOp::URem, + 6 => BinOp::SRem, + 7 => BinOp::FAdd, + 8 => BinOp::FSub, + 9 => BinOp::FMul, + 10 => BinOp::FDiv, + 11 => BinOp::FRem, + 12 => BinOp::And, + 13 => BinOp::Or, + 14 => BinOp::Xor, + 15 => BinOp::Shl, + 16 => BinOp::LShr, + 17 => BinOp::AShr, + _ => return None, + }) +} + +fn cast(sub: u64) -> Option { + Some(match sub { + 0 => CastOp::CheckedInt, + 1 => CastOp::ZExt, + 2 => CastOp::SExt, + 3 => CastOp::Trunc, + 4 => CastOp::FExt, + 5 => CastOp::FTrunc, + 6 => CastOp::IToF_S, + 7 => CastOp::IToF_U, + 8 => CastOp::FToI_S, + 9 => CastOp::FToI_U, + 10 => CastOp::Bitcast, + 11 => CastOp::PtrToInt, + 12 => CastOp::IntToPtr, + _ => return None, + }) +} + +fn cmp(sub: u64) -> Option { + Some(match sub { + 0 => CmpOp::Eq, + 1 => CmpOp::Ne, + 2 => CmpOp::SLt, + 3 => CmpOp::SLe, + 4 => CmpOp::SGt, + 5 => CmpOp::SGe, + 6 => CmpOp::ULt, + 7 => CmpOp::ULe, + 8 => CmpOp::UGt, + 9 => CmpOp::UGe, + 10 => CmpOp::FEq, + 11 => CmpOp::FNe, + 12 => CmpOp::FLt, + 13 => CmpOp::FLe, + 14 => CmpOp::FGt, + 15 => CmpOp::FGe, + _ => return None, + }) +} + +fn icmp(sub: u64) -> Option { + Some(match sub { + 0 => ICmpPred::Eq, + 1 => ICmpPred::Ne, + 2 => ICmpPred::Ult, + 3 => ICmpPred::Ule, + 4 => ICmpPred::Ugt, + 5 => ICmpPred::Uge, + 6 => ICmpPred::Slt, + 7 => ICmpPred::Sle, + 8 => ICmpPred::Sgt, + 9 => ICmpPred::Sge, + _ => return None, + }) +} + +fn fcmp(sub: u64) -> Option { + Some(match sub { + 0 => FCmpPred::Oeq, + 1 => FCmpPred::One, + 2 => FCmpPred::Olt, + 3 => FCmpPred::Ole, + 4 => FCmpPred::Ogt, + 5 => FCmpPred::Oge, + 6 => FCmpPred::Ord, + 7 => FCmpPred::Uno, + 8 => FCmpPred::Ueq, + 9 => FCmpPred::Une, + 10 => FCmpPred::Ult, + 11 => FCmpPred::Ule, + 12 => FCmpPred::Ugt, + 13 => FCmpPred::Uge, + _ => return None, + }) +} + +fn checked(sub: u64) -> Option { + Some(match sub { + 0 => CheckedOp::UAdd, + 1 => CheckedOp::USub, + 2 => CheckedOp::UMul, + 3 => CheckedOp::SAdd, + 4 => CheckedOp::SSub, + 5 => CheckedOp::SMul, + _ => return None, + }) +} + +struct Materialization { + types: [Option; 3], + literal: Option, + expression: Option, + incomings: Vec<(ValueId, BlockId)>, + values: Vec, + cases: Vec<(ConstValue, BlockId)>, +} + +impl Materialization { + fn new() -> Self { + Self { + types: [None, None, None], + literal: None, + expression: None, + incomings: Vec::new(), + values: Vec::new(), + cases: Vec::new(), + } + } +} + +enum Body { + Instruction(ParsedInstruction), + Terminator(Terminator), +} + +impl Parser<'_> { + fn instruction_backend(&self) -> ParseError { + ParseError { + location: self.location(), + kind: ParseErrorKind::Backend("instruction parser"), + } + } + + fn instruction_string(&mut self, index: u64) -> Result { + match self.tokens.get_mut(index as usize).map(|token| &mut token.kind) { + Some(Kind::String(value)) => Ok(std::mem::take(value)), + _ => Err(self.instruction_backend()), + } + } + + fn instruction_equal(&mut self, role: u64, values: &Materialization) -> Result<(), ParseError> { + let location = self.location(); + let invalid = + || ParseError { location, kind: ParseErrorKind::Backend("instruction parser") }; + let annotation = || values.types[0].as_ref().ok_or_else(invalid); + let primary = || values.types[1].as_ref().ok_or_else(invalid); + let secondary = || values.types[2].as_ref().ok_or_else(invalid); + match role { + 0 => self.equal_type(annotation()?, primary()?), + 1 => self.equal_type(annotation()?, &Type::Bool), + 2 => self.equal_type(annotation()?, &Type::I128), + 3 => self.equal_type(annotation()?, &Type::ptr_to(primary()?.clone())), + 4 => self.equal_type(annotation()?, &Type::Tuple(vec![primary()?.clone(), Type::Bool])), + 5 => self.equal_type(annotation()?, secondary()?), + 6 => self.equal_type(primary()?, secondary()?), + 7 => self.equal_type(&Type::ptr_to(primary()?.clone()), secondary()?), + 8 => self.equal_type(primary()?, &values.expression.as_ref().ok_or_else(invalid)?.ty), + 9 => { + self.equal_type(annotation()?, &values.expression.as_ref().ok_or_else(invalid)?.ty) + }, + _ => Err(invalid()), + } + } + + fn instruction_materialize( + &mut self, + event: &Event, + mut m: Materialization, + ) -> Result { + let location = self.location(); + let invalid = + || ParseError { location, kind: ParseErrorKind::Backend("instruction parser") }; + if event.has_dst > 1 || (event.op == 29 && (event.sub > 1 || event.e > 1)) { + return Err(invalid()); + } + let a = u32::try_from(event.a).map_err(|_| invalid())?; + let b = u32::try_from(event.b).map_err(|_| invalid())?; + let c = u32::try_from(event.c).map_err(|_| invalid())?; + let d = u32::try_from(event.d).map_err(|_| invalid())?; + let dst = ValueId(u32::try_from(event.dst).map_err(|_| invalid())?); + if event.op >= 31 { + return Ok(Body::Terminator(match event.op { + 31 => Terminator::Br { target: BlockId(a) }, + 32 => { + Terminator::CBr { cond: ValueId(a), then_bb: BlockId(b), else_bb: BlockId(c) } + }, + 33 => Terminator::Switch { + ty: m.types[1].take().ok_or_else(invalid)?, + value: ValueId(a), + default_bb: BlockId(b), + cases: m.cases, + }, + 34 => Terminator::Ret { + ty: m.types[1].take().ok_or_else(invalid)?, + value: (event.aux != 0).then_some(ValueId(a)), + }, + 35 => Terminator::Trap { reason: self.instruction_string(event.name)? }, + _ => return Err(invalid()), + })); + } + let instruction = match event.op { + 0 => Instruction::GlobalAddr { + dst, + global: GlobalId(a), + ty: match &m.types[0] { + Some(Type::Ptr(ty)) => (**ty).clone(), + _ => return Err(invalid()), + }, + }, + 1 => Instruction::LifetimeEnd { ptr: ValueId(a) }, + 2 => Instruction::PtrDiff { dst, lhs: ValueId(a), rhs: ValueId(b) }, + 3 => Instruction::ConstDecl { + dst, + name: self.instruction_string(event.name)?, + expression: m.expression.take().ok_or_else(invalid)?, + value: m.literal.take().ok_or_else(invalid)?, + }, + 4 => Instruction::Const { + dst, + ty: m.types[1].take().ok_or_else(invalid)?, + value: m.literal.take().ok_or_else(invalid)?, + }, + 5 => Instruction::Undef { dst, ty: m.types[1].take().ok_or_else(invalid)? }, + 6 => Instruction::Mov { + dst, + ty: m.types[1].take().ok_or_else(invalid)?, + src: ValueId(a), + }, + 7 => Instruction::Bin { + dst, + op: bin(event.sub).ok_or_else(invalid)?, + ty: m.types[1].take().ok_or_else(invalid)?, + lhs: ValueId(a), + rhs: ValueId(b), + }, + 8 => Instruction::Neg { + dst, + ty: m.types[1].take().ok_or_else(invalid)?, + src: ValueId(a), + }, + 9 => Instruction::Not { + dst, + ty: m.types[1].take().ok_or_else(invalid)?, + src: ValueId(a), + }, + 10 => Instruction::Cmp { + dst, + op: cmp(event.sub).ok_or_else(invalid)?, + ty: m.types[1].take().ok_or_else(invalid)?, + lhs: ValueId(a), + rhs: ValueId(b), + }, + 11 => Instruction::ICmp { + dst, + pred: icmp(event.sub).ok_or_else(invalid)?, + ty: m.types[1].take().ok_or_else(invalid)?, + lhs: ValueId(a), + rhs: ValueId(b), + }, + 12 => Instruction::FCmp { + dst, + pred: fcmp(event.sub).ok_or_else(invalid)?, + ty: m.types[1].take().ok_or_else(invalid)?, + lhs: ValueId(a), + rhs: ValueId(b), + }, + 13 => Instruction::Select { + dst, + ty: m.types[1].take().ok_or_else(invalid)?, + cond: ValueId(a), + on_true: ValueId(b), + on_false: ValueId(c), + }, + 14 => Instruction::Cast { + dst, + op: cast(event.sub).ok_or_else(invalid)?, + dst_ty: m.types[2].take().ok_or_else(invalid)?, + src_ty: m.types[1].take().ok_or_else(invalid)?, + src: ValueId(a), + }, + 15 => Instruction::Phi { + dst, + ty: m.types[1].take().ok_or_else(invalid)?, + incomings: m.incomings, + }, + 16 => Instruction::Extract { + dst, + dst_ty: m.types[0].as_ref().ok_or_else(invalid)?.clone(), + tuple: ValueId(a), + index: d, + }, + 17 => Instruction::Checked { + dst, + op: checked(event.sub).ok_or_else(invalid)?, + ty: m.types[1].take().ok_or_else(invalid)?, + lhs: ValueId(a), + rhs: ValueId(b), + }, + 18 => Instruction::Alloca { dst, ty: m.types[1].take().ok_or_else(invalid)?, align: d }, + 19 => Instruction::VolatileLoad { + dst, + ty: m.types[1].take().ok_or_else(invalid)?, + ptr: ValueId(b), + align: d, + }, + 20 => Instruction::VolatileStore { + ty: m.types[1].take().ok_or_else(invalid)?, + value: ValueId(a), + ptr: ValueId(b), + align: d, + }, + 21 => Instruction::Load { + dst, + ty: m.types[1].take().ok_or_else(invalid)?, + ptr: ValueId(b), + align: d, + }, + 22 => Instruction::Uninit { + ty: m.types[1].take().ok_or_else(invalid)?, + ptr: ValueId(b), + align: d, + }, + 23 => Instruction::Store { + ty: m.types[1].take().ok_or_else(invalid)?, + value: ValueId(a), + ptr: ValueId(b), + align: d, + }, + 24 => Instruction::Gep { + dst, + dst_ty: m.types[0].as_ref().ok_or_else(invalid)?.clone(), + base_ptr: ValueId(a), + indices: m.values, + }, + 25 => Instruction::Memcpy { dst: ValueId(a), src: ValueId(b), n: ValueId(c), align: d }, + 26 => Instruction::Memset { dst: ValueId(a), val: ValueId(b), n: ValueId(c), align: d }, + 27 | 28 => { + let signature = match &m.types[0] { + Some(Type::FnPtr(signature)) => (**signature).clone(), + _ => return Err(invalid()), + }; + if event.op == 27 { + Instruction::NullFunction { dst, signature } + } else { + Instruction::FunctionAddr { dst, function: FunctionId(a), signature } + } + }, + 29 => Instruction::Call { + convention: if event.sub == 0 { + CallingConvention::Whale + } else { + CallingConvention::SysV64 + }, + dst: (event.has_dst != 0).then_some(dst), + ret_ty: m.types[1].take().ok_or_else(invalid)?, + callee: if event.e == 0 { + Callee::Direct(FunctionId(a)) + } else { + Callee::Indirect(ValueId(a)) + }, + args: m.values, + }, + 30 => Instruction::TrapIf { + cond: ValueId(a), + reason: self.instruction_string(event.name)?, + }, + _ => return Err(invalid()), + }; + let result = if event.has_dst == 0 { + None + } else { + Some((dst, m.types[0].take().ok_or_else(invalid)?)) + }; + Ok(Body::Instruction((instruction, result))) + } + + fn instruction_body_wave(&mut self, terminator: bool) -> Result { + let mut state = State { + at: self.at as u64, + format: self.format_version.into(), + mode: u64::from(terminator), + ..State::default() + }; + let mut m = Materialization::new(); + loop { + state.at = self.at as u64; + let nodes = self.limits.max_nodes.saturating_sub(self.nodes); + let work = self.limits.max_analysis_work.saturating_sub(self.grammar_work); + let mut event = Event::default(); + let status = unsafe { + whale_ir_instruction_step( + self.raw_tokens.as_ptr(), + self.raw_tokens.len() as u64, + &mut state, + nodes as u64, + work as u64, + &mut event, + ) + }; + if status != event.status as i32 + || event.nodes > nodes as u64 + || event.work > work as u64 + || event.next >= self.tokens.len() as u64 + { + return Err(self.instruction_backend()); + } + if status != 0 { + return Err(error(&self.tokens, &event, self.limits)); + } + self.at = event.next as usize; + self.nodes += event.nodes as usize; + self.grammar_work += event.work as usize; + match event.event { + 100 if event.role <= 2 => { + let ty = self.ty(0)?; + state.type_kind = type_kind(&ty); + m.types[event.role as usize] = Some(ty); + }, + 101 => { + m.literal = + Some(self.literal( + m.types[1].as_ref().ok_or_else(|| self.instruction_backend())?, + )?) + }, + 102 => m.expression = Some(self.expression(0)?), + 110 => self.instruction_equal(event.role, &m)?, + 200 => m.incomings.push(( + ValueId(u32::try_from(event.a).map_err(|_| self.instruction_backend())?), + BlockId(u32::try_from(event.b).map_err(|_| self.instruction_backend())?), + )), + 201 => m + .values + .push(ValueId(u32::try_from(event.b).map_err(|_| self.instruction_backend())?)), + 202 => m.cases.push(( + m.literal.take().ok_or_else(|| self.instruction_backend())?, + BlockId(u32::try_from(event.c).map_err(|_| self.instruction_backend())?), + )), + 1 => return self.instruction_materialize(&event, m), + _ => return Err(self.instruction_backend()), + } + } + } + + pub(super) fn instruction_wave(&mut self) -> Result { + match self.instruction_body_wave(false)? { + Body::Instruction(result) => Ok(result), + Body::Terminator(_) => Err(self.instruction_backend()), + } + } + + pub(super) fn terminator_wave(&mut self) -> Result { + match self.instruction_body_wave(true)? { + Body::Terminator(result) => Ok(result), + Body::Instruction(_) => Err(self.instruction_backend()), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + use crate::parser::lexer; + + fn parse_case( + text: &str, + format: u32, + terminator: bool, + reference: bool, + limits: IrLimits, + ) -> Result<(String, String, usize), ParseError> { + let tokens = + if reference { lexer::lex_reference(text, limits)? } else { lexer::lex(text, limits)? }; + let mut parser = Parser::new(tokens, limits); + parser.reference_types = reference; + parser.format_version = format; + let parsed = if terminator { + format!("{:?}", parser.terminator()?) + } else { + format!("{:?}", parser.instruction()?) + }; + Ok((parsed, parser.peek().into(), parser.nodes)) + } + + fn compare(text: &str, format: u32, terminator: bool, limits: IrLimits) { + match (parse_case(text, format, terminator, false, limits), + parse_case(text, format, terminator, true, limits)) { + (Ok(actual), Ok(expected)) => assert_eq!(actual, expected, "format{format} {text:?}"), + (Err(actual), Err(expected)) => { + assert_eq!(actual.location, expected.location, "format{format} {text:?}"); + assert_eq!(actual.to_string(), expected.to_string(), "format{format} {text:?}"); + }, + (actual, expected) => panic!("Wave/reference instruction divergence format{format} {text:?}: {actual:?} / {expected:?}"), + } + } + + fn seeds() -> Vec { + let mut cases = vec![ + "%v3: ptr = global_addr @g9", + "lifetime_end %v7", + "%v4: i128 = ptrdiff %v1, %v2", + "%v5: i32 = const_decl \"named λ\" add(i32 1, i32 2) => const i32 3", + "%v2: i32 = const i32 -7", + "%v2: i32 = undef i32", + "%v2: i32 = mov i32 %v1", + "%v2: i32 = neg i32 %v1", + "%v2: i32 = not i32 %v1", + "%v2: i32 = select bool %v1, i32 %v3, i32 %v4", + "%v2: i32 = phi i32", + "%v2: i32 = phi i32 [%v1, %b0], [%v3, %b2]", + "%v4: bool = extract %v2, 1", + "%v2: ptr = alloca i32, align 4", + "%v2: i32 = load i32, ptr %v1, align 4", + "store i32 %v1, ptr %v2, align 4", + "%v2: i32 = volatile_load i32, ptr %v1, align 4", + "volatile_store i32 %v1, ptr %v2, align 4", + "uninit i32, ptr %v1, align 4", + "%v2: ptr = gep %v1, %v3, %v4", + "memcpy ptr %v1, ptr %v2, u64 %v3, align 1", + "memset ptr %v1, u8 %v2, u64 %v3, align 1", + "%v1: fnptr void> = null_function", + "%v1: fnptr void> = function_addr @f9", + "%v2: i32 = call whale i32 @f7(%v1, %v3)", + "call sysv64 void indirect %v1()", + "trap_if bool %v1, reason = \"trap\\nmessage\"", + "%v4294967295: i32 = const i32 0", + "%v2: f32 = const f32 0x7fa00001", + ] + .into_iter() + .map(str::to_owned) + .collect::>(); + for op in + "add sub mul udiv sdiv urem srem fadd fsub fmul fdiv frem and or xor shl lshr ashr" + .split_whitespace() + { + for ty in ["i1", "u1", "i32", "u128", "f16", "f64", "ptr"] { + cases.push(format!("%v2: {ty} = {op} {ty} %v0, %v1")); + } + } + for (op, predicates) in [ + ("cmp", "eq ne slt sle sgt sge ult ule ugt uge feq fne flt fle fgt fge"), + ("icmp", "eq ne ult ule ugt uge slt sle sgt sge"), + ("fcmp", "oeq one olt ole ogt oge ord uno ueq une ult ule ugt uge"), + ] { + for pred in predicates.split_whitespace() { + cases.push(format!("%v2: bool = {op} {pred} i32 %v0, %v1")); + cases.push(format!("%v2: bool = {op} {pred} ptr %v0, %v1")); + } + } + for op in "checked_int zext sext trunc fext ftrunc itof_s itof_u ftoi_s ftoi_u bitcast ptrtoint inttoptr".split_whitespace() { + cases.push(format!("%v2: i64 = {op} i32 %v0 to i64")); + } + for op in "uadd_chk usub_chk umul_chk sadd_chk ssub_chk smul_chk".split_whitespace() { + cases.push(format!("%v2: tuple = {op} i32 %v0, %v1")); + } + cases + } + + #[test] + fn complete_inventory_and_version_gates_match_reference() { + for text in seeds() { + for format in 3..=8 { + compare(&text, format, false, IrLimits::default()); + } + } + for text in [ + "br label %b0", + "cbr bool %v1, label %b0, label %b3", + "switch i32 %v1, label %b0 []", + "switch i32 %v1, label %b0 [1: %b2, -2: %b3]", + "ret void", + "ret i32 %v1", + "trap reason = \"reason\"", + ] { + for format in 3..=8 { + compare(text, format, true, IrLimits::default()); + } + } + } + + #[test] + fn malformed_tokens_and_type_annotations_match_exact_diagnostics() { + for text in [ + "", + "unknown %v1", + "%v0", + "%v0:", + "%v: i32 = const i32 0", + "%v4294967296: i32 = const i32 0", + "const i32 1", + "load i32, ptr %v1, align 4", + "%v2: i64 = const i32 2", + "%v2: i32 = store i32 %v0, ptr %v1, align 4", + "%v2: i32 = global_addr @g0", + "%v2: i32 = function_addr @f0", + "%v2: i32 = phi i32 [%v0, %b1],", + "%v2: ptr = gep %v0,", + "%v2: bool = cmp unknown i32 %v0, %v1", + "%v2: bool = icmp unknown i32 %v0, %v1", + "%v2: bool = fcmp unknown i32 %v0, %v1", + "%v2: bool = cmp unknown ptr %v0, %v1", + "%v2: i32 = select bool %v0, i32 %v1, u32 %v2", + "%v2: i32 = load i32, ptr %v0, align 4", + "%v2: i32 = call mystery i32 @f0()", + "call whale i32 @f0()", + "%v2: i32 = call whale void @f0()", + "call whale void @f0(%v1,)", + "memcpy ptr %v0, ptr %v1, u64 %v2, align 4294967296", + ] { + for format in [3, 5, 6, 8] { + compare(text, format, false, IrLimits::default()); + } + } + for text in [ + "", + "unknown", + "ret", + "ret i32", + "cbr bool %v0, label %b1, label %b", + "switch i32 %v0, label %b0 [1: %b1,]", + "switch i32 %v0, label %b0 [true: %b1]", + "trap reason = not_a_string", + ] { + compare(text, 8, true, IrLimits::default()); + } + } + + #[test] + fn bounded_list_nodes_and_mutations_match_reference() { + let mut random = 0x41b823dd71_u64; + for text in seeds() { + if !text.is_ascii() { + continue; + } + for _ in 0..24 { + random ^= random << 13; + random ^= random >> 7; + random ^= random << 17; + let mut bytes = text.as_bytes().to_vec(); + let index = random as usize % bytes.len(); + if random & 1 == 0 { + bytes.truncate(index); + } else { + bytes[index] = b"[]{} =,:\"%v@f0ab"[(random >> 17) as usize % 16]; + } + compare(std::str::from_utf8(&bytes).unwrap(), 8, false, IrLimits::default()); + } + } + let text = format!( + "%v2: i32 = phi i32 {}", + (0..200).map(|i| format!("[%v{i}, %b{i}]")).collect::>().join(", ") + ); + for nodes in [0, 1, 2, 50, 202, 203, 1000] { + compare(&text, 8, false, IrLimits { max_nodes: nodes, ..IrLimits::default() }); + } + } +} + +#[cfg(test)] +mod protocol_tests { + use super::*; + + use crate::parser::lexer; + + #[test] + fn transport_and_unknown_protocol_statuses_are_backend_faults() { + let tokens = lexer::lex("", IrLimits::default()).unwrap(); + for (status, reason) in [(6, 0), (1, 99), (8, 0)] { + let event = Event { status, reason, ..Event::default() }; + assert!(matches!( + error(&tokens, &event, IrLimits::default()).kind, + ParseErrorKind::Backend("instruction parser") + )); + } + } + + #[test] + fn instruction_grammar_applies_cumulative_work_limits() { + let limits = IrLimits { max_analysis_work: 0, ..IrLimits::default() }; + let tokens = lexer::lex("lifetime_end %v0", limits).unwrap(); + let mut parser = Parser::new(tokens, limits); + parser.format_version = 8; + assert!(matches!( + parser.instruction().unwrap_err().kind, + ParseErrorKind::ResourceLimit(LimitError { + resource: Resource::AnalysisWork, + limit: 0 + }) + )); + } +} diff --git a/ir/src/parser/wave_lexer.rs b/ir/src/parser/wave_lexer.rs new file mode 100644 index 0000000..29c85e5 --- /dev/null +++ b/ir/src/parser/wave_lexer.rs @@ -0,0 +1,206 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Internal borrowed bridge to the Wave IR lexer. Rust owns allocation and +//! parser objects; Wave owns token boundaries, escapes and source positions. + +use super::{ + lexer::{Kind, Token}, + ParseError, ParseErrorKind, SourceLocation, +}; + +use crate::{IrLimits, LimitError, Resource}; + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct RawToken { + kind: u64, + start: u64, + end: u64, + line: u64, + column: u64, + decoded_start: u64, + decoded_len: u64, +} + +#[repr(C)] +#[derive(Default)] +struct RawResult { + status: u64, + reason: u64, + offset: u64, + line: u64, + column: u64, + token_count: u64, + decoded_count: u64, +} + +unsafe extern "C" { + fn whale_ir_lex( + source: *const u8, + length: u64, + max_tokens: u64, + max_work: u64, + mode: u64, + scratch_tokens: *mut RawToken, + token_capacity: u64, + scratch_decoded: *mut u8, + decoded_capacity: u64, + output_tokens: *mut RawToken, + output_token_capacity: u64, + output_decoded: *mut u8, + output_decoded_capacity: u64, + result: *mut RawResult, + ) -> i32; +} + +fn error(result: &RawResult, limits: IrLimits) -> ParseError { + let location = SourceLocation { + byte_offset: result.offset as usize, + line: result.line as usize, + column: result.column as usize, + }; + let kind = match result.status { + 2 => ParseErrorKind::ResourceLimit(LimitError { + resource: Resource::Tokens, + limit: limits.max_tokens, + }), + 3 => ParseErrorKind::ResourceLimit(LimitError { + resource: Resource::InputBytes, + limit: limits.max_input_bytes, + }), + 4 => ParseErrorKind::ResourceLimit(LimitError { + resource: Resource::AnalysisWork, + limit: limits.max_analysis_work, + }), + 1 if (1..=8).contains(&result.reason) => ParseErrorKind::Syntax( + match result.reason { + 2 => "unterminated string", + 3 => "unterminated escape", + 4 => "expected '{' in Unicode escape", + 5 => "invalid Unicode escape", + 6 => "unknown string escape", + 7 => "string control characters must be escaped", + 8 => "invalid Unicode scalar", + _ => "invalid UTF-8 in IR source", + } + .into(), + ), + _ => ParseErrorKind::Backend("lexer transport"), + }; + ParseError { location, kind } +} + +pub(super) fn lex(source: &str, limits: IrLimits) -> Result>, ParseError> { + let start = SourceLocation { byte_offset: 0, line: 1, column: 1 }; + if source.len() > limits.max_input_bytes { + return Err(ParseError { + location: start, + kind: ParseErrorKind::ResourceLimit(LimitError { + resource: Resource::InputBytes, + limit: limits.max_input_bytes, + }), + }); + } + let length = source.len() as u64; + let work = length.saturating_mul(8).saturating_add(32); + let mut result = RawResult::default(); + let status = unsafe { + whale_ir_lex( + source.as_ptr(), + length, + limits.max_tokens as u64, + work, + 0, + std::ptr::null_mut(), + 0, + std::ptr::null_mut(), + 0, + std::ptr::null_mut(), + 0, + std::ptr::null_mut(), + 0, + &mut result, + ) + }; + if status != 0 || result.status != 0 { + return Err(error(&result, limits)); + } + let count = usize::try_from(result.token_count).map_err(|_| error(&result, limits))?; + let decoded_count = + usize::try_from(result.decoded_count).map_err(|_| error(&result, limits))?; + if count == 0 + || count > limits.max_tokens.saturating_add(1) + || count > source.len().saturating_add(1) + || decoded_count > source.len() + { + return Err(error(&result, limits)); + } + let mut scratch = Vec::new(); + let mut output = Vec::new(); + let mut scratch_decoded = Vec::new(); + let mut decoded = Vec::new(); + for tokens in [&mut scratch, &mut output] { + tokens.try_reserve_exact(count).map_err(|_| error(&result, limits))?; + tokens.resize(count, RawToken::default()); + } + for bytes in [&mut scratch_decoded, &mut decoded] { + bytes.try_reserve_exact(decoded_count).map_err(|_| error(&result, limits))?; + bytes.resize(decoded_count, 0); + } + result = RawResult::default(); + let status = unsafe { + whale_ir_lex( + source.as_ptr(), + length, + limits.max_tokens as u64, + work, + 1, + scratch.as_mut_ptr(), + count as u64, + scratch_decoded.as_mut_ptr(), + decoded_count as u64, + output.as_mut_ptr(), + count as u64, + decoded.as_mut_ptr(), + decoded_count as u64, + &mut result, + ) + }; + if status != 0 + || result.status != 0 + || result.token_count != count as u64 + || result.decoded_count != decoded_count as u64 + { + return Err(error(&result, limits)); + } + let mut tokens = Vec::new(); + tokens.try_reserve_exact(count).map_err(|_| error(&result, limits))?; + for raw in output { + let offset = usize::try_from(raw.start).map_err(|_| error(&result, limits))?; + let end = usize::try_from(raw.end).map_err(|_| error(&result, limits))?; + let decoded_start = + usize::try_from(raw.decoded_start).map_err(|_| error(&result, limits))?; + let decoded_len = usize::try_from(raw.decoded_len).map_err(|_| error(&result, limits))?; + let word = source.get(offset..end).ok_or_else(|| error(&result, limits))?; + let kind = match raw.kind { + 0 => Kind::Word(word), + 1 => { + let bytes = decoded + .get(decoded_start..decoded_start.saturating_add(decoded_len)) + .ok_or_else(|| error(&result, limits))?; + Kind::String(String::from_utf8(bytes.to_vec()).map_err(|_| error(&result, limits))?) + }, + 2 => Kind::Mark(word), + 3 if offset == source.len() && end == offset => Kind::Mark(""), + _ => return Err(error(&result, limits)), + }; + tokens.push(Token { + kind, + location: SourceLocation { + byte_offset: offset, + line: raw.line as usize, + column: raw.column as usize, + }, + }); + } + Ok(tokens) +} diff --git a/ir/src/parser/wave_literal.rs b/ir/src/parser/wave_literal.rs new file mode 100644 index 0000000..c591f13 --- /dev/null +++ b/ir/src/parser/wave_literal.rs @@ -0,0 +1,210 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Exact scalar payload transport for Wave text decoding. + +use super::ParseErrorKind; + +use crate::{ConstValue, FloatBits, LimitError, Resource, Type}; + +#[repr(C)] +#[derive(Default)] +struct RawResult { + status: u64, + low: u64, + high: u64, + work: u64, +} + +unsafe extern "C" { + fn whale_ir_parse_literal( + source: *const u8, + length: u64, + category: u64, + width: u64, + max_work: u64, + result: *mut RawResult, + ) -> i32; +} + +pub(super) fn parse( + text: &str, + ty: &Type, + remaining_work: usize, + work_limit: usize, +) -> Result<(ConstValue, usize), ParseErrorKind> { + let (category, width) = match ty { + Type::Bool => (1, 1), + Type::I1 => (2, 1), + Type::I8 => (2, 8), + Type::I16 => (2, 16), + Type::I32 => (2, 32), + Type::I64 => (2, 64), + Type::I128 => (2, 128), + Type::U1 => (3, 1), + Type::U8 => (3, 8), + Type::U16 => (3, 16), + Type::U32 => (3, 32), + Type::U64 => (3, 64), + Type::U128 => (3, 128), + Type::F16 => (4, 16), + Type::F32 => (4, 32), + Type::F64 => (4, 64), + _ => (0, 0), + }; + let mut result = RawResult::default(); + let status = unsafe { + whale_ir_parse_literal( + text.as_ptr(), + text.len() as u64, + category, + width, + remaining_work as u64, + &mut result, + ) + }; + if status != 0 || result.status != 0 { + if result.status == 10 { + return Err(ParseErrorKind::ResourceLimit(LimitError { + resource: Resource::AnalysisWork, + limit: work_limit, + })); + } + if !(1..=9).contains(&result.status) { + return Err(ParseErrorKind::Backend("literal transport")); + } + return Err(ParseErrorKind::Syntax(match result.status { + 1 => "expected boolean literal".into(), + 2 => "expected signed decimal literal".into(), + 3 => "signed literal out of range".into(), + 4 => "expected unsigned decimal literal".into(), + 5 => "unsigned literal out of range".into(), + 6 => "float value must start with 0x".into(), + 7 => format!("f{width} requires exactly {} hexadecimal digits", width / 4), + 8 => "type has no scalar literal".into(), + 9 => "literal outside type range".into(), + _ => "invalid Wave IR literal result".into(), + })); + } + let invalid = || ParseErrorKind::Backend("literal transport"); + if result.work != text.len() as u64 || result.work > remaining_work as u64 { + return Err(invalid()); + } + let bits = (u128::from(result.high) << 64) | u128::from(result.low); + let value = match category { + 1 if result.high == 0 && result.low <= 1 => ConstValue::Bool(result.low != 0), + 2 => ConstValue::I(bits as i128), + 3 => ConstValue::U(bits), + 4 if result.high == 0 => ConstValue::F(match width { + 16 if result.low <= u16::MAX.into() => FloatBits::F16(result.low as u16), + 32 if result.low <= u32::MAX.into() => FloatBits::F32(result.low as u32), + 64 => FloatBits::F64(result.low), + _ => return Err(invalid()), + }), + _ => return Err(invalid()), + }; + Ok((value, result.work as usize)) +} + +#[cfg(test)] +mod tests { + use super::*; + + use crate::parser::{lexer, syntax::Parser, ParseError}; + + use crate::IrLimits; + + fn run(text: &str, ty: &Type, reference: bool) -> Result { + let limits = IrLimits::default(); + let tokens = + if reference { lexer::lex_reference(text, limits)? } else { lexer::lex(text, limits)? }; + let mut parser = Parser::new(tokens, limits); + parser.reference_types = reference; + parser.literal(ty) + } + + fn compare(text: &str, ty: &Type) { + match (run(text, ty, false), run(text, ty, true)) { + (Ok(a), Ok(b)) => assert_eq!(a, b, "{text:?}: {ty}"), + (Err(a), Err(b)) => { + assert_eq!(a.location, b.location, "{text:?}: {ty}"); + assert_eq!(a.to_string(), b.to_string(), "{text:?}: {ty}"); + }, + (a, b) => panic!("Wave/reference literal divergence for {text:?}: {ty}: {a:?} / {b:?}"), + } + } + + #[test] + fn wave_literals_match_reference_for_exact_bits_ranges_and_lexical_errors() { + let types = [ + Type::Void, + Type::Bool, + Type::I1, + Type::U1, + Type::I8, + Type::I16, + Type::I32, + Type::I64, + Type::I128, + Type::U8, + Type::U16, + Type::U32, + Type::U64, + Type::U128, + Type::F16, + Type::F32, + Type::F64, + Type::ptr_to(Type::U8), + ]; + for ty in &types { + for text in [ + "", + "-", + "-0", + "+1", + "true", + "false", + "\"1\"", + "🐋", + "0x0000", + "0x7F800001", + "0x7ff0000000000001", + "0X0000", + "0xgggg", + "170141183460469231731687303715884105727", + "170141183460469231731687303715884105728", + "-170141183460469231731687303715884105728", + "-170141183460469231731687303715884105729", + "340282366920938463463374607431768211455", + "340282366920938463463374607431768211456", + "340282366920938463463374607431768211456x", + ] { + compare(text, ty); + } + } + let mut state = 0x349_352_u128; + for index in 0..10000 { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + let ty = &types[index % types.len()]; + compare(&state.to_string(), ty); + compare(&(state as i128).to_string(), ty); + if index % 4 == 0 { + compare(&format!("{state}x"), ty); + } + } + } + + #[test] + fn type_and_literal_parsing_share_the_work_ceiling() { + let limits = IrLimits { max_analysis_work: 3, ..IrLimits::default() }; + let mut parser = Parser::new(lexer::lex("i32 1", limits).unwrap(), limits); + let ty = parser.ty(0).unwrap(); + assert!(matches!( + parser.literal(&ty).unwrap_err().kind, + ParseErrorKind::ResourceLimit(LimitError { + resource: Resource::AnalysisWork, + limit: 3 + }) + )); + } +} diff --git a/ir/src/parser/wave_module.rs b/ir/src/parser/wave_module.rs new file mode 100644 index 0000000..378a70d --- /dev/null +++ b/ir/src/parser/wave_module.rs @@ -0,0 +1,499 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Materialization of typed events from the Wave module grammar machine. + +use super::{ + lexer::{Kind, Token}, + syntax::Parser, + wave_text::RawToken, + ParseError, ParseErrorKind, +}; + +use crate::*; + +#[repr(C)] +#[derive(Default)] +struct State { + phase: u64, + at: u64, + format: u64, + nodes: u64, + work: u64, + a: u64, + b: u64, + c: u64, + d: u64, + e: u64, + f: u64, + g: u64, + name: u64, + link: u64, + terminated: u64, +} + +#[repr(C)] +#[derive(Default)] +struct Event { + status: u64, + reason: u64, + at: u64, + expected: u64, + event: u64, + role: u64, + a: u64, + b: u64, + c: u64, + d: u64, + e: u64, + f: u64, + g: u64, + name: u64, + link: u64, + next: u64, + nodes: u64, + work: u64, +} + +unsafe extern "C" { + fn whale_ir_module_step( + tokens: *const RawToken, + token_count: u64, + state: *mut State, + max_nodes: u64, + max_work: u64, + result: *mut Event, + ) -> i32; +} + +const WORDS: &[&str] = &[ + "}", + ":", + "=", + "const", + ",", + "align", + "init_expr", + "value", + "uninitialized", + "access", + "readonly", + "readwrite", + "linkage", + "internal", + "external", + "link_name", + "whale", + "sysv64", + "(", + ")", + "->", + "entry", + "{", + "source_file", + "original", + "none", + "source_map", + "instruction", + "terminator", + "global", + "storage", + "declare", + "fn", + "br", + "cbr", + "switch", + "ret", + "trap", +]; + +fn error(tokens: &[Token<'_>], result: &Event, limits: IrLimits) -> ParseError { + let index = (result.at as usize).min(tokens.len() - 1); + let found = match &tokens[index].kind { + Kind::Word(word) | Kind::Mark(word) => *word, + Kind::String(_) => "", + }; + let kind = match result.status { + 3 => ParseErrorKind::ResourceLimit(LimitError { + resource: Resource::Nodes, + limit: limits.max_nodes, + }), + 4 => ParseErrorKind::ResourceLimit(LimitError { + resource: Resource::AnalysisWork, + limit: limits.max_analysis_work, + }), + 1 if (1..=17).contains(&result.reason) + && (result.reason != 1 || (result.expected as usize) < WORDS.len()) + && (result.reason != 4 || result.expected < 5) => + { + ParseErrorKind::Syntax(match result.reason { + 1 => format!( + "expected '{}', found '{found}'", + WORDS.get(result.expected as usize).unwrap_or(&"?") + ), + 2 => "expected unsigned decimal integer".into(), + 3 => "integer out of range".into(), + 4 => format!( + "expected {} ID", + ["%v", "%b", "@g", "@f", "@s"].get(result.expected as usize).unwrap_or(&"?") + ), + 5 => "invalid numeric ID".into(), + 6 => "ID out of range".into(), + 7 => "expected quoted string".into(), + 8 => "expected word".into(), + 9 => "source metadata requires IR format 7".into(), + 10 => "global storage requires typed IR format 6".into(), + 11 => "unknown source mapping target".into(), + 12 => "expected value or uninitialized global storage".into(), + 13 => "expected readonly or readwrite".into(), + 14 => "unknown linkage".into(), + 15 => "unknown calling convention".into(), + 16 => "unknown module field".into(), + 17 => "instruction after terminator".into(), + _ => "invalid Wave IR module result".into(), + }) + }, + _ => ParseErrorKind::Backend("module parser transport"), + }; + ParseError { location: tokens[index].location, kind } +} + +impl Parser<'_> { + fn module_string(&mut self, index: u64) -> Result { + match self.tokens.get_mut(index as usize) { + Some(Token { kind: Kind::String(string), .. }) => Ok(std::mem::take(string)), + _ => Err(self.backend("module parser transport")), + } + } + + pub(super) fn module_wave(&mut self) -> Result { + let (target, layout, version, next) = super::wave_header::parse(&self.tokens)?; + self.format_version = version; + self.at = next; + let mut module = Module::new(target, layout); + let mut state = State { at: next as u64, format: u64::from(version), ..State::default() }; + let mut ty = None; + let mut literal = None; + let mut expression = None; + let mut signature_params = Vec::new(); + let mut signature_return = None; + let mut parameter_type = None; + let mut function: Option = None; + let mut block: Option = None; + loop { + state.at = self.at as u64; + let nodes = self.limits.max_nodes.saturating_sub(self.nodes); + let work = self.limits.max_analysis_work.saturating_sub(self.grammar_work); + let mut event = Event::default(); + let status = unsafe { + whale_ir_module_step( + self.raw_tokens.as_ptr(), + self.raw_tokens.len() as u64, + &mut state, + nodes as u64, + work as u64, + &mut event, + ) + }; + if status != event.status as i32 + || event.nodes > nodes as u64 + || event.work > work as u64 + || event.next >= self.tokens.len() as u64 + { + return Err(self.backend("module parser transport")); + } + if status != 0 { + return Err(error(&self.tokens, &event, self.limits)); + } + self.at = event.next as usize; + self.nodes += event.nodes as usize; + self.grammar_work += event.work as usize; + match event.event { + 100 => { + let parsed = self.ty(0)?; + match event.role { + 1 | 3 => ty = Some(parsed), + 2 | 4 => self.equal_type( + ty.as_ref().ok_or_else(|| self.backend("module parser transport"))?, + &parsed, + )?, + 5 => signature_params.push(parsed), + 6 => signature_return = Some(parsed), + 7 => parameter_type = Some(parsed), + 8 => { + function + .as_mut() + .ok_or_else(|| self.backend("module parser transport"))? + .ret_ty = parsed + }, + _ => return Err(self.backend("module parser transport")), + } + }, + 101 => { + literal = Some(self.literal( + ty.as_ref().ok_or_else(|| self.backend("module parser transport"))?, + )?) + }, + 102 => expression = Some(self.expression(0)?), + 103 => { + let (instruction, result) = self.instruction()?; + if let Some(result) = result { + function + .as_mut() + .ok_or_else(|| self.backend("module parser transport"))? + .value_types + .push(result); + } + block + .as_mut() + .ok_or_else(|| self.backend("module parser transport"))? + .instructions + .push(instruction); + }, + 104 => { + let terminator = self.terminator()?; + block + .as_mut() + .ok_or_else(|| self.backend("module parser transport"))? + .terminator = Some(terminator); + }, + 1 => { + let name = self.module_string(event.name)?; + module.sources.files.push(SourceFile { id: event.a as u32, name }); + }, + 2 => module.sources.originals.push(OriginalNode { + id: event.a, + span: (event.g != 0).then_some(SourceSpan { + file: event.b as u32, + line: event.c as u32, + column: event.d as u32, + end_line: event.e as u32, + end_column: event.f as u32, + }), + }), + 3 => { + let target = match event.a { + 0 => SourceTarget::Instruction { + function: FunctionId(event.b as u32), + block: BlockId(event.c as u32), + index: event.d as usize, + }, + 1 => SourceTarget::Terminator { + function: FunctionId(event.b as u32), + block: BlockId(event.c as u32), + }, + 2 => SourceTarget::Global(GlobalId(event.b as u32)), + _ => return Err(self.backend("module parser transport")), + }; + module.sources.mappings.push(SourceMapping { target, original: event.e }); + }, + 4 => { + let name = self.module_string(event.name)?; + let id = GlobalId(event.a as u32); + let location = self.tokens[event.name as usize].location; + self.global_locations.entry(name.clone()).or_insert(location); + self.global_constant_locations.entry(id).or_insert(location); + module.globals.push(Global { + id, + name, + ty: ty.take().ok_or_else(|| self.backend("module parser transport"))?, + init: literal + .take() + .ok_or_else(|| self.backend("module parser transport"))?, + init_expr: expression + .take() + .ok_or_else(|| self.backend("module parser transport"))?, + align: event.b as u32, + }); + }, + 5 => { + let name = self.module_string(event.name)?; + let location = self.tokens[event.name as usize].location; + self.global_locations.entry(name.clone()).or_insert(location); + let link_name = if event.link == u64::MAX { + None + } else { + Some(self.module_string(event.link)?) + }; + module.global_storage.push(GlobalStorage { + id: GlobalId(event.a as u32), + name, + ty: ty.take().ok_or_else(|| self.backend("module parser transport"))?, + init: if event.e == 0 { + GlobalStorageInit::Uninitialized + } else { + GlobalStorageInit::Value( + literal + .take() + .ok_or_else(|| self.backend("module parser transport"))?, + ) + }, + align: event.b as u32, + readonly: event.c != 0, + linkage: if event.d == 0 { Linkage::Internal } else { Linkage::External }, + link_name, + }); + }, + 6 => { + let name = self.module_string(event.name)?; + let location = self.tokens[event.name as usize].location; + self.declaration_locations.entry(name.clone()).or_insert(location); + let link_name = if event.link == u64::MAX { + None + } else { + Some(self.module_string(event.link)?) + }; + module.declarations.push(FunctionDecl { + id: FunctionId(event.a as u32), + name, + signature: FunctionSignature { + params: std::mem::take(&mut signature_params), + ret: signature_return + .take() + .ok_or_else(|| self.backend("module parser transport"))?, + convention: if event.c == 0 { + CallingConvention::Whale + } else { + CallingConvention::SysV64 + }, + variadic: false, + }, + linkage: if event.d == 0 { Linkage::Internal } else { Linkage::External }, + link_name, + }); + }, + 7 => { + let name = self.module_string(event.name)?; + let location = self.tokens[event.name as usize].location; + self.function_locations.entry(name.clone()).or_insert(location); + function = Some(Function { + id: FunctionId(event.a as u32), + name, + params: Vec::new(), + ret_ty: Type::Void, + blocks: Vec::new(), + entry: BlockId(0), + value_types: Vec::new(), + }); + }, + 8 => { + let name = self.module_string(event.name)?; + let id = ValueId(event.a as u32); + let ty = parameter_type + .take() + .ok_or_else(|| self.backend("module parser transport"))?; + let function = + function.as_mut().ok_or_else(|| self.backend("module parser transport"))?; + function.value_types.push((id, ty.clone())); + function.params.push(Param { id, name, ty }); + }, + 9 => { + function + .as_mut() + .ok_or_else(|| self.backend("module parser transport"))? + .entry = BlockId(event.a as u32) + }, + 10 => { + block = Some(BasicBlock::new( + BlockId(event.a as u32), + self.module_string(event.name)?, + )) + }, + 12 => { + let completed = + block.take().ok_or_else(|| self.backend("module parser transport"))?; + function + .as_mut() + .ok_or_else(|| self.backend("module parser transport"))? + .blocks + .push(completed); + }, + 13 => module + .functions + .push(function.take().ok_or_else(|| self.backend("module parser transport"))?), + 14 => return Ok(module), + _ => return Err(self.backend("module parser transport")), + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const PREFIX: &str = "module { format_version 8 semantics_version 1 target \"x86_64-whale-linux\" datalayout { ptr=64, endian=little } "; + + fn compare(source: &str, limits: IrLimits) { + let tokens = match super::super::lexer::lex(source, limits) { + Ok(tokens) => tokens, + Err(_) => return, + }; + let mut wave = Parser::new(tokens, limits); + let tokens = super::super::lexer::lex(source, limits).unwrap(); + let mut reference = Parser::new(tokens, limits); + reference.reference_types = true; + match (wave.module(), reference.module()) { + (Ok(actual), Ok(expected)) => { + assert_eq!(actual, expected, "{source:?}"); + assert_eq!(wave.at, reference.at, "{source:?}"); + assert_eq!(wave.nodes, reference.nodes, "{source:?}"); + }, + (Err(actual), Err(expected)) => { + assert_eq!(actual.location, expected.location, "{source:?}\n{actual}\n{expected}"); + assert_eq!(actual.to_string(), expected.to_string(), "{source:?}"); + }, + (actual, expected) => { + panic!("module grammar disagreement: {source:?}\n{actual:?}\n{expected:?}") + }, + } + } + + #[test] + fn wave_outer_grammar_preserves_modules_versions_and_exact_error_locations() { + let fields = [ + "", + "source_file @s4 \"src.whale\" original 7 @s4 1 2 1 3 source_map global @g2 7", + "global @g2 \"c\": i32 = const i32 7, align 4, init_expr i32 7", + "storage @g8 \"mutable\": ptr = uninitialized, align 8, access readwrite, linkage internal", + "storage @g9 \"constant\": u32 = value u32 17, align 4, access readonly, linkage external, link_name \"published\"", + "declare @f3 \"f\": whale (i32, ptr) -> i32, linkage external, link_name \"f\"", + "declare @f3 \"f\": whale () -> void, linkage internal fn @f3 \"f\"() -> void, entry %b8 { %b8 \"entry\": ret void }", + "fn @f3 \"f\"(%v7 \"a\": i32, %v9 \"b\": ptr) -> i32, entry %b8 { %b8 \"entry\": %v12: i32 = mov i32 %v7 ret i32 %v12 %b9 \"dead\": ret i32 %v7 }", + "unknown", "source_file", "storage @g0 \"x\": i32 = unknown", "fn @f0 \"f\"(,)", + "original 18446744073709551616 none", "source_file @s4294967296 \"x\"", + "source_map invalid @g0 1", "declare @f0 \"f\": invalid () -> void, linkage internal", + "fn @f0 \"f\"() -> void, entry %b0 { %b0 \"b\": ret void ret void }", + "fn @f0 \"f\"(%v0 \"a\": i32,) -> void, entry %b0 {}", + "global @g0 \"x\": array = const array 1, align 4, init_expr i32 1", + ]; + for field in fields { + let source = format!("{PREFIX}{field} }}"); + compare(&source, IrLimits::default()); + for version in 3..=8 { + compare( + &source.replace("format_version 8", &format!("format_version {version}")), + IrLimits::default(), + ); + } + for end in source.char_indices().map(|(index, _)| index) { + compare(&source[..end], IrLimits::default()); + } + for max_nodes in 0..16 { + compare(&source, IrLimits { max_nodes, ..IrLimits::default() }); + } + } + let mut state = 0x349_501u64; + for _ in 0..2000 { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + let count = state as usize % 12; + let mut source = PREFIX.to_string(); + for index in 0..count { + source.push_str(fields[(state as usize + index) % fields.len()]); + source.push(' '); + } + source.push('}'); + compare(&source, IrLimits::default()); + } + } +} diff --git a/ir/src/parser/wave_text.rs b/ir/src/parser/wave_text.rs new file mode 100644 index 0000000..cb5c725 --- /dev/null +++ b/ir/src/parser/wave_text.rs @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Borrowed token transport shared by the Wave grammar parsers. + +use super::lexer::{Kind, Token}; + +#[repr(C)] +pub(super) struct RawToken { + pub data: *const u8, + pub length: u64, + pub kind: u64, +} + +impl From<&Token<'_>> for RawToken { + fn from(token: &Token<'_>) -> Self { + // Grammar parsing only inspects the kind of decoded string tokens. + // Do not borrow their allocation: the compatibility parser can move + // strings out of its tokens while these descriptors remain alive. + let (bytes, kind): (&[u8], u64) = match &token.kind { + Kind::Word(s) => (s.as_bytes(), 0), + Kind::String(_) => (&[], 1), + Kind::Mark(s) if *s == "" => (s.as_bytes(), 3), + Kind::Mark(s) => (s.as_bytes(), 2), + }; + Self { data: bytes.as_ptr(), length: bytes.len() as u64, kind } + } +} diff --git a/ir/src/parser/wave_type.rs b/ir/src/parser/wave_type.rs new file mode 100644 index 0000000..2526930 --- /dev/null +++ b/ir/src/parser/wave_type.rs @@ -0,0 +1,368 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Conversion between the internal Wave postorder type model and Rust callers. + +use super::{lexer::Kind, lexer::Token, wave_text::RawToken, ParseError, ParseErrorKind}; + +use crate::{CallingConvention, FunctionSignature, IrLimits, LimitError, Resource, Type}; + +#[repr(C)] +#[derive(Clone, Copy, Default)] +pub(super) struct Node { + kind: u64, + value: u64, + count: u64, +} + +#[repr(C)] +#[derive(Default)] +struct RawResult { + status: u64, + reason: u64, + at: u64, + expected: u64, + next: u64, + nodes: u64, + work: u64, +} + +unsafe extern "C" { + fn whale_ir_parse_type( + tokens: *const RawToken, + token_count: u64, + start: u64, + depth: u64, + max_depth: u64, + max_nodes: u64, + max_work: u64, + mode: u64, + scratch: *mut Node, + capacity: u64, + output: *mut Node, + output_capacity: u64, + result: *mut RawResult, + ) -> i32; +} + +pub(super) struct Options { + pub start: usize, + pub depth: usize, + pub limits: IrLimits, + pub remaining_nodes: usize, + pub remaining_work: usize, +} + +pub(super) struct Parsed { + pub ty: Type, + pub next: usize, + pub nodes: usize, + pub work: usize, +} + +fn error(tokens: &[Token<'_>], result: &RawResult, options: &Options) -> ParseError { + let index = usize::try_from(result.at).unwrap_or(usize::MAX).min(tokens.len() - 1); + let resource = |resource, limit| ParseErrorKind::ResourceLimit(LimitError { resource, limit }); + let kind = match result.status { + 2 => resource(Resource::TypeDepth, options.limits.max_type_depth), + 3 => resource(Resource::Nodes, options.limits.max_nodes), + 4 => resource(Resource::AnalysisWork, options.limits.max_analysis_work), + 1 if (1..=6).contains(&result.reason) + && (result.reason != 1 || (24..=31).contains(&result.expected)) => + { + ParseErrorKind::Syntax(match result.reason { + 1 => { + let expected = match result.expected { + 24 => "<", + 25 => ">", + 26 => "{", + 27 => "}", + 28 => "(", + 29 => ")", + 30 => "->", + 31 => ",", + _ => "?", + }; + let found = match &tokens[index].kind { + Kind::Word(s) | Kind::Mark(s) => *s, + Kind::String(_) => "", + }; + format!("expected '{expected}', found '{found}'") + }, + 2 => "expected unsigned decimal integer".into(), + 3 => "integer out of range".into(), + 4 => "expected word".into(), + 5 => "unknown type".into(), + 6 => "unknown calling convention".into(), + _ => "invalid Wave IR type result".into(), + }) + }, + _ => ParseErrorKind::Backend("type parser transport"), + }; + ParseError { location: tokens[index].location, kind } +} + +fn children(stack: &mut Vec, count: u64) -> Option> { + let count = usize::try_from(count).ok()?; + let first = stack.len().checked_sub(count)?; + let mut result = Vec::new(); + result.try_reserve_exact(count).ok()?; + result.extend(stack.drain(first..)); + Some(result) +} + +pub(super) fn decode(nodes: &[Node]) -> Option { + let mut stack = Vec::new(); + stack.try_reserve_exact(nodes.len()).ok()?; + for node in nodes { + let ty = match node.kind { + 0..=16 if node.count == 0 && node.value == 0 => match node.kind { + 0 => Type::Void, + 1 => Type::Bool, + 2 => Type::I1, + 3 => Type::U1, + 4 => Type::I8, + 5 => Type::I16, + 6 => Type::I32, + 7 => Type::I64, + 8 => Type::I128, + 9 => Type::U8, + 10 => Type::U16, + 11 => Type::U32, + 12 => Type::U64, + 13 => Type::U128, + 14 => Type::F16, + 15 => Type::F32, + 16 => Type::F64, + _ => unreachable!(), + }, + 17 if node.count == 1 && node.value == 0 => Type::ptr_to(stack.pop()?), + 18 if node.value <= 1 => { + let ret = stack.pop()?; + let params = children(&mut stack, node.count)?; + Type::FnPtr(Box::new(FunctionSignature { + params, + ret, + variadic: false, + convention: if node.value == 0 { + CallingConvention::Whale + } else { + CallingConvention::SysV64 + }, + })) + }, + 19 if node.count == 1 => Type::Array(Box::new(stack.pop()?), node.value), + 20 if node.value == 0 => Type::Struct(children(&mut stack, node.count)?), + 21 if node.value == 0 => Type::Tuple(children(&mut stack, node.count)?), + _ => return None, + }; + stack.push(ty); + } + if stack.len() != 1 { + return None; + } + stack.pop() +} + +pub(super) fn parse( + tokens: &[Token<'_>], + raw: &[RawToken], + options: Options, +) -> Result { + let mut result = RawResult::default(); + let status = unsafe { + whale_ir_parse_type( + raw.as_ptr(), + raw.len() as u64, + options.start as u64, + options.depth as u64, + options.limits.max_type_depth as u64, + options.remaining_nodes as u64, + options.remaining_work as u64, + 0, + std::ptr::null_mut(), + 0, + std::ptr::null_mut(), + 0, + &mut result, + ) + }; + if status != 0 || result.status != 0 { + return Err(error(tokens, &result, &options)); + } + let count = usize::try_from(result.nodes).map_err(|_| error(tokens, &result, &options))?; + let next = usize::try_from(result.next).map_err(|_| error(tokens, &result, &options))?; + let work = usize::try_from(result.work).map_err(|_| error(tokens, &result, &options))?; + if count == 0 + || count > options.remaining_nodes + || count > raw.len() + || next <= options.start + || next >= raw.len() + || work > options.remaining_work + { + return Err(error(tokens, &result, &options)); + } + let mut scratch = Vec::new(); + let mut output = Vec::new(); + for buffer in [&mut scratch, &mut output] { + buffer.try_reserve_exact(count).map_err(|_| error(tokens, &result, &options))?; + buffer.resize(count, Node::default()); + } + let status = unsafe { + whale_ir_parse_type( + raw.as_ptr(), + raw.len() as u64, + options.start as u64, + options.depth as u64, + options.limits.max_type_depth as u64, + options.remaining_nodes as u64, + options.remaining_work as u64, + 1, + scratch.as_mut_ptr(), + count as u64, + output.as_mut_ptr(), + count as u64, + &mut result, + ) + }; + if status != 0 + || result.status != 0 + || result.nodes != count as u64 + || result.next != next as u64 + || result.work != work as u64 + { + return Err(error(tokens, &result, &options)); + } + let ty = decode(&output).ok_or_else(|| error(tokens, &result, &options))?; + Ok(Parsed { ty, next, nodes: count, work }) +} + +#[cfg(test)] +mod tests { + use super::*; + + use crate::parser::{lexer, syntax::Parser}; + + fn parse_case( + text: &str, + limits: IrLimits, + reference: bool, + ) -> Result<(Type, String), ParseError> { + let tokens = + if reference { lexer::lex_reference(text, limits)? } else { lexer::lex(text, limits)? }; + let mut parser = Parser::new(tokens, limits); + parser.reference_types = reference; + let ty = parser.ty(0)?; + Ok((ty, parser.peek().to_owned())) + } + + fn compare(text: &str, limits: IrLimits) { + match (parse_case(text, limits, false), parse_case(text, limits, true)) { + (Ok(actual), Ok(expected)) => assert_eq!(actual, expected, "{text:?}"), + (Err(actual), Err(expected)) => { + assert_eq!(actual.location, expected.location, "{text:?}"); + assert_eq!(actual.to_string(), expected.to_string(), "{text:?}"); + }, + (actual, expected) => { + panic!("Wave/reference type divergence for {text:?}: {actual:?} / {expected:?}") + }, + } + } + + fn random(state: &mut u64) -> u64 { + *state ^= *state << 13; + *state ^= *state >> 7; + *state ^= *state << 17; + *state + } + + fn generated(state: &mut u64, depth: usize) -> String { + const LEAVES: [&str; 17] = [ + "void", "bool", "i1", "u1", "i8", "i16", "i32", "i64", "i128", "u8", "u16", "u32", + "u64", "u128", "f16", "f32", "f64", + ]; + let choice = random(state) % if depth == 0 { 17 } else { 22 }; + match choice { + 0..=16 => LEAVES[choice as usize].into(), + 17 => format!("ptr<{}>", generated(state, depth - 1)), + 18 => { + let convention = if random(state) & 1 == 0 { "whale" } else { "sysv64" }; + let params = (0..random(state) % 4) + .map(|_| generated(state, depth - 1)) + .collect::>() + .join(", "); + format!("fnptr<{convention} ({params}) -> {}>", generated(state, depth - 1)) + }, + 19 => { + let count = random(state); + format!("array<{}, {count}>", generated(state, depth - 1)) + }, + 20 | 21 => { + let fields = (0..random(state) % 4) + .map(|_| generated(state, depth - 1)) + .collect::>() + .join(", "); + if choice == 20 { + format!("struct{{{fields}}}") + } else { + format!("tuple<{fields}>") + } + }, + _ => unreachable!(), + } + } + + #[test] + fn wave_types_match_reference_for_complete_grammar_and_failures() { + let seeds = [ + "fnptr void>", + "fnptr, tuple) -> struct{u1, array}>", + "tuple<>", "struct{}", "ptr>>", + "array", "array", + "array", "fnptr i32>", "fnptr<\"whale\" () -> i32>", + "struct{i32,}", "tuple<,i32>", "\"i32\"", "", "🐋", "array", + ]; + for seed in seeds { + compare(seed, IrLimits::default()); + for (end, _) in seed.char_indices() { + compare(&seed[..end], IrLimits::default()); + } + for max_type_depth in 0..4 { + compare(seed, IrLimits { max_type_depth, ..IrLimits::default() }); + } + for max_nodes in 0..8 { + compare(seed, IrLimits { max_nodes, ..IrLimits::default() }); + } + } + let mut state = 0x348_349_350_u64; + for _ in 0..10000 { + let text = generated(&mut state, 5); + compare(&text, IrLimits::default()); + if text.len() > 1 { + let end = (random(&mut state) as usize) % text.len(); + compare(&text[..end], IrLimits::default()); + } + } + } + + #[test] + fn wave_type_limits_are_cumulative_across_types() { + let limits = IrLimits { max_nodes: 2, ..IrLimits::default() }; + let mut parser = Parser::new(lexer::lex("i32 ptr", limits).unwrap(), limits); + assert_eq!(parser.ty(0).unwrap(), Type::I32); + let error = parser.ty(0).unwrap_err(); + assert!(matches!( + error.kind, + ParseErrorKind::ResourceLimit(LimitError { resource: Resource::Nodes, limit: 2 }) + )); + assert_eq!(error.location.byte_offset, 8); + let limits = IrLimits { max_analysis_work: 3, ..IrLimits::default() }; + let mut parser = Parser::new(lexer::lex("i32 i32", limits).unwrap(), limits); + assert_eq!(parser.ty(0).unwrap(), Type::I32); + assert!(matches!( + parser.ty(0).unwrap_err().kind, + ParseErrorKind::ResourceLimit(LimitError { + resource: Resource::AnalysisWork, + limit: 3 + }) + )); + } +} diff --git a/ir/src/printer.rs b/ir/src/printer.rs index 9f3d3ef..01d6a3f 100644 --- a/ir/src/printer.rs +++ b/ir/src/printer.rs @@ -1,519 +1,189 @@ // SPDX-License-Identifier: MPL-2.0 +//! Canonical, versioned IR text. The product path prints in Wave and drains +//! bounded chunks through a Rust writer; ordinary Cargo keeps a reference path. +use crate::{ConstExpr, Module}; + +use std::{fmt, io}; + +#[cfg(any(test, not(whale_wave_ir)))] +#[path = "printer_reference.rs"] +mod reference; + +#[cfg(whale_wave_ir)] +#[path = "printer_wave.rs"] +mod wave; + +/// Bounds both the caller-owned transport and the Wave output traversal. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct PrintLimits { + pub max_output_bytes: usize, + pub max_nodes: usize, + pub max_work: usize, + pub max_depth: usize, + pub max_stack: usize, +} -use crate::{ - BasicBlock, BinOp, Callee, CmpOp, ConstValue, Endian, Function, ICmpPred, Instruction, Module, - Terminator, Type, -}; - -pub fn print_module(m: &Module) -> String { - let mut out = String::new(); - out.push_str("module {\n"); - out.push_str(&format!( - " format_version {}\n semantics_version {}\n", - crate::IR_FORMAT_VERSION, - crate::SEMANTICS_VERSION - )); - out.push_str(&format!(" target \"{}\"\n", escape(&m.target))); - out.push_str(" datalayout { "); - out.push_str(&format!( - "ptr={}, endian={}", - m.datalayout.ptr_bits, - match m.datalayout.endian { - Endian::Little => "little", - Endian::Big => "big", - } - )); - out.push_str(" }\n\n"); - for file in &m.sources.files { - out.push_str(&format!(" source_file @s{} \"{}\"\n", file.id, escape(&file.name))); - } - for original in &m.sources.originals { - out.push_str(&format!(" original {} ", original.id)); - if let Some(s) = &original.span { - out.push_str(&format!( - "@s{} {} {} {} {}\n", - s.file, s.line, s.column, s.end_line, s.end_column - )); - } else { - out.push_str("none\n"); - } - } - for mapping in &m.sources.mappings { - out.push_str(" source_map "); - match mapping.target { - crate::SourceTarget::Instruction { function, block, index } => { - out.push_str(&format!("instruction @f{} {} {}", function.0, block, index)) - }, - crate::SourceTarget::Terminator { function, block } => { - out.push_str(&format!("terminator @f{} {}", function.0, block)) - }, - crate::SourceTarget::Global(id) => out.push_str(&format!("global @g{}", id.0)), - } - out.push_str(&format!(" {}\n", mapping.original)); - } - - for g in &m.globals { - out.push_str(&format!( - " global @g{} \"{}\": {} = const {} {}, align {}, init_expr {}\n", - g.id.0, - escape(&g.name), - g.ty, - g.ty, - fmt_const(&g.init), - g.align, - print_const_expr(&g.init_expr) - )); - } - if !m.globals.is_empty() { - out.push('\n'); - } - - for g in &m.global_storage { - out.push_str(&format!(" storage @g{} \"{}\": {} = ", g.id.0, escape(&g.name), g.ty)); - match &g.init { - crate::GlobalStorageInit::Value(value) => { - out.push_str(&format!("value {} {}", g.ty, fmt_const(value))) - }, - crate::GlobalStorageInit::Uninitialized => out.push_str("uninitialized"), +impl Default for PrintLimits { + fn default() -> Self { + Self { + max_output_bytes: 64 * 1024 * 1024, + max_nodes: 1_000_000, + max_work: 512 * 1024 * 1024, + max_depth: crate::MAX_IR_NESTING, + max_stack: 16_384, } - out.push_str(&format!( - ", align {}, access {}, linkage {}", - g.align, - if g.readonly { "readonly" } else { "readwrite" }, - if g.linkage == crate::Linkage::Internal { "internal" } else { "external" } - )); - if let Some(name) = &g.link_name { - out.push_str(&format!(", link_name \"{}\"", escape(name))); - } - out.push('\n'); - } - if !m.global_storage.is_empty() { - out.push('\n'); } - for d in &m.declarations { - out.push_str(&format!( - " declare @f{} \"{}\": {}, linkage {}", - d.id.0, - escape(&d.name), - d.signature, - match d.linkage { - crate::Linkage::Internal => "internal", - crate::Linkage::External => "external", - } - )); - if let Some(link) = &d.link_name { - out.push_str(&format!(", link_name \"{}\"", escape(link))); - } - out.push('\n'); - } - if !m.declarations.is_empty() { - out.push('\n'); - } - for f in &m.functions { - out.push_str(&print_function(f)); - out.push('\n'); - } - - out.push_str("}\n"); - out } -fn print_function(f: &Function) -> String { - let mut out = String::new(); - out.push_str(&format!(" fn @f{} \"{}\"(", f.id.0, escape(&f.name))); - for (i, p) in f.params.iter().enumerate() { - if i != 0 { - out.push_str(", "); +impl PrintLimits { + fn validate(self) -> Result<(), PrintError> { + if self.max_depth > crate::MAX_IR_NESTING { + return Err(PrintError::Depth); } - out.push_str(&format!("{} \"{}\": {}", p.id, escape(&p.name), p.ty)); + Ok(()) } - out.push_str(&format!(") -> {}, entry {} {{\n", f.ret_ty, f.entry)); - - for b in &f.blocks { - out.push_str(&print_block(b)); - } - - out.push_str(" }\n"); - out } -fn print_block(b: &BasicBlock) -> String { - let mut out = String::new(); - out.push_str(&format!(" {} \"{}\":\n", b.id, escape(&b.name))); - - for ins in &b.instructions { - out.push_str(" "); - out.push_str(&print_instr(ins)); - out.push('\n'); - } +#[derive(Debug)] +pub enum PrintError { + Output, + Nodes, + Work, + Depth, + Stack, + Allocation, + Backend, + Io(io::Error), +} - if let Some(t) = &b.terminator { - out.push_str(" "); - out.push_str(&print_term(t)); - out.push('\n'); +impl fmt::Display for PrintError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Output => f.write_str("IR printer output limit exceeded"), + Self::Nodes => f.write_str("IR printer model limit exceeded"), + Self::Work => f.write_str("IR printer work limit exceeded"), + Self::Depth => f.write_str("IR printer depth limit exceeded"), + Self::Stack => f.write_str("IR printer workspace limit exceeded"), + Self::Allocation => f.write_str("IR printer allocation failed"), + Self::Backend => f.write_str("IR printer rejected its model transport"), + Self::Io(error) => write!(f, "IR printer write failed: {error}"), + } } - - out } -fn print_instr(i: &Instruction) -> String { - use Instruction::*; - match i { - GlobalAddr { dst, global, ty } => format!("{dst}: ptr<{ty}> = global_addr @g{}", global.0), - LifetimeEnd { ptr } => format!("lifetime_end {ptr}"), - PtrDiff { dst, lhs, rhs } => format!("{dst}: i128 = ptrdiff {lhs}, {rhs}"), - ConstDecl { dst, name, expression, value } => format!( - "{dst}: {} = const_decl \"{}\" {} => const {} {}", - expression.ty, - escape(name), - print_const_expr(expression), - expression.ty, - fmt_const(value) - ), - Const { dst, ty, value } => format!("{dst}: {ty} = const {ty} {}", fmt_const(value)), - Undef { dst, ty } => format!("{dst}: {ty} = undef {ty}"), - Mov { dst, ty, src } => format!("{dst}: {ty} = mov {ty} {src}"), - - Bin { dst, op, ty, lhs, rhs } => { - format!("{dst}: {ty} = {} {ty} {lhs}, {rhs}", fmt_binop(op)) - }, - Neg { dst, ty, src } => format!("{dst}: {ty} = neg {ty} {src}"), - Not { dst, ty, src } => format!("{dst}: {ty} = not {ty} {src}"), - - Cmp { dst, op, ty, lhs, rhs } => { - format!("{dst}: bool = cmp {} {ty} {lhs}, {rhs}", fmt_cmpop(op)) - }, - - ICmp { dst, pred, ty, lhs, rhs } => { - format!("{dst}: bool = icmp {} {ty} {lhs}, {rhs}", fmt_icmp(pred)) - }, - FCmp { dst, pred, ty, lhs, rhs } => { - format!("{dst}: bool = fcmp {} {ty} {lhs}, {rhs}", fmt_fcmp(pred)) - }, - - Select { dst, ty, cond, on_true, on_false } => { - format!("{dst}: {ty} = select bool {cond}, {ty} {on_true}, {ty} {on_false}") - }, - - Cast { dst, op, dst_ty, src_ty, src } => { - format!("{dst}: {dst_ty} = {} {src_ty} {src} to {dst_ty}", fmt_cast(op)) - }, - - Phi { dst, ty, incomings } => { - let mut s = format!("{dst}: {ty} = phi {ty} "); - for (i, (v, bb)) in incomings.iter().enumerate() { - if i != 0 { - s.push_str(", "); - } - s.push_str(&format!("[ {v}, {bb} ]")); - } - s - }, - - Extract { dst, dst_ty, tuple, index } => { - format!("{dst}: {dst_ty} = extract {tuple}, {}", index) - }, - - Checked { dst, op, ty, lhs, rhs } => { - format!("{dst}: tuple<{ty}, bool> = {}_chk {ty} {lhs}, {rhs}", fmt_checked(op)) - }, - - Alloca { dst, ty, align } => format!("{dst}: ptr<{ty}> = alloca {ty}, align {align}"), - - VolatileLoad { dst, ty, ptr, align } => { - format!("{dst}: {ty} = volatile_load {ty}, ptr<{ty}> {ptr}, align {align}") - }, - VolatileStore { ty, value, ptr, align } => { - format!("volatile_store {ty} {value}, ptr<{ty}> {ptr}, align {align}") - }, - Load { dst, ty, ptr, align } => { - format!("{dst}: {ty} = load {ty}, ptr<{ty}> {ptr}, align {align}") - }, - - Uninit { ty, ptr, align } => format!("uninit {ty}, ptr<{ty}> {ptr}, align {align}"), - Store { ty, value, ptr, align } => { - format!("store {ty} {value}, ptr<{ty}> {ptr}, align {align}") - }, - - Gep { dst, dst_ty, base_ptr, indices } => { - let mut s = format!("{dst}: {dst_ty} = gep {base_ptr}"); - for idx in indices { - s.push_str(&format!(", {idx}")); - } - s - }, - - Memcpy { dst, src, n, align } => { - format!("memcpy ptr {dst}, ptr {src}, u64 {n}, align {align}") - }, - - Memset { dst, val, n, align } => { - format!("memset ptr {dst}, u8 {val}, u64 {n}, align {align}") - }, - - NullFunction { dst, signature } => format!("{dst}: fnptr<{signature}> = null_function"), - FunctionAddr { dst, function, signature } => { - format!("{dst}: fnptr<{signature}> = function_addr @f{}", function.0) - }, - Call { convention, dst, ret_ty, callee, args } => { - let mut s = String::new(); - if let Some(v) = dst { - s.push_str(&format!("{v}: {ret_ty} = ")); - } - s.push_str(&format!( - "call {} {ret_ty} {}(", - match convention { - crate::CallingConvention::Whale => "whale", - crate::CallingConvention::SysV64 => "sysv64", - }, - fmt_callee(callee) - )); - for (i, a) in args.iter().enumerate() { - if i != 0 { - s.push_str(", "); - } - s.push_str(&format!("{a}")); - } - s.push(')'); - s - }, - - TrapIf { cond, reason } => format!("trap_if bool {cond}, reason=\"{}\"", escape(reason)), +impl std::error::Error for PrintError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Io(error) => Some(error), + _ => None, + } } } -pub fn print_const_expr(expr: &crate::ConstExpr) -> String { - use crate::{ConstBinaryOp as B, ConstCompareOp as C, ConstExprKind as K, ConstRef}; - match &expr.kind { - K::Neg(value) => format!("neg({})", print_const_expr(value)), - K::Not(value) => format!("bit_not({})", print_const_expr(value)), - K::Literal(value) => format!("{} {}", expr.ty, fmt_const(value)), - K::Reference(reference) => match reference { - ConstRef::Global(id) => format!("{} @g{}", expr.ty, id.0), - ConstRef::Local(id) => format!("{} {id}", expr.ty), - }, - K::Binary { op, left, right } => format!( - "{}({}, {})", - match op { - B::Add => "add", - B::Sub => "sub", - B::Mul => "mul", - B::BitAnd => "bit_and", - B::BitOr => "bit_or", - B::BitXor => "bit_xor", - B::Div => "div", - B::Rem => "rem", - B::ShiftLeft => "shift_left", - B::ShiftRight => "shift_right", - B::LogicalAnd => "logical_and", - B::LogicalOr => "logical_or", - }, - print_const_expr(left), - print_const_expr(right) - ), - K::Compare { op, left, right } => format!( - "{}({}, {})", - match op { - C::Eq => "eq", - C::Ne => "ne", - C::Lt => "lt", - C::Le => "le", - C::Gt => "gt", - C::Ge => "ge", +/// Stream canonical bytes without accumulating the rendered module. A writer +/// failure or resource limit can leave a prefix; it never exceeds the ceiling. +pub fn write_module( + module: &Module, + writer: &mut impl io::Write, + limits: PrintLimits, +) -> Result<(), PrintError> { + #[cfg(whale_wave_ir)] + { + wave::write_module(module, writer, limits) + } + #[cfg(not(whale_wave_ir))] + { + limits.validate()?; + // Reference builds retain the existing printer for compatibility. + crate::limits::check_module( + module, + crate::IrLimits { + max_nodes: limits.max_nodes, + max_type_depth: limits.max_depth, + max_const_depth: limits.max_depth, + ..crate::IrLimits::default() }, - print_const_expr(left), - print_const_expr(right) - ), + ) + .map_err(|_| PrintError::Nodes)?; + let output = reference::print_module(module); + if output.len() > limits.max_output_bytes { + return Err(PrintError::Output); + } + writer.write_all(output.as_bytes()).map_err(PrintError::Io) } } -fn print_term(t: &Terminator) -> String { - use Terminator::*; - match t { - Br { target } => format!("br label {target}"), - CBr { cond, then_bb, else_bb } => { - format!("cbr bool {cond}, label {then_bb}, label {else_bb}") - }, - Switch { ty, value, default_bb, cases } => { - let mut s = format!("switch {ty} {value}, label {default_bb} ["); - for (i, (c, bb)) in cases.iter().enumerate() { - if i != 0 { - s.push(','); - } - s.push_str(&format!(" {}: {bb}", fmt_const(c))); - } - s.push_str(" ]"); - s - }, - Ret { ty, value } => { - if *ty == Type::Void { - "ret void".to_string() - } else if let Some(v) = value { - format!("ret {ty} {v}") - } else { - format!("ret {ty} ") - } - }, - Trap { reason } => format!("trap reason=\"{}\"", escape(reason)), +/// Collect canonical bytes within the chosen ceiling and return no partial result. +pub fn try_print_module(module: &Module, limits: PrintLimits) -> Result { + let mut output = CappedBuffer::new(limits.max_output_bytes); + let result = write_module(module, &mut output, limits); + if output.allocation_failed { + return Err(PrintError::Allocation); } + result?; + String::from_utf8(output.bytes).map_err(|_| PrintError::Backend) } -fn fmt_binop(op: &BinOp) -> &'static str { - use BinOp::*; - match op { - Add => "add", - Sub => "sub", - Mul => "mul", - UDiv => "udiv", - SDiv => "sdiv", - URem => "urem", - SRem => "srem", - FAdd => "fadd", - FSub => "fsub", - FMul => "fmul", - FDiv => "fdiv", - FRem => "frem", - And => "and", - Or => "or", - Xor => "xor", - Shl => "shl", - LShr => "lshr", - AShr => "ashr", - } +struct CappedBuffer { + bytes: Vec, + limit: usize, + allocation_failed: bool, } -fn fmt_checked(op: &crate::CheckedOp) -> &'static str { - use crate::CheckedOp::*; - match op { - UAdd => "uadd", - USub => "usub", - UMul => "umul", - SAdd => "sadd", - SSub => "ssub", - SMul => "smul", +impl CappedBuffer { + fn new(limit: usize) -> Self { + Self { bytes: Vec::new(), limit, allocation_failed: false } } } -fn fmt_icmp(p: &ICmpPred) -> &'static str { - use ICmpPred::*; - match p { - Eq => "eq", - Ne => "ne", - Ult => "ult", - Ule => "ule", - Ugt => "ugt", - Uge => "uge", - Slt => "slt", - Sle => "sle", - Sgt => "sgt", - Sge => "sge", +impl io::Write for CappedBuffer { + fn write(&mut self, bytes: &[u8]) -> io::Result { + if bytes.len() > self.limit.saturating_sub(self.bytes.len()) { + return Err(io::Error::other("IR printer output limit exceeded")); + } + let required = self.bytes.len() + bytes.len(); + if required > self.bytes.capacity() { + let capacity = self.limit.min(required.max(self.bytes.capacity().saturating_mul(2))); + if self.bytes.try_reserve_exact(capacity - self.bytes.len()).is_err() { + self.allocation_failed = true; + return Err(io::Error::other("IR printer allocation failed")); + } + } + self.bytes.extend_from_slice(bytes); + Ok(bytes.len()) } -} -fn fmt_fcmp(p: &crate::FCmpPred) -> &'static str { - use crate::FCmpPred::*; - match p { - Oeq => "oeq", - One => "one", - Olt => "olt", - Ole => "ole", - Ogt => "ogt", - Oge => "oge", - Ord => "ord", - Uno => "uno", - Ueq => "ueq", - Une => "une", - Ult => "ult", - Ule => "ule", - Ugt => "ugt", - Uge => "uge", + fn flush(&mut self) -> io::Result<()> { + Ok(()) } } -fn fmt_cast(op: &crate::CastOp) -> &'static str { - use crate::CastOp::*; - match op { - CheckedInt => "checked_int", - ZExt => "zext", - SExt => "sext", - Trunc => "trunc", - FExt => "fext", - FTrunc => "ftrunc", - IToF_S => "itof_s", - IToF_U => "itof_u", - FToI_S => "ftoi_s", - FToI_U => "ftoi_u", - Bitcast => "bitcast", - PtrToInt => "ptrtoint", - IntToPtr => "inttoptr", +pub fn print_module(module: &Module) -> String { + #[cfg(whale_wave_ir)] + { + try_print_module(module, PrintLimits::default()).expect("printing canonical IR") } -} - -fn fmt_callee(c: &Callee) -> String { - match c { - Callee::Direct(id) => format!("@f{}", id.0), - Callee::Indirect(value) => format!("indirect {value}"), + #[cfg(not(whale_wave_ir))] + { + reference::print_module(module) } } -fn fmt_const(c: &ConstValue) -> String { - match c { - ConstValue::Bool(b) => { - if *b { - "true".into() - } else { - "false".into() - } - }, - ConstValue::I(i) => i.to_string(), - ConstValue::U(u) => u.to_string(), - ConstValue::F(x) => x.to_string(), +pub fn print_const_expr(expression: &ConstExpr) -> String { + #[cfg(whale_wave_ir)] + { + let limits = PrintLimits::default(); + let mut output = CappedBuffer::new(limits.max_output_bytes); + wave::write_expression(expression, &mut output, limits) + .expect("printing canonical constant expression"); + String::from_utf8(output.bytes).expect("canonical IR is UTF-8") } -} - -// String fields use one syntax, independent of Rust's Debug formatting. -// Printable Unicode is preserved; control and line-separator characters are escaped. -fn escape(s: &str) -> String { - let mut out = String::new(); - for ch in s.chars() { - match ch { - '\\' => out.push_str("\\\\"), - '"' => out.push_str("\\\""), - '\n' => out.push_str("\\n"), - '\r' => out.push_str("\\r"), - '\t' => out.push_str("\\t"), - '\0' => out.push_str("\\0"), - ch if ch.is_control() || matches!(ch, '\u{2028}' | '\u{2029}') => { - use std::fmt::Write; - write!(&mut out, "\\u{{{:x}}}", ch as u32).expect("writing to a String"); - }, - ch => out.push(ch), - } + #[cfg(not(whale_wave_ir))] + { + reference::print_const_expr(expression) } - out } -fn fmt_cmpop(op: &CmpOp) -> &'static str { - use CmpOp::*; - match op { - Eq => "eq", - Ne => "ne", - - SLt => "slt", - SLe => "sle", - SGt => "sgt", - SGe => "sge", - - ULt => "ult", - ULe => "ule", - UGt => "ugt", - UGe => "uge", - - FEq => "feq", - FNe => "fne", - FLt => "flt", - FLe => "fle", - FGt => "fgt", - FGe => "fge", - } -} +#[cfg(test)] +#[path = "printer_tests.rs"] +mod tests; diff --git a/ir/src/printer_reference.rs b/ir/src/printer_reference.rs new file mode 100644 index 0000000..9f3d3ef --- /dev/null +++ b/ir/src/printer_reference.rs @@ -0,0 +1,519 @@ +// SPDX-License-Identifier: MPL-2.0 + +use crate::{ + BasicBlock, BinOp, Callee, CmpOp, ConstValue, Endian, Function, ICmpPred, Instruction, Module, + Terminator, Type, +}; + +pub fn print_module(m: &Module) -> String { + let mut out = String::new(); + out.push_str("module {\n"); + out.push_str(&format!( + " format_version {}\n semantics_version {}\n", + crate::IR_FORMAT_VERSION, + crate::SEMANTICS_VERSION + )); + out.push_str(&format!(" target \"{}\"\n", escape(&m.target))); + out.push_str(" datalayout { "); + out.push_str(&format!( + "ptr={}, endian={}", + m.datalayout.ptr_bits, + match m.datalayout.endian { + Endian::Little => "little", + Endian::Big => "big", + } + )); + out.push_str(" }\n\n"); + for file in &m.sources.files { + out.push_str(&format!(" source_file @s{} \"{}\"\n", file.id, escape(&file.name))); + } + for original in &m.sources.originals { + out.push_str(&format!(" original {} ", original.id)); + if let Some(s) = &original.span { + out.push_str(&format!( + "@s{} {} {} {} {}\n", + s.file, s.line, s.column, s.end_line, s.end_column + )); + } else { + out.push_str("none\n"); + } + } + for mapping in &m.sources.mappings { + out.push_str(" source_map "); + match mapping.target { + crate::SourceTarget::Instruction { function, block, index } => { + out.push_str(&format!("instruction @f{} {} {}", function.0, block, index)) + }, + crate::SourceTarget::Terminator { function, block } => { + out.push_str(&format!("terminator @f{} {}", function.0, block)) + }, + crate::SourceTarget::Global(id) => out.push_str(&format!("global @g{}", id.0)), + } + out.push_str(&format!(" {}\n", mapping.original)); + } + + for g in &m.globals { + out.push_str(&format!( + " global @g{} \"{}\": {} = const {} {}, align {}, init_expr {}\n", + g.id.0, + escape(&g.name), + g.ty, + g.ty, + fmt_const(&g.init), + g.align, + print_const_expr(&g.init_expr) + )); + } + if !m.globals.is_empty() { + out.push('\n'); + } + + for g in &m.global_storage { + out.push_str(&format!(" storage @g{} \"{}\": {} = ", g.id.0, escape(&g.name), g.ty)); + match &g.init { + crate::GlobalStorageInit::Value(value) => { + out.push_str(&format!("value {} {}", g.ty, fmt_const(value))) + }, + crate::GlobalStorageInit::Uninitialized => out.push_str("uninitialized"), + } + out.push_str(&format!( + ", align {}, access {}, linkage {}", + g.align, + if g.readonly { "readonly" } else { "readwrite" }, + if g.linkage == crate::Linkage::Internal { "internal" } else { "external" } + )); + if let Some(name) = &g.link_name { + out.push_str(&format!(", link_name \"{}\"", escape(name))); + } + out.push('\n'); + } + if !m.global_storage.is_empty() { + out.push('\n'); + } + for d in &m.declarations { + out.push_str(&format!( + " declare @f{} \"{}\": {}, linkage {}", + d.id.0, + escape(&d.name), + d.signature, + match d.linkage { + crate::Linkage::Internal => "internal", + crate::Linkage::External => "external", + } + )); + if let Some(link) = &d.link_name { + out.push_str(&format!(", link_name \"{}\"", escape(link))); + } + out.push('\n'); + } + if !m.declarations.is_empty() { + out.push('\n'); + } + for f in &m.functions { + out.push_str(&print_function(f)); + out.push('\n'); + } + + out.push_str("}\n"); + out +} + +fn print_function(f: &Function) -> String { + let mut out = String::new(); + out.push_str(&format!(" fn @f{} \"{}\"(", f.id.0, escape(&f.name))); + for (i, p) in f.params.iter().enumerate() { + if i != 0 { + out.push_str(", "); + } + out.push_str(&format!("{} \"{}\": {}", p.id, escape(&p.name), p.ty)); + } + out.push_str(&format!(") -> {}, entry {} {{\n", f.ret_ty, f.entry)); + + for b in &f.blocks { + out.push_str(&print_block(b)); + } + + out.push_str(" }\n"); + out +} + +fn print_block(b: &BasicBlock) -> String { + let mut out = String::new(); + out.push_str(&format!(" {} \"{}\":\n", b.id, escape(&b.name))); + + for ins in &b.instructions { + out.push_str(" "); + out.push_str(&print_instr(ins)); + out.push('\n'); + } + + if let Some(t) = &b.terminator { + out.push_str(" "); + out.push_str(&print_term(t)); + out.push('\n'); + } + + out +} + +fn print_instr(i: &Instruction) -> String { + use Instruction::*; + match i { + GlobalAddr { dst, global, ty } => format!("{dst}: ptr<{ty}> = global_addr @g{}", global.0), + LifetimeEnd { ptr } => format!("lifetime_end {ptr}"), + PtrDiff { dst, lhs, rhs } => format!("{dst}: i128 = ptrdiff {lhs}, {rhs}"), + ConstDecl { dst, name, expression, value } => format!( + "{dst}: {} = const_decl \"{}\" {} => const {} {}", + expression.ty, + escape(name), + print_const_expr(expression), + expression.ty, + fmt_const(value) + ), + Const { dst, ty, value } => format!("{dst}: {ty} = const {ty} {}", fmt_const(value)), + Undef { dst, ty } => format!("{dst}: {ty} = undef {ty}"), + Mov { dst, ty, src } => format!("{dst}: {ty} = mov {ty} {src}"), + + Bin { dst, op, ty, lhs, rhs } => { + format!("{dst}: {ty} = {} {ty} {lhs}, {rhs}", fmt_binop(op)) + }, + Neg { dst, ty, src } => format!("{dst}: {ty} = neg {ty} {src}"), + Not { dst, ty, src } => format!("{dst}: {ty} = not {ty} {src}"), + + Cmp { dst, op, ty, lhs, rhs } => { + format!("{dst}: bool = cmp {} {ty} {lhs}, {rhs}", fmt_cmpop(op)) + }, + + ICmp { dst, pred, ty, lhs, rhs } => { + format!("{dst}: bool = icmp {} {ty} {lhs}, {rhs}", fmt_icmp(pred)) + }, + FCmp { dst, pred, ty, lhs, rhs } => { + format!("{dst}: bool = fcmp {} {ty} {lhs}, {rhs}", fmt_fcmp(pred)) + }, + + Select { dst, ty, cond, on_true, on_false } => { + format!("{dst}: {ty} = select bool {cond}, {ty} {on_true}, {ty} {on_false}") + }, + + Cast { dst, op, dst_ty, src_ty, src } => { + format!("{dst}: {dst_ty} = {} {src_ty} {src} to {dst_ty}", fmt_cast(op)) + }, + + Phi { dst, ty, incomings } => { + let mut s = format!("{dst}: {ty} = phi {ty} "); + for (i, (v, bb)) in incomings.iter().enumerate() { + if i != 0 { + s.push_str(", "); + } + s.push_str(&format!("[ {v}, {bb} ]")); + } + s + }, + + Extract { dst, dst_ty, tuple, index } => { + format!("{dst}: {dst_ty} = extract {tuple}, {}", index) + }, + + Checked { dst, op, ty, lhs, rhs } => { + format!("{dst}: tuple<{ty}, bool> = {}_chk {ty} {lhs}, {rhs}", fmt_checked(op)) + }, + + Alloca { dst, ty, align } => format!("{dst}: ptr<{ty}> = alloca {ty}, align {align}"), + + VolatileLoad { dst, ty, ptr, align } => { + format!("{dst}: {ty} = volatile_load {ty}, ptr<{ty}> {ptr}, align {align}") + }, + VolatileStore { ty, value, ptr, align } => { + format!("volatile_store {ty} {value}, ptr<{ty}> {ptr}, align {align}") + }, + Load { dst, ty, ptr, align } => { + format!("{dst}: {ty} = load {ty}, ptr<{ty}> {ptr}, align {align}") + }, + + Uninit { ty, ptr, align } => format!("uninit {ty}, ptr<{ty}> {ptr}, align {align}"), + Store { ty, value, ptr, align } => { + format!("store {ty} {value}, ptr<{ty}> {ptr}, align {align}") + }, + + Gep { dst, dst_ty, base_ptr, indices } => { + let mut s = format!("{dst}: {dst_ty} = gep {base_ptr}"); + for idx in indices { + s.push_str(&format!(", {idx}")); + } + s + }, + + Memcpy { dst, src, n, align } => { + format!("memcpy ptr {dst}, ptr {src}, u64 {n}, align {align}") + }, + + Memset { dst, val, n, align } => { + format!("memset ptr {dst}, u8 {val}, u64 {n}, align {align}") + }, + + NullFunction { dst, signature } => format!("{dst}: fnptr<{signature}> = null_function"), + FunctionAddr { dst, function, signature } => { + format!("{dst}: fnptr<{signature}> = function_addr @f{}", function.0) + }, + Call { convention, dst, ret_ty, callee, args } => { + let mut s = String::new(); + if let Some(v) = dst { + s.push_str(&format!("{v}: {ret_ty} = ")); + } + s.push_str(&format!( + "call {} {ret_ty} {}(", + match convention { + crate::CallingConvention::Whale => "whale", + crate::CallingConvention::SysV64 => "sysv64", + }, + fmt_callee(callee) + )); + for (i, a) in args.iter().enumerate() { + if i != 0 { + s.push_str(", "); + } + s.push_str(&format!("{a}")); + } + s.push(')'); + s + }, + + TrapIf { cond, reason } => format!("trap_if bool {cond}, reason=\"{}\"", escape(reason)), + } +} + +pub fn print_const_expr(expr: &crate::ConstExpr) -> String { + use crate::{ConstBinaryOp as B, ConstCompareOp as C, ConstExprKind as K, ConstRef}; + match &expr.kind { + K::Neg(value) => format!("neg({})", print_const_expr(value)), + K::Not(value) => format!("bit_not({})", print_const_expr(value)), + K::Literal(value) => format!("{} {}", expr.ty, fmt_const(value)), + K::Reference(reference) => match reference { + ConstRef::Global(id) => format!("{} @g{}", expr.ty, id.0), + ConstRef::Local(id) => format!("{} {id}", expr.ty), + }, + K::Binary { op, left, right } => format!( + "{}({}, {})", + match op { + B::Add => "add", + B::Sub => "sub", + B::Mul => "mul", + B::BitAnd => "bit_and", + B::BitOr => "bit_or", + B::BitXor => "bit_xor", + B::Div => "div", + B::Rem => "rem", + B::ShiftLeft => "shift_left", + B::ShiftRight => "shift_right", + B::LogicalAnd => "logical_and", + B::LogicalOr => "logical_or", + }, + print_const_expr(left), + print_const_expr(right) + ), + K::Compare { op, left, right } => format!( + "{}({}, {})", + match op { + C::Eq => "eq", + C::Ne => "ne", + C::Lt => "lt", + C::Le => "le", + C::Gt => "gt", + C::Ge => "ge", + }, + print_const_expr(left), + print_const_expr(right) + ), + } +} + +fn print_term(t: &Terminator) -> String { + use Terminator::*; + match t { + Br { target } => format!("br label {target}"), + CBr { cond, then_bb, else_bb } => { + format!("cbr bool {cond}, label {then_bb}, label {else_bb}") + }, + Switch { ty, value, default_bb, cases } => { + let mut s = format!("switch {ty} {value}, label {default_bb} ["); + for (i, (c, bb)) in cases.iter().enumerate() { + if i != 0 { + s.push(','); + } + s.push_str(&format!(" {}: {bb}", fmt_const(c))); + } + s.push_str(" ]"); + s + }, + Ret { ty, value } => { + if *ty == Type::Void { + "ret void".to_string() + } else if let Some(v) = value { + format!("ret {ty} {v}") + } else { + format!("ret {ty} ") + } + }, + Trap { reason } => format!("trap reason=\"{}\"", escape(reason)), + } +} + +fn fmt_binop(op: &BinOp) -> &'static str { + use BinOp::*; + match op { + Add => "add", + Sub => "sub", + Mul => "mul", + UDiv => "udiv", + SDiv => "sdiv", + URem => "urem", + SRem => "srem", + FAdd => "fadd", + FSub => "fsub", + FMul => "fmul", + FDiv => "fdiv", + FRem => "frem", + And => "and", + Or => "or", + Xor => "xor", + Shl => "shl", + LShr => "lshr", + AShr => "ashr", + } +} + +fn fmt_checked(op: &crate::CheckedOp) -> &'static str { + use crate::CheckedOp::*; + match op { + UAdd => "uadd", + USub => "usub", + UMul => "umul", + SAdd => "sadd", + SSub => "ssub", + SMul => "smul", + } +} + +fn fmt_icmp(p: &ICmpPred) -> &'static str { + use ICmpPred::*; + match p { + Eq => "eq", + Ne => "ne", + Ult => "ult", + Ule => "ule", + Ugt => "ugt", + Uge => "uge", + Slt => "slt", + Sle => "sle", + Sgt => "sgt", + Sge => "sge", + } +} + +fn fmt_fcmp(p: &crate::FCmpPred) -> &'static str { + use crate::FCmpPred::*; + match p { + Oeq => "oeq", + One => "one", + Olt => "olt", + Ole => "ole", + Ogt => "ogt", + Oge => "oge", + Ord => "ord", + Uno => "uno", + Ueq => "ueq", + Une => "une", + Ult => "ult", + Ule => "ule", + Ugt => "ugt", + Uge => "uge", + } +} + +fn fmt_cast(op: &crate::CastOp) -> &'static str { + use crate::CastOp::*; + match op { + CheckedInt => "checked_int", + ZExt => "zext", + SExt => "sext", + Trunc => "trunc", + FExt => "fext", + FTrunc => "ftrunc", + IToF_S => "itof_s", + IToF_U => "itof_u", + FToI_S => "ftoi_s", + FToI_U => "ftoi_u", + Bitcast => "bitcast", + PtrToInt => "ptrtoint", + IntToPtr => "inttoptr", + } +} + +fn fmt_callee(c: &Callee) -> String { + match c { + Callee::Direct(id) => format!("@f{}", id.0), + Callee::Indirect(value) => format!("indirect {value}"), + } +} + +fn fmt_const(c: &ConstValue) -> String { + match c { + ConstValue::Bool(b) => { + if *b { + "true".into() + } else { + "false".into() + } + }, + ConstValue::I(i) => i.to_string(), + ConstValue::U(u) => u.to_string(), + ConstValue::F(x) => x.to_string(), + } +} + +// String fields use one syntax, independent of Rust's Debug formatting. +// Printable Unicode is preserved; control and line-separator characters are escaped. +fn escape(s: &str) -> String { + let mut out = String::new(); + for ch in s.chars() { + match ch { + '\\' => out.push_str("\\\\"), + '"' => out.push_str("\\\""), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + '\0' => out.push_str("\\0"), + ch if ch.is_control() || matches!(ch, '\u{2028}' | '\u{2029}') => { + use std::fmt::Write; + write!(&mut out, "\\u{{{:x}}}", ch as u32).expect("writing to a String"); + }, + ch => out.push(ch), + } + } + out +} + +fn fmt_cmpop(op: &CmpOp) -> &'static str { + use CmpOp::*; + match op { + Eq => "eq", + Ne => "ne", + + SLt => "slt", + SLe => "sle", + SGt => "sgt", + SGe => "sge", + + ULt => "ult", + ULe => "ule", + UGt => "ugt", + UGe => "uge", + + FEq => "feq", + FNe => "fne", + FLt => "flt", + FLe => "fle", + FGt => "fgt", + FGe => "fge", + } +} diff --git a/ir/src/printer_tests.rs b/ir/src/printer_tests.rs new file mode 100644 index 0000000..d618891 --- /dev/null +++ b/ir/src/printer_tests.rs @@ -0,0 +1,598 @@ +// SPDX-License-Identifier: MPL-2.0 +use super::*; + +use crate::*; + +#[test] +fn canonical_empty_module_is_versioned_and_exact() { + let module = Module::new( + "x86_64-unknown-linux-gnu", + DataLayout { ptr_bits: 64, endian: Endian::Little }, + ); + let expected = format!( + "module {{\n format_version {}\n semantics_version {}\n target \"x86_64-unknown-linux-gnu\"\n datalayout {{ ptr=64, endian=little }}\n\n}}\n", + IR_FORMAT_VERSION, SEMANTICS_VERSION + ); + assert_eq!(print_module(&module), expected); +} + +fn exhaustive_module() -> Module { + let mut module = Module::new( + "name\"\\\n\r\t\0\u{7f}\u{85}\u{2028}😀", + DataLayout { ptr_bits: 32, endian: Endian::Big }, + ); + let names = "mixed\"\\\n\0\u{1f}\u{9f}\u{2029}한글"; + module.sources.files.push(SourceFile { id: 9, name: names.into() }); + module.sources.originals.push(OriginalNode { + id: u64::MAX, + span: Some(SourceSpan { file: 9, line: 1, column: 2, end_line: 3, end_column: 4 }), + }); + module.sources.originals.push(OriginalNode { id: 0, span: None }); + module.sources.mappings.extend([ + SourceMapping { + target: SourceTarget::Instruction { + function: FunctionId(8), + block: BlockId(9), + index: usize::MAX, + }, + original: u64::MAX, + }, + SourceMapping { + target: SourceTarget::Terminator { function: FunctionId(8), block: BlockId(9) }, + original: 1, + }, + SourceMapping { target: SourceTarget::Global(GlobalId(5)), original: 2 }, + ]); + let literal = |x| ConstExpr::literal(Type::I128, ConstValue::I(x)); + let mut expressions = vec![ + literal(i128::MIN), + ConstExpr { + ty: Type::I128, + kind: ConstExprKind::Reference(ConstRef::Global(GlobalId(u32::MAX))), + }, + ConstExpr { + ty: Type::I128, + kind: ConstExprKind::Reference(ConstRef::Local(ValueId(u32::MAX))), + }, + ConstExpr { ty: Type::I128, kind: ConstExprKind::Neg(Box::new(literal(12))) }, + ConstExpr { ty: Type::I128, kind: ConstExprKind::Not(Box::new(literal(12))) }, + ]; + for op in [ + ConstBinaryOp::Add, + ConstBinaryOp::Sub, + ConstBinaryOp::Mul, + ConstBinaryOp::BitAnd, + ConstBinaryOp::BitOr, + ConstBinaryOp::BitXor, + ConstBinaryOp::Div, + ConstBinaryOp::Rem, + ConstBinaryOp::ShiftLeft, + ConstBinaryOp::ShiftRight, + ConstBinaryOp::LogicalAnd, + ConstBinaryOp::LogicalOr, + ] { + expressions.push(ConstExpr { + ty: Type::I128, + kind: ConstExprKind::Binary { + op, + left: Box::new(literal(2)), + right: Box::new(literal(3)), + }, + }); + } + for op in [ + ConstCompareOp::Eq, + ConstCompareOp::Ne, + ConstCompareOp::Lt, + ConstCompareOp::Le, + ConstCompareOp::Gt, + ConstCompareOp::Ge, + ] { + expressions.push(ConstExpr { + ty: Type::Bool, + kind: ConstExprKind::Compare { + op, + left: Box::new(literal(2)), + right: Box::new(literal(3)), + }, + }); + } + for (i, expression) in expressions.iter().enumerate() { + module.globals.push(Global { + id: GlobalId(i as u32), + name: names.into(), + ty: expression.ty.clone(), + init: ConstValue::I(0), + init_expr: expression.clone(), + align: 16, + }); + } + for (i, init) in [ + GlobalStorageInit::Value(ConstValue::Bool(true)), + GlobalStorageInit::Value(ConstValue::Bool(false)), + GlobalStorageInit::Uninitialized, + ] + .into_iter() + .enumerate() + { + module.global_storage.push(GlobalStorage { + id: GlobalId(i as u32), + name: names.into(), + ty: Type::Bool, + init, + readonly: i % 2 == 0, + align: 8, + linkage: if i % 2 == 0 { Linkage::Internal } else { Linkage::External }, + link_name: if i % 2 == 0 { None } else { Some(names.into()) }, + }); + } + let mut types = vec![ + Type::Void, + Type::Bool, + Type::I1, + Type::U1, + Type::I8, + Type::I16, + Type::I32, + Type::I64, + Type::I128, + Type::U8, + Type::U16, + Type::U32, + Type::U64, + Type::U128, + Type::F16, + Type::F32, + Type::F64, + Type::Ptr(Box::new(Type::I8)), + Type::Array(Box::new(Type::U16), u64::MAX), + Type::Struct(vec![Type::Bool, Type::I32]), + Type::Tuple(vec![Type::Void, Type::U128]), + Type::Struct(vec![]), + Type::Tuple(vec![]), + ]; + let sig = FunctionSignature { + params: types.clone(), + ret: Type::Void, + convention: CallingConvention::Whale, + variadic: false, + }; + types.push(Type::FnPtr(Box::new(sig.clone()))); + module.declarations.push(FunctionDecl { + id: FunctionId(99), + name: names.into(), + signature: sig.clone(), + linkage: Linkage::Internal, + link_name: None, + }); + module.declarations.push(FunctionDecl { + id: FunctionId(100), + name: names.into(), + signature: FunctionSignature { + params: vec![], + ret: Type::I8, + convention: CallingConvention::SysV64, + variadic: true, + }, + linkage: Linkage::External, + link_name: Some(names.into()), + }); + let a = ValueId(1); + let b = ValueId(u32::MAX); + let c = ValueId(3); + let mut instructions = vec![ + Instruction::GlobalAddr { dst: a, global: GlobalId(5), ty: Type::I32 }, + Instruction::LifetimeEnd { ptr: b }, + Instruction::PtrDiff { dst: a, lhs: b, rhs: c }, + Instruction::ConstDecl { + dst: a, + name: names.into(), + expression: expressions[0].clone(), + value: ConstValue::I(i128::MIN), + }, + ]; + for ty in &types { + instructions.push(Instruction::Undef { dst: a, ty: ty.clone() }); + } + for value in [ + ConstValue::Bool(true), + ConstValue::Bool(false), + ConstValue::I(i128::MIN), + ConstValue::I(i128::MAX), + ConstValue::U(u128::MAX), + ConstValue::U(0), + ConstValue::F(FloatBits::F16(0x8000)), + ConstValue::F(FloatBits::F32(0x7fa01234)), + ConstValue::F(FloatBits::F64(0xffff123456789abc)), + ] { + instructions.push(Instruction::Const { dst: a, ty: Type::I128, value }); + } + instructions.push(Instruction::Mov { dst: a, ty: Type::I32, src: b }); + for op in [ + BinOp::Add, + BinOp::Sub, + BinOp::Mul, + BinOp::UDiv, + BinOp::SDiv, + BinOp::URem, + BinOp::SRem, + BinOp::FAdd, + BinOp::FSub, + BinOp::FMul, + BinOp::FDiv, + BinOp::FRem, + BinOp::And, + BinOp::Or, + BinOp::Xor, + BinOp::Shl, + BinOp::LShr, + BinOp::AShr, + ] { + instructions.push(Instruction::Bin { dst: a, op, ty: Type::I64, lhs: b, rhs: c }); + } + instructions.push(Instruction::Neg { dst: a, ty: Type::I32, src: b }); + instructions.push(Instruction::Not { dst: a, ty: Type::I32, src: b }); + for op in [ + CmpOp::Eq, + CmpOp::Ne, + CmpOp::SLt, + CmpOp::SLe, + CmpOp::SGt, + CmpOp::SGe, + CmpOp::ULt, + CmpOp::ULe, + CmpOp::UGt, + CmpOp::UGe, + CmpOp::FEq, + CmpOp::FNe, + CmpOp::FLt, + CmpOp::FLe, + CmpOp::FGt, + CmpOp::FGe, + ] { + instructions.push(Instruction::Cmp { dst: a, op, ty: Type::I32, lhs: b, rhs: c }); + } + for pred in [ + ICmpPred::Eq, + ICmpPred::Ne, + ICmpPred::Ult, + ICmpPred::Ule, + ICmpPred::Ugt, + ICmpPred::Uge, + ICmpPred::Slt, + ICmpPred::Sle, + ICmpPred::Sgt, + ICmpPred::Sge, + ] { + instructions.push(Instruction::ICmp { dst: a, pred, ty: Type::I32, lhs: b, rhs: c }); + } + for pred in [ + FCmpPred::Oeq, + FCmpPred::One, + FCmpPred::Olt, + FCmpPred::Ole, + FCmpPred::Ogt, + FCmpPred::Oge, + FCmpPred::Ord, + FCmpPred::Uno, + FCmpPred::Ueq, + FCmpPred::Une, + FCmpPred::Ult, + FCmpPred::Ule, + FCmpPred::Ugt, + FCmpPred::Uge, + ] { + instructions.push(Instruction::FCmp { dst: a, pred, ty: Type::F64, lhs: b, rhs: c }); + } + instructions.push(Instruction::Select { + dst: a, + ty: Type::I32, + cond: b, + on_true: c, + on_false: a, + }); + for op in [ + CastOp::CheckedInt, + CastOp::ZExt, + CastOp::SExt, + CastOp::Trunc, + CastOp::FExt, + CastOp::FTrunc, + CastOp::IToF_S, + CastOp::IToF_U, + CastOp::FToI_S, + CastOp::FToI_U, + CastOp::Bitcast, + CastOp::PtrToInt, + CastOp::IntToPtr, + ] { + instructions.push(Instruction::Cast { + dst: a, + op, + dst_ty: Type::U128, + src_ty: Type::I32, + src: b, + }); + } + instructions.extend([ + Instruction::Phi { + dst: a, + ty: Type::I32, + incomings: vec![(b, BlockId(1)), (c, BlockId(2))], + }, + Instruction::Phi { dst: a, ty: Type::I32, incomings: vec![] }, + Instruction::Extract { dst: a, dst_ty: Type::I32, tuple: b, index: 2 }, + ]); + for op in [ + CheckedOp::UAdd, + CheckedOp::USub, + CheckedOp::UMul, + CheckedOp::SAdd, + CheckedOp::SSub, + CheckedOp::SMul, + ] { + instructions.push(Instruction::Checked { dst: a, op, ty: Type::I32, lhs: b, rhs: c }); + } + instructions.extend([ + Instruction::Alloca { dst: a, ty: Type::I32, align: u32::MAX }, + Instruction::VolatileLoad { dst: a, ty: Type::I32, ptr: b, align: 4 }, + Instruction::VolatileStore { ty: Type::I32, value: a, ptr: b, align: 4 }, + Instruction::Load { dst: a, ty: Type::I32, ptr: b, align: 4 }, + Instruction::Uninit { ty: Type::I32, ptr: b, align: 4 }, + Instruction::Store { ty: Type::I32, value: a, ptr: b, align: 4 }, + Instruction::Gep { + dst: a, + dst_ty: Type::Ptr(Box::new(Type::I32)), + base_ptr: b, + indices: vec![a, b, c], + }, + Instruction::Gep { + dst: a, + dst_ty: Type::Ptr(Box::new(Type::I32)), + base_ptr: b, + indices: vec![], + }, + Instruction::Memcpy { dst: a, src: b, n: c, align: 1 }, + Instruction::Memset { dst: a, val: b, n: c, align: 1 }, + Instruction::NullFunction { dst: a, signature: sig.clone() }, + Instruction::FunctionAddr { dst: a, function: FunctionId(100), signature: sig.clone() }, + Instruction::Call { + convention: CallingConvention::Whale, + dst: Some(a), + ret_ty: Type::I32, + callee: Callee::Direct(FunctionId(99)), + args: vec![b, c], + }, + Instruction::Call { + convention: CallingConvention::SysV64, + dst: None, + ret_ty: Type::Void, + callee: Callee::Indirect(b), + args: vec![], + }, + Instruction::TrapIf { cond: a, reason: names.into() }, + ]); + let terms = vec![ + Some(Terminator::Br { target: BlockId(2) }), + Some(Terminator::CBr { cond: a, then_bb: BlockId(3), else_bb: BlockId(4) }), + Some(Terminator::Switch { + ty: Type::I128, + value: a, + default_bb: BlockId(1), + cases: vec![ + (ConstValue::I(i128::MIN), BlockId(2)), + (ConstValue::U(u128::MAX), BlockId(3)), + ], + }), + Some(Terminator::Switch { + ty: Type::Bool, + value: a, + default_bb: BlockId(1), + cases: vec![], + }), + Some(Terminator::Ret { ty: Type::I32, value: Some(a) }), + Some(Terminator::Ret { ty: Type::I32, value: None }), + Some(Terminator::Ret { ty: Type::Void, value: Some(a) }), + Some(Terminator::Trap { reason: names.into() }), + None, + ]; + module.functions.push(Function { + id: FunctionId(8), + name: names.into(), + params: types + .iter() + .enumerate() + .map(|(i, ty)| Param { id: ValueId(i as u32), name: names.into(), ty: ty.clone() }) + .collect(), + ret_ty: Type::Tuple(types), + blocks: terms + .into_iter() + .enumerate() + .map(|(i, terminator)| BasicBlock { + id: BlockId(i as u32), + name: names.into(), + instructions: if i == 0 { instructions.clone() } else { vec![] }, + terminator, + }) + .collect(), + entry: BlockId(0), + value_types: vec![], + }); + module +} + +#[test] +fn all_current_model_variants_match_canonical_reference() { + let module = exhaustive_module(); + assert_eq!(print_module(&module), reference::print_module(&module)); + for global in &module.globals { + assert_eq!( + print_const_expr(&global.init_expr), + reference::print_const_expr(&global.init_expr) + ); + } +} + +#[cfg(whale_wave_ir)] +#[test] +fn exact_byte_ceiling_and_streaming_writer_failure() { + let module = exhaustive_module(); + let expected = reference::print_module(&module); + let limits = PrintLimits { max_output_bytes: expected.len(), ..PrintLimits::default() }; + assert_eq!(try_print_module(&module, limits).unwrap(), expected); + assert!(matches!( + try_print_module(&module, PrintLimits { max_output_bytes: expected.len() - 1, ..limits }), + Err(PrintError::Output) + )); + struct Sink { + bytes: usize, + calls: usize, + } + + impl std::io::Write for Sink { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + assert!(bytes.len() <= 4096); + self.bytes += bytes.len(); + self.calls += 1; + Ok(bytes.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + let mut sink = Sink { bytes: 0, calls: 0 }; + write_module(&module, &mut sink, limits).unwrap(); + assert_eq!(sink.bytes, expected.len()); + assert!(sink.calls > 1); + struct Failing; + + impl std::io::Write for Failing { + fn write(&mut self, _: &[u8]) -> std::io::Result { + Err(std::io::Error::other("injected")) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + assert!(matches!(write_module(&module, &mut Failing, limits), Err(PrintError::Io(_)))); + for (limits, expected) in [ + (PrintLimits { max_output_bytes: 0, ..limits }, "output"), + (PrintLimits { max_nodes: 0, ..limits }, "model"), + (PrintLimits { max_work: 0, ..limits }, "work"), + (PrintLimits { max_stack: 0, ..limits }, "workspace"), + (PrintLimits { max_depth: 0, ..limits }, "depth"), + ] { + assert!(try_print_module(&module, limits).unwrap_err().to_string().contains(expected)); + } +} + +#[cfg(whale_wave_ir)] +#[test] +fn generated_128_bit_values_exact_float_bits_and_unicode() { + let mut seed = 0x123456789abcdef0u64; + let mut next = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + for _ in 0..4096 { + let low = next(); + let high = next(); + let bits = (u128::from(high) << 64) | u128::from(low); + for value in [ + ConstValue::I(bits as i128), + ConstValue::U(bits), + ConstValue::F(FloatBits::F16(low as u16)), + ConstValue::F(FloatBits::F32(low as u32)), + ConstValue::F(FloatBits::F64(high)), + ] { + let expr = ConstExpr::literal(Type::U128, value); + assert_eq!(print_const_expr(&expr), reference::print_const_expr(&expr)); + } + } + let mut module = Module::new("", DataLayout { ptr_bits: 64, endian: Endian::Little }); + module.target = (0..=159) + .filter_map(char::from_u32) + .chain(['\u{2028}', '\u{2029}', 'é', '🦀', '\u{10ffff}']) + .collect(); + assert_eq!(print_module(&module), reference::print_module(&module)); +} + +#[cfg(whale_wave_ir)] +#[test] +fn long_instruction_lists_use_bounded_resumable_workspace() { + let mut module = Module::new( + "x86_64-unknown-linux-gnu", + DataLayout { ptr_bits: 64, endian: Endian::Little }, + ); + module.functions.push(Function { + id: FunctionId(0), + name: "long".into(), + params: vec![], + ret_ty: Type::Void, + blocks: vec![BasicBlock { + id: BlockId(0), + name: "entry".into(), + instructions: (0..60_000) + .map(|i| Instruction::Const { + dst: ValueId(i), + ty: Type::I32, + value: ConstValue::I(i128::from(i)), + }) + .collect(), + terminator: Some(Terminator::Ret { ty: Type::Void, value: None }), + }], + entry: BlockId(0), + value_types: vec![], + }); + let limits = PrintLimits { max_stack: 128, ..PrintLimits::default() }; + assert_eq!(try_print_module(&module, limits).unwrap(), reference::print_module(&module)); +} + +#[cfg(whale_wave_ir)] +#[test] +fn nested_function_signatures_do_not_confuse_model_and_vm_depth() { + let mut ty = Type::I32; + for _ in 0..180 { + ty = Type::FnPtr(Box::new(FunctionSignature::whale(vec![], ty))); + } + let expression = ConstExpr::literal(ty, ConstValue::U(0)); + let limits = PrintLimits { max_depth: 256, ..PrintLimits::default() }; + let mut output = Vec::new(); + wave::write_expression(&expression, &mut output, limits).unwrap(); + assert_eq!(String::from_utf8(output).unwrap(), reference::print_const_expr(&expression)); +} + +#[cfg(whale_wave_ir)] +#[test] +fn printer_preserves_the_supported_256_level_type_and_constant_ceiling() { + let mut ty = Type::I32; + for _ in 0..MAX_IR_NESTING { + ty = Type::FnPtr(Box::new(FunctionSignature::whale(vec![ty], Type::Void))); + } + let mut module = Module::new("x86_64-whale-linux", DataLayout::default_64bit_le()); + module.declarations.push(FunctionDecl { + id: FunctionId(0), + name: "deep".into(), + signature: FunctionSignature::whale(vec![ty], Type::Void), + linkage: Linkage::External, + link_name: Some("deep".into()), + }); + assert_eq!(print_module(&module), reference::print_module(&module)); + assert!(matches!( + try_print_module( + &module, + PrintLimits { max_depth: MAX_IR_NESTING - 1, ..PrintLimits::default() } + ), + Err(PrintError::Depth) + )); + let mut expression = ConstExpr::literal(Type::I32, ConstValue::I(0)); + for _ in 0..MAX_IR_NESTING { + expression = ConstExpr { ty: Type::I32, kind: ConstExprKind::Neg(Box::new(expression)) }; + } + assert_eq!(print_const_expr(&expression), reference::print_const_expr(&expression)); +} diff --git a/ir/src/printer_wave.rs b/ir/src/printer_wave.rs new file mode 100644 index 0000000..f234dd4 --- /dev/null +++ b/ir/src/printer_wave.rs @@ -0,0 +1,711 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Allocation and borrowed-model transport for the Wave canonical printer. +//! All text grammar, numeric spelling and escaping are owned by printer.wave. + +use super::{PrintError, PrintLimits}; + +use crate::*; + +use std::io::Write; + +const NONE: u64 = u64::MAX; + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct Node([u64; 12]); + +#[repr(C)] +struct State { + nodes: *const Node, + node_count: u64, + edges: *const u64, + edge_count: u64, + stack: *mut [u64; 10], + stack_capacity: u64, + stack_len: u64, + output_limit: u64, + total: u64, + work: u64, + depth_limit: u64, + status: u64, + initialized: u64, +} + +unsafe extern "C" { + fn whale_ir_print_step( + state: *mut State, + root: u64, + output: *mut u8, + capacity: u64, + written: *mut u64, + ) -> i32; +} + +macro_rules! node { + ($self:ident, $tag:expr $(, $field:expr)* $(,)?) => {{ + let fields = [$($field),*]; + $self.add($tag, &fields) + }}; +} + +struct Transport { + nodes: Vec, + edges: Vec, + limits: PrintLimits, + type_depth: usize, + expression_depth: usize, +} + +impl Transport { + fn new(limits: PrintLimits) -> Self { + Self { nodes: Vec::new(), edges: Vec::new(), limits, type_depth: 0, expression_depth: 0 } + } + + fn add(&mut self, tag: u64, fields: &[u64]) -> Result { + if self.nodes.len() >= self.limits.max_nodes { + return Err(PrintError::Nodes); + } + self.nodes.try_reserve(1).map_err(|_| PrintError::Allocation)?; + let mut n = Node::default(); + n.0[0] = tag; + n.0[1..1 + fields.len()].copy_from_slice(fields); + let id = self.nodes.len() as u64; + self.nodes.push(n); + Ok(id) + } + + fn string(&mut self, value: &str) -> Result { + node!(self, 30, value.as_ptr() as u64, value.len() as u64) + } + + fn list(&mut self, values: &[u64]) -> Result<(u64, u64), PrintError> { + if values.len() > self.limits.max_nodes.saturating_sub(self.edges.len()) { + return Err(PrintError::Nodes); + } + self.edges.try_reserve(values.len()).map_err(|_| PrintError::Allocation)?; + let start = self.edges.len() as u64; + self.edges.extend_from_slice(values); + Ok((start, values.len() as u64)) + } + + fn collect( + &mut self, + items: &[T], + mut visit: impl FnMut(&mut Self, &T) -> Result, + ) -> Result<(u64, u64), PrintError> { + if items.len() > self.limits.max_nodes.saturating_sub(self.nodes.len()) { + return Err(PrintError::Nodes); + } + let mut values = Vec::new(); + values.try_reserve(items.len()).map_err(|_| PrintError::Allocation)?; + for item in items { + values.push(visit(self, item)?); + } + self.list(&values) + } + + fn ty(&mut self, ty: &Type) -> Result { + if self.type_depth > self.limits.max_depth { + return Err(PrintError::Depth); + } + self.type_depth += 1; + let result = match ty { + Type::Void => self.add(1, &[]), + Type::Bool => self.add(2, &[]), + Type::I1 => self.add(3, &[]), + Type::U1 => self.add(4, &[]), + Type::I8 => self.add(5, &[]), + Type::I16 => self.add(6, &[]), + Type::I32 => self.add(7, &[]), + Type::I64 => self.add(8, &[]), + Type::I128 => self.add(9, &[]), + Type::U8 => self.add(10, &[]), + Type::U16 => self.add(11, &[]), + Type::U32 => self.add(12, &[]), + Type::U64 => self.add(13, &[]), + Type::U128 => self.add(14, &[]), + Type::F16 => self.add(15, &[]), + Type::F32 => self.add(16, &[]), + Type::F64 => self.add(17, &[]), + Type::Ptr(inner) => node!(self, 18, self.ty(inner)?), + Type::FnPtr(signature) => node!(self, 19, self.signature(signature)?), + Type::Array(inner, count) => node!(self, 20, self.ty(inner)?, *count), + Type::Struct(fields) | Type::Tuple(fields) => { + let (first, count) = self.collect(fields, Self::ty)?; + node!(self, if matches!(ty, Type::Struct(_)) { 21 } else { 22 }, first, count) + }, + }; + self.type_depth -= 1; + result + } + + fn signature(&mut self, signature: &FunctionSignature) -> Result { + let (first, count) = self.collect(&signature.params, Self::ty)?; + node!( + self, + 23, + convention(signature.convention), + first, + count, + self.ty(&signature.ret)?, + u64::from(signature.variadic) + ) + } + + fn constant(&mut self, value: &ConstValue) -> Result { + match value { + ConstValue::Bool(value) => node!(self, 31, u64::from(*value)), + ConstValue::I(value) => node!(self, 32, *value as u64, (*value >> 64) as u64), + ConstValue::U(value) => node!(self, 33, *value as u64, (*value >> 64) as u64), + ConstValue::F(value) => node!(self, 34, value.bits(), u64::from(value.width())), + } + } + + fn expression(&mut self, expression: &ConstExpr) -> Result { + if self.expression_depth > self.limits.max_depth { + return Err(PrintError::Depth); + } + self.expression_depth += 1; + let result = match &expression.kind { + ConstExprKind::Literal(value) => { + node!(self, 40, self.ty(&expression.ty)?, self.constant(value)?) + }, + ConstExprKind::Reference(reference) => { + let reference = match reference { + ConstRef::Global(id) => node!(self, 37, u64::from(id.0))?, + ConstRef::Local(id) => node!(self, 35, u64::from(id.0))?, + }; + node!(self, 41, self.ty(&expression.ty)?, reference) + }, + ConstExprKind::Neg(value) => node!(self, 42, self.expression(value)?), + ConstExprKind::Not(value) => node!(self, 43, self.expression(value)?), + ConstExprKind::Binary { op, left, right } => node!( + self, + 44, + binary_constant(op), + self.expression(left)?, + self.expression(right)? + ), + ConstExprKind::Compare { op, left, right } => node!( + self, + 45, + compare_constant(op), + self.expression(left)?, + self.expression(right)? + ), + }; + self.expression_depth -= 1; + result + } + + fn group(&mut self, first: u64, count: u64, gap: bool) -> Result { + node!(self, 51, first, count, u64::from(gap)) + } + + fn module(&mut self, module: &Module) -> Result { + let target = self.string(&module.target)?; + let (first, count) = self.collect(&module.sources.files, |this, file| { + node!(this, 52, u64::from(file.id), this.string(&file.name)?) + })?; + let files = self.group(first, count, false)?; + let (first, count) = self.collect(&module.sources.originals, |this, original| { + let span = if let Some(span) = &original.span { + node!( + this, + 54, + u64::from(span.file), + u64::from(span.line), + u64::from(span.column), + u64::from(span.end_line), + u64::from(span.end_column) + )? + } else { + NONE + }; + node!(this, 53, original.id, span) + })?; + let originals = self.group(first, count, false)?; + let (first, count) = + self.collect(&module.sources.mappings, |this, mapping| match mapping.target { + SourceTarget::Instruction { function, block, index } => node!( + this, + 55, + u64::from(function.0), + u64::from(block.0), + index as u64, + mapping.original + ), + SourceTarget::Terminator { function, block } => { + node!(this, 56, u64::from(function.0), u64::from(block.0), mapping.original) + }, + SourceTarget::Global(id) => node!(this, 57, u64::from(id.0), mapping.original), + })?; + let mappings = self.group(first, count, false)?; + let (first, count) = self.collect(&module.globals, |this, global| { + node!( + this, + 58, + u64::from(global.id.0), + this.string(&global.name)?, + this.ty(&global.ty)?, + this.constant(&global.init)?, + u64::from(global.align), + this.expression(&global.init_expr)? + ) + })?; + let globals = self.group(first, count, true)?; + let (first, count) = self.collect(&module.global_storage, |this, global| { + let init = match &global.init { + GlobalStorageInit::Value(value) => this.constant(value)?, + GlobalStorageInit::Uninitialized => NONE, + }; + let link_name = match &global.link_name { + Some(name) => this.string(name)?, + None => NONE, + }; + node!( + this, + 59, + u64::from(global.id.0), + this.string(&global.name)?, + this.ty(&global.ty)?, + init, + u64::from(global.align), + u64::from(global.readonly), + linkage(global.linkage), + link_name + ) + })?; + let storage = self.group(first, count, true)?; + let (first, count) = self.collect(&module.declarations, |this, declaration| { + let link_name = match &declaration.link_name { + Some(name) => this.string(name)?, + None => NONE, + }; + node!( + this, + 60, + u64::from(declaration.id.0), + this.string(&declaration.name)?, + this.signature(&declaration.signature)?, + linkage(declaration.linkage), + link_name + ) + })?; + let declarations = self.group(first, count, true)?; + let (first, count) = self.collect(&module.functions, Self::function)?; + let functions = self.group(first, count, false)?; + let (first, count) = self.list(&[globals, storage, declarations, functions])?; + let entities = self.group(first, count, false)?; + node!( + self, + 50, + target, + u64::from(module.datalayout.ptr_bits), + if module.datalayout.endian == Endian::Little { 0 } else { 1 }, + files, + originals, + mappings, + entities, + u64::from(crate::IR_FORMAT_VERSION), + u64::from(crate::SEMANTICS_VERSION) + ) + } + + fn function(&mut self, function: &Function) -> Result { + let (params, param_count) = self.collect(&function.params, |this, param| { + node!(this, 62, u64::from(param.id.0), this.string(¶m.name)?, this.ty(¶m.ty)?) + })?; + let (blocks, block_count) = self.collect(&function.blocks, |this, block| { + let (instructions, instruction_count) = + this.collect(&block.instructions, Self::instruction)?; + let term = match &block.terminator { + Some(term) => this.terminator(term)?, + None => NONE, + }; + node!( + this, + 63, + u64::from(block.id.0), + this.string(&block.name)?, + instructions, + instruction_count, + term + ) + })?; + node!( + self, + 61, + u64::from(function.id.0), + self.string(&function.name)?, + params, + param_count, + self.ty(&function.ret_ty)?, + u64::from(function.entry.0), + blocks, + block_count + ) + } + + fn instruction(&mut self, instruction: &Instruction) -> Result { + use Instruction::*; + let v = |value: &ValueId| u64::from(value.0); + match instruction { + GlobalAddr { dst, global, ty } => { + node!(self, 100, v(dst), u64::from(global.0), self.ty(ty)?) + }, + LifetimeEnd { ptr } => node!(self, 101, v(ptr)), + PtrDiff { dst, lhs, rhs } => node!(self, 102, v(dst), v(lhs), v(rhs)), + ConstDecl { dst, name, expression, value } => node!( + self, + 103, + v(dst), + self.string(name)?, + self.expression(expression)?, + self.constant(value)?, + self.ty(&expression.ty)? + ), + Const { dst, ty, value } => { + node!(self, 104, v(dst), self.ty(ty)?, self.constant(value)?) + }, + Undef { dst, ty } => node!(self, 105, v(dst), self.ty(ty)?), + Mov { dst, ty, src } => node!(self, 106, v(dst), self.ty(ty)?, v(src)), + Bin { dst, op, ty, lhs, rhs } => { + node!(self, 107, v(dst), binop(op), self.ty(ty)?, v(lhs), v(rhs)) + }, + Neg { dst, ty, src } => node!(self, 108, v(dst), self.ty(ty)?, v(src)), + Not { dst, ty, src } => node!(self, 109, v(dst), self.ty(ty)?, v(src)), + Cmp { dst, op, ty, lhs, rhs } => { + node!(self, 110, v(dst), cmpop(op), self.ty(ty)?, v(lhs), v(rhs)) + }, + ICmp { dst, pred, ty, lhs, rhs } => { + node!(self, 111, v(dst), icmp(pred), self.ty(ty)?, v(lhs), v(rhs)) + }, + FCmp { dst, pred, ty, lhs, rhs } => { + node!(self, 112, v(dst), fcmp(pred), self.ty(ty)?, v(lhs), v(rhs)) + }, + Select { dst, ty, cond, on_true, on_false } => { + node!(self, 113, v(dst), self.ty(ty)?, v(cond), v(on_true), v(on_false)) + }, + Cast { dst, op, dst_ty, src_ty, src } => { + node!(self, 114, v(dst), cast(op), self.ty(dst_ty)?, self.ty(src_ty)?, v(src)) + }, + Phi { dst, ty, incomings } => { + let (first, count) = self.collect(incomings, |this, (value, block)| { + node!(this, 140, v(value), u64::from(block.0)) + })?; + node!(self, 115, v(dst), self.ty(ty)?, first, count) + }, + Extract { dst, dst_ty, tuple, index } => { + node!(self, 116, v(dst), self.ty(dst_ty)?, v(tuple), u64::from(*index)) + }, + Checked { dst, op, ty, lhs, rhs } => { + node!(self, 117, v(dst), checked(op), self.ty(ty)?, v(lhs), v(rhs)) + }, + Alloca { dst, ty, align } => node!(self, 118, v(dst), self.ty(ty)?, u64::from(*align)), + VolatileLoad { dst, ty, ptr, align } => { + node!(self, 119, v(dst), self.ty(ty)?, v(ptr), u64::from(*align)) + }, + VolatileStore { ty, value, ptr, align } => { + node!(self, 120, self.ty(ty)?, v(value), v(ptr), u64::from(*align)) + }, + Load { dst, ty, ptr, align } => { + node!(self, 121, v(dst), self.ty(ty)?, v(ptr), u64::from(*align)) + }, + Uninit { ty, ptr, align } => node!(self, 122, self.ty(ty)?, v(ptr), u64::from(*align)), + Store { ty, value, ptr, align } => { + node!(self, 123, self.ty(ty)?, v(value), v(ptr), u64::from(*align)) + }, + Gep { dst, dst_ty, base_ptr, indices } => { + let (first, count) = + self.collect(indices, |this, index| node!(this, 35, v(index)))?; + node!(self, 124, v(dst), self.ty(dst_ty)?, v(base_ptr), first, count) + }, + Memcpy { dst, src, n, align } => { + node!(self, 125, v(dst), v(src), v(n), u64::from(*align)) + }, + Memset { dst, val, n, align } => { + node!(self, 126, v(dst), v(val), v(n), u64::from(*align)) + }, + NullFunction { dst, signature } => node!(self, 127, v(dst), self.signature(signature)?), + FunctionAddr { dst, function, signature } => { + node!(self, 128, v(dst), u64::from(function.0), self.signature(signature)?) + }, + Call { convention: cc, dst, ret_ty, callee, args } => { + let callee = match callee { + Callee::Direct(id) => node!(self, 141, u64::from(id.0))?, + Callee::Indirect(value) => node!(self, 142, v(value))?, + }; + let (first, count) = self.collect(args, |this, arg| node!(this, 35, v(arg)))?; + node!( + self, + 129, + convention(*cc), + dst.map(|id| u64::from(id.0)).unwrap_or(NONE), + self.ty(ret_ty)?, + callee, + first, + count + ) + }, + TrapIf { cond, reason } => node!(self, 130, v(cond), self.string(reason)?), + } + } + + fn terminator(&mut self, term: &Terminator) -> Result { + match term { + Terminator::Br { target } => node!(self, 150, u64::from(target.0)), + Terminator::CBr { cond, then_bb, else_bb } => { + node!(self, 151, u64::from(cond.0), u64::from(then_bb.0), u64::from(else_bb.0)) + }, + Terminator::Switch { ty, value, default_bb, cases } => { + let (first, count) = self.collect(cases, |this, (constant, block)| { + node!(this, 155, this.constant(constant)?, u64::from(block.0)) + })?; + node!( + self, + 152, + self.ty(ty)?, + u64::from(value.0), + u64::from(default_bb.0), + first, + count + ) + }, + Terminator::Ret { ty, value } => { + node!( + self, + 153, + self.ty(ty)?, + value.map(|value| u64::from(value.0)).unwrap_or(NONE) + ) + }, + Terminator::Trap { reason } => node!(self, 154, self.string(reason)?), + } + } + + fn write(&self, root: u64, writer: &mut impl Write) -> Result<(), PrintError> { + let mut stack = Vec::new(); + let capacity = + self.limits.max_stack.min(self.nodes.len().saturating_mul(32).saturating_add(128)); + stack.try_reserve_exact(capacity).map_err(|_| PrintError::Allocation)?; + stack.resize(capacity, [0u64; 10]); + let mut state = State { + nodes: self.nodes.as_ptr(), + node_count: self.nodes.len() as u64, + edges: self.edges.as_ptr(), + edge_count: self.edges.len() as u64, + stack: stack.as_mut_ptr(), + stack_capacity: stack.len() as u64, + stack_len: 0, + output_limit: self.limits.max_output_bytes as u64, + total: 0, + work: self.limits.max_work as u64, + depth_limit: 1024, + status: 0, + initialized: 0, + }; + let mut buffer = [0u8; 4096]; + loop { + let mut written = 0; + // SAFETY: all model spans are borrowed from the live module; the + // mutable task and output spans are exclusively owned by this call. + let status = unsafe { + whale_ir_print_step( + &mut state, + root, + buffer.as_mut_ptr(), + buffer.len() as u64, + &mut written, + ) + }; + if written > buffer.len() as u64 || state.total > self.limits.max_output_bytes as u64 { + return Err(PrintError::Backend); + } + if status != 0 && status != 6 { + return Err(match status { + 2 => PrintError::Output, + 3 => PrintError::Stack, + 4 => PrintError::Work, + 5 => PrintError::Depth, + _ => PrintError::Backend, + }); + } + writer.write_all(&buffer[..written as usize]).map_err(PrintError::Io)?; + if status == 0 { + return Ok(()); + } + } + } +} + +pub(super) fn write_module( + module: &Module, + writer: &mut impl Write, + limits: PrintLimits, +) -> Result<(), PrintError> { + limits.validate()?; + let mut model = Transport::new(limits); + let root = model.module(module)?; + model.write(root, writer) +} + +pub(super) fn write_expression( + expression: &ConstExpr, + writer: &mut impl Write, + limits: PrintLimits, +) -> Result<(), PrintError> { + limits.validate()?; + let mut model = Transport::new(limits); + let root = model.expression(expression)?; + model.write(root, writer) +} + +fn convention(value: CallingConvention) -> u64 { + match value { + CallingConvention::Whale => 0, + CallingConvention::SysV64 => 1, + } +} + +fn linkage(value: Linkage) -> u64 { + match value { + Linkage::Internal => 0, + Linkage::External => 1, + } +} + +fn binary_constant(value: &ConstBinaryOp) -> u64 { + match value { + ConstBinaryOp::Add => 0, + ConstBinaryOp::Sub => 1, + ConstBinaryOp::Mul => 2, + ConstBinaryOp::BitAnd => 3, + ConstBinaryOp::BitOr => 4, + ConstBinaryOp::BitXor => 5, + ConstBinaryOp::Div => 6, + ConstBinaryOp::Rem => 7, + ConstBinaryOp::ShiftLeft => 8, + ConstBinaryOp::ShiftRight => 9, + ConstBinaryOp::LogicalAnd => 10, + ConstBinaryOp::LogicalOr => 11, + } +} + +fn compare_constant(value: &ConstCompareOp) -> u64 { + match value { + ConstCompareOp::Eq => 0, + ConstCompareOp::Ne => 1, + ConstCompareOp::Lt => 2, + ConstCompareOp::Le => 3, + ConstCompareOp::Gt => 4, + ConstCompareOp::Ge => 5, + } +} + +fn binop(value: &BinOp) -> u64 { + match value { + BinOp::Add => 0, + BinOp::Sub => 1, + BinOp::Mul => 2, + BinOp::UDiv => 3, + BinOp::SDiv => 4, + BinOp::URem => 5, + BinOp::SRem => 6, + BinOp::FAdd => 7, + BinOp::FSub => 8, + BinOp::FMul => 9, + BinOp::FDiv => 10, + BinOp::FRem => 11, + BinOp::And => 12, + BinOp::Or => 13, + BinOp::Xor => 14, + BinOp::Shl => 15, + BinOp::LShr => 16, + BinOp::AShr => 17, + } +} + +fn cmpop(value: &CmpOp) -> u64 { + match value { + CmpOp::Eq => 0, + CmpOp::Ne => 1, + CmpOp::SLt => 2, + CmpOp::SLe => 3, + CmpOp::SGt => 4, + CmpOp::SGe => 5, + CmpOp::ULt => 6, + CmpOp::ULe => 7, + CmpOp::UGt => 8, + CmpOp::UGe => 9, + CmpOp::FEq => 10, + CmpOp::FNe => 11, + CmpOp::FLt => 12, + CmpOp::FLe => 13, + CmpOp::FGt => 14, + CmpOp::FGe => 15, + } +} + +fn icmp(value: &ICmpPred) -> u64 { + match value { + ICmpPred::Eq => 0, + ICmpPred::Ne => 1, + ICmpPred::Ult => 2, + ICmpPred::Ule => 3, + ICmpPred::Ugt => 4, + ICmpPred::Uge => 5, + ICmpPred::Slt => 6, + ICmpPred::Sle => 7, + ICmpPred::Sgt => 8, + ICmpPred::Sge => 9, + } +} + +fn fcmp(value: &FCmpPred) -> u64 { + match value { + FCmpPred::Oeq => 0, + FCmpPred::One => 1, + FCmpPred::Olt => 2, + FCmpPred::Ole => 3, + FCmpPred::Ogt => 4, + FCmpPred::Oge => 5, + FCmpPred::Ord => 6, + FCmpPred::Uno => 7, + FCmpPred::Ueq => 8, + FCmpPred::Une => 9, + FCmpPred::Ult => 10, + FCmpPred::Ule => 11, + FCmpPred::Ugt => 12, + FCmpPred::Uge => 13, + } +} + +fn cast(value: &CastOp) -> u64 { + match value { + CastOp::CheckedInt => 0, + CastOp::ZExt => 1, + CastOp::SExt => 2, + CastOp::Trunc => 3, + CastOp::FExt => 4, + CastOp::FTrunc => 5, + CastOp::IToF_S => 6, + CastOp::IToF_U => 7, + CastOp::FToI_S => 8, + CastOp::FToI_U => 9, + CastOp::Bitcast => 10, + CastOp::PtrToInt => 11, + CastOp::IntToPtr => 12, + } +} + +fn checked(value: &CheckedOp) -> u64 { + match value { + CheckedOp::UAdd => 0, + CheckedOp::USub => 1, + CheckedOp::UMul => 2, + CheckedOp::SAdd => 3, + CheckedOp::SSub => 4, + CheckedOp::SMul => 5, + } +} diff --git a/ir/src/source.rs b/ir/src/source.rs index 2d4d757..1a36161 100644 --- a/ir/src/source.rs +++ b/ir/src/source.rs @@ -5,6 +5,7 @@ use crate::{BlockId, FunctionId, GlobalId, Module}; use diagnostic::EscapedName; +#[cfg(any(not(whale_wave_ir), test))] use std::collections::{HashMap, HashSet}; #[cfg_attr(feature = "socket", derive(serde::Serialize, serde::Deserialize))] @@ -137,6 +138,23 @@ impl SourceMetadata { } pub fn validate(&self, module: &Module) -> Result<(), SourceMetadataError> { + #[cfg(whale_wave_ir)] + { + crate::source_wave::validate(self, module, crate::IrLimits::default().max_analysis_work) + .map(|_| ()) + .map_err(|error| match error { + crate::source_wave::ValidationError::Invalid(error) => error, + crate::source_wave::ValidationError::Work => { + SourceMetadataError("source metadata work limit exceeded") + }, + }) + } + #[cfg(not(whale_wave_ir))] + self.validate_reference(module) + } + + #[cfg(any(not(whale_wave_ir), test))] + fn validate_reference(&self, module: &Module) -> Result<(), SourceMetadataError> { if self.files.is_empty() && self.originals.is_empty() && self.mappings.is_empty() { return Ok(()); } @@ -223,3 +241,91 @@ impl SourceMetadata { Ok(()) } } + +#[cfg(all(test, whale_wave_ir))] +mod wave_tests { + use super::*; + + use crate::*; + + #[test] + fn wave_metadata_matches_reference_identity_span_and_mapping_rules() { + let mut module = Module::new("x86_64-whale-linux", DataLayout::default_64bit_le()); + let mut block = BasicBlock::new(BlockId(17), "body"); + block.instructions.push(Instruction::Const { + dst: ValueId(0), + ty: Type::U8, + value: ConstValue::U(1), + }); + block.terminator = Some(Terminator::Ret { ty: Type::Void, value: None }); + module.functions.push(Function { + id: FunctionId(91), + name: "probe".into(), + params: vec![], + ret_ty: Type::Void, + blocks: vec![block], + entry: BlockId(17), + value_types: vec![], + }); + let valid = SourceMetadata { + files: vec![SourceFile { id: u32::MAX, name: "경로/source.wave".into() }], + originals: vec![OriginalNode { + id: u64::MAX, + span: Some(SourceSpan { + file: u32::MAX, + line: 9, + column: 4, + end_line: 9, + end_column: 7, + }), + }], + mappings: vec![SourceMapping { + original: u64::MAX, + target: SourceTarget::Instruction { + function: FunctionId(91), + block: BlockId(17), + index: 0, + }, + }], + }; + for defect in 0..16 { + let mut m = valid.clone(); + match defect { + 0 => {}, + 1 => m.files[0].name.clear(), + 2 => m.files[0].name.push('\0'), + 3 => m.files.push(m.files[0].clone()), + 4 => m.originals.push(m.originals[0].clone()), + 5 => m.originals[0].span.as_mut().unwrap().file = 7, + 6 => m.originals[0].span.as_mut().unwrap().line = 0, + 7 => m.originals[0].span.as_mut().unwrap().column = 0, + 8 => m.originals[0].span.as_mut().unwrap().end_line = 8, + 9 => m.originals[0].span.as_mut().unwrap().end_column = 3, + 10 => m.mappings[0].original = 0, + 11 => m.mappings.push(m.mappings[0].clone()), + 12 => { + m.mappings[0].target = SourceTarget::Instruction { + function: FunctionId(91), + block: BlockId(17), + index: 1, + } + }, + 13 => { + m.mappings[0].target = + SourceTarget::Terminator { function: FunctionId(91), block: BlockId(17) } + }, + 14 => { + m.mappings[0].target = + SourceTarget::Terminator { function: FunctionId(0), block: BlockId(17) } + }, + _ => m.mappings[0].target = SourceTarget::Global(GlobalId(0)), + } + assert_eq!(m.validate(&module), m.validate_reference(&module), "defect {defect}"); + } + let budget = 1; + assert!(matches!( + crate::source_wave::validate(&valid, &module, budget), + Err(crate::source_wave::ValidationError::Work) + )); + } +} diff --git a/ir/src/source_wave.rs b/ir/src/source_wave.rs new file mode 100644 index 0000000..7c9de80 --- /dev/null +++ b/ir/src/source_wave.rs @@ -0,0 +1,208 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Borrowed source metadata transport; Wave validates spans and identities. +use crate::{Module, SourceMetadata, SourceMetadataError, SourceTarget}; + +#[repr(C)] +struct File { + id: u64, + bytes: *const u8, + length: u64, +} + +#[repr(C)] +#[derive(Default)] +struct Original { + id: u64, + has_span: u64, + file: u64, + line: u64, + column: u64, + end_line: u64, + end_column: u64, +} + +#[repr(C)] +struct Block { + function: u64, + block: u64, + instructions: u64, + terminated: u64, +} + +#[repr(C)] +struct Mapping { + kind: u64, + function: u64, + block: u64, + index: u64, + original: u64, +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct Slot { + kind: u64, + a: u64, + b: u64, + c: u64, + value: u64, + extra: u64, +} + +#[repr(C)] +#[derive(Default)] +struct RawResult { + status: u64, + index: u64, + work: u64, +} + +unsafe extern "C" { + fn whale_ir_verify_sources( + files: *const File, + file_count: u64, + originals: *const Original, + original_count: u64, + blocks: *const Block, + block_count: u64, + globals: *const u64, + global_count: u64, + mappings: *const Mapping, + mapping_count: u64, + table: *mut Slot, + capacity: u64, + max_work: u64, + result: *mut RawResult, + ) -> i32; +} + +pub(crate) enum ValidationError { + Invalid(SourceMetadataError), + Work, +} + +pub(crate) fn validate( + metadata: &SourceMetadata, + module: &Module, + max_work: usize, +) -> Result { + if metadata.files.is_empty() && metadata.originals.is_empty() && metadata.mappings.is_empty() { + return Ok(0); + } + let block_count = module + .functions + .iter() + .try_fold(0usize, |n, f| n.checked_add(f.blocks.len())) + .ok_or(ValidationError::Work)?; + let count = [ + metadata.files.len(), + metadata.originals.len(), + metadata.mappings.len(), + block_count, + module.globals.len(), + module.global_storage.len(), + ] + .into_iter() + .try_fold(0usize, usize::checked_add) + .ok_or(ValidationError::Work)?; + let capacity = count + .max(1) + .checked_mul(2) + .and_then(usize::checked_next_power_of_two) + .ok_or(ValidationError::Work)?; + // The Wave initialization and every subsequent probe consume this budget. + if capacity > max_work { + return Err(ValidationError::Work); + } + let mut files = Vec::new(); + files.try_reserve_exact(metadata.files.len()).map_err(|_| ValidationError::Work)?; + for file in &metadata.files { + files.push(File { + id: file.id.into(), + bytes: file.name.as_ptr(), + length: file.name.len() as u64, + }); + } + let mut originals = Vec::new(); + originals.try_reserve_exact(metadata.originals.len()).map_err(|_| ValidationError::Work)?; + for node in &metadata.originals { + let mut raw = Original { id: node.id, ..Original::default() }; + if let Some(span) = &node.span { + raw.has_span = 1; + raw.file = span.file.into(); + raw.line = span.line.into(); + raw.column = span.column.into(); + raw.end_line = span.end_line.into(); + raw.end_column = span.end_column.into(); + } + originals.push(raw); + } + let mut blocks = Vec::new(); + blocks.try_reserve_exact(block_count).map_err(|_| ValidationError::Work)?; + for f in &module.functions { + for b in &f.blocks { + blocks.push(Block { + function: f.id.0.into(), + block: b.id.0.into(), + instructions: b.instructions.len() as u64, + terminated: u64::from(b.terminator.is_some()), + }); + } + } + let mut globals = Vec::new(); + globals + .try_reserve_exact(module.globals.len() + module.global_storage.len()) + .map_err(|_| ValidationError::Work)?; + globals.extend(module.globals.iter().map(|g| u64::from(g.id.0))); + globals.extend(module.global_storage.iter().map(|g| u64::from(g.id.0))); + let mut mappings = Vec::new(); + mappings.try_reserve_exact(metadata.mappings.len()).map_err(|_| ValidationError::Work)?; + for mapping in &metadata.mappings { + let (kind, function, block, index) = match mapping.target { + SourceTarget::Instruction { function, block, index } => { + (0, u64::from(function.0), u64::from(block.0), index as u64) + }, + SourceTarget::Terminator { function, block } => { + (1, u64::from(function.0), u64::from(block.0), 0) + }, + SourceTarget::Global(id) => (2, u64::from(id.0), 0, 0), + }; + mappings.push(Mapping { kind, function, block, index, original: mapping.original }); + } + let mut table = Vec::new(); + table.try_reserve_exact(capacity).map_err(|_| ValidationError::Work)?; + table.resize(capacity, Slot::default()); + let mut result = RawResult::default(); + let status = unsafe { + whale_ir_verify_sources( + files.as_ptr(), + files.len() as u64, + originals.as_ptr(), + originals.len() as u64, + blocks.as_ptr(), + blocks.len() as u64, + globals.as_ptr(), + globals.len() as u64, + mappings.as_ptr(), + mappings.len() as u64, + table.as_mut_ptr(), + capacity as u64, + max_work as u64, + &mut result, + ) + }; + let invalid = |s| ValidationError::Invalid(SourceMetadataError(s)); + if status != result.status as i32 || result.work > max_work as u64 { + return Err(invalid("invalid Wave source metadata result")); + } + match status { + 0 => Ok(result.work as usize), + 1 => Err(invalid("invalid or duplicate source file")), + 2 => Err(invalid("duplicate original node identity")), + 3 => Err(invalid("invalid original source span")), + 4 => Err(invalid("unknown original node or duplicate source mapping")), + 5 => Err(invalid("source mapping targets a missing IR operation")), + 7 => Err(ValidationError::Work), + _ => Err(invalid("invalid Wave source metadata result")), + } +} diff --git a/ir/src/verifier.rs b/ir/src/verifier.rs index 48483b4..d613d2d 100644 --- a/ir/src/verifier.rs +++ b/ir/src/verifier.rs @@ -1,5 +1,6 @@ // SPDX-License-Identifier: MPL-2.0 +#[cfg(not(whale_wave_ir))] use std::collections::HashSet; use crate::{BlockId, ConstValue, Instruction, Module, Terminator, Type, ValueId}; @@ -8,6 +9,21 @@ mod calls; mod cfg; +#[cfg(whale_wave_ir)] +mod wave_cfg; + +#[cfg(whale_wave_ir)] +mod wave_shape; + +#[cfg(whale_wave_ir)] +mod wave_semantics; + +#[cfg(whale_wave_ir)] +mod wave_ssa; + +#[cfg(whale_wave_ir)] +mod wave_index; + mod constants; mod index; @@ -213,6 +229,22 @@ pub fn verify_module(m: &Module) -> Result<(), VerifyError> { verify_module_with_limits(m, crate::IrLimits::default()) } +/// Shared internal type comparison for parser annotation consistency. +#[cfg(whale_wave_ir)] +pub(crate) fn wave_types_equal( + left: &Type, + right: &Type, + max_work: usize, +) -> Result<(bool, usize), crate::LimitError> { + let budget = AnalysisBudget { limit: max_work, work: Cell::new(0), queries: Cell::new(0) }; + match wave_semantics::types_equal(left, right, &budget) { + Ok(equal) => Ok((equal, budget.work.get())), + Err(_) => { + Err(crate::LimitError { resource: crate::Resource::AnalysisWork, limit: max_work }) + }, + } +} + pub fn verify_module_with_limits(m: &Module, limits: crate::IrLimits) -> Result<(), VerifyError> { verify_module_with_stats(m, limits).map(|_| ()) } @@ -242,6 +274,20 @@ pub fn verify_module_for_target_with_stats( limits: crate::IrLimits, ) -> Result { crate::limits::check_module(m, limits).map_err(VerifyError::ResourceLimit)?; + #[cfg(whale_wave_ir)] + let source_work = crate::source_wave::validate(&m.sources, m, limits.max_analysis_work) + .map_err(|error| match error { + crate::source_wave::ValidationError::Invalid(error) => { + VerifyError::SourceMetadata(error) + }, + crate::source_wave::ValidationError::Work => { + VerifyError::ResourceLimit(crate::LimitError { + resource: crate::Resource::AnalysisWork, + limit: limits.max_analysis_work, + }) + }, + })?; + #[cfg(not(whale_wave_ir))] m.sources.validate(m).map_err(VerifyError::SourceMetadata)?; target.validate().map_err(|e| VerifyError::Target(crate::TargetError::Contract(e)))?; if m.target != target.id || m.datalayout != target.storage.data { @@ -253,7 +299,16 @@ pub fn verify_module_for_target_with_stats( let indexed: Vec<_> = m.functions.iter().map(IndexedFunction::new).collect(); let analysis = AnalysisBudget { limit: limits.max_analysis_work, - work: Cell::new(0), + work: Cell::new({ + #[cfg(whale_wave_ir)] + { + source_work + } + #[cfg(not(whale_wave_ir))] + { + 0 + } + }), queries: Cell::new(0), }; for f in &indexed { @@ -281,7 +336,11 @@ pub fn verify_module_for_target_with_stats( }; if let Some((operation, ty)) = storage { // Category errors keep their existing diagnostics below. - if operands::is_storable(ty) { + #[cfg(whale_wave_ir)] + let storable = wave_semantics::storable(ty, &analysis)?; + #[cfg(not(whale_wave_ir))] + let storable = operands::is_storable(ty); + if storable { crate::layout_for_target(ty, target, limits.max_type_depth).map_err( |reason| VerifyError::InvalidMemoryLayout { func: f.name.clone(), @@ -294,40 +353,94 @@ pub fn verify_module_for_target_with_stats( } } } + #[cfg(whale_wave_ir)] + let mut globals = wave_index::Index::new(m.globals.len() + m.global_storage.len(), &analysis)?; + #[cfg(not(whale_wave_ir))] let mut globals = HashSet::new(); for g in &m.globals { - if !globals.insert(&g.name) { + #[cfg(whale_wave_ir)] + let inserted = globals.name(&g.name, &analysis)?; + #[cfg(not(whale_wave_ir))] + let inserted = globals.insert(&g.name); + if !inserted { return Err(VerifyError::DuplicateGlobal { name: g.name.clone() }); } - if !crate::constant::valid_constant(&g.ty, &g.init) { + #[cfg(whale_wave_ir)] + let valid = wave_semantics::literal_valid(&g.ty, &g.init, &analysis)?; + #[cfg(not(whale_wave_ir))] + let valid = crate::constant::valid_constant(&g.ty, &g.init); + if !valid { return Err(VerifyError::InvalidGlobalInitializer { name: g.name.clone(), ty: g.ty.clone(), payload: g.init.clone(), }); } - if !g.align.is_power_of_two() { + #[cfg(whale_wave_ir)] + let aligned = wave_semantics::alignment(g.align, &analysis)?; + #[cfg(not(whale_wave_ir))] + let aligned = g.align.is_power_of_two(); + if !aligned { return Err(VerifyError::InvalidGlobalAlignment { name: g.name.clone(), align: g.align, }); } } + #[cfg(whale_wave_ir)] + let mut global_ids = { + let mut ids = wave_index::Index::new(m.globals.len() + m.global_storage.len(), &analysis)?; + for global in &m.globals { + ids.id(global.id.0, &analysis)?; + } + ids + }; + #[cfg(not(whale_wave_ir))] let mut global_ids: HashSet<_> = m.globals.iter().map(|g| g.id).collect(); + #[cfg(whale_wave_ir)] + let mut links = { + let mut links = + wave_index::Index::new(m.declarations.len() + m.global_storage.len(), &analysis)?; + for declaration in &m.declarations { + if let Some(link) = &declaration.link_name { + links.name(link, &analysis)?; + } + } + links + }; + #[cfg(not(whale_wave_ir))] let mut links: HashSet<_> = m.declarations.iter().filter_map(|d| d.link_name.as_deref()).collect(); let mut storage_types = std::collections::HashMap::new(); for g in &m.global_storage { let error = |reason| VerifyError::GlobalStorage { name: g.name.clone(), global: g.id, reason }; + #[cfg(whale_wave_ir)] + wave_semantics::global_storage(g, &analysis)?; + #[cfg(not(whale_wave_ir))] g.validate_with_limits(limits).map_err(error)?; - if !global_ids.insert(g.id) { + #[cfg(whale_wave_ir)] + let inserted = global_ids.id(g.id.0, &analysis)?; + #[cfg(not(whale_wave_ir))] + let inserted = global_ids.insert(g.id); + if !inserted { return Err(error(crate::GlobalStorageError::DuplicateIdentity)); } - if !globals.insert(&g.name) { + #[cfg(whale_wave_ir)] + let inserted = globals.name(&g.name, &analysis)?; + #[cfg(not(whale_wave_ir))] + let inserted = globals.insert(&g.name); + if !inserted { return Err(error(crate::GlobalStorageError::DuplicateName)); } - if g.link_name.as_deref().is_some_and(|link| !links.insert(link)) { + #[cfg(whale_wave_ir)] + let link_collision = match g.link_name.as_deref() { + Some(link) => !links.name(link, &analysis)?, + None => false, + }; + #[cfg(not(whale_wave_ir))] + let link_collision = g.link_name.as_deref().is_some_and(|link| !links.insert(link)); + if link_collision { return Err(error(crate::GlobalStorageError::LinkNameCollision)); } crate::layout_for_target(&g.ty, target, limits.max_type_depth).map_err(|reason| { @@ -340,50 +453,69 @@ pub fn verify_module_for_target_with_stats( storage_types.insert(g.id, &g.ty); } let constant_globals = constants::verify_globals(m, limits)?; + #[cfg(whale_wave_ir)] + let mut functions = wave_index::Index::new(m.functions.len(), &analysis)?; + #[cfg(not(whale_wave_ir))] let mut functions = HashSet::new(); for f in &indexed { - if !functions.insert(&f.name) { + #[cfg(whale_wave_ir)] + let inserted = functions.name(&f.name, &analysis)?; + #[cfg(not(whale_wave_ir))] + let inserted = functions.insert(&f.name); + if !inserted { return Err(VerifyError::DuplicateFunction { name: f.name.clone() }); } } - let declarations = calls::verify_declarations(m, limits)?; + let declarations = calls::verify_declarations(m, limits, &analysis)?; for f in &indexed { - let mut blocks = HashSet::new(); - for block in &f.blocks { - if !blocks.insert(block.id) { - return Err(VerifyError::DuplicateBlock { func: f.name.clone(), block: block.id }); + #[cfg(whale_wave_ir)] + let defined = wave_shape::verify(f, &analysis)?; + #[cfg(not(whale_wave_ir))] + let (blocks, defined) = { + let mut blocks = HashSet::new(); + for block in &f.blocks { + if !blocks.insert(block.id) { + return Err(VerifyError::DuplicateBlock { + func: f.name.clone(), + block: block.id, + }); + } } - } - if !blocks.contains(&f.entry) { - return Err(VerifyError::InvalidEntryBlock { func: f.name.clone(), entry: f.entry }); - } - // value id set - let mut defined = std::collections::HashSet::::new(); - for p in &f.params { - if p.ty == Type::Void { - return Err(VerifyError::VoidParameter { + if !blocks.contains(&f.entry) { + return Err(VerifyError::InvalidEntryBlock { func: f.name.clone(), - param: p.name.clone(), + entry: f.entry, }); } - if !defined.insert(p.id) { - return Err(VerifyError::DuplicateValue { func: f.name.clone(), value: p.id }); + // value id set + let mut defined = std::collections::HashSet::::new(); + for p in &f.params { + if p.ty == Type::Void { + return Err(VerifyError::VoidParameter { + func: f.name.clone(), + param: p.name.clone(), + }); + } + if !defined.insert(p.id) { + return Err(VerifyError::DuplicateValue { func: f.name.clone(), value: p.id }); + } } - } - // Collect identities before inspecting uses. Physical block storage - // order does not describe execution order or loop backedges. - for block in &f.blocks { - for ins in &block.instructions { - if let Some((dst, _)) = instr_result(ins) { - if !defined.insert(dst) { - return Err(VerifyError::DuplicateValue { - func: f.name.clone(), - value: dst, - }); + // Collect identities before inspecting uses. Physical block storage + // order does not describe execution order or loop backedges. + for block in &f.blocks { + for ins in &block.instructions { + if let Some((dst, _)) = instr_result(ins) { + if !defined.insert(dst) { + return Err(VerifyError::DuplicateValue { + func: f.name.clone(), + value: dst, + }); + } } } } - } + (blocks, defined) + }; for b in &f.blocks { let Some(terminator) = &b.terminator else { @@ -393,37 +525,44 @@ pub fn verify_module_for_target_with_stats( }); }; - let check_target = |target: BlockId| { - if blocks.contains(&target) { - Ok(()) - } else { - Err(VerifyError::InvalidBranchTarget { - func: f.name.clone(), - block: b.id, - target, - }) - } - }; - match terminator { - Terminator::Br { target } => check_target(*target)?, - Terminator::CBr { then_bb, else_bb, .. } => { - check_target(*then_bb)?; - check_target(*else_bb)?; - }, - Terminator::Switch { default_bb, cases, .. } => { - check_target(*default_bb)?; - for (_, target) in cases { - check_target(*target)?; + #[cfg(not(whale_wave_ir))] + { + let check_target = |target: BlockId| { + if blocks.contains(&target) { + Ok(()) + } else { + Err(VerifyError::InvalidBranchTarget { + func: f.name.clone(), + block: b.id, + target, + }) } - }, - Terminator::Ret { .. } | Terminator::Trap { .. } => {}, + }; + match terminator { + Terminator::Br { target } => check_target(*target)?, + Terminator::CBr { then_bb, else_bb, .. } => { + check_target(*then_bb)?; + check_target(*else_bb)?; + }, + Terminator::Switch { default_bb, cases, .. } => { + check_target(*default_bb)?; + for (_, target) in cases { + check_target(*target)?; + } + }, + Terminator::Ret { .. } | Terminator::Trap { .. } => {}, + } } for ins in &b.instructions { - check_uses(ins, &defined, &f.name)?; + check_uses(ins, &defined, &f.name, &analysis)?; match ins { Instruction::Const { dst, ty, value } => { - if !crate::constant::valid_constant(ty, value) { + #[cfg(whale_wave_ir)] + let valid = wave_semantics::literal_valid(ty, value, &analysis)?; + #[cfg(not(whale_wave_ir))] + let valid = crate::constant::valid_constant(ty, value); + if !valid { return Err(VerifyError::InvalidConstant { func: f.name.clone(), value: *dst, @@ -433,7 +572,7 @@ pub fn verify_module_for_target_with_stats( } }, Instruction::Select { cond, .. } | Instruction::TrapIf { cond, .. } => { - verify_condition(f, *cond)?; + verify_condition(f, *cond, &analysis)?; }, _ => {}, } @@ -443,31 +582,42 @@ pub fn verify_module_for_target_with_stats( match terminator { Terminator::Br { .. } => {}, Terminator::CBr { cond, .. } => { - if !defined.contains(cond) { + if !is_defined(&defined, *cond, &analysis)? { return Err(VerifyError::UseOfUndefinedValue { func: f.name.clone(), value: *cond, }); } - verify_condition(f, *cond)?; + verify_condition(f, *cond, &analysis)?; }, Terminator::Switch { value, ty, cases, .. } => { - if !defined.contains(value) { + if !is_defined(&defined, *value, &analysis)? { return Err(VerifyError::UseOfUndefinedValue { func: f.name.clone(), value: *value, }); } + #[cfg(whale_wave_ir)] + wave_semantics::switch(f, *value, ty, &analysis)?; + #[cfg(not(whale_wave_ir))] operands::verify_type_category( f, "switch", ty, operands::is_integer(ty) || *ty == Type::Bool, )?; + #[cfg(not(whale_wave_ir))] operands::verify_operand(f, *value, ty)?; + #[cfg(whale_wave_ir)] + let mut keys = wave_index::Index::new(cases.len(), &analysis)?; + #[cfg(not(whale_wave_ir))] let mut keys = HashSet::new(); for (index, (key, _)) in cases.iter().enumerate() { - if !crate::constant::valid_constant(ty, key) { + #[cfg(whale_wave_ir)] + let valid = wave_semantics::literal_valid(ty, key, &analysis)?; + #[cfg(not(whale_wave_ir))] + let valid = crate::constant::valid_constant(ty, key); + if !valid { return Err(VerifyError::InvalidSwitchCase { func: f.name.clone(), block: b.id, @@ -480,7 +630,11 @@ pub fn verify_module_for_target_with_stats( ConstValue::Bool(value) => u128::from(*value), _ => unreachable!("validated integer key"), }; - if !keys.insert(bits) { + #[cfg(whale_wave_ir)] + let inserted = keys.bits(bits, &analysis)?; + #[cfg(not(whale_wave_ir))] + let inserted = keys.insert(bits); + if !inserted { return Err(VerifyError::DuplicateSwitchCase { func: f.name.clone(), block: b.id, @@ -491,40 +645,54 @@ pub fn verify_module_for_target_with_stats( }, Terminator::Trap { .. } => {}, Terminator::Ret { ty, value } => { - if *ty != f.ret_ty { - return Err(VerifyError::RetTypeMismatch { - func: f.name.clone(), - expected: f.ret_ty.clone(), - got: Some(ty.clone()), - }); + #[cfg(whale_wave_ir)] + { + let present = match value { + Some(value) => is_defined(&defined, *value, &analysis)?, + None => true, + }; + wave_semantics::return_value(f, ty, *value, present, &analysis)?; } - if let Some(v) = value { - if !defined.contains(v) { - return Err(VerifyError::UseOfUndefinedValue { + #[cfg(not(whale_wave_ir))] + { + if *ty != f.ret_ty { + return Err(VerifyError::RetTypeMismatch { func: f.name.clone(), - value: *v, + expected: f.ret_ty.clone(), + got: Some(ty.clone()), }); } - let value_ty = f.value_type(*v).ok_or_else(|| { - VerifyError::MissingValueType { func: f.name.clone(), value: *v } - })?; - if f.ret_ty == Type::Void || value_ty != &f.ret_ty { + if let Some(v) = value { + if !is_defined(&defined, *v, &analysis)? { + return Err(VerifyError::UseOfUndefinedValue { + func: f.name.clone(), + value: *v, + }); + } + let value_ty = f.value_type(*v).ok_or_else(|| { + VerifyError::MissingValueType { func: f.name.clone(), value: *v } + })?; + if f.ret_ty == Type::Void || value_ty != &f.ret_ty { + return Err(VerifyError::RetTypeMismatch { + func: f.name.clone(), + expected: f.ret_ty.clone(), + got: Some(value_ty.clone()), + }); + } + } else if f.ret_ty != Type::Void { return Err(VerifyError::RetTypeMismatch { func: f.name.clone(), expected: f.ret_ty.clone(), - got: Some(value_ty.clone()), + got: None, }); } - } else if f.ret_ty != Type::Void { - return Err(VerifyError::RetTypeMismatch { - func: f.name.clone(), - expected: f.ret_ty.clone(), - got: None, - }); } }, } } + #[cfg(whale_wave_ir)] + wave_semantics::value_types(f, &analysis)?; + #[cfg(not(whale_wave_ir))] verify_value_types(f)?; constants::verify_locals(f, &constant_globals, limits)?; cfg::verify(f, &analysis)?; @@ -534,6 +702,18 @@ pub fn verify_module_for_target_with_stats( for block in &f.blocks { for instruction in &block.instructions { if let Instruction::GlobalAddr { global, ty, .. } = instruction { + #[cfg(whale_wave_ir)] + let reason = match storage_types.get(global) { + None => Some(crate::GlobalStorageError::UnknownGlobal), + Some(declared) => { + if wave_semantics::types_equal(declared, ty, &analysis)? { + None + } else { + Some(crate::GlobalStorageError::AddressTypeMismatch) + } + }, + }; + #[cfg(not(whale_wave_ir))] let reason = match storage_types.get(global) { None => Some(crate::GlobalStorageError::UnknownGlobal), Some(declared) if *declared != ty => { @@ -549,8 +729,8 @@ pub fn verify_module_for_target_with_stats( }); } } - calls::verify_instruction(&declarations, f, instruction, limits)?; - operands::verify_instruction(f, instruction)?; + calls::verify_instruction(&declarations, f, instruction, limits, &analysis)?; + operands::verify_instruction(f, instruction, &analysis)?; } } } @@ -562,7 +742,21 @@ pub fn verify_module_for_target_with_stats( }) } -fn verify_condition(f: &IndexedFunction<'_>, value: ValueId) -> Result<(), VerifyError> { +#[cfg(whale_wave_ir)] +fn verify_condition( + f: &IndexedFunction<'_>, + value: ValueId, + budget: &AnalysisBudget, +) -> Result<(), VerifyError> { + wave_semantics::condition(f, value, budget) +} + +#[cfg(not(whale_wave_ir))] +fn verify_condition( + f: &IndexedFunction<'_>, + value: ValueId, + _budget: &AnalysisBudget, +) -> Result<(), VerifyError> { let ty = f .value_type(value) .ok_or_else(|| VerifyError::MissingValueType { func: f.name.clone(), value })?; @@ -576,6 +770,7 @@ fn verify_condition(f: &IndexedFunction<'_>, value: ValueId) -> Result<(), Verif Ok(()) } +#[cfg(not(whale_wave_ir))] fn verify_value_types(f: &IndexedFunction<'_>) -> Result<(), VerifyError> { let mut seen = HashSet::new(); for (value, _) in &f.value_types { @@ -650,10 +845,45 @@ fn instr_result(ins: &Instruction) -> Option<(ValueId, Type)> { } } +#[cfg(whale_wave_ir)] +fn is_defined( + defined: &wave_shape::Definitions, + value: ValueId, + budget: &AnalysisBudget, +) -> Result { + defined.contains(value, budget) +} + +#[cfg(not(whale_wave_ir))] +fn is_defined( + defined: &std::collections::HashSet, + value: ValueId, + _budget: &AnalysisBudget, +) -> Result { + Ok(defined.contains(&value)) +} + +#[cfg(whale_wave_ir)] +fn check_uses( + ins: &Instruction, + defined: &wave_shape::Definitions, + func: &str, + budget: &AnalysisBudget, +) -> Result<(), VerifyError> { + for value in instr_uses(ins) { + if !defined.contains(value, budget)? { + return Err(VerifyError::UseOfUndefinedValue { func: func.into(), value }); + } + } + Ok(()) +} + +#[cfg(not(whale_wave_ir))] fn check_uses( ins: &Instruction, defined: &std::collections::HashSet, func: &str, + _budget: &AnalysisBudget, ) -> Result<(), VerifyError> { for u in instr_uses(ins) { if !defined.contains(&u) { diff --git a/ir/src/verifier/calls.rs b/ir/src/verifier/calls.rs index 8bcc5d8..3721250 100644 --- a/ir/src/verifier/calls.rs +++ b/ir/src/verifier/calls.rs @@ -3,7 +3,10 @@ use crate::{CallError, Callee, FunctionDecl, FunctionId, Instruction, Module, Ty use std::cell::Cell; -use std::collections::{HashMap, HashSet}; +use std::collections::HashMap; + +#[cfg(not(whale_wave_ir))] +use std::collections::HashSet; pub(super) struct DeclarationIndex<'a> { by_id: HashMap, @@ -25,12 +28,19 @@ fn error(name: &str, reason: CallError) -> VerifyError { VerifyError::Call { func: name.into(), reason } } -pub(super) fn verify_declarations( - m: &Module, +pub(super) fn verify_declarations<'a>( + m: &'a Module, limits: crate::IrLimits, -) -> Result, VerifyError> { + analysis: &super::AnalysisBudget, +) -> Result, VerifyError> { + #[cfg(not(whale_wave_ir))] + let _ = analysis; for f in &m.functions { for (_, ty) in &f.value_types { + #[cfg(whale_wave_ir)] + super::wave_semantics::pointer_signatures(ty, analysis) + .map_err(|e| with_name(e, &f.name))?; + #[cfg(not(whale_wave_ir))] validate_pointer_types(ty, limits).map_err(|e| error(&f.name, e))?; } for p in &f.params { @@ -42,23 +52,66 @@ pub(super) fn verify_declarations( } } } + #[cfg(whale_wave_ir)] + let mut ids = super::wave_index::Index::new(m.declarations.len(), analysis)?; + #[cfg(not(whale_wave_ir))] let mut ids = HashSet::new(); + #[cfg(whale_wave_ir)] + let mut names = super::wave_index::Index::new(m.declarations.len(), analysis)?; + #[cfg(not(whale_wave_ir))] let mut names = HashSet::new(); + #[cfg(whale_wave_ir)] + let mut links = super::wave_index::Index::new(m.declarations.len(), analysis)?; + #[cfg(not(whale_wave_ir))] let mut links = HashSet::new(); + #[cfg(whale_wave_ir)] + let mut body_ids = { + let mut index = super::wave_index::Index::new(m.functions.len(), analysis)?; + for function in &m.functions { + index.id(function.id.0, analysis)?; + } + index + }; + #[cfg(not(whale_wave_ir))] let body_ids: HashSet<_> = m.functions.iter().map(|f| f.id).collect(); let mut by_id = HashMap::new(); for decl in &m.declarations { + #[cfg(whale_wave_ir)] + { + super::wave_semantics::signature(&decl.signature, limits, analysis) + .map_err(|e| with_name(e, &decl.name))?; + if !super::wave_semantics::valid_link( + decl.linkage, + decl.link_name.as_deref(), + analysis, + )? { + return Err(error(&decl.name, CallError::InvalidLinkName(decl.name.clone()))); + } + } + #[cfg(not(whale_wave_ir))] crate::function::validate_decl_with_limits(decl, limits) .map_err(|e| error(&decl.name, e))?; - if !ids.insert(decl.id) || !names.insert(&decl.name) { + #[cfg(whale_wave_ir)] + let conflicting = !ids.id(decl.id.0, analysis)? || !names.name(&decl.name, analysis)?; + #[cfg(not(whale_wave_ir))] + let conflicting = !ids.insert(decl.id) || !names.insert(&decl.name); + if conflicting { return Err(error(&decl.name, CallError::ConflictingDeclaration(decl.name.clone()))); } if let Some(link) = &decl.link_name { - if !links.insert(link) { + #[cfg(whale_wave_ir)] + let inserted = links.name(link, analysis)?; + #[cfg(not(whale_wave_ir))] + let inserted = links.insert(link); + if !inserted { return Err(error(&decl.name, CallError::LinkNameCollision(link.clone()))); } } - if decl.linkage == crate::Linkage::Internal && !body_ids.contains(&decl.id) { + #[cfg(whale_wave_ir)] + let missing_body = !body_ids.contains_id(decl.id.0, analysis)?; + #[cfg(not(whale_wave_ir))] + let missing_body = !body_ids.contains(&decl.id); + if decl.linkage == crate::Linkage::Internal && missing_body { return Err(error(&decl.name, CallError::MissingDefinition(decl.id))); } by_id.insert(decl.id, decl); @@ -67,28 +120,103 @@ pub(super) fn verify_declarations( by_id, work: Cell::new(m.functions.len().saturating_add(m.declarations.len().saturating_mul(2))), }; + #[cfg(whale_wave_ir)] + let mut bodies = super::wave_index::Index::new(m.functions.len(), analysis)?; + #[cfg(not(whale_wave_ir))] let mut bodies = HashSet::new(); for f in &m.functions { - if !bodies.insert(f.id) { + #[cfg(whale_wave_ir)] + let inserted = bodies.id(f.id.0, analysis)?; + #[cfg(not(whale_wave_ir))] + let inserted = bodies.insert(f.id); + if !inserted { return Err(error(&f.name, CallError::DuplicateDefinition(f.id))); } let decl = index.get(f.id).ok_or_else(|| error(&f.name, CallError::UnknownFunction(f.id)))?; - if decl.name != f.name + #[cfg(whale_wave_ir)] + let mismatch = { + let actual = crate::FunctionSignature { + params: f.params.iter().map(|param| param.ty.clone()).collect(), + ret: f.ret_ty.clone(), + convention: decl.signature.convention, + variadic: decl.signature.variadic, + }; + decl.name != f.name + || !super::wave_semantics::signature_equal(&decl.signature, &actual, analysis)? + }; + #[cfg(not(whale_wave_ir))] + let mismatch = decl.name != f.name || decl.signature.ret != f.ret_ty - || decl.signature.params != f.params.iter().map(|p| p.ty.clone()).collect::>() - { + || decl.signature.params != f.params.iter().map(|p| p.ty.clone()).collect::>(); + if mismatch { return Err(error(&f.name, CallError::DefinitionMismatch(f.id))); } } Ok(index) } +#[cfg(whale_wave_ir)] +fn with_name(error: VerifyError, name: &str) -> VerifyError { + match error { + VerifyError::Call { reason, .. } => VerifyError::Call { func: name.into(), reason }, + other => other, + } +} + +#[cfg(whale_wave_ir)] +pub(super) fn verify_instruction( + declarations: &DeclarationIndex<'_>, + f: &super::IndexedFunction<'_>, + ins: &Instruction, + limits: crate::IrLimits, + analysis: &super::AnalysisBudget, +) -> Result<(), VerifyError> { + match ins { + Instruction::NullFunction { signature, .. } => { + super::wave_semantics::signature(signature, limits, analysis) + .map_err(|e| with_name(e, &f.name)) + }, + Instruction::FunctionAddr { function, signature, .. } => { + let decl = declarations + .get(*function) + .ok_or_else(|| error(&f.name, CallError::UnknownFunction(*function)))?; + if super::wave_semantics::signature_equal(&decl.signature, signature, analysis)? { + Ok(()) + } else { + Err(error(&f.name, CallError::AddressTypeMismatch)) + } + }, + Instruction::Call { callee, .. } => { + let signature; + let ty = match callee { + Callee::Direct(id) => { + let declaration = declarations + .get(*id) + .ok_or_else(|| error(&f.name, CallError::UnknownFunction(*id)))?; + signature = Type::FnPtr(Box::new(declaration.signature.clone())); + &signature + }, + Callee::Indirect(value) => f + .value_type(*value) + .ok_or_else(|| error(&f.name, CallError::UnknownValue(*value)))?, + }; + super::wave_semantics::call(f, ty, ins, analysis) + }, + Instruction::Cast { src, src_ty, dst_ty, op, .. } => { + super::wave_semantics::function_pointer_cast(f, *src, src_ty, dst_ty, op, analysis) + }, + _ => Ok(()), + } +} + +#[cfg(not(whale_wave_ir))] pub(super) fn verify_instruction( declarations: &DeclarationIndex<'_>, f: &super::IndexedFunction<'_>, ins: &Instruction, limits: crate::IrLimits, + _analysis: &super::AnalysisBudget, ) -> Result<(), VerifyError> { let check = || -> Result<(), CallError> { match ins { @@ -161,6 +289,7 @@ pub(super) fn verify_instruction( check().map_err(|e| error(&f.name, e)) } +#[cfg(not(whale_wave_ir))] fn contains_function_pointer(ty: &Type) -> bool { match ty { Type::FnPtr(_) => true, @@ -170,6 +299,7 @@ fn contains_function_pointer(ty: &Type) -> bool { } } +#[cfg(not(whale_wave_ir))] fn validate_pointer_types(ty: &Type, limits: crate::IrLimits) -> Result<(), CallError> { match ty { Type::FnPtr(sig) => crate::function::validate_signature_with_limits(sig, limits), diff --git a/ir/src/verifier/cfg.rs b/ir/src/verifier/cfg.rs index 5f0c443..e44a8ad 100644 --- a/ir/src/verifier/cfg.rs +++ b/ir/src/verifier/cfg.rs @@ -1,16 +1,24 @@ //! Read-only SSA checks. Reachability never removes or simplifies O0 IR. use std::collections::{HashMap, HashSet}; -use crate::{BlockId, Instruction, Terminator, ValueId}; +use crate::{BlockId, Terminator}; -use super::{instr_result, instr_uses, operands, VerifyError}; +#[cfg(not(whale_wave_ir))] +use crate::{Instruction, ValueId}; -struct Cfg { - indices: HashMap, - predecessors: Vec>, +use super::VerifyError; + +#[cfg(not(whale_wave_ir))] +use super::{instr_result, instr_uses, operands}; + +pub(super) struct Cfg { + pub(super) indices: HashMap, + pub(super) predecessors: Vec>, // None means structurally unreachable from the function entry. + #[cfg(not(whale_wave_ir))] idom: Vec>, - intervals: Vec>, + pub(super) intervals: Vec>, + #[cfg(not(whale_wave_ir))] predecessor_sets: Vec>, } @@ -45,75 +53,103 @@ impl Cfg { } } - // Iterative DFS avoids consuming the host call stack for deep CFGs. let entry = indices[&f.entry]; - // Entry represents a fresh invocation, never a branch destination. - // Check all edges, including those from unreachable blocks, without - // rewriting the original control flow. - if let Some(&predecessor) = predecessors[entry].first() { - return Err(VerifyError::EntryHasPredecessor { - func: f.name.clone(), - entry: f.entry, - predecessor: f.blocks[predecessor].id, - }); - } - let mut seen = vec![false; f.blocks.len()]; - let mut stack = vec![(entry, false)]; - let mut order = Vec::new(); - while let Some((block, exiting)) = stack.pop() { - budget.charge()?; - if exiting { - order.push(block); - continue; - } - if std::mem::replace(&mut seen[block], true) { - continue; + #[cfg(whale_wave_ir)] + let order = match super::wave_cfg::rpo(&successors, entry, budget) { + Ok(order) => order, + Err(super::wave_cfg::WalkError::EntryPredecessor(predecessor)) => { + return Err(VerifyError::EntryHasPredecessor { + func: f.name.clone(), + entry: f.entry, + predecessor: f.blocks[predecessor].id, + }); + }, + Err(super::wave_cfg::WalkError::ResourceLimit) => { + return Err(super::wave_cfg::resource_error(budget)); + }, + Err(super::wave_cfg::WalkError::InvalidGraph) => { + return Err(super::wave_cfg::resource_error(budget)); + }, + }; + #[cfg(not(whale_wave_ir))] + let order = { + // Iterative DFS avoids consuming the host call stack for deep CFGs. + // Entry represents a fresh invocation, never a branch destination. + // Check all edges, including those from unreachable blocks, without + // rewriting the original control flow. + if let Some(&predecessor) = predecessors[entry].first() { + return Err(VerifyError::EntryHasPredecessor { + func: f.name.clone(), + entry: f.entry, + predecessor: f.blocks[predecessor].id, + }); } - stack.push((block, true)); - stack.extend(successors[block].iter().rev().map(|&next| (next, false))); - } - order.reverse(); - let mut rank = vec![0; f.blocks.len()]; - for (i, &block) in order.iter().enumerate() { - rank[block] = i; - } - let mut idom = vec![None; f.blocks.len()]; - idom[entry] = Some(entry); - loop { - let mut changed = false; - for &block in order.iter().skip(1) { + let mut seen = vec![false; f.blocks.len()]; + let mut stack = vec![(entry, false)]; + let mut order = Vec::new(); + while let Some((block, exiting)) = stack.pop() { budget.charge()?; - let mut next: Option = None; - for &predecessor in &predecessors[block] { + if exiting { + order.push(block); + continue; + } + if std::mem::replace(&mut seen[block], true) { + continue; + } + stack.push((block, true)); + stack.extend(successors[block].iter().rev().map(|&next| (next, false))); + } + order.reverse(); + order + }; + #[cfg(not(whale_wave_ir))] + let idom = { + let mut rank = vec![0; f.blocks.len()]; + for (i, &block) in order.iter().enumerate() { + rank[block] = i; + } + let mut idom = vec![None; f.blocks.len()]; + idom[entry] = Some(entry); + loop { + let mut changed = false; + for &block in order.iter().skip(1) { budget.charge()?; - if idom[predecessor].is_none() { - continue; - } - next = Some(match next { - None => predecessor, - Some(mut a) => { - let mut b = predecessor; - while a != b { - budget.charge()?; - if rank[a] > rank[b] { - a = idom[a].unwrap(); - } else { - b = idom[b].unwrap(); + let mut next: Option = None; + for &predecessor in &predecessors[block] { + budget.charge()?; + if idom[predecessor].is_none() { + continue; + } + next = Some(match next { + None => predecessor, + Some(mut a) => { + let mut b = predecessor; + while a != b { + budget.charge()?; + if rank[a] > rank[b] { + a = idom[a].unwrap(); + } else { + b = idom[b].unwrap(); + } } - } - a - }, - }); + a + }, + }); + } + if next != idom[block] { + idom[block] = next; + changed = true; + } } - if next != idom[block] { - idom[block] = next; - changed = true; + if !changed { + break; } } - if !changed { - break; - } - } + idom + }; + #[cfg(whale_wave_ir)] + let idom = super::wave_cfg::idom(&predecessors, &order, entry, budget) + .map_err(|_| super::wave_cfg::resource_error(budget))?; // Euler intervals in the dominator tree turn each later query into // two comparisons. Build iteratively to preserve deep-CFG safety. let mut children = vec![Vec::new(); f.blocks.len()]; @@ -140,10 +176,20 @@ impl Cfg { stack.extend(children[block].iter().rev().map(|&child| (child, false))); } } + #[cfg(not(whale_wave_ir))] let predecessor_sets = predecessors.iter().map(|ps| ps.iter().copied().collect()).collect(); - Ok(Self { indices, predecessors, idom, intervals, predecessor_sets }) + Ok(Self { + indices, + predecessors, + #[cfg(not(whale_wave_ir))] + idom, + intervals, + #[cfg(not(whale_wave_ir))] + predecessor_sets, + }) } + #[cfg(not(whale_wave_ir))] fn dominates( &self, definition: usize, @@ -166,98 +212,103 @@ pub(super) fn verify( budget: &super::AnalysisBudget, ) -> Result<(), VerifyError> { let cfg = Cfg::new(f, budget)?; - let mut definitions: HashMap> = - f.params.iter().map(|p| (p.id, None)).collect(); - for (block, b) in f.blocks.iter().enumerate() { - for (position, ins) in b.instructions.iter().enumerate() { - if let Some((value, _)) = instr_result(ins) { - definitions.insert(value, Some((block, position))); + #[cfg(whale_wave_ir)] + return super::wave_ssa::verify(f, &cfg, budget); + #[cfg(not(whale_wave_ir))] + { + let mut definitions: HashMap> = + f.params.iter().map(|p| (p.id, None)).collect(); + for (block, b) in f.blocks.iter().enumerate() { + for (position, ins) in b.instructions.iter().enumerate() { + if let Some((value, _)) = instr_result(ins) { + definitions.insert(value, Some((block, position))); + } } } - } - let available = |value: ValueId, block: usize, position: usize| { - let definition = definitions - .get(&value) - .ok_or_else(|| VerifyError::UseOfUndefinedValue { func: f.name.clone(), value })?; - // Unreachable code remains in the module and still undergoes identity, - // operand/type and CFG checks. No executable entry path exists on which - // to require a dominating definition for its uses. - if cfg.idom[block].is_none() { - return Ok(()); - } - if let Some((def_block, def_position)) = *definition { - let valid = if def_block == block { - def_position < position - } else { - cfg.dominates(def_block, block, budget)? - }; - if !valid { - return Err(VerifyError::NonDominatingValue { - func: f.name.clone(), - value, - block: f.blocks[block].id, - }); + let available = |value: ValueId, block: usize, position: usize| { + let definition = definitions + .get(&value) + .ok_or_else(|| VerifyError::UseOfUndefinedValue { func: f.name.clone(), value })?; + // Unreachable code remains in the module and still undergoes identity, + // operand/type and CFG checks. No executable entry path exists on which + // to require a dominating definition for its uses. + if cfg.idom[block].is_none() { + return Ok(()); } - } - Ok(()) - }; - for (block, b) in f.blocks.iter().enumerate() { - let mut past_phi = false; - for (position, ins) in b.instructions.iter().enumerate() { - budget.charge()?; - if let Instruction::Phi { dst, ty, incomings } = ins { - let invalid = |reason| VerifyError::InvalidPhi { - func: f.name.clone(), - block: b.id, - value: *dst, - reason, + if let Some((def_block, def_position)) = *definition { + let valid = if def_block == block { + def_position < position + } else { + cfg.dominates(def_block, block, budget)? }; - if past_phi { - return Err(invalid("phi must precede non-phi instructions")); - } - if b.id == f.entry { - return Err(invalid("function entry has no incoming SSA value")); - } - if incomings.is_empty() { - return Err(invalid("phi requires incoming values")); + if !valid { + return Err(VerifyError::NonDominatingValue { + func: f.name.clone(), + value, + block: f.blocks[block].id, + }); } - operands::verify_type_category(f, "phi", ty, operands::is_storable(ty))?; - let mut seen = HashSet::new(); - for (value, predecessor) in incomings { - budget.charge()?; - let Some(&pred) = cfg.indices.get(predecessor) else { - return Err(invalid("phi names an unknown predecessor")); + } + Ok(()) + }; + for (block, b) in f.blocks.iter().enumerate() { + let mut past_phi = false; + for (position, ins) in b.instructions.iter().enumerate() { + budget.charge()?; + if let Instruction::Phi { dst, ty, incomings } = ins { + let invalid = |reason| VerifyError::InvalidPhi { + func: f.name.clone(), + block: b.id, + value: *dst, + reason, }; - if !cfg.predecessor_sets[block].contains(&pred) { - return Err(invalid("phi input is not a predecessor")); + if past_phi { + return Err(invalid("phi must precede non-phi instructions")); } - if !seen.insert(pred) { - return Err(invalid("duplicate phi predecessor")); + if b.id == f.entry { + return Err(invalid("function entry has no incoming SSA value")); + } + if incomings.is_empty() { + return Err(invalid("phi requires incoming values")); + } + operands::verify_type_category(f, "phi", ty, operands::is_storable(ty))?; + let mut seen = HashSet::new(); + for (value, predecessor) in incomings { + budget.charge()?; + let Some(&pred) = cfg.indices.get(predecessor) else { + return Err(invalid("phi names an unknown predecessor")); + }; + if !cfg.predecessor_sets[block].contains(&pred) { + return Err(invalid("phi input is not a predecessor")); + } + if !seen.insert(pred) { + return Err(invalid("duplicate phi predecessor")); + } + operands::verify_operand(f, *value, ty)?; + // A phi operand is used on its incoming edge, after that + // predecessor's instructions, including loop backedges. + available(*value, pred, f.blocks[pred].instructions.len())?; + } + if seen.len() != cfg.predecessors[block].len() { + return Err(invalid("phi is missing a predecessor")); + } + } else { + past_phi = true; + for value in instr_uses(ins) { + available(value, block, position)?; } - operands::verify_operand(f, *value, ty)?; - // A phi operand is used on its incoming edge, after that - // predecessor's instructions, including loop backedges. - available(*value, pred, f.blocks[pred].instructions.len())?; - } - if seen.len() != cfg.predecessors[block].len() { - return Err(invalid("phi is missing a predecessor")); - } - } else { - past_phi = true; - for value in instr_uses(ins) { - available(value, block, position)?; } } + let uses = match b.terminator.as_ref().unwrap() { + Terminator::CBr { cond, .. } => Some(*cond), + Terminator::Switch { value, .. } => Some(*value), + Terminator::Ret { value, .. } => *value, + Terminator::Br { .. } | Terminator::Trap { .. } => None, + }; + if let Some(value) = uses { + available(value, block, b.instructions.len())?; + } } - let uses = match b.terminator.as_ref().unwrap() { - Terminator::CBr { cond, .. } => Some(*cond), - Terminator::Switch { value, .. } => Some(*value), - Terminator::Ret { value, .. } => *value, - Terminator::Br { .. } | Terminator::Trap { .. } => None, - }; - if let Some(value) = uses { - available(value, block, b.instructions.len())?; - } + Ok(()) } - Ok(()) } diff --git a/ir/src/verifier/operands.rs b/ir/src/verifier/operands.rs index 9516862..47a40cc 100644 --- a/ir/src/verifier/operands.rs +++ b/ir/src/verifier/operands.rs @@ -1,23 +1,31 @@ use super::VerifyError; -use crate::{BinOp, CmpOp, ConstValue, ICmpPred, Instruction, Type, ValueId}; +use crate::Instruction; +#[cfg(not(whale_wave_ir))] +use crate::{BinOp, CmpOp, ConstValue, ICmpPred, Type, ValueId}; + +#[cfg(not(whale_wave_ir))] fn is_signed(ty: &Type) -> bool { matches!(ty, Type::I1 | Type::I8 | Type::I16 | Type::I32 | Type::I64 | Type::I128) } +#[cfg(not(whale_wave_ir))] fn is_unsigned(ty: &Type) -> bool { matches!(ty, Type::U1 | Type::U8 | Type::U16 | Type::U32 | Type::U64 | Type::U128) } +#[cfg(not(whale_wave_ir))] pub(super) fn is_integer(ty: &Type) -> bool { is_signed(ty) || is_unsigned(ty) } +#[cfg(not(whale_wave_ir))] fn is_float(ty: &Type) -> bool { matches!(ty, Type::F16 | Type::F32 | Type::F64) } +#[cfg(not(whale_wave_ir))] fn integer_width(ty: &Type) -> Option { match ty { Type::I1 | Type::U1 => Some(1), @@ -30,6 +38,7 @@ fn integer_width(ty: &Type) -> Option { } } +#[cfg(not(whale_wave_ir))] fn float_width(ty: &Type) -> Option { match ty { Type::F16 => Some(16), @@ -39,6 +48,7 @@ fn float_width(ty: &Type) -> Option { } } +#[cfg(not(whale_wave_ir))] fn valid_cast(op: &crate::CastOp, source: &Type, destination: &Type) -> bool { use crate::CastOp::*; let integer_pair = integer_width(source).zip(integer_width(destination)); @@ -69,12 +79,14 @@ fn valid_cast(op: &crate::CastOp, source: &Type, destination: &Type) -> bool { } } +#[cfg(not(whale_wave_ir))] fn supports_equality(ty: &Type) -> bool { is_integer(ty) || matches!(ty, Type::Bool | Type::Ptr(_)) } // A pointer to void may describe an opaque address, but void itself has no // stored value. Concrete aggregate layout and dynamic access checks are separate. +#[cfg(not(whale_wave_ir))] pub(super) fn is_storable(ty: &Type) -> bool { match ty { Type::Void => false, @@ -84,6 +96,7 @@ pub(super) fn is_storable(ty: &Type) -> bool { } } +#[cfg(not(whale_wave_ir))] pub(super) fn verify_type_category( f: &super::IndexedFunction<'_>, operation: &'static str, @@ -97,6 +110,7 @@ pub(super) fn verify_type_category( } } +#[cfg(not(whale_wave_ir))] pub(super) fn verify_operand( f: &super::IndexedFunction<'_>, value: ValueId, @@ -116,6 +130,7 @@ pub(super) fn verify_operand( Ok(()) } +#[cfg(not(whale_wave_ir))] fn verify_alignment(f: &super::IndexedFunction<'_>, align: u32) -> Result<(), VerifyError> { if !align.is_power_of_two() { return Err(VerifyError::InvalidMemoryAlignment { func: f.name.clone(), align }); @@ -123,6 +138,7 @@ fn verify_alignment(f: &super::IndexedFunction<'_>, align: u32) -> Result<(), Ve Ok(()) } +#[cfg(not(whale_wave_ir))] fn verify_gep( f: &super::IndexedFunction<'_>, dst: ValueId, @@ -195,9 +211,20 @@ fn verify_gep( Ok(()) } +#[cfg(whale_wave_ir)] +pub(super) fn verify_instruction( + f: &super::IndexedFunction<'_>, + ins: &Instruction, + budget: &super::AnalysisBudget, +) -> Result<(), VerifyError> { + super::wave_semantics::verify_instruction(f, ins, budget) +} + +#[cfg(not(whale_wave_ir))] pub(super) fn verify_instruction( f: &super::IndexedFunction<'_>, ins: &Instruction, + budget: &super::AnalysisBudget, ) -> Result<(), VerifyError> { match ins { Instruction::Neg { ty, src, .. } => { @@ -296,7 +323,7 @@ pub(super) fn verify_instruction( verify_operand(f, *rhs, ty)?; }, Instruction::Select { ty, cond, on_true, on_false, .. } => { - super::verify_condition(f, *cond)?; + super::verify_condition(f, *cond, budget)?; verify_type_category(f, "select", ty, is_storable(ty))?; verify_operand(f, *on_true, ty)?; verify_operand(f, *on_false, ty)?; diff --git a/ir/src/verifier/wave_cfg.rs b/ir/src/verifier/wave_cfg.rs new file mode 100644 index 0000000..e7934bc --- /dev/null +++ b/ir/src/verifier/wave_cfg.rs @@ -0,0 +1,185 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Borrowed bridge for Wave-owned CFG reverse-postorder traversal. + +use super::{AnalysisBudget, VerifyError}; + +#[repr(C)] +#[derive(Clone, Copy)] +struct Block { + first: u64, + count: u64, +} + +#[repr(C)] +#[derive(Default)] +struct ResultRecord { + status: u64, + index: u64, + count: u64, + work: u64, +} + +unsafe extern "C" { + fn whale_ir_cfg_rpo( + blocks: *const Block, + block_count: u64, + edges: *const u64, + edge_count: u64, + entry: u64, + max_work: u64, + scratch_seen: *mut u8, + seen_capacity: u64, + scratch_stack_block: *mut u64, + scratch_stack_next: *mut u64, + stack_capacity: u64, + scratch_order: *mut u64, + scratch_capacity: u64, + output_order: *mut u64, + output_capacity: u64, + result: *mut ResultRecord, + ) -> i32; + + fn whale_ir_cfg_idom( + blocks: *const Block, + block_count: u64, + predecessors: *const u64, + predecessor_count: u64, + order: *const u64, + order_count: u64, + entry: u64, + max_work: u64, + scratch_rank: *mut u64, + rank_capacity: u64, + scratch_idom: *mut u64, + idom_capacity: u64, + output_idom: *mut u64, + output_capacity: u64, + result: *mut ResultRecord, + ) -> i32; +} + +pub(super) enum WalkError { + EntryPredecessor(usize), + ResourceLimit, + InvalidGraph, +} + +pub(super) fn rpo( + successors: &[Vec], + entry: usize, + budget: &AnalysisBudget, +) -> Result, WalkError> { + let count = successors.len(); + let edge_count: usize = successors.iter().map(Vec::len).sum(); + let mut blocks = Vec::new(); + let mut edges = Vec::new(); + blocks.try_reserve_exact(count).map_err(|_| WalkError::ResourceLimit)?; + edges.try_reserve_exact(edge_count).map_err(|_| WalkError::ResourceLimit)?; + for targets in successors { + blocks.push(Block { first: edges.len() as u64, count: targets.len() as u64 }); + edges.extend(targets.iter().map(|index| *index as u64)); + } + let mut seen = vec![0_u8; count]; + let mut stack_block = vec![0_u64; count]; + let mut stack_next = vec![0_u64; count]; + let mut scratch_order = vec![0_u64; count]; + let mut output = vec![0_u64; count]; + let mut result = ResultRecord::default(); + let remaining = budget.limit.saturating_sub(budget.work.get()) as u64; + let status = unsafe { + whale_ir_cfg_rpo( + blocks.as_ptr(), + count as u64, + edges.as_ptr(), + edge_count as u64, + entry as u64, + remaining, + seen.as_mut_ptr(), + count as u64, + stack_block.as_mut_ptr(), + stack_next.as_mut_ptr(), + count as u64, + scratch_order.as_mut_ptr(), + count as u64, + output.as_mut_ptr(), + count as u64, + &mut result, + ) + }; + if status != result.status as i32 { + return Err(WalkError::InvalidGraph); + } + match status { + 0 if result.count <= count as u64 && result.work <= remaining => { + budget.work.set(budget.work.get() + result.work as usize); + Ok(output[..result.count as usize].iter().map(|index| *index as usize).collect()) + }, + 1 if result.index < count as u64 => Err(WalkError::EntryPredecessor(result.index as usize)), + 3 => Err(WalkError::ResourceLimit), + _ => Err(WalkError::InvalidGraph), + } +} + +pub(super) fn resource_error(budget: &AnalysisBudget) -> VerifyError { + VerifyError::ResourceLimit(crate::LimitError { + resource: crate::Resource::AnalysisWork, + limit: budget.limit, + }) +} + +pub(super) fn idom( + predecessors: &[Vec], + order: &[usize], + entry: usize, + budget: &AnalysisBudget, +) -> Result>, WalkError> { + let count = predecessors.len(); + let edge_count: usize = predecessors.iter().map(Vec::len).sum(); + let mut blocks = Vec::new(); + let mut edges = Vec::new(); + blocks.try_reserve_exact(count).map_err(|_| WalkError::ResourceLimit)?; + edges.try_reserve_exact(edge_count).map_err(|_| WalkError::ResourceLimit)?; + for sources in predecessors { + blocks.push(Block { first: edges.len() as u64, count: sources.len() as u64 }); + edges.extend(sources.iter().map(|index| *index as u64)); + } + let order: Vec = order.iter().map(|index| *index as u64).collect(); + let mut rank = vec![0_u64; count]; + let mut scratch_idom = vec![0_u64; count]; + let mut output = vec![0_u64; count]; + let mut result = ResultRecord::default(); + let remaining = budget.limit.saturating_sub(budget.work.get()) as u64; + let status = unsafe { + whale_ir_cfg_idom( + blocks.as_ptr(), + count as u64, + edges.as_ptr(), + edge_count as u64, + order.as_ptr(), + order.len() as u64, + entry as u64, + remaining, + rank.as_mut_ptr(), + count as u64, + scratch_idom.as_mut_ptr(), + count as u64, + output.as_mut_ptr(), + count as u64, + &mut result, + ) + }; + if status != result.status as i32 { + return Err(WalkError::InvalidGraph); + } + match status { + 0 if result.count == count as u64 && result.work <= remaining => { + budget.work.set(budget.work.get() + result.work as usize); + Ok(output + .into_iter() + .map(|index| (index != u64::MAX).then_some(index as usize)) + .collect()) + }, + 3 => Err(WalkError::ResourceLimit), + _ => Err(WalkError::InvalidGraph), + } +} diff --git a/ir/src/verifier/wave_index.rs b/ir/src/verifier/wave_index.rs new file mode 100644 index 0000000..f11a6f9 --- /dev/null +++ b/ir/src/verifier/wave_index.rs @@ -0,0 +1,170 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Borrowed identity keys; hashing, collision checks and insertion run in Wave. + +use super::{AnalysisBudget, VerifyError}; + +#[repr(C)] +#[derive(Clone, Copy)] +struct Key { + kind: u64, + number: u64, + bytes: *const u8, + count: u64, +} + +#[repr(C)] +#[derive(Clone, Copy)] +struct Slot { + kind: u64, + number: u64, + bytes: *const u8, + count: u64, + occupied: u64, +} + +#[repr(C)] +#[derive(Default)] +struct ResultRecord { + status: u64, + index: u64, + expected: u64, + actual: u64, + detail: u64, + work: u64, +} + +unsafe extern "C" { + fn whale_ir_verify_index_insert( + table: *mut Slot, + capacity: u64, + key: *const Key, + max_work: u64, + result: *mut ResultRecord, + ) -> i32; + + fn whale_ir_verify_index_contains( + table: *mut Slot, + capacity: u64, + key: *const Key, + max_work: u64, + result: *mut ResultRecord, + ) -> i32; +} + +pub(super) struct Index<'a> { + table: Vec, + borrowed: std::marker::PhantomData<&'a str>, +} + +fn resource_error(budget: &AnalysisBudget) -> VerifyError { + VerifyError::ResourceLimit(crate::LimitError { + resource: crate::Resource::AnalysisWork, + limit: budget.limit, + }) +} + +impl<'a> Index<'a> { + pub(super) fn new(count: usize, budget: &AnalysisBudget) -> Result { + let capacity = count + .max(1) + .checked_mul(2) + .and_then(usize::checked_next_power_of_two) + .ok_or_else(|| resource_error(budget))?; + if capacity > budget.limit.saturating_sub(budget.work.get()) { + return Err(resource_error(budget)); + } + budget.work.set(budget.work.get() + capacity); + let table = vec![ + Slot { kind: 0, number: 0, bytes: std::ptr::null(), count: 0, occupied: 0 }; + capacity + ]; + Ok(Self { table, borrowed: std::marker::PhantomData }) + } + + pub(super) fn name( + &mut self, + name: &'a str, + budget: &AnalysisBudget, + ) -> Result { + self.run( + Key { kind: 1, number: 0, bytes: name.as_ptr(), count: name.len() as u64 }, + true, + budget, + ) + } + + pub(super) fn id(&mut self, id: u32, budget: &AnalysisBudget) -> Result { + self.run( + Key { kind: 0, number: u64::from(id), bytes: std::ptr::null(), count: 0 }, + true, + budget, + ) + } + + pub(super) fn contains_id( + &mut self, + id: u32, + budget: &AnalysisBudget, + ) -> Result { + self.run( + Key { kind: 0, number: u64::from(id), bytes: std::ptr::null(), count: 0 }, + false, + budget, + ) + } + + pub(super) fn bits( + &mut self, + value: u128, + budget: &AnalysisBudget, + ) -> Result { + self.run( + Key { + kind: 2, + number: value as u64, + bytes: std::ptr::null(), + count: (value >> 64) as u64, + }, + true, + budget, + ) + } + + fn run( + &mut self, + key: Key, + insert: bool, + budget: &AnalysisBudget, + ) -> Result { + let remaining = budget.limit.saturating_sub(budget.work.get()) as u64; + let mut result = ResultRecord::default(); + let status = unsafe { + if insert { + whale_ir_verify_index_insert( + self.table.as_mut_ptr(), + self.table.len() as u64, + &key, + remaining, + &mut result, + ) + } else { + whale_ir_verify_index_contains( + self.table.as_mut_ptr(), + self.table.len() as u64, + &key, + remaining, + &mut result, + ) + } + }; + if status != result.status as i32 || result.work > remaining { + return Err(resource_error(budget)); + } + budget.work.set(budget.work.get() + result.work as usize); + match status { + 0 => Ok(insert), + 1 => Ok(!insert), + _ => Err(resource_error(budget)), + } + } +} diff --git a/ir/src/verifier/wave_semantics.rs b/ir/src/verifier/wave_semantics.rs new file mode 100644 index 0000000..9c769e5 --- /dev/null +++ b/ir/src/verifier/wave_semantics.rs @@ -0,0 +1,937 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Transport and diagnostic conversion for Wave semantic verification. + +use super::{AnalysisBudget, IndexedFunction, VerifyError}; + +use crate::{ + BinOp, CallError, CastOp, CmpOp, ConstValue, FloatBits, ICmpPred, Instruction, Type, ValueId, +}; + +const MISSING: u64 = u64::MAX; + +#[repr(C)] +pub(super) struct Node { + kind: u64, + child: u64, + first: u64, + count: u64, + extra: u64, +} + +#[repr(C)] +#[derive(Default)] +struct Operand { + value: u64, + ty: u64, + literal: u64, + low: u64, + high: u64, +} + +#[repr(C)] +#[derive(Default)] +struct Operation { + op: u64, + sub: u64, + ty: u64, + other: u64, + dst: u64, + align: u64, +} + +#[repr(C)] +#[derive(Default)] +struct ResultRecord { + status: u64, + index: u64, + expected: u64, + actual: u64, + detail: u64, + work: u64, +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct Binding { + id: u64, + ty: u64, + index: u64, + present: u64, +} + +unsafe extern "C" { + fn whale_ir_verify_semantics( + types: *const Node, + type_count: u64, + edges: *const u64, + edge_count: u64, + instruction: *const Operation, + operands: *const Operand, + operand_count: u64, + max_work: u64, + result: *mut ResultRecord, + ) -> i32; + + fn whale_ir_verify_value_types( + types: *const Node, + type_count: u64, + edges: *const u64, + edge_count: u64, + annotations: *const Binding, + annotation_count: u64, + definitions: *const Binding, + definition_count: u64, + table: *mut Binding, + capacity: u64, + max_work: u64, + result: *mut ResultRecord, + ) -> i32; + + fn whale_ir_verify_link( + external: u64, + present: u64, + bytes: *const u8, + count: u64, + max_work: u64, + result: *mut ResultRecord, + ) -> i32; +} + +#[derive(Default)] +pub(super) struct Input { + pub(super) nodes: Vec, + pub(super) edges: Vec, + operands: Vec, +} + +impl Input { + // This only serializes syntax. Wave decides all type equality/category rules. + pub(super) fn ty(&mut self, ty: &Type) -> u64 { + let mut node = Node { kind: 0, child: 0, first: 0, count: 0, extra: 0 }; + node.kind = match ty { + Type::Void => 0, + Type::Bool => 1, + Type::I1 => 2, + Type::U1 => 3, + Type::I8 => 4, + Type::I16 => 5, + Type::I32 => 6, + Type::I64 => 7, + Type::I128 => 8, + Type::U8 => 9, + Type::U16 => 10, + Type::U32 => 11, + Type::U64 => 12, + Type::U128 => 13, + Type::F16 => 14, + Type::F32 => 15, + Type::F64 => 16, + Type::Ptr(child) => { + node.child = self.ty(child); + 17 + }, + Type::FnPtr(signature) => { + let mut children = vec![self.ty(&signature.ret)]; + children.extend(signature.params.iter().map(|ty| self.ty(ty))); + node.first = self.edges.len() as u64; + node.count = children.len() as u64; + node.extra = + convention(signature.convention) | (u64::from(signature.variadic) << 1); + self.edges.extend(children); + 18 + }, + Type::Array(child, count) => { + node.child = self.ty(child); + node.count = *count; + 19 + }, + Type::Struct(fields) | Type::Tuple(fields) => { + let children: Vec<_> = fields.iter().map(|ty| self.ty(ty)).collect(); + node.first = self.edges.len() as u64; + node.count = children.len() as u64; + self.edges.extend(children); + if matches!(ty, Type::Struct(_)) { + 20 + } else { + 21 + } + }, + }; + let id = self.nodes.len() as u64; + self.nodes.push(node); + id + } + + // Build a diagnostic type only on failure. Keeping a clone at every graph + // node would multiply the memory of deeply nested types by their depth. + pub(super) fn decode_type(&self, id: u64) -> Option { + let node = self.nodes.get(usize::try_from(id).ok()?)?; + Some(match node.kind { + 0 => Type::Void, + 1 => Type::Bool, + 2 => Type::I1, + 3 => Type::U1, + 4 => Type::I8, + 5 => Type::I16, + 6 => Type::I32, + 7 => Type::I64, + 8 => Type::I128, + 9 => Type::U8, + 10 => Type::U16, + 11 => Type::U32, + 12 => Type::U64, + 13 => Type::U128, + 14 => Type::F16, + 15 => Type::F32, + 16 => Type::F64, + 17 => Type::ptr_to(self.decode_type(node.child)?), + 19 => Type::Array(Box::new(self.decode_type(node.child)?), node.count), + 18 | 20 | 21 => { + let first = usize::try_from(node.first).ok()?; + let end = first.checked_add(usize::try_from(node.count).ok()?)?; + let mut fields = self + .edges + .get(first..end)? + .iter() + .map(|id| self.decode_type(*id)) + .collect::>>()?; + match node.kind { + 20 => Type::Struct(fields), + 21 => Type::Tuple(fields), + _ => { + if fields.is_empty() { + return None; + } + let ret = fields.remove(0); + Type::FnPtr(Box::new(crate::FunctionSignature { + params: fields, + ret, + convention: if node.extra & 1 == 0 { + crate::CallingConvention::Whale + } else { + crate::CallingConvention::SysV64 + }, + variadic: node.extra & 2 != 0, + })) + }, + } + }, + _ => return None, + }) + } + + fn operand(&mut self, f: &IndexedFunction<'_>, value: ValueId) { + let ty = f.value_type(value).map(|ty| self.ty(ty)).unwrap_or(MISSING); + let mut operand = Operand { value: u64::from(value.0), ty, ..Operand::default() }; + if let Some(value) = f.constant(value) { + Self::literal(&mut operand, value); + } + self.operands.push(operand); + } + + fn literal(operand: &mut Operand, value: &ConstValue) { + let (kind, bits) = match value { + ConstValue::I(value) => (1, *value as u128), + ConstValue::U(value) => (2, *value), + ConstValue::Bool(value) => (3, u128::from(*value)), + ConstValue::F(FloatBits::F16(value)) => (4, u128::from(*value)), + ConstValue::F(FloatBits::F32(value)) => (5, u128::from(*value)), + ConstValue::F(FloatBits::F64(value)) => (6, u128::from(*value)), + }; + operand.literal = kind; + operand.low = bits as u64; + operand.high = (bits >> 64) as u64; + } + + fn run( + &self, + operation: &Operation, + budget: &AnalysisBudget, + ) -> Result { + let mut result = ResultRecord::default(); + let remaining = budget.limit.saturating_sub(budget.work.get()) as u64; + let status = unsafe { + whale_ir_verify_semantics( + self.nodes.as_ptr(), + self.nodes.len() as u64, + self.edges.as_ptr(), + self.edges.len() as u64, + operation, + self.operands.as_ptr(), + self.operands.len() as u64, + remaining, + &mut result, + ) + }; + if status != result.status as i32 || result.work > remaining || status == 7 || status == 8 { + return Err(resource_error(budget)); + } + budget.work.set(budget.work.get() + result.work as usize); + Ok(result) + } + + fn diagnostic( + &self, + f: &IndexedFunction<'_>, + name: &'static str, + ins: Option<&Instruction>, + result: ResultRecord, + budget: &AnalysisBudget, + ) -> Result<(), VerifyError> { + let operand = || self.operands.get(result.index as usize); + let ty = |id: u64| self.decode_type(id); + let error = match result.status { + 0 => return Ok(()), + 1 => VerifyError::InvalidInstructionType { + func: f.name.clone(), + operation: name, + ty: ty(result.expected).ok_or_else(|| resource_error(budget))?, + }, + 2 => VerifyError::MissingValueType { + func: f.name.clone(), + value: ValueId(operand().ok_or_else(|| resource_error(budget))?.value as u32), + }, + 3 => { + let mut expected = ty(result.expected).ok_or_else(|| resource_error(budget))?; + if result.detail != 0 { + expected = Type::ptr_to(expected); + } + let value = if result.detail == 2 { + match ins { + Some(Instruction::Gep { dst, .. }) => *dst, + _ => return Err(resource_error(budget)), + } + } else { + ValueId(operand().ok_or_else(|| resource_error(budget))?.value as u32) + }; + VerifyError::OperandTypeMismatch { + func: f.name.clone(), + value, + expected, + got: ty(result.actual).ok_or_else(|| resource_error(budget))?, + } + }, + 4 => { + let align = match ins { + Some( + Instruction::Alloca { align, .. } + | Instruction::Uninit { align, .. } + | Instruction::Load { align, .. } + | Instruction::Store { align, .. } + | Instruction::VolatileLoad { align, .. } + | Instruction::VolatileStore { align, .. } + | Instruction::Memcpy { align, .. } + | Instruction::Memset { align, .. }, + ) => *align, + _ => return Err(resource_error(budget)), + }; + VerifyError::InvalidMemoryAlignment { func: f.name.clone(), align } + }, + 5 => match ins { + Some(Instruction::Cast { dst, op, src_ty, dst_ty, .. }) => { + VerifyError::InvalidCast { + func: f.name.clone(), + value: *dst, + op: op.clone(), + source: src_ty.clone(), + destination: dst_ty.clone(), + } + }, + _ => return Err(resource_error(budget)), + }, + 6 => { + let dst = match ins { + Some(Instruction::Gep { dst, .. }) => *dst, + _ => return Err(resource_error(budget)), + }; + let reason = match result.detail { + 0 => "base must be a pointer", + 1 => "element addressing requires a concrete stored type", + 2 => "index must be an integer", + 3 => "field index must be a nonnegative integer constant", + 4 => "field index is outside the aggregate type", + 5 => "further indices require an array, struct, or tuple; GEP does not load pointers", + _ => return Err(resource_error(budget)), + }; + VerifyError::InvalidGep { + func: f.name.clone(), + value: dst, + index: (result.index != 0).then_some(result.index.saturating_sub(1) as usize), + reason, + } + }, + 10 => VerifyError::ConditionTypeMismatch { + func: f.name.clone(), + value: ValueId(operand().ok_or_else(|| resource_error(budget))?.value as u32), + got: ty(result.actual).ok_or_else(|| resource_error(budget))?, + }, + _ => return Err(resource_error(budget)), + }; + Err(error) + } +} + +fn resource_error(budget: &AnalysisBudget) -> VerifyError { + VerifyError::ResourceLimit(crate::LimitError { + resource: crate::Resource::AnalysisWork, + limit: budget.limit, + }) +} + +pub(super) fn value_types( + f: &IndexedFunction<'_>, + budget: &AnalysisBudget, +) -> Result<(), VerifyError> { + let mut input = Input::default(); + let annotations: Vec<_> = f + .value_types + .iter() + .map(|(value, ty)| Binding { + id: u64::from(value.0), + ty: input.ty(ty), + ..Binding::default() + }) + .collect(); + let definitions: Vec<_> = f + .params + .iter() + .map(|param| (param.id, param.ty.clone())) + .chain( + f.blocks.iter().flat_map(|block| &block.instructions).filter_map(super::instr_result), + ) + .map(|(value, ty)| Binding { + id: u64::from(value.0), + ty: input.ty(&ty), + ..Binding::default() + }) + .collect(); + let capacity = annotations + .len() + .max(1) + .checked_mul(2) + .and_then(usize::checked_next_power_of_two) + .ok_or_else(|| resource_error(budget))?; + let mut table = vec![Binding::default(); capacity]; + let mut result = ResultRecord::default(); + let remaining = budget.limit.saturating_sub(budget.work.get()) as u64; + let status = unsafe { + whale_ir_verify_value_types( + input.nodes.as_ptr(), + input.nodes.len() as u64, + input.edges.as_ptr(), + input.edges.len() as u64, + annotations.as_ptr(), + annotations.len() as u64, + definitions.as_ptr(), + definitions.len() as u64, + table.as_mut_ptr(), + capacity as u64, + remaining, + &mut result, + ) + }; + if status != result.status as i32 || result.work > remaining { + return Err(resource_error(budget)); + } + budget.work.set(budget.work.get() + result.work as usize); + let value = ValueId(result.detail as u32); + Err(match status { + 0 => return Ok(()), + 1 => VerifyError::DuplicateValueType { func: f.name.clone(), value }, + 2 => VerifyError::MissingValueType { func: f.name.clone(), value }, + 3 => VerifyError::ValueTypeMismatch { + func: f.name.clone(), + value, + expected: input.decode_type(result.expected).ok_or_else(|| resource_error(budget))?, + got: input.decode_type(result.actual).ok_or_else(|| resource_error(budget))?, + }, + 4 => VerifyError::UnexpectedValueType { func: f.name.clone(), value }, + _ => resource_error(budget), + }) +} + +fn convention(convention: crate::CallingConvention) -> u64 { + match convention { + crate::CallingConvention::Whale => 0, + crate::CallingConvention::SysV64 => 1, + } +} + +pub(super) fn valid_link( + linkage: crate::Linkage, + name: Option<&str>, + budget: &AnalysisBudget, +) -> Result { + let bytes = name.unwrap_or("").as_bytes(); + let mut result = ResultRecord::default(); + let remaining = budget.limit.saturating_sub(budget.work.get()) as u64; + let status = unsafe { + whale_ir_verify_link( + u64::from(matches!(linkage, crate::Linkage::External)), + u64::from(name.is_some()), + bytes.as_ptr(), + bytes.len() as u64, + remaining, + &mut result, + ) + }; + if status != result.status as i32 || result.work > remaining { + return Err(resource_error(budget)); + } + budget.work.set(budget.work.get() + result.work as usize); + match status { + 0 => Ok(true), + 20 => Ok(false), + _ => Err(resource_error(budget)), + } +} + +pub(super) fn alignment(align: u32, budget: &AnalysisBudget) -> Result { + let mut input = Input::default(); + let ty = input.ty(&Type::Void); + let operation = + Operation { op: 32, ty, other: ty, align: u64::from(align), ..Operation::default() }; + let result = input.run(&operation, budget)?; + match result.status { + 0 => Ok(true), + 4 => Ok(false), + _ => Err(resource_error(budget)), + } +} + +pub(super) fn storable(ty: &Type, budget: &AnalysisBudget) -> Result { + let mut input = Input::default(); + let ty = input.ty(ty); + let operation = Operation { op: 33, ty, other: ty, ..Operation::default() }; + let result = input.run(&operation, budget)?; + match result.status { + 0 => Ok(true), + 1 => Ok(false), + _ => Err(resource_error(budget)), + } +} + +pub(super) fn types_equal( + a: &Type, + b: &Type, + budget: &AnalysisBudget, +) -> Result { + let mut input = Input::default(); + let ty = input.ty(a); + let other = input.ty(b); + let operation = Operation { op: 27, ty, other, ..Operation::default() }; + let result = input.run(&operation, budget)?; + match result.status { + 0 => Ok(true), + 12 => Ok(false), + _ => Err(resource_error(budget)), + } +} + +pub(super) fn switch( + f: &IndexedFunction<'_>, + value: ValueId, + ty: &Type, + budget: &AnalysisBudget, +) -> Result<(), VerifyError> { + let mut input = Input::default(); + let ty = input.ty(ty); + input.operand(f, value); + let operation = Operation { op: 34, ty, other: ty, ..Operation::default() }; + let result = input.run(&operation, budget)?; + input.diagnostic(f, "switch", None, result, budget) +} + +pub(super) fn return_value( + f: &IndexedFunction<'_>, + declared: &Type, + value: Option, + defined: bool, + budget: &AnalysisBudget, +) -> Result<(), VerifyError> { + let mut input = Input::default(); + let ty = input.ty(&f.ret_ty); + let other = input.ty(declared); + if let Some(value) = value { + input.operand(f, value); + } + let operation = Operation { + op: 35, + ty, + other, + dst: u64::from(value.is_some()), + sub: u64::from(defined), + ..Operation::default() + }; + let result = input.run(&operation, budget)?; + match result.status { + 0 => Ok(()), + 2 => input.diagnostic(f, "return", None, result, budget), + 27 => Err(VerifyError::UseOfUndefinedValue { + func: f.name.clone(), + value: value.ok_or_else(|| resource_error(budget))?, + }), + 25 | 26 => Err(VerifyError::RetTypeMismatch { + func: f.name.clone(), + expected: f.ret_ty.clone(), + got: if result.status == 26 { + None + } else { + Some(input.decode_type(result.actual).ok_or_else(|| resource_error(budget))?) + }, + }), + _ => Err(resource_error(budget)), + } +} + +pub(super) fn global_storage( + global: &crate::GlobalStorage, + budget: &AnalysisBudget, +) -> Result<(), VerifyError> { + let mut input = Input::default(); + let ty = input.ty(&global.ty); + let mut operand = Operand::default(); + let initialized = match &global.init { + crate::GlobalStorageInit::Value(value) => { + Input::literal(&mut operand, value); + true + }, + crate::GlobalStorageInit::Uninitialized => false, + }; + input.operands.push(operand); + let operation = Operation { + op: 31, + ty, + other: ty, + sub: u64::from(global.readonly), + dst: u64::from(initialized), + align: u64::from(global.align), + }; + let result = input.run(&operation, budget)?; + let reason = match result.status { + 0 => { + if valid_link(global.linkage, global.link_name.as_deref(), budget)? { + return Ok(()); + } + crate::GlobalStorageError::InvalidLinkName + }, + 21 => crate::GlobalStorageError::InvalidType, + 22 => crate::GlobalStorageError::InvalidAlignment, + 23 => crate::GlobalStorageError::InvalidInitializer, + 24 => crate::GlobalStorageError::ReadOnlyUninitialized, + _ => return Err(resource_error(budget)), + }; + Err(VerifyError::GlobalStorage { name: global.name.clone(), global: global.id, reason }) +} + +fn signature_error(status: u64, detail: u64) -> CallError { + match (status, detail) { + (11, 1) => CallError::InvalidSignature( + "void parameters, malformed types and variadic calls are unsupported".into(), + ), + (11, 2) => { + CallError::InvalidSignature("SysV64 aggregate signatures are unsupported".into()) + }, + _ => CallError::InvalidSignature("invalid Wave verification response".into()), + } +} + +pub(super) fn signature( + signature: &crate::FunctionSignature, + limits: crate::IrLimits, + budget: &AnalysisBudget, +) -> Result<(), VerifyError> { + crate::limits::Budget::new(limits) + .and_then(|mut budget| budget.signature(signature)) + .map_err(VerifyError::ResourceLimit)?; + let mut input = Input::default(); + let ty = input.ty(&Type::FnPtr(Box::new(signature.clone()))); + let operation = Operation { op: 25, ty, other: ty, ..Operation::default() }; + let result = input.run(&operation, budget)?; + match result.status { + 0 => Ok(()), + 11 => Err(VerifyError::Call { + func: String::new(), + reason: signature_error(result.status, result.detail), + }), + _ => Err(resource_error(budget)), + } +} + +pub(super) fn pointer_signatures(ty: &Type, budget: &AnalysisBudget) -> Result<(), VerifyError> { + let mut input = Input::default(); + let ty = input.ty(ty); + let operation = Operation { op: 29, ty, other: ty, ..Operation::default() }; + let result = input.run(&operation, budget)?; + match result.status { + 0 => Ok(()), + 11 => Err(VerifyError::Call { + func: String::new(), + reason: signature_error(result.status, result.detail), + }), + _ => Err(resource_error(budget)), + } +} + +pub(super) fn signature_equal( + expected: &crate::FunctionSignature, + actual: &crate::FunctionSignature, + budget: &AnalysisBudget, +) -> Result { + let mut input = Input::default(); + let ty = input.ty(&Type::FnPtr(Box::new(expected.clone()))); + let other = input.ty(&Type::FnPtr(Box::new(actual.clone()))); + let operation = Operation { op: 27, ty, other, ..Operation::default() }; + let result = input.run(&operation, budget)?; + match result.status { + 0 => Ok(true), + 12 => Ok(false), + _ => Err(resource_error(budget)), + } +} + +pub(super) fn call( + f: &IndexedFunction<'_>, + signature: &Type, + ins: &Instruction, + budget: &AnalysisBudget, +) -> Result<(), VerifyError> { + let Instruction::Call { dst, ret_ty, convention: call_convention, args, .. } = ins else { + return Err(resource_error(budget)); + }; + let mut input = Input::default(); + let ty = input.ty(signature); + let other = input.ty(ret_ty); + for arg in args { + input.operand(f, *arg); + } + let operation = Operation { + op: 28, + ty, + other, + sub: convention(*call_convention), + dst: u64::from(dst.is_some()), + ..Operation::default() + }; + let result = input.run(&operation, budget)?; + let error = match result.status { + 0 => return Ok(()), + 2 => CallError::UnknownValue( + *args.get(result.index as usize).ok_or_else(|| resource_error(budget))?, + ), + 11 => signature_error(result.status, result.detail), + 13 => CallError::ConventionMismatch, + 14 => CallError::ReturnType { + expected: input.decode_type(result.expected).ok_or_else(|| resource_error(budget))?, + got: input.decode_type(result.actual).ok_or_else(|| resource_error(budget))?, + }, + 15 => CallError::ResultPresence, + 16 => CallError::ArgumentCount { + expected: result.expected as usize, + got: result.actual as usize, + }, + 17 => CallError::ArgumentType { + index: result.index as usize, + expected: input.decode_type(result.expected).ok_or_else(|| resource_error(budget))?, + got: input.decode_type(result.actual).ok_or_else(|| resource_error(budget))?, + }, + 19 => match ins { + Instruction::Call { callee: crate::Callee::Indirect(value), .. } => { + CallError::NotFunctionPointer(*value) + }, + _ => return Err(resource_error(budget)), + }, + _ => return Err(resource_error(budget)), + }; + Err(VerifyError::Call { func: f.name.clone(), reason: error }) +} + +pub(super) fn function_pointer_cast( + f: &IndexedFunction<'_>, + src: ValueId, + source: &Type, + destination: &Type, + op: &CastOp, + budget: &AnalysisBudget, +) -> Result<(), VerifyError> { + let mut input = Input::default(); + let ty = input.ty(source); + let other = input.ty(destination); + input.operand(f, src); + let operation = Operation { + op: 30, + ty, + other, + sub: if matches!(op, CastOp::Bitcast) { 9 } else { 0 }, + ..Operation::default() + }; + let result = input.run(&operation, budget)?; + match result.status { + 0 => Ok(()), + 18 => Err(VerifyError::Call { + func: f.name.clone(), + reason: CallError::ForbiddenFunctionPointerCast, + }), + _ => Err(resource_error(budget)), + } +} + +pub(super) fn condition( + f: &IndexedFunction<'_>, + value: ValueId, + budget: &AnalysisBudget, +) -> Result<(), VerifyError> { + let mut input = Input::default(); + let ty = input.ty(&Type::Void); + input.operand(f, value); + let operation = Operation { op: 22, ty, other: ty, ..Operation::default() }; + let result = input.run(&operation, budget)?; + input.diagnostic(f, "condition", None, result, budget) +} + +pub(super) fn literal_valid( + ty: &Type, + value: &ConstValue, + budget: &AnalysisBudget, +) -> Result { + let mut input = Input::default(); + let ty = input.ty(ty); + let mut operand = Operand::default(); + Input::literal(&mut operand, value); + input.operands.push(operand); + let operation = Operation { op: 24, ty, other: ty, ..Operation::default() }; + let result = input.run(&operation, budget)?; + match result.status { + 0 => Ok(true), + 9 => Ok(false), + _ => Err(resource_error(budget)), + } +} + +pub(super) fn verify_instruction( + f: &IndexedFunction<'_>, + ins: &Instruction, + budget: &AnalysisBudget, +) -> Result<(), VerifyError> { + let mut input = Input::default(); + let mut operation = Operation::default(); + let (op, name, ty, other, operands) = match ins { + Instruction::Neg { ty, src, .. } => (1, "neg", ty.clone(), Type::Void, vec![*src]), + Instruction::Cast { op, src_ty, src, dst_ty, .. } => { + operation.sub = match op { + CastOp::ZExt => 0, + CastOp::SExt => 1, + CastOp::Trunc => 2, + CastOp::FExt => 3, + CastOp::FTrunc => 4, + CastOp::IToF_S => 5, + CastOp::IToF_U => 6, + CastOp::FToI_S => 7, + CastOp::FToI_U => 8, + CastOp::Bitcast => 9, + CastOp::PtrToInt => 10, + CastOp::IntToPtr => 11, + CastOp::CheckedInt => 12, + }; + (2, "cast", src_ty.clone(), dst_ty.clone(), vec![*src]) + }, + Instruction::Checked { op, ty, lhs, rhs, .. } => { + operation.sub = match op { + crate::CheckedOp::SAdd | crate::CheckedOp::SSub | crate::CheckedOp::SMul => 0, + crate::CheckedOp::UAdd | crate::CheckedOp::USub | crate::CheckedOp::UMul => 1, + }; + (3, "checked arithmetic", ty.clone(), Type::Void, vec![*lhs, *rhs]) + }, + Instruction::Bin { op, ty, lhs, rhs, .. } => { + operation.sub = match op { + BinOp::SDiv | BinOp::SRem => 1, + BinOp::UDiv | BinOp::URem => 2, + BinOp::FAdd | BinOp::FSub | BinOp::FMul | BinOp::FDiv | BinOp::FRem => 3, + _ => 0, + }; + (4, "binary operation", ty.clone(), Type::Void, vec![*lhs, *rhs]) + }, + Instruction::LifetimeEnd { ptr } => (5, "lifetime_end", Type::Void, Type::Void, vec![*ptr]), + Instruction::PtrDiff { lhs, rhs, .. } => { + (6, "ptrdiff", Type::Void, Type::Void, vec![*lhs, *rhs]) + }, + Instruction::Not { ty, src, .. } => (7, "not", ty.clone(), Type::Void, vec![*src]), + Instruction::Mov { ty, src, .. } => (8, "mov", ty.clone(), Type::Void, vec![*src]), + Instruction::Cmp { op, ty, lhs, rhs, .. } => { + operation.sub = match op { + CmpOp::Eq | CmpOp::Ne => 0, + CmpOp::SLt | CmpOp::SLe | CmpOp::SGt | CmpOp::SGe => 1, + CmpOp::ULt | CmpOp::ULe | CmpOp::UGt | CmpOp::UGe => 2, + _ => 3, + }; + (9, "comparison", ty.clone(), Type::Void, vec![*lhs, *rhs]) + }, + Instruction::ICmp { pred, ty, lhs, rhs, .. } => { + operation.sub = match pred { + ICmpPred::Eq | ICmpPred::Ne => 0, + ICmpPred::Slt | ICmpPred::Sle | ICmpPred::Sgt | ICmpPred::Sge => 1, + _ => 2, + }; + (9, "integer comparison", ty.clone(), Type::Void, vec![*lhs, *rhs]) + }, + Instruction::FCmp { ty, lhs, rhs, .. } => { + (10, "floating comparison", ty.clone(), Type::Void, vec![*lhs, *rhs]) + }, + Instruction::Select { ty, cond, on_true, on_false, .. } => { + // Keep condition diagnostics ahead of the selected type category. + condition(f, *cond, budget)?; + (11, "select", ty.clone(), Type::Void, vec![*cond, *on_true, *on_false]) + }, + Instruction::Extract { dst_ty, tuple, index, .. } => { + operation.sub = u64::from(*index); + (12, "extract", dst_ty.clone(), Type::Void, vec![*tuple]) + }, + Instruction::Uninit { ty, ptr, align } => { + operation.align = u64::from(*align); + (13, "uninit", ty.clone(), Type::Void, vec![*ptr]) + }, + Instruction::Alloca { ty, align, .. } => { + operation.align = u64::from(*align); + (14, "alloca", ty.clone(), Type::Void, vec![]) + }, + Instruction::VolatileLoad { ty, ptr, align, .. } => { + operation.align = u64::from(*align); + (15, "volatile load", ty.clone(), Type::Void, vec![*ptr]) + }, + Instruction::VolatileStore { ty, ptr, value, align } => { + operation.align = u64::from(*align); + (16, "volatile store", ty.clone(), Type::Void, vec![*ptr, *value]) + }, + Instruction::Load { ty, ptr, align, .. } => { + operation.align = u64::from(*align); + (17, "load", ty.clone(), Type::Void, vec![*ptr]) + }, + Instruction::Store { ty, ptr, value, align } => { + operation.align = u64::from(*align); + (18, "store", ty.clone(), Type::Void, vec![*ptr, *value]) + }, + Instruction::Gep { dst, dst_ty, base_ptr, indices } => { + operation.dst = u64::from(dst.0); + let mut operands = vec![*base_ptr]; + operands.extend(indices); + (19, "gep", dst_ty.clone(), Type::Void, operands) + }, + Instruction::Memcpy { dst, src, n, align } => { + operation.align = u64::from(*align); + (20, "memcpy", Type::U8, Type::U64, vec![*dst, *src, *n]) + }, + Instruction::Memset { dst, val, n, align } => { + operation.align = u64::from(*align); + (21, "memset", Type::U8, Type::U64, vec![*dst, *val, *n]) + }, + _ => return Ok(()), + }; + operation.op = op; + operation.ty = input.ty(&ty); + operation.other = input.ty(&other); + for operand in operands { + input.operand(f, operand); + } + let result = input.run(&operation, budget)?; + input.diagnostic(f, name, Some(ins), result, budget) +} diff --git a/ir/src/verifier/wave_shape.rs b/ir/src/verifier/wave_shape.rs new file mode 100644 index 0000000..1d72b79 --- /dev/null +++ b/ir/src/verifier/wave_shape.rs @@ -0,0 +1,194 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Flat, caller-owned bridge for Wave-owned structural IR verification. + +use super::{instr_result, AnalysisBudget, IndexedFunction, VerifyError}; + +use crate::{BlockId, Terminator, Type, ValueId}; + +#[repr(C)] +struct Block { + id: u64, + terminated: u64, + first_edge: u64, + edge_count: u64, +} + +#[repr(C)] +struct Value { + id: u64, + void_parameter: u64, +} + +#[repr(C)] +#[derive(Default)] +struct ResultRecord { + status: u64, + index: u64, + detail: u64, + work: u64, +} + +unsafe extern "C" { + fn whale_ir_verify_shape( + blocks: *const Block, + block_count: u64, + entry: u64, + values: *const Value, + value_count: u64, + edges: *const u64, + edge_count: u64, + max_work: u64, + block_table: *mut u64, + block_table_capacity: u64, + value_table: *mut u64, + value_table_capacity: u64, + result: *mut ResultRecord, + ) -> i32; + + fn whale_ir_shape_contains( + table: *const u64, + capacity: u64, + id: u64, + max_work: u64, + result: *mut ResultRecord, + ) -> i32; +} + +pub(super) struct Definitions { + table: Vec, +} + +impl Definitions { + pub(super) fn contains( + &self, + value: ValueId, + budget: &AnalysisBudget, + ) -> Result { + let remaining = budget.limit.saturating_sub(budget.work.get()) as u64; + let mut result = ResultRecord::default(); + let status = unsafe { + whale_ir_shape_contains( + self.table.as_ptr(), + self.table.len() as u64, + u64::from(value.0), + remaining, + &mut result, + ) + }; + if status != 0 || result.status != 0 || result.detail > 1 || result.work > remaining { + return Err(resource_error(budget)); + } + budget.work.set(budget.work.get() + result.work as usize); + Ok(result.detail != 0) + } +} + +fn table_capacity(count: usize) -> Option { + count.max(1).checked_mul(2)?.checked_next_power_of_two() +} + +pub(super) fn verify( + f: &IndexedFunction<'_>, + budget: &AnalysisBudget, +) -> Result { + let mut blocks = Vec::new(); + let mut values = Vec::new(); + let mut edges = Vec::new(); + for param in &f.params { + values.push(Value { + id: u64::from(param.id.0), + void_parameter: u64::from(param.ty == Type::Void), + }); + } + for block in &f.blocks { + for ins in &block.instructions { + if let Some((dst, _)) = instr_result(ins) { + values.push(Value { id: u64::from(dst.0), void_parameter: 0 }); + } + } + } + for block in &f.blocks { + let first = edges.len(); + match &block.terminator { + Some(Terminator::Br { target }) => edges.push(u64::from(target.0)), + Some(Terminator::CBr { then_bb, else_bb, .. }) => { + edges.push(u64::from(then_bb.0)); + edges.push(u64::from(else_bb.0)); + }, + Some(Terminator::Switch { default_bb, cases, .. }) => { + edges.push(u64::from(default_bb.0)); + edges.extend(cases.iter().map(|(_, target)| u64::from(target.0))); + }, + Some(Terminator::Ret { .. } | Terminator::Trap { .. }) | None => {}, + } + blocks.push(Block { + id: u64::from(block.id.0), + terminated: u64::from(block.terminator.is_some()), + first_edge: first as u64, + edge_count: (edges.len() - first) as u64, + }); + } + let block_capacity = table_capacity(blocks.len()).ok_or_else(|| resource_error(budget))?; + let value_capacity = table_capacity(values.len()).ok_or_else(|| resource_error(budget))?; + let mut block_table = vec![0_u64; block_capacity]; + let mut value_table = vec![0_u64; value_capacity]; + let mut result = ResultRecord::default(); + let remaining = budget.limit.saturating_sub(budget.work.get()) as u64; + let status = unsafe { + whale_ir_verify_shape( + blocks.as_ptr(), + blocks.len() as u64, + u64::from(f.entry.0), + values.as_ptr(), + values.len() as u64, + edges.as_ptr(), + edges.len() as u64, + remaining, + block_table.as_mut_ptr(), + block_capacity as u64, + value_table.as_mut_ptr(), + value_capacity as u64, + &mut result, + ) + }; + if status != result.status as i32 { + return Err(resource_error(budget)); + } + let index = result.index as usize; + match status { + 0 if result.work <= remaining => { + budget.work.set(budget.work.get() + result.work as usize); + Ok(Definitions { table: value_table }) + }, + 1 => Err(VerifyError::DuplicateBlock { + func: f.name.clone(), + block: BlockId(result.detail as u32), + }), + 2 => Err(VerifyError::InvalidEntryBlock { func: f.name.clone(), entry: f.entry }), + 3 => Err(VerifyError::DuplicateValue { + func: f.name.clone(), + value: ValueId(result.detail as u32), + }), + 4 if index < f.blocks.len() => Err(VerifyError::UnterminatedBlock { + func: f.name.clone(), + block: f.blocks[index].name.clone(), + }), + 5 if index < f.blocks.len() => Err(VerifyError::InvalidBranchTarget { + func: f.name.clone(), + block: f.blocks[index].id, + target: BlockId(result.detail as u32), + }), + 8 if index < f.params.len() => Err(VerifyError::VoidParameter { + func: f.name.clone(), + param: f.params[index].name.clone(), + }), + _ => Err(resource_error(budget)), + } +} + +fn resource_error(budget: &AnalysisBudget) -> VerifyError { + VerifyError::ResourceLimit(crate::LimitError { + resource: crate::Resource::AnalysisWork, + limit: budget.limit, + }) +} diff --git a/ir/src/verifier/wave_ssa.rs b/ir/src/verifier/wave_ssa.rs new file mode 100644 index 0000000..1a3b98a --- /dev/null +++ b/ir/src/verifier/wave_ssa.rs @@ -0,0 +1,284 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Borrowed instruction/CFG transport for the Wave SSA verifier. + +use std::collections::HashMap; + +use super::{wave_semantics, AnalysisBudget, IndexedFunction, VerifyError}; + +use crate::{Instruction, Terminator, Type, ValueId}; + +const NONE: u64 = u64::MAX; + +#[repr(C)] +struct Block { + id: u64, + first: u64, + count: u64, + pred_first: u64, + pred_count: u64, + reachable: u64, + start: u64, + end: u64, + terminator_use: u64, +} + +#[repr(C)] +struct InstructionRecord { + phi: u64, + dst: u64, + ty: u64, + first: u64, + count: u64, +} + +#[repr(C)] +struct Usage { + value: u64, + ty: u64, + pred: u64, + def_block: u64, + def_position: u64, + defined: u64, +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct Predecessor { + block: u64, + seen: u64, +} + +#[repr(C)] +#[derive(Default)] +struct ResultRecord { + status: u64, + instruction: u64, + usage: u64, + detail: u64, + work: u64, + queries: u64, +} + +unsafe extern "C" { + fn whale_ir_verify_ssa( + types: *const wave_semantics::Node, + type_count: u64, + edges: *const u64, + edge_count: u64, + blocks: *const Block, + block_count: u64, + entry: u64, + instructions: *const InstructionRecord, + instruction_count: u64, + uses: *const Usage, + use_count: u64, + predecessors: *const u64, + predecessor_count: u64, + table: *mut Predecessor, + capacity: u64, + max_work: u64, + result: *mut ResultRecord, + ) -> i32; +} + +fn resource_error(budget: &AnalysisBudget) -> VerifyError { + VerifyError::ResourceLimit(crate::LimitError { + resource: crate::Resource::AnalysisWork, + limit: budget.limit, + }) +} + +pub(super) fn verify( + f: &IndexedFunction<'_>, + cfg: &super::cfg::Cfg, + budget: &AnalysisBudget, +) -> Result<(), VerifyError> { + let mut definitions: HashMap> = + f.params.iter().map(|param| (param.id, None)).collect(); + for (block, body) in f.blocks.iter().enumerate() { + for (position, instruction) in body.instructions.iter().enumerate() { + if let Some((value, _)) = super::instr_result(instruction) { + definitions.insert(value, Some((block, position))); + } + } + } + let mut input = wave_semantics::Input::default(); + let void = input.ty(&Type::Void); + let mut blocks = Vec::new(); + let mut instructions = Vec::new(); + let mut uses = Vec::new(); + let mut predecessors = Vec::new(); + let mut source = Vec::new(); + let make_use = |value: ValueId, ty: u64, pred: u64| { + let (defined, def_block, def_position) = match definitions.get(&value) { + Some(Some((block, position))) => (1, *block as u64, *position as u64), + Some(None) => (1, NONE, 0), + None => (0, NONE, 0), + }; + Usage { value: u64::from(value.0), ty, pred, defined, def_block, def_position } + }; + for (block_index, block) in f.blocks.iter().enumerate() { + let first = instructions.len(); + for instruction in &block.instructions { + let first_use = uses.len(); + let (phi, dst, ty) = match instruction { + Instruction::Phi { dst, ty, incomings } => { + let root = input.ty(ty); + for (value, predecessor) in incomings { + let ty = f.value_type(*value).map(|ty| input.ty(ty)).unwrap_or(NONE); + let pred = + cfg.indices.get(predecessor).map(|index| *index as u64).unwrap_or(NONE); + uses.push(make_use(*value, ty, pred)); + } + (1, u64::from(dst.0), root) + }, + _ => { + uses.extend( + super::instr_uses(instruction) + .into_iter() + .map(|value| make_use(value, NONE, NONE)), + ); + (0, 0, void) + }, + }; + instructions.push(InstructionRecord { + phi, + dst, + ty, + first: first_use as u64, + count: (uses.len() - first_use) as u64, + }); + source.push((block_index, instruction)); + } + let terminator_value = match block.terminator.as_ref().unwrap() { + Terminator::CBr { cond, .. } => Some(*cond), + Terminator::Switch { value, .. } => Some(*value), + Terminator::Ret { value, .. } => *value, + Terminator::Br { .. } | Terminator::Trap { .. } => None, + }; + let terminator_use = terminator_value + .map(|value| { + let index = uses.len() as u64; + uses.push(make_use(value, NONE, NONE)); + index + }) + .unwrap_or(NONE); + let pred_first = predecessors.len(); + predecessors.extend(cfg.predecessors[block_index].iter().map(|index| *index as u64)); + let (reachable, start, end) = match cfg.intervals[block_index] { + Some((start, end)) => (1, start as u64, end as u64), + None => (0, 0, 0), + }; + blocks.push(Block { + id: u64::from(block.id.0), + first: first as u64, + count: (instructions.len() - first) as u64, + pred_first: pred_first as u64, + pred_count: (predecessors.len() - pred_first) as u64, + reachable, + start, + end, + terminator_use, + }); + } + let max_pred = cfg.predecessors.iter().map(Vec::len).max().unwrap_or(0); + let capacity = max_pred + .max(1) + .checked_mul(2) + .and_then(usize::checked_next_power_of_two) + .ok_or_else(|| resource_error(budget))?; + let mut table = vec![Predecessor::default(); capacity]; + let remaining = budget.limit.saturating_sub(budget.work.get()) as u64; + let mut result = ResultRecord::default(); + let status = unsafe { + whale_ir_verify_ssa( + input.nodes.as_ptr(), + input.nodes.len() as u64, + input.edges.as_ptr(), + input.edges.len() as u64, + blocks.as_ptr(), + blocks.len() as u64, + cfg.indices[&f.entry] as u64, + instructions.as_ptr(), + instructions.len() as u64, + uses.as_ptr(), + uses.len() as u64, + predecessors.as_ptr(), + predecessors.len() as u64, + table.as_mut_ptr(), + capacity as u64, + remaining, + &mut result, + ) + }; + if status != result.status as i32 || result.work > remaining || result.queries > result.work { + return Err(resource_error(budget)); + } + budget.work.set(budget.work.get() + result.work as usize); + budget.queries.set(budget.queries.get() + result.queries as usize); + let usage = || uses.get(result.usage as usize).ok_or_else(|| resource_error(budget)); + let instruction = + || source.get(result.instruction as usize).ok_or_else(|| resource_error(budget)); + Err(match status { + 0 => return Ok(()), + 1 => { + let (block, instruction) = instruction()?; + let Instruction::Phi { dst, .. } = instruction else { + return Err(resource_error(budget)); + }; + let reason = match result.detail { + 0 => "phi must precede non-phi instructions", + 1 => "function entry has no incoming SSA value", + 2 => "phi requires incoming values", + 3 => "phi names an unknown predecessor", + 4 => "phi input is not a predecessor", + 5 => "duplicate phi predecessor", + 6 => "phi is missing a predecessor", + _ => return Err(resource_error(budget)), + }; + VerifyError::InvalidPhi { + func: f.name.clone(), + block: f.blocks[*block].id, + value: *dst, + reason, + } + }, + 2 => VerifyError::UseOfUndefinedValue { + func: f.name.clone(), + value: ValueId(usage()?.value as u32), + }, + 3 => VerifyError::NonDominatingValue { + func: f.name.clone(), + value: ValueId(usage()?.value as u32), + block: f.blocks.get(result.detail as usize).ok_or_else(|| resource_error(budget))?.id, + }, + 4 => { + let (_, instruction) = instruction()?; + let Instruction::Phi { ty, .. } = instruction else { + return Err(resource_error(budget)); + }; + VerifyError::InvalidInstructionType { + func: f.name.clone(), + operation: "phi", + ty: ty.clone(), + } + }, + 5 => { + let (_, instruction) = instruction()?; + let Instruction::Phi { ty, .. } = instruction else { + return Err(resource_error(budget)); + }; + VerifyError::OperandTypeMismatch { + func: f.name.clone(), + value: ValueId(usage()?.value as u32), + expected: ty.clone(), + got: input.decode_type(usage()?.ty).ok_or_else(|| resource_error(budget))?, + } + }, + 6 => VerifyError::MissingValueType { + func: f.name.clone(), + value: ValueId(usage()?.value as u32), + }, + _ => resource_error(budget), + }) +} diff --git a/ir/src/wave_layout.rs b/ir/src/wave_layout.rs new file mode 100644 index 0000000..cb46754 --- /dev/null +++ b/ir/src/wave_layout.rs @@ -0,0 +1,244 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Internal borrowed data bridge for the Wave IR layout kernel. + +use crate::{LayoutError, Type, TypeLayout}; + +use target_spec::StorageLayout; + +const MAX_NODES: usize = 1_000_000; + +const MAX_EDGES: usize = 1_000_000; + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct Node { + kind: u64, + child: u64, + first: u64, + count: u64, +} + +#[repr(C)] +#[derive(Clone, Copy)] +struct Storage { + ptr_bits: u64, + pointer_align: u64, + scalar_align1: u64, + scalar_align2: u64, + scalar_align4: u64, + scalar_align8: u64, + scalar_align16: u64, + large_array_threshold: u64, + large_array_align: u64, + has_large_array: u64, +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct Layout { + size: u64, + align: u64, + stride: u64, + allocation_align: u64, + depth: u64, +} + +#[repr(C)] +#[derive(Default)] +struct ResultRecord { + status: u64, + index: u64, +} + +unsafe extern "C" { + fn whale_ir_layout( + storage: *const Storage, + nodes: *const Node, + node_count: u64, + edges: *const u64, + edge_count: u64, + root: u64, + max_depth: u64, + max_work: u64, + scratch: *mut Layout, + scratch_count: u64, + scratch_offsets: *mut u64, + scratch_offset_count: u64, + output: *mut Layout, + output_count: u64, + output_offsets: *mut u64, + output_offset_count: u64, + result: *mut ResultRecord, + ) -> i32; +} + +fn add_type(ty: &Type, nodes: &mut Vec, edges: &mut Vec) -> Result { + enum Task<'a> { + Visit(&'a Type), + Array(u64), + Aggregate { kind: u64, count: usize }, + } + let mut pending = vec![Task::Visit(ty)]; + let mut values = Vec::::new(); + while let Some(task) = pending.pop() { + let node = match task { + Task::Visit(Type::Array(child, count)) => { + pending.try_reserve(2).map_err(|_| LayoutError::Overflow)?; + pending.push(Task::Array(*count)); + pending.push(Task::Visit(child)); + continue; + }, + Task::Visit(Type::Struct(fields)) => { + if fields.len() > MAX_EDGES.saturating_sub(edges.len()) { + return Err(LayoutError::Overflow); + } + pending.try_reserve(fields.len() + 1).map_err(|_| LayoutError::Overflow)?; + pending.push(Task::Aggregate { kind: 9, count: fields.len() }); + pending.extend(fields.iter().rev().map(Task::Visit)); + continue; + }, + Task::Visit(Type::Tuple(fields)) => { + if fields.len() > MAX_EDGES.saturating_sub(edges.len()) { + return Err(LayoutError::Overflow); + } + pending.try_reserve(fields.len() + 1).map_err(|_| LayoutError::Overflow)?; + pending.push(Task::Aggregate { kind: 10, count: fields.len() }); + pending.extend(fields.iter().rev().map(Task::Visit)); + continue; + }, + Task::Visit(leaf) => { + let kind = match leaf { + Type::Void => 0, + Type::Bool | Type::I1 | Type::U1 | Type::I8 | Type::U8 => 1, + Type::I16 | Type::U16 | Type::F16 => 2, + Type::I32 | Type::U32 | Type::F32 => 3, + Type::I64 | Type::U64 | Type::F64 => 4, + Type::I128 | Type::U128 => 5, + Type::Ptr(_) => 6, + Type::FnPtr(_) => 7, + Type::Array(..) | Type::Struct(_) | Type::Tuple(_) => unreachable!(), + }; + Node { kind, ..Node::default() } + }, + Task::Array(count) => Node { + kind: 8, + child: values.pop().expect("array child was traversed"), + count, + ..Node::default() + }, + Task::Aggregate { kind, count } => { + let first_value = values.len() - count; + if count > MAX_EDGES.saturating_sub(edges.len()) { + return Err(LayoutError::Overflow); + } + edges.try_reserve(count).map_err(|_| LayoutError::Overflow)?; + let first = u64::try_from(edges.len()).map_err(|_| LayoutError::Overflow)?; + edges.extend_from_slice(&values[first_value..]); + values.truncate(first_value); + Node { kind, first, count: count as u64, ..Node::default() } + }, + }; + if nodes.len() == MAX_NODES { + return Err(LayoutError::Overflow); + } + nodes.try_reserve(1).map_err(|_| LayoutError::Overflow)?; + values.try_reserve(1).map_err(|_| LayoutError::Overflow)?; + let index = u64::try_from(nodes.len()).map_err(|_| LayoutError::Overflow)?; + let mut node = node; + if node.kind == 6 || node.kind == 7 { + // Pointees and function signatures do not participate in storage layout. + node.child = index; + } + nodes.push(node); + values.push(index); + } + Ok(values.pop().expect("root type was traversed")) +} + +pub(super) fn layout( + ty: &Type, + storage: &StorageLayout, + max_depth: usize, +) -> Result<(TypeLayout, u32), LayoutError> { + let mut nodes = Vec::new(); + let mut edges = Vec::new(); + let depth = max_depth.min(crate::MAX_IR_NESTING); + let root = add_type(ty, &mut nodes, &mut edges)?; + let (threshold, large_align, has_large_array) = match storage.large_array { + Some((threshold, align)) => (threshold, u64::from(align), 1), + None => (0, 0, 0), + }; + let input = Storage { + ptr_bits: u64::from(storage.data.ptr_bits), + pointer_align: u64::from(storage.pointer_align), + scalar_align1: u64::from(storage.scalar_align[0]), + scalar_align2: u64::from(storage.scalar_align[1]), + scalar_align4: u64::from(storage.scalar_align[2]), + scalar_align8: u64::from(storage.scalar_align[3]), + scalar_align16: u64::from(storage.scalar_align[4]), + large_array_threshold: threshold, + large_array_align: large_align, + has_large_array, + }; + let mut scratch = vec![Layout::default(); nodes.len()]; + let mut output = vec![Layout::default(); nodes.len()]; + let mut scratch_offsets = vec![0; edges.len()]; + let mut output_offsets = vec![0; edges.len()]; + let mut result = ResultRecord::default(); + let node_count = u64::try_from(nodes.len()).map_err(|_| LayoutError::Overflow)?; + let edge_count = u64::try_from(edges.len()).map_err(|_| LayoutError::Overflow)?; + let work = node_count + .checked_mul(3) + .and_then(|n| edge_count.checked_mul(3).and_then(|e| n.checked_add(e))) + .ok_or(LayoutError::Overflow)?; + // The Wave kernel validates every span and writes only caller-owned scratch + // until all type, target, depth, work and output checks have succeeded. + let status = unsafe { + whale_ir_layout( + &input, + nodes.as_ptr(), + node_count, + edges.as_ptr(), + edge_count, + root, + u64::try_from(depth).map_err(|_| LayoutError::DepthLimit)?, + work, + scratch.as_mut_ptr(), + node_count, + scratch_offsets.as_mut_ptr(), + edge_count, + output.as_mut_ptr(), + node_count, + output_offsets.as_mut_ptr(), + edge_count, + &mut result, + ) + }; + if status != 0 { + return Err(match status { + 1 => LayoutError::Void, + 2 => LayoutError::DepthLimit, + 3 | 4 | 6 => LayoutError::Overflow, + _ => LayoutError::InvalidTarget, + }); + } + let root = usize::try_from(root).map_err(|_| LayoutError::Overflow)?; + let layout = output[root]; + let root_node = nodes[root]; + let field_offsets = if root_node.kind == 9 || root_node.kind == 10 { + let first = usize::try_from(root_node.first).map_err(|_| LayoutError::Overflow)?; + let count = usize::try_from(root_node.count).map_err(|_| LayoutError::Overflow)?; + output_offsets[first..first + count].to_vec() + } else { + Vec::new() + }; + let natural = TypeLayout { + size: layout.size, + align: u32::try_from(layout.align).map_err(|_| LayoutError::InvalidTarget)?, + field_offsets, + element_stride: (root_node.kind == 8).then_some(layout.stride), + }; + let allocation_align = + u32::try_from(layout.allocation_align).map_err(|_| LayoutError::InvalidTarget)?; + Ok((natural, allocation_align)) +} diff --git a/ir/tests/builder_checked.rs b/ir/tests/builder_checked.rs index e562735..b7383f0 100644 --- a/ir/tests/builder_checked.rs +++ b/ir/tests/builder_checked.rs @@ -1,5 +1,67 @@ use ir::*; +#[cfg(whale_wave_ir)] +#[test] +fn complete_body_resource_failures_preserve_values_and_terminator_state() { + let mut module = ModuleBuilder::with_limits( + "x86_64-whale-linux", + DataLayout::default_64bit_le(), + IrLimits { max_input_bytes: 16, ..IrLimits::default() }, + ) + .unwrap(); + let mut function = module.begin_function("f", vec![], Type::Void); + let condition = function.try_const_bool(true).unwrap(); + let expected = + BuilderError::ResourceLimit(LimitError { resource: Resource::InputBytes, limit: 16 }); + assert_eq!(function.try_trap("x".repeat(17)), Err(expected.clone())); + assert_eq!(function.try_trap_if(condition, "x".repeat(17)), Err(expected.clone())); + assert_eq!( + function.try_const_decl( + "x".repeat(17), + ConstExpr::literal(Type::I32, ConstValue::I(4)), + ConstValue::I(4) + ), + Err(expected) + ); + assert_eq!(function.try_const_i32(42), Ok(ValueId(condition.0 + 1))); + function.try_ret(None).unwrap(); + function.finish(); + let module = module.finish(); + verify_module(&module).unwrap(); + assert_eq!(module.functions[0].blocks[0].instructions.len(), 2); +} + +#[cfg(whale_wave_ir)] +#[test] +fn rejected_constant_body_expression_is_discarded_iteratively() { + std::thread::Builder::new() + .stack_size(128 * 1024) + .spawn(|| { + let mut expression = ConstExpr::literal(Type::I32, ConstValue::I(0)); + for _ in 0..5000 { + expression = + ConstExpr { ty: Type::I32, kind: ConstExprKind::Not(Box::new(expression)) }; + } + let mut module = + ModuleBuilder::new("x86_64-whale-linux", DataLayout::default_64bit_le()); + let mut function = module.begin_function("f", vec![], Type::Void); + assert!(matches!( + function.try_const_decl("deep", expression, ConstValue::I(0)), + Err(BuilderError::ResourceLimit(LimitError { + resource: Resource::ConstantDepth, + .. + })) + )); + assert_eq!(function.try_const_i32(42), Ok(ValueId(0))); + function.try_ret(None).unwrap(); + function.finish(); + verify_module(&module.finish()).unwrap(); + }) + .unwrap() + .join() + .unwrap(); +} + #[test] fn checked_entry_allocation_cannot_mutate_a_terminated_entry() { let mut mb = ModuleBuilder::new("x86_64-whale-linux", DataLayout::default_64bit_le()); @@ -138,3 +200,74 @@ fn function_and_storage_link_collisions_fail_atomically_in_both_orders() { verify_module(&m).unwrap(); } } + +#[test] +fn legacy_entry_hoisting_preserves_a_preexisting_terminator() { + let mut mb = ModuleBuilder::new("x86_64-whale-linux", DataLayout::default_64bit_le()); + let mut f = mb.begin_function("hoist_after_branch", vec![], Type::Void); + let entry = f.entry_block(); + let next = f.create_block("body"); + f.br(next); + f.set_insert_point(next); + let slot = f.alloca_in_entry(Type::I32, 4); + assert_eq!(f.try_alloca_in_entry(Type::I32, 4), Err(BuilderError::TerminatedBlock(entry))); + let value = f.const_i32(7); + f.store(Type::I32, value, slot, 4); + f.ret(None); + f.finish(); + let module = mb.finish(); + assert!(matches!( + module.functions[0].blocks[0].instructions.as_slice(), + [Instruction::Alloca { .. }] + )); + assert!( + matches!(module.functions[0].blocks[0].terminator, Some(Terminator::Br { target }) if target == next) + ); + verify_module(&module).unwrap(); +} + +#[test] +fn deep_rejected_builder_type_is_discarded_before_clone_on_a_small_stack() { + std::thread::Builder::new() + .stack_size(128 * 1024) + .spawn(|| { + let mut ty = Type::I32; + for _ in 0..50_000 { + ty = Type::ptr_to(ty); + } + let mut mb = ModuleBuilder::new("x86_64-whale-linux", DataLayout::default_64bit_le()); + let mut f = mb.begin_function("bounded_type", vec![], Type::I32); + assert!(matches!( + f.try_const_int(ty, 1), + Err(BuilderError::ResourceLimit(LimitError { resource: Resource::TypeDepth, .. })) + )); + let value = f.try_const_i32(9).unwrap(); + assert_eq!(value, ValueId(0), "rejected type cannot consume a value identity"); + f.ret(Some(value)); + f.finish(); + verify_module(&mb.finish()).unwrap(); + }) + .unwrap() + .join() + .unwrap(); +} + +#[cfg(whale_wave_ir)] +#[test] +fn checked_function_admission_reserves_all_parameter_storage_before_publication() { + let mut mb = ModuleBuilder::with_limits( + "x86_64-whale-linux", + DataLayout::default_64bit_le(), + IrLimits { max_nodes: 10, ..IrLimits::default() }, + ) + .unwrap(); + let signature = FunctionSignature::whale(vec![Type::I32; 5], Type::Void); + let id = mb.declare_function("f", signature, Linkage::Internal, None).unwrap(); + assert!(matches!( + mb.begin_declared_function(id, vec![String::new(); 5]), + Err(CallError::ResourceLimit(LimitError { resource: Resource::Nodes, .. })) + )); + let module = mb.finish(); + assert!(module.functions.is_empty()); + assert_eq!(module.declarations.len(), 1); +} diff --git a/ir/tests/fixtures/README.md b/ir/tests/fixtures/README.md index 6532149..78f4549 100644 --- a/ir/tests/fixtures/README.md +++ b/ir/tests/fixtures/README.md @@ -11,8 +11,8 @@ fixtures remain here; the old Wave source examples have been removed. They exercise control flow, scoped IDs, calls and numeric conversions. `text_parser.rs` verifies these outputs and requires canonical print-parse-print -equality, upgrading the header to format 8. These tests run the Rust IR module -and do not require a Wave compiler. +equality, upgrading the header to format 8. Reference Cargo tests do not require a Wave compiler. Set `WHALE_WAVE_IR_DIR` +to a matching pinned archive to execute the Wave parser, printer and verifier. Legacy AST JSON formats 2/3/4 remain readable; canonical AST JSON is format 5. Canonical typed text IR is format 8 (the reader also accepts 3/4/5/6/7). Readers reject @@ -30,9 +30,8 @@ updated loop-carried phis; `@f7` with `u32 3` returns `i32 22` in 32 steps. The interpreter regression suite supplies independent expected boundary values for all twelve integer types (signed/unsigned widths 1, 8, 16, 32, 64, 128). It checks wrapping add/sub/mul against both the runtime and the separate -ConstExpr evaluator. ConstExpr currently exposes only add/sub/mul and -comparisons; division/remainder/shifts remain runtime instructions, with -explicit edge vectors ready for any future constant-evaluation extension. +ConstExpr evaluator. ConstExpr also covers bitwise, division/remainder, shifts and lazy logical +operators, preserving the shared width and trap rules. The preserved Wave fixtures use memory and are parser/verifier fixtures; `wave-control-v3.wir` @f0 now executes through tracked integer memory; its main function still rejects calls, and the cast fixture still rejects float execution. diff --git a/ir/tests/fixtures/wave_typed_hir_scalar.json b/ir/tests/fixtures/wave_typed_hir_scalar.json new file mode 100644 index 0000000..971098d --- /dev/null +++ b/ir/tests/fixtures/wave_typed_hir_scalar.json @@ -0,0 +1,189 @@ +{ + "wave_revision": "e0952ed65d07e14c6ed0aa64f3c9a5532dd7533b", + "functions": [ + { + "name": "hir_scalar", + "parameters": [ + { + "name": "x", + "ty": { + "Integer": { + "bits": 32, + "signed": true + } + } + }, + { + "name": "n", + "ty": { + "Integer": { + "bits": 32, + "signed": true + } + } + }, + { + "name": "flag", + "ty": "Bool" + } + ], + "return_type": { + "Integer": { + "bits": 32, + "signed": true + } + }, + "body": [ + { + "Variable": { + "name": "acc", + "ty": { + "Integer": { + "bits": 32, + "signed": true + } + }, + "init": { + "id": 0, + "resolved_type": { + "Integer": { + "bits": 32, + "signed": true + } + }, + "kind": { + "Local": "x" + } + } + } + }, + { + "While": { + "condition": { + "id": 1, + "resolved_type": "Bool", + "kind": { + "Binary": { + "left": { + "id": 2, + "resolved_type": { + "Integer": { + "bits": 32, + "signed": true + } + }, + "kind": { + "Local": "acc" + } + }, + "operator": "Less", + "right": { + "id": 3, + "resolved_type": { + "Integer": { + "bits": 32, + "signed": true + } + }, + "kind": { + "Local": "n" + } + } + } + } + }, + "body": [ + { + "Assign": { + "name": "acc", + "value": { + "id": 4, + "resolved_type": { + "Integer": { + "bits": 32, + "signed": true + } + }, + "kind": { + "Binary": { + "left": { + "id": 5, + "resolved_type": { + "Integer": { + "bits": 32, + "signed": true + } + }, + "kind": { + "Local": "acc" + } + }, + "operator": "Add", + "right": { + "id": 6, + "resolved_type": { + "Integer": { + "bits": 32, + "signed": true + } + }, + "kind": { + "Integer": "1" + } + } + } + } + } + } + } + ] + } + }, + { + "If": { + "condition": { + "id": 7, + "resolved_type": "Bool", + "kind": { + "Local": "flag" + } + }, + "body": [ + { + "Return": { + "id": 8, + "resolved_type": { + "Integer": { + "bits": 32, + "signed": true + } + }, + "kind": { + "Local": "acc" + } + } + } + ], + "else_body": [ + { + "Return": { + "id": 9, + "resolved_type": { + "Integer": { + "bits": 32, + "signed": true + } + }, + "kind": { + "Local": "x" + } + } + } + ] + } + } + ], + "is_async": false + } + ] +} diff --git a/ir/tests/frontend_error_order.rs b/ir/tests/frontend_error_order.rs new file mode 100644 index 0000000..167bf44 --- /dev/null +++ b/ir/tests/frontend_error_order.rs @@ -0,0 +1,141 @@ +#![cfg(feature = "socket")] +use ir::lower_ast::{frontend as a, lower_o0, LowerError}; + +use ir::{CallingConvention, ConstEvalError, DataLayout, Linkage}; + +fn integer(value: &str) -> a::Expr { + a::Expr::Lit(a::Lit::Int { bits: 32, signed: true, value: value.into() }) +} + +fn ty() -> a::TypeRef { + a::TypeRef::Int { bits: 32, signed: true } +} + +fn zero_division() -> a::Expr { + a::Expr::Binary { + left: Box::new(integer("1")), + op: a::BinOpRef::Div, + right: Box::new(integer("0")), + } +} + +fn program(body: Vec) -> a::Program { + a::Program { + declarations: vec![], + globals: vec![], + functions: vec![a::Function { + name: "main".into(), + convention: CallingConvention::Whale, + linkage: Linkage::Internal, + link_name: None, + parameters: vec![], + return_type: a::TypeRef::Void, + body, + }], + } +} + +fn error(p: &a::Program) -> LowerError { + lower_o0(p, "x86_64-whale-linux", DataLayout::default_64bit_le()).unwrap_err() +} + +fn assert_division(error: LowerError) { + assert!( + matches!( + error.root_cause(), + LowerError::ConstantEvaluation(ConstEvalError::DivisionByZero) + ), + "{error:?}" + ); +} + +#[test] +fn global_constant_arithmetic_precedes_later_declarations_and_its_type_comparison() { + for declared in [ty(), a::TypeRef::Bool] { + let mut p = program(vec![a::Stmt::ExprStmt(a::Expr::Var("missing".into()))]); + p.globals.push(a::GlobalConst { + name: "first".into(), + ty: declared, + init: zero_division(), + }); + p.globals.push(a::GlobalConst { + name: "later".into(), + ty: ty(), + init: a::Expr::Var("absent".into()), + }); + assert_division(error(&p)); + } + let mut p = program(vec![]); + p.globals = vec![ + a::GlobalConst { name: "same".into(), ty: ty(), init: zero_division() }, + a::GlobalConst { name: "same".into(), ty: ty(), init: integer("0") }, + ]; + assert_division(error(&p)); +} + +#[test] +fn local_constant_arithmetic_precedes_later_statements_and_its_type_comparison() { + for declared in [ty(), a::TypeRef::Bool] { + let p = program(vec![ + a::Stmt::ConstDecl { name: "first".into(), ty: declared, init: zero_division() }, + a::Stmt::ExprStmt(a::Expr::Var("missing".into())), + ]); + assert_division(error(&p)); + } +} + +#[test] +fn complete_expression_binding_validation_precedes_its_arithmetic() { + let expr = a::Expr::Binary { + left: Box::new(zero_division()), + op: a::BinOpRef::Add, + right: Box::new(a::Expr::Var("inside".into())), + }; + let p = program(vec![a::Stmt::ConstDecl { name: "first".into(), ty: ty(), init: expr }]); + let e = error(&p); + assert!( + matches!(e.root_cause(), LowerError::UnknownVariable(name) if name == "inside"), + "{e:?}" + ); +} + +#[test] +fn lazy_constant_evaluation_does_not_execute_a_skipped_division() { + let comparison = a::Expr::Cmp { + left: Box::new(zero_division()), + op: a::CmpOpRef::Eq, + right: Box::new(integer("0")), + }; + let expr = a::Expr::Binary { + left: Box::new(a::Expr::Lit(a::Lit::Bool(false))), + op: a::BinOpRef::LogicalAnd, + right: Box::new(comparison), + }; + let p = program(vec![ + a::Stmt::ConstDecl { name: "first".into(), ty: a::TypeRef::Bool, init: expr }, + a::Stmt::ExprStmt(a::Expr::Var("later".into())), + ]); + let e = error(&p); + assert!( + matches!(e.root_cause(), LowerError::UnknownVariable(name) if name == "later"), + "{e:?}" + ); +} + +#[test] +fn earlier_constant_arithmetic_retains_the_innermost_original_identity() { + let expr = a::Expr::Located { + annotation: ir::SourceAnnotation { id: 71, source: None }, + expression: Box::new(a::Expr::Located { + annotation: ir::SourceAnnotation { id: 83, source: None }, + expression: Box::new(zero_division()), + }), + }; + let p = program(vec![ + a::Stmt::ConstDecl { name: "first".into(), ty: ty(), init: expr }, + a::Stmt::ExprStmt(a::Expr::Var("later".into())), + ]); + let e = error(&p); + assert_eq!(e.annotation().map(|a| a.id), Some(83), "{e:?}"); + assert_division(e); +} diff --git a/ir/tests/frontend_storage.rs b/ir/tests/frontend_storage.rs index f88f689..e9f2424 100644 --- a/ir/tests/frontend_storage.rs +++ b/ir/tests/frontend_storage.rs @@ -398,8 +398,29 @@ fn aggregate_storage_expansion_and_new_ast_forms_are_bounded_and_versioned() { let json = interchange::encode(p.clone()).unwrap(); assert!(interchange::decode(&json.replace("\"format_version\": 5", "\"format_version\": 4")) .is_err()); + // Wave restores scope bindings in place, so empty branches no longer copy + // the wide aggregate environment. The retained Rust oracle bounds those + // copies; the production Wave path has no corresponding amplification. + #[cfg(whale_wave_ir)] + assert!(lower_o0(&p, "x86_64-whale-linux", DataLayout::default_64bit_le()).is_ok()); + #[cfg(not(whale_wave_ir))] assert!(matches!( lower_o0(&p, "x86_64-whale-linux", DataLayout::default_64bit_le()), Err(LowerError::ResourceLimit(AstLimitError::Expansion)) )); + + // Actual emitted pointer annotations repeat the wide pointee tree. Bound + // that storage expansion in both implementations before publishing output. + let mut expanded = p; + expanded.functions[0].body.truncate(1); + for _ in 0..3000 { + expanded.functions[0].body.push(a::Stmt::ExprStmt(a::Expr::PointerOffset { + base: Box::new(address(var("s"))), + index: Box::new(n(64, 0)), + })); + } + assert!(matches!( + lower_o0(&expanded, "x86_64-whale-linux", DataLayout::default_64bit_le()), + Err(LowerError::ResourceLimit(AstLimitError::Expansion)) + )); } diff --git a/ir/tests/source_metadata.rs b/ir/tests/source_metadata.rs index f5b9537..1f440e7 100644 --- a/ir/tests/source_metadata.rs +++ b/ir/tests/source_metadata.rs @@ -491,6 +491,11 @@ mod frontend { lower_budget(&p, 0), Err(LowerError::ResourceLimit(AstLimitError::SourceWork)) )); + let minimum = (1..256).find(|&work| lower_budget(&p, work).is_ok()).unwrap(); + assert!(matches!( + lower_budget(&p, minimum - 1), + Err(LowerError::ResourceLimit(AstLimitError::SourceWork)) + )); for id in 1..100 { let mut f = p.functions[0].clone(); f.name = format!("f{id}"); @@ -499,27 +504,27 @@ mod frontend { } // Only the two annotated globals consume source work. Hoisted slots in // the ninety-nine unannotated functions never scan their global maps. - let m = lower_budget(&p, 12).unwrap(); + let m = lower_budget(&p, minimum).unwrap(); verify_module(&m).unwrap(); assert_eq!(m.sources.mappings.len(), 2); } #[test] - fn final_hoisted_alloca_mapping_adjustment_is_charged_before_returning_ir() { + fn final_hoisted_alloca_mappings_are_bounded_and_use_final_physical_indices() { let declaration = |name: &str| ast::Stmt::VarDecl { name: name.into(), ty: i32_type(), init: Some(lit(1)), }; let base = program(vec![stmt(10, declaration("a")), ast::Stmt::Return(Some(lit(1)))]); - let minimum = (0..100).find(|&work| lower_budget(&base, work).is_ok()).unwrap(); let mut late = base; late.functions[0].body.insert(1, declaration("b")); + let minimum = (1..256).find(|&work| lower_budget(&late, work).is_ok()).unwrap(); assert!(matches!( - lower_budget(&late, minimum), + lower_budget(&late, minimum - 1), Err(LowerError::ResourceLimit(AstLimitError::SourceWork)) )); - let m = lower_budget(&late, minimum + 3).unwrap(); + let m = lower_budget(&late, minimum).unwrap(); verify_module(&m).unwrap(); assert_eq!(m.sources.original(target(3)).unwrap().id, 10); assert_eq!(m.sources.original(target(2)).unwrap().id, 10); diff --git a/ir/tests/verification_scaling.rs b/ir/tests/verification_scaling.rs index ad2b69d..183d2aa 100644 --- a/ir/tests/verification_scaling.rs +++ b/ir/tests/verification_scaling.rs @@ -135,7 +135,11 @@ fn lookup_and_dominance_work_grow_linearly_without_reordering_ir() { let s = verify_module_with_stats(&m, IrLimits::default()).unwrap(); assert_eq!(print_module(&m), before); assert!(s.value_type_lookups <= 5 * size as usize, "{s:?}"); - assert!(s.analysis_work <= 20 * size as usize, "{s:?}"); + // Wave charges identity/type tables, semantic operand type graphs, + // SSA transport validation and predecessor hash probes as well as + // dominance. Every traversal remains linear in this fixture. + let work_per_node = if IR_WAVE_ENABLED { 50 } else { 20 }; + assert!(s.analysis_work <= work_per_node * size as usize, "{s:?}"); stats.push(s); } assert!(stats[2].analysis_work <= 3 * stats[1].analysis_work); diff --git a/ir/tests/wave_ast_lowering.rs b/ir/tests/wave_ast_lowering.rs new file mode 100644 index 0000000..5fd6aaf --- /dev/null +++ b/ir/tests/wave_ast_lowering.rs @@ -0,0 +1,448 @@ +// SPDX-License-Identifier: MPL-2.0 +#![cfg(feature = "socket")] +//! Independent frontend fixtures exercise the complete production lowerer against +//! its explicit conformance reference, including identities and source ordering. +use ir::lower_ast::{ + frontend as a, lower_o0, lower_o0_reference, lower_o0_reference_with_limits, + lower_o0_with_limits, AstLimits, +}; + +use ir::*; + +const TARGET: &str = "x86_64-whale-linux"; + +fn ty() -> a::TypeRef { + a::TypeRef::Int { bits: 32, signed: true } +} + +fn lit(value: i32) -> a::Expr { + a::Expr::Lit(a::Lit::Int { bits: 32, signed: true, value: value.to_string() }) +} + +fn var(name: &str) -> a::Expr { + a::Expr::Var(name.into()) +} + +fn bin(left: a::Expr, op: a::BinOpRef, right: a::Expr) -> a::Expr { + a::Expr::Binary { left: Box::new(left), op, right: Box::new(right) } +} + +fn cmp(left: a::Expr, op: a::CmpOpRef, right: a::Expr) -> a::Expr { + a::Expr::Cmp { left: Box::new(left), op, right: Box::new(right) } +} + +fn assign(name: &str, value: a::Expr) -> a::Stmt { + a::Stmt::Assign { name: name.into(), value } +} + +fn func(name: &str, parameters: Vec, body: Vec) -> a::Function { + a::Function { + name: name.into(), + parameters, + return_type: ty(), + body, + convention: CallingConvention::Whale, + linkage: Linkage::Internal, + link_name: None, + } +} + +fn program(body: Vec) -> a::Program { + a::Program { + declarations: vec![], + globals: vec![], + functions: vec![func("entry", vec![], body)], + } +} + +fn compare(p: &a::Program) -> Module { + let actual = lower_o0(p, TARGET, DataLayout::default_64bit_le()).unwrap(); + let expected = lower_o0_reference(p, TARGET, DataLayout::default_64bit_le()).unwrap(); + assert_eq!(actual, expected, "production/reference full typed module differs"); + verify_module(&actual).unwrap(); + let text = print_module(&actual); + assert_eq!(text, print_module(&parse_module(&text).unwrap())); + actual +} + +fn compare_error(p: &a::Program, limits: AstLimits) { + let a = lower_o0_with_limits(p, TARGET, DataLayout::default_64bit_le(), limits).unwrap_err(); + let b = lower_o0_reference_with_limits(p, TARGET, DataLayout::default_64bit_le(), limits) + .unwrap_err(); + assert_eq!(format!("{a:?}"), format!("{b:?}")); + assert_eq!(a.to_string(), b.to_string()); +} + +fn located(id: u64, e: a::Expr) -> a::Expr { + a::Expr::Located { annotation: annotation(id), expression: Box::new(e) } +} + +fn statement(id: u64, s: a::Stmt) -> a::Stmt { + a::Stmt::Located { annotation: annotation(id), statement: Box::new(s) } +} + +fn annotation(id: u64) -> SourceAnnotation { + SourceAnnotation { + id, + source: Some(FrontendSource { + file: if id % 2 == 0 { "a.wave" } else { "b.wave" }.into(), + line: 1, + column: 1, + end_line: 1, + end_column: 4, + }), + } +} + +#[test] +fn generated_integer_control_flow_matches_reference_and_independent_execution() { + for seed in 0i32..128 { + let offset = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + let op = if seed & 1 == 0 { a::BinOpRef::BitXor } else { a::BinOpRef::Add }; + let body = vec![ + a::Stmt::ConstDecl { name: "bias".into(), ty: ty(), init: lit(offset) }, + a::Stmt::VarDecl { + name: "x".into(), + ty: ty(), + init: Some(bin(var("p"), op, var("bias"))), + }, + a::Stmt::If { + cond: cmp(var("x"), a::CmpOpRef::Lt, lit(0)), + then_body: vec![assign("x", bin(var("x"), a::BinOpRef::Add, lit(3)))], + else_body: vec![assign("x", bin(var("x"), a::BinOpRef::Sub, lit(5)))], + }, + a::Stmt::VarDecl { name: "i".into(), ty: ty(), init: Some(lit(0)) }, + a::Stmt::While { + cond: cmp(var("i"), a::CmpOpRef::Lt, lit(5)), + body: vec![ + assign("i", bin(var("i"), a::BinOpRef::Add, lit(1))), + a::Stmt::If { + cond: cmp(var("i"), a::CmpOpRef::Eq, lit(1)), + then_body: vec![a::Stmt::Continue], + else_body: vec![], + }, + a::Stmt::If { + cond: cmp(var("i"), a::CmpOpRef::Eq, lit(4)), + then_body: vec![a::Stmt::Break], + else_body: vec![], + }, + assign("x", bin(var("x"), a::BinOpRef::Add, lit(1))), + ], + }, + a::Stmt::Return(Some(a::Expr::Neg(Box::new(a::Expr::BitNot(Box::new(var("x"))))))), + ]; + let p = a::Program { + declarations: vec![], + globals: vec![], + functions: vec![func("entry", vec![a::Parameter { name: "p".into(), ty: ty() }], body)], + }; + let m = compare(&p); + for input in [i32::MIN, -31, 0, 7, i32::MAX] { + let x = if seed & 1 == 0 { input ^ offset } else { input.wrapping_add(offset) }; + let x = if x < 0 { x.wrapping_add(3) } else { x.wrapping_sub(5) }; + let expected = (!x.wrapping_add(2)).wrapping_neg(); + assert_eq!( + interpret(&m, FunctionId(0), &[ConstValue::I(input.into())]).unwrap().value, + Some(ConstValue::I(expected.into())) + ); + } + } +} + +#[test] +fn globals_local_constants_calls_and_shared_identity_order_match() { + let signature = a::SignatureRef { + params: vec![ty()], + ret: ty(), + convention: CallingConvention::Whale, + variadic: false, + }; + let helper = func( + "helper", + vec![a::Parameter { name: "p".into(), ty: ty() }], + vec![a::Stmt::Return(Some(bin(var("p"), a::BinOpRef::Add, var("global"))))], + ); + let pointer = a::TypeRef::FnPtr(Box::new(signature.clone())); + let mut p = program(vec![ + a::Stmt::ConstDecl { + name: "local".into(), + ty: ty(), + init: bin(var("global"), a::BinOpRef::Mul, lit(2)), + }, + a::Stmt::VarDecl { + name: "f".into(), + ty: pointer, + init: Some(a::Expr::FunctionRef("helper".into())), + }, + a::Stmt::Return(Some(a::Expr::Call { + callee: a::CalleeRef::Indirect(Box::new(var("f"))), + args: vec![var("local")], + })), + ]); + p.globals = vec![a::GlobalConst { + name: "global".into(), + ty: ty(), + init: bin(lit(11), a::BinOpRef::Add, lit(3)), + }]; + p.functions.push(helper); + let m = compare(&p); + assert_eq!(interpret(&m, FunctionId(0), &[]).unwrap().value, Some(ConstValue::I(42))); +} + +#[test] +fn aggregates_pointer_access_and_volatile_storage_match() { + let array = a::TypeRef::Array { elem: Box::new(ty()), len: 3 }; + let index = |i| a::Expr::Index { base: Box::new(var("array")), index: Box::new(lit(i)) }; + let ptr = || a::Expr::AddressOf(Box::new(index(1))); + let body = vec![ + a::Stmt::VarDecl { + name: "array".into(), + ty: array.clone(), + init: Some(a::Expr::Array { ty: array, elements: vec![lit(1), lit(2), lit(3)] }), + }, + a::Stmt::VolatileStore { pointer: ptr(), value: lit(42) }, + a::Stmt::Return(Some(a::Expr::VolatileLoad(Box::new(ptr())))), + ]; + let m = compare(&program(body)); + assert_eq!(interpret(&m, FunctionId(0), &[]).unwrap().value, Some(ConstValue::I(42))); + let structure = a::TypeRef::Struct { + fields: vec![ + a::StructField { name: "left".into(), ty: ty() }, + a::StructField { name: "right".into(), ty: ty() }, + ], + }; + let p = program(vec![ + a::Stmt::VarDecl { + name: "s".into(), + ty: structure.clone(), + init: Some(a::Expr::Struct { + ty: structure.clone(), + fields: vec![ + a::FieldInit { name: "right".into(), value: lit(40) }, + a::FieldInit { name: "left".into(), value: lit(2) }, + ], + }), + }, + a::Stmt::Return(Some(a::Expr::Field { + base: Box::new(var("s")), + layout: structure, + name: "right".into(), + })), + ]); + let m = compare(&p); + assert_eq!(interpret(&m, FunctionId(0), &[]).unwrap().value, Some(ConstValue::I(40))); +} + +#[test] +fn nested_source_annotations_preserve_original_order_mappings_and_hoisting() { + let mut p = program(vec![ + statement( + 1, + a::Stmt::ConstDecl { + name: "k".into(), + ty: ty(), + init: located( + 2, + bin(located(3, lit(4)), a::BinOpRef::Add, located(4, var("global"))), + ), + }, + ), + statement( + 5, + a::Stmt::If { + cond: located(6, cmp(var("k"), a::CmpOpRef::Gt, lit(0))), + then_body: vec![ + statement( + 7, + a::Stmt::VarDecl { + name: "x".into(), + ty: ty(), + init: Some(located(8, var("k"))), + }, + ), + statement(9, a::Stmt::Return(Some(located(10, var("x"))))), + ], + else_body: vec![statement(11, a::Stmt::Return(Some(located(12, lit(0)))))], + }, + ), + ]); + p.globals.push(a::GlobalConst { + name: "global".into(), + ty: ty(), + init: located(13, bin(located(14, lit(2)), a::BinOpRef::Add, located(15, lit(3)))), + }); + let m = compare(&p); + assert!(!m.sources.mappings.is_empty()); + m.sources.validate(&m).unwrap(); + assert_eq!(interpret(&m, FunctionId(0), &[]).unwrap().value, Some(ConstValue::I(9))); +} + +#[test] +fn invalid_frontend_operations_and_attributed_failures_match() { + for body in [ + vec![a::Stmt::Break], + vec![a::Stmt::Continue], + vec![a::Stmt::ExprStmt(var("missing"))], + vec![a::Stmt::ConstDecl { name: "x".into(), ty: ty(), init: lit(1) }, assign("x", lit(2))], + vec![a::Stmt::Return(Some(a::Expr::Lit(a::Lit::Bool(true))))], + vec![a::Stmt::ConstDecl { + name: "x".into(), + ty: ty(), + init: bin(lit(1), a::BinOpRef::Div, lit(0)), + }], + ] { + compare_error(&program(body), AstLimits::default()); + } + let p = program(vec![statement(101, a::Stmt::Return(Some(located(102, var("missing")))))]); + compare_error(&p, AstLimits::default()); + let p = program(vec![statement( + 103, + a::Stmt::ConstDecl { + name: "bad".into(), + ty: ty(), + init: located(104, bin(located(105, lit(1)), a::BinOpRef::Div, located(106, lit(0)))), + }, + )]); + compare_error(&p, AstLimits::default()); + let p = program(vec![a::Stmt::VarDecl { + name: "bad".into(), + ty: a::TypeRef::Int { bits: 7, signed: true }, + init: None, + }]); + compare_error(&p, AstLimits::default()); + let mut p = program(vec![]); + p.functions[0].parameters = vec![ + a::Parameter { name: "same".into(), ty: ty() }, + a::Parameter { name: "same".into(), ty: ty() }, + ]; + compare_error(&p, AstLimits::default()); +} + +#[test] +fn resource_boundaries_reject_before_publishing_partial_modules() { + let plain = program(vec![a::Stmt::Return(Some(lit(42)))]); + for limits in [ + AstLimits { max_nodes: 1, ..AstLimits::default() }, + AstLimits { max_string_bytes: 1, ..AstLimits::default() }, + AstLimits { max_depth: 0, ..AstLimits::default() }, + ] { + compare_error(&plain, limits) + } + let minimal = AstLimits { max_source_work: 0, ..AstLimits::default() }; + assert!(lower_o0_with_limits(&plain, TARGET, DataLayout::default_64bit_le(), minimal).is_ok()); + let located = program(vec![statement(1, a::Stmt::Return(Some(lit(42))))]); + assert!(matches!( + lower_o0_with_limits(&located, TARGET, DataLayout::default_64bit_le(), minimal), + Err(ir::lower_ast::LowerError::ResourceLimit(ir::lower_ast::AstLimitError::SourceWork)) + )); +} + +#[test] +fn declaration_call_literal_and_aggregate_diagnostics_match_complete_reference() { + let mut cases = Vec::new(); + let signature = a::SignatureRef { + params: vec![ty()], + ret: ty(), + convention: CallingConvention::Whale, + variadic: false, + }; + let declaration = a::FunctionDeclaration { + name: "external".into(), + signature: signature.clone(), + linkage: Linkage::External, + link_name: Some("external".into()), + }; + cases.push(program(vec![a::Stmt::ExprStmt(a::Expr::Call { + callee: a::CalleeRef::Direct("missing".into()), + args: vec![], + })])); + cases.push(program(vec![a::Stmt::ExprStmt(a::Expr::FunctionRef("missing".into()))])); + cases.push(program(vec![a::Stmt::ExprStmt(a::Expr::Call { + callee: a::CalleeRef::Indirect(Box::new(lit(0))), + args: vec![], + })])); + for args in [vec![], vec![a::Expr::Lit(a::Lit::Bool(true))]] { + let mut p = program(vec![a::Stmt::ExprStmt(a::Expr::Call { + callee: a::CalleeRef::Direct("external".into()), + args, + })]); + p.declarations.push(declaration.clone()); + cases.push(p); + } + let mut p = program(vec![]); + let mut d = declaration.clone(); + d.linkage = Linkage::Internal; + d.link_name = None; + p.declarations.push(d); + cases.push(p); + let mut p = program(vec![]); + let mut d = declaration.clone(); + d.link_name = None; + p.declarations.push(d); + cases.push(p); + let mut p = program(vec![]); + let mut d = declaration.clone(); + d.link_name = Some("bad\0symbol".into()); + p.declarations.push(d); + cases.push(p); + let mut p = program(vec![]); + let mut other = declaration.clone(); + other.name = "other".into(); + p.declarations = vec![declaration.clone(), other]; + cases.push(p); + let mut p = program(vec![]); + let mut other = declaration.clone(); + other.signature.ret = a::TypeRef::Bool; + p.declarations = vec![declaration, other]; + cases.push(p); + let structure = + a::TypeRef::Struct { fields: vec![a::StructField { name: "field".into(), ty: ty() }] }; + for fields in [vec![], vec![a::FieldInit { name: "unknown".into(), value: lit(1) }]] { + cases.push(program(vec![a::Stmt::ExprStmt(a::Expr::Struct { + ty: structure.clone(), + fields, + })])); + } + cases.push(program(vec![ + a::Stmt::VarDecl { name: "s".into(), ty: structure.clone(), init: None }, + a::Stmt::ExprStmt(a::Expr::Field { + base: Box::new(var("s")), + layout: structure, + name: "absent".into(), + }), + ])); + for (bits, signed, value) in [ + (8, true, "128"), + (8, false, "256"), + (32, true, "+1"), + (32, false, "-1"), + (128, true, "170141183460469231731687303715884105728"), + (128, false, "340282366920938463463374607431768211456"), + ] { + cases.push(program(vec![a::Stmt::ExprStmt(a::Expr::Lit(a::Lit::Int { + bits, + signed, + value: value.into(), + }))])); + } + for value in ["1.0", "0x123", "0xgggggggg"] { + cases.push(program(vec![a::Stmt::ExprStmt(a::Expr::Lit(a::Lit::Float { + bits: 32, + value: value.into(), + }))])); + } + cases.push(program(vec![a::Stmt::ConstDecl { + name: "bad".into(), + ty: a::TypeRef::Bool, + init: bin( + a::Expr::Lit(a::Lit::Bool(true)), + a::BinOpRef::BitAnd, + a::Expr::Lit(a::Lit::Bool(false)), + ), + }])); + for (ordinal, p) in cases.iter().enumerate() { + let actual = lower_o0(p, TARGET, DataLayout::default_64bit_le()).unwrap_err(); + let expected = lower_o0_reference(p, TARGET, DataLayout::default_64bit_le()).unwrap_err(); + assert_eq!(format!("{actual:?}"), format!("{expected:?}"), "diagnostic case {ordinal}"); + } +} diff --git a/ir/tests/wave_typed_hir.rs b/ir/tests/wave_typed_hir.rs new file mode 100644 index 0000000..01941e3 --- /dev/null +++ b/ir/tests/wave_typed_hir.rs @@ -0,0 +1,282 @@ +#![cfg(all(whale_wave_ir, feature = "socket"))] +// SPDX-License-Identifier: MPL-2.0 +use ir::lower_ast::{wave_hir as h, AstLimits}; + +use ir::*; + +fn fixture() -> h::Program { + serde_json::from_str(include_str!("fixtures/wave_typed_hir_scalar.json")).unwrap() +} + +fn int() -> h::ResolvedType { + h::ResolvedType::Integer { bits: 32, signed: true } +} + +fn literal(id: u64, value: &str) -> h::Expression { + h::Expression { id, resolved_type: int(), kind: h::ExpressionKind::Integer(value.into()) } +} + +fn program(expression: h::Expression) -> h::Program { + h::Program { + wave_revision: h::WAVE_HIR_REVISION.into(), + functions: vec![h::Function { + name: "test".into(), + parameters: vec![], + return_type: expression.resolved_type.clone(), + body: vec![h::Statement::Return(Some(expression))], + is_async: false, + }], + } +} + +#[test] +fn actual_pinned_typed_hir_fixture_lowers_verifies_executes_and_preserves_identity() { + let program = fixture(); + let module = h::lower( + &program, + "x86_64-whale-linux", + DataLayout::default_64bit_le(), + AstLimits::default(), + ) + .unwrap(); + verify_module(&module).unwrap(); + let function = module.functions.iter().find(|f| f.name == "hir_scalar").unwrap().id; + for (x, n, flag, expected) in [(2, 5, true, 5), (2, 5, false, 2), (10, 5, true, 10)] { + let result = interpret( + &module, + function, + &[ConstValue::I(x), ConstValue::I(n), ConstValue::Bool(flag)], + ) + .unwrap(); + assert_eq!(result.value, Some(ConstValue::I(expected))); + } + fn expression(expr: &h::Expression, ids: &mut Vec) { + ids.push(expr.id); + if let h::ExpressionKind::Binary { left, right, .. } = &expr.kind { + expression(left, ids); + expression(right, ids); + } + } + + fn statements(values: &[h::Statement], ids: &mut Vec) { + for statement in values { + match statement { + h::Statement::Variable { init: Some(value), .. } + | h::Statement::Assign { value, .. } + | h::Statement::Return(Some(value)) + | h::Statement::Expression(value) => expression(value, ids), + h::Statement::If { condition, body, else_body } => { + expression(condition, ids); + statements(body, ids); + statements(else_body, ids); + }, + h::Statement::While { condition, body } => { + expression(condition, ids); + statements(body, ids); + }, + _ => {}, + } + } + } + let mut expected = vec![]; + statements(&program.functions[0].body, &mut expected); + expected.sort_unstable(); + let mut actual: Vec<_> = module.sources.originals.iter().map(|original| original.id).collect(); + actual.sort_unstable(); + assert_eq!(actual, expected); +} + +#[test] +fn resolved_type_mismatches_unknown_bindings_and_duplicate_ids_fail_transactionally() { + let mut input = program(literal(7, "2")); + let before = serde_json::to_value(&input).unwrap(); + input.functions[0].return_type = h::ResolvedType::Bool; + assert!(matches!( + h::adapt(&input, AstLimits::default()), + Err(h::AdapterError::ResolvedType { .. }) + )); + input = serde_json::from_value(before.clone()).unwrap(); + assert_eq!(serde_json::to_value(&input).unwrap(), before); + input.functions[0].body = vec![h::Statement::Return(Some(h::Expression { + id: 2, + resolved_type: int(), + kind: h::ExpressionKind::Local("absent".into()), + }))]; + assert!(matches!( + h::adapt(&input, AstLimits::default()), + Err(h::AdapterError::UnknownBinding { .. }) + )); + input = program(h::Expression { + id: 7, + resolved_type: int(), + kind: h::ExpressionKind::Binary { + left: Box::new(literal(7, "1")), + operator: h::Operator::Add, + right: Box::new(literal(9, "2")), + }, + }); + assert!(matches!( + h::adapt(&input, AstLimits::default()), + Err(h::AdapterError::DuplicateExpression { id: 7 }) + )); + input = program(literal(1, "2147483648")); + assert!(matches!( + h::adapt(&input, AstLimits::default()), + Err(h::AdapterError::NumericLiteral { .. }) + )); + input = program(literal(1, "1")); + input.wave_revision = "other".into(); + assert!(matches!(h::adapt(&input, AstLimits::default()), Err(h::AdapterError::Revision))); +} + +#[test] +fn calls_aggregates_async_and_inline_assembly_are_explicit_whole_program_errors() { + for kind in [ + h::Unsupported::Call, + h::Unsupported::Aggregate, + h::Unsupported::Async, + h::Unsupported::InlineAssembly, + ] { + let mut input = fixture(); + input.functions[0].body.push(h::Statement::Unsupported(kind)); + let before = serde_json::to_value(&input).unwrap(); + assert!( + matches!(h::adapt(&input,AstLimits::default()),Err(h::AdapterError::Unsupported{category,..}) if category==kind as u64) + ); + assert_eq!(serde_json::to_value(&input).unwrap(), before); + } + let mut input = fixture(); + input.functions[0].is_async = true; + assert!(matches!( + h::adapt(&input, AstLimits::default()), + Err(h::AdapterError::Unsupported { category: 3, .. }) + )); +} + +#[test] +fn all_scalar_operators_use_resolved_facts_and_reference_execution() { + for operator in [ + h::Operator::Add, + h::Operator::Subtract, + h::Operator::Multiply, + h::Operator::Divide, + h::Operator::Remainder, + h::Operator::BitwiseAnd, + h::Operator::BitwiseOr, + h::Operator::BitwiseXor, + h::Operator::ShiftLeft, + h::Operator::ShiftRight, + h::Operator::Equal, + h::Operator::NotEqual, + h::Operator::Less, + h::Operator::LessEqual, + h::Operator::Greater, + h::Operator::GreaterEqual, + ] { + let compare = operator as u64 >= 12; + let input = program(h::Expression { + id: 2, + resolved_type: if compare { h::ResolvedType::Bool } else { int() }, + kind: h::ExpressionKind::Binary { + left: Box::new(literal(0, "7")), + operator, + right: Box::new(literal(1, "2")), + }, + }); + let module = h::lower( + &input, + "x86_64-whale-linux", + DataLayout::default_64bit_le(), + AstLimits::default(), + ) + .unwrap(); + verify_module(&module).unwrap(); + let result = interpret(&module, module.functions[0].id, &[]).unwrap().value.unwrap(); + let expected = match operator { + h::Operator::Add => ConstValue::I(9), + h::Operator::Subtract => ConstValue::I(5), + h::Operator::Multiply => ConstValue::I(14), + h::Operator::Divide => ConstValue::I(3), + h::Operator::Remainder => ConstValue::I(1), + h::Operator::BitwiseAnd => ConstValue::I(2), + h::Operator::BitwiseOr => ConstValue::I(7), + h::Operator::BitwiseXor => ConstValue::I(5), + h::Operator::ShiftLeft => ConstValue::I(28), + h::Operator::ShiftRight => ConstValue::I(1), + h::Operator::Equal => ConstValue::Bool(false), + h::Operator::NotEqual => ConstValue::Bool(true), + h::Operator::Less | h::Operator::LessEqual => ConstValue::Bool(false), + h::Operator::Greater | h::Operator::GreaterEqual => ConstValue::Bool(true), + _ => unreachable!(), + }; + assert_eq!(result, expected, "{operator:?}"); + } + for operator in [h::Operator::LogicalAnd, h::Operator::LogicalOr] { + let input = program(h::Expression { + id: 2, + resolved_type: h::ResolvedType::Bool, + kind: h::ExpressionKind::Binary { + left: Box::new(h::Expression { + id: 0, + resolved_type: h::ResolvedType::Bool, + kind: h::ExpressionKind::Bool(false), + }), + operator, + right: Box::new(h::Expression { + id: 1, + resolved_type: h::ResolvedType::Bool, + kind: h::ExpressionKind::Bool(true), + }), + }, + }); + let module = h::lower( + &input, + "x86_64-whale-linux", + DataLayout::default_64bit_le(), + AstLimits::default(), + ) + .unwrap(); + assert_eq!( + interpret(&module, module.functions[0].id, &[]).unwrap().value, + Some(ConstValue::Bool(matches!(operator, h::Operator::LogicalOr))) + ); + } +} + +#[test] +fn typed_hir_adapter_limits_and_lexical_branch_bindings_are_checked() { + let input = fixture(); + for limits in [ + AstLimits { max_nodes: 1, ..AstLimits::default() }, + AstLimits { max_depth: 1, ..AstLimits::default() }, + AstLimits { max_string_bytes: 1, ..AstLimits::default() }, + AstLimits { max_source_work: 1, ..AstLimits::default() }, + ] { + assert!(matches!(h::adapt(&input, limits), Err(h::AdapterError::Resource))); + } + let mut input = program(h::Expression { + id: 2, + resolved_type: int(), + kind: h::ExpressionKind::Local("branch_local".into()), + }); + input.functions[0].body.insert( + 0, + h::Statement::If { + condition: h::Expression { + id: 0, + resolved_type: h::ResolvedType::Bool, + kind: h::ExpressionKind::Bool(true), + }, + body: vec![h::Statement::Variable { + name: "branch_local".into(), + ty: int(), + init: Some(literal(1, "1")), + }], + else_body: vec![], + }, + ); + assert!(matches!( + h::adapt(&input, AstLimits::default()), + Err(h::AdapterError::UnknownBinding { .. }) + )); +} diff --git a/ir/type_parser.wave b/ir/type_parser.wave new file mode 100644 index 0000000..dfbd270 --- /dev/null +++ b/ir/type_parser.wave @@ -0,0 +1,248 @@ +// SPDX-License-Identifier: MPL-2.0 +// Bounded recursive descent for the complete typed IR type grammar. Postorder +// records preserve exact scalar identity, aggregate order and call convention. +struct IrParsedType { + kind: u64; + value: u64; + count: u64; +} + +struct IrTypeParseResult { + status: u64; // 1 syntax, 2 depth, 3 nodes, 4 work, 5 capacity, 6 transport + reason: u64; // 1 expected token, 2 decimal, 3 range, 4 word, 5 type, 6 convention + at: u64; + expected: u64; + next: u64; + nodes: u64; + work: u64; +} + +struct IrTypeParser { + tokens: ptr; + token_count: u64; + at: u64; + max_depth: u64; + max_nodes: u64; + max_work: u64; + work: u64; + nodes: u64; + emitted: u64; + mode: u64; + scratch: ptr; + capacity: u64; + result: ptr; +} + +// Expected bytes are packed constants so independent Wave object modules do +// not acquire the pinned compiler's globally named string literal symbols. +fun ir_type_word(token: ptr, code: u64) -> bool { + var packed: u64 = 0; + var length: u64 = 0; + if (code == 0) { packed = 1684631414; length = 4; } // void + else if (code == 1) { packed = 1819242338; length = 4; } // bool + else if (code == 2) { packed = 12649; length = 2; } // i1 + else if (code == 3) { packed = 12661; length = 2; } // u1 + else if (code == 4) { packed = 14441; length = 2; } // i8 + else if (code == 5) { packed = 3551593; length = 3; } // i16 + else if (code == 6) { packed = 3289961; length = 3; } // i32 + else if (code == 7) { packed = 3421801; length = 3; } // i64 + else if (code == 8) { packed = 942813545; length = 4; } // i128 + else if (code == 9) { packed = 14453; length = 2; } // u8 + else if (code == 10) { packed = 3551605; length = 3; } // u16 + else if (code == 11) { packed = 3289973; length = 3; } // u32 + else if (code == 12) { packed = 3421813; length = 3; } // u64 + else if (code == 13) { packed = 942813557; length = 4; } // u128 + else if (code == 14) { packed = 3551590; length = 3; } // f16 + else if (code == 15) { packed = 3289958; length = 3; } // f32 + else if (code == 16) { packed = 3421798; length = 3; } // f64 + else if (code == 17) { packed = 7500912; length = 3; } // ptr + else if (code == 18) { packed = 491579797094; length = 5; } // fnptr + else if (code == 19) { packed = 521325933153; length = 5; } // array + else if (code == 20) { packed = 127970521019507; length = 6; } // struct + else if (code == 21) { packed = 435611006324; length = 5; } // tuple + else if (code == 22) { packed = 435610019959; length = 5; } // whale + else if (code == 23) { packed = 57408520157555; length = 6; } // sysv64 + else if (code == 24) { packed = 60; length = 1; } // < + else if (code == 25) { packed = 62; length = 1; } // > + else if (code == 26) { packed = 123; length = 1; } // { + else if (code == 27) { packed = 125; length = 1; } // } + else if (code == 28) { packed = 40; length = 1; } // ( + else if (code == 29) { packed = 41; length = 1; } // ) + else if (code == 30) { packed = 15917; length = 2; } // -> + else if (code == 31) { packed = 44; length = 1; } // , + else { return false; } + if (token.kind == 1 || token.kind == 3 || token.length != length) { return false; } + var i: u64 = 0; + while (i < length) { + if (token.data[i] as u64 != ((packed >> (i * 8)) & 255)) { return false; } + i += 1; + } + return true; +} + +fun ir_type_fail(parser: ptr, status: u64, reason: u64, at: u64, + expected: u64) -> bool { + parser.result.status = status; parser.result.reason = reason; + parser.result.at = at; parser.result.expected = expected; + return false; +} + +fun ir_type_charge(parser: ptr, amount: u64) -> bool { + if (amount > parser.max_work - parser.work) { + return ir_type_fail(parser, 4, 0, parser.at, 0); + } + parser.work += amount; + return true; +} + +fun ir_type_read(parser: ptr) -> bool { + if (!ir_type_charge(parser, 1)) { return false; } + if (parser.at >= parser.token_count) { + return ir_type_fail(parser, 6, 0, parser.at, 0); + } + var token: ptr = &parser.tokens[parser.at]; + if (token.kind > 3 || !ir_span_valid(token.data, token.length, 1)) { + return ir_type_fail(parser, 6, 0, parser.at, 0); + } + return true; +} + +fun ir_type_eat(parser: ptr, code: u64) -> bool { + if (!ir_type_read(parser)) { return false; } + if (!ir_type_word(&parser.tokens[parser.at], code)) { return false; } + parser.at += 1; + return true; +} + +fun ir_type_expect(parser: ptr, code: u64) -> bool { + if (ir_type_eat(parser, code)) { return true; } + if (parser.result.status != 0) { return false; } + return ir_type_fail(parser, 1, 1, parser.at, code); +} + +fun ir_type_number(parser: ptr, output: ptr) -> bool { + if (!ir_type_read(parser)) { return false; } + var token: ptr = &parser.tokens[parser.at]; + if (token.kind != 0 || token.length == 0) { + return ir_type_fail(parser, 1, 2, parser.at, 0); + } + var n: u64 = 0; + var i: u64 = 0; + var digit: u64 = 0; + var octet: u64 = 0; + var overflow: bool = false; + while (i < token.length) { + if (!ir_type_charge(parser, 1)) { return false; } + octet = token.data[i] as u64; + if (octet < 48 || octet > 57) { return ir_type_fail(parser, 1, 2, parser.at, 0); } + digit = octet - 48; + if (n > (18446744073709551615 - digit) / 10) { overflow = true; } + if (!overflow) { n = n * 10 + digit; } + i += 1; + } + if (overflow) { return ir_type_fail(parser, 1, 3, parser.at, 0); } + output[0] = n; parser.at += 1; + return true; +} + +fun ir_type_emit(parser: ptr, kind: u64, value: u64, count: u64) -> bool { + // Reserve both scratch emission and the final publication in both passes. + if (!ir_type_charge(parser, 2)) { return false; } + if (parser.mode == 1) { + if (parser.emitted >= parser.capacity) { + return ir_type_fail(parser, 5, 0, parser.at, 0); + } + parser.scratch[parser.emitted].kind = kind; + parser.scratch[parser.emitted].value = value; + parser.scratch[parser.emitted].count = count; + } + parser.emitted += 1; + return true; +} + +fun ir_type_parse_node(parser: ptr, depth: u64) -> bool { + if (depth > parser.max_depth) { return ir_type_fail(parser, 2, 0, parser.at, 0); } + if (parser.nodes >= parser.max_nodes) { return ir_type_fail(parser, 3, 0, parser.at, 0); } + parser.nodes += 1; + if (!ir_type_read(parser)) { return false; } + var token: ptr = &parser.tokens[parser.at]; + var start: u64 = parser.at; + if (token.kind != 0) { return ir_type_fail(parser, 1, 4, start, 0); } + parser.at += 1; + var kind: u64 = 0; + while (kind < 22 && !ir_type_word(token, kind)) { kind += 1; } + if (kind == 22) { return ir_type_fail(parser, 1, 5, start, 0); } + if (kind < 17) { return ir_type_emit(parser, kind, 0, 0); } + var count: u64 = 0; + var value: u64 = 0; + var end: u64 = 25; + if (kind == 20) { + if (!ir_type_expect(parser, 26)) { return false; } + end = 27; + } else if (!ir_type_expect(parser, 24)) { return false; } + if (kind == 17) { + if (!ir_type_parse_node(parser, depth + 1) || !ir_type_expect(parser, 25)) { return false; } + return ir_type_emit(parser, kind, 0, 1); + } + if (kind == 19) { + if (!ir_type_parse_node(parser, depth + 1) || !ir_type_expect(parser, 31) + || !ir_type_number(parser, &value) || !ir_type_expect(parser, 25)) { return false; } + return ir_type_emit(parser, kind, value, 1); + } + if (kind == 18) { + if (!ir_type_read(parser)) { return false; } + if (parser.tokens[parser.at].kind != 0) { return ir_type_fail(parser, 1, 4, parser.at, 0); } + if (ir_type_word(&parser.tokens[parser.at], 22)) { value = 0; } + else if (ir_type_word(&parser.tokens[parser.at], 23)) { value = 1; } + else { return ir_type_fail(parser, 1, 6, parser.at, 0); } + parser.at += 1; + if (!ir_type_expect(parser, 28)) { return false; } + end = 29; + } + if (!ir_type_eat(parser, end)) { + if (parser.result.status != 0) { return false; } + while (true) { + if (!ir_type_parse_node(parser, depth + 1)) { return false; } + count += 1; + if (ir_type_eat(parser, end)) { break; } + if (parser.result.status != 0 || !ir_type_expect(parser, 31)) { return false; } + } + } + if (kind == 18) { + if (!ir_type_expect(parser, 30) || !ir_type_parse_node(parser, depth + 1) + || !ir_type_expect(parser, 25)) { return false; } + } + return ir_type_emit(parser, kind, value, count); +} + +export(c) fun whale_ir_parse_type(tokens: ptr, token_count: u64, + start: u64, depth: u64, max_depth: u64, max_nodes: u64, max_work: u64, + mode: u64, scratch: ptr, capacity: u64, + output: ptr, output_capacity: u64, result: ptr) -> i32 { + if (result == null) { return 6; } + result.status = 0; result.reason = 0; result.at = start; result.expected = 0; + result.next = 0; result.nodes = 0; result.work = 0; + if (mode > 1 || max_depth > 256 || start >= token_count + || !ir_span_valid(tokens as ptr, token_count, 24) + || (mode == 1 && (!ir_span_valid(scratch as ptr, capacity, 24) + || !ir_span_valid(output as ptr, output_capacity, 24)))) { + result.status = 6; return 6; + } + var parser: IrTypeParser = IrTypeParser { tokens: tokens, token_count: token_count, + at: start, max_depth: max_depth, max_nodes: max_nodes, max_work: max_work, + work: 0, nodes: 0, emitted: 0, mode: mode, scratch: scratch, + capacity: capacity, result: result }; + if (!ir_type_parse_node(&parser, depth)) { + result.work = parser.work; + return result.status as i32; + } + if (parser.nodes != parser.emitted || (mode == 1 && parser.nodes > output_capacity)) { + result.status = 5; result.work = parser.work; return 5; + } + var index: u64 = 0; + if (mode == 1) { + while (index < parser.nodes) { output[index] = scratch[index]; index += 1; } + } + result.next = parser.at; result.nodes = parser.nodes; result.work = parser.work; + return 0; +} diff --git a/ir/verifier_index.wave b/ir/verifier_index.wave new file mode 100644 index 0000000..a3e0f94 --- /dev/null +++ b/ir/verifier_index.wave @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: MPL-2.0 +// Incremental, bounded, caller-owned declaration identity index. Names are +// borrowed from immutable module storage for the lifetime of verification. +struct IrVerifyKey { kind: u64; number: u64; bytes: ptr; count: u64; } + +struct IrVerifySlot { kind: u64; number: u64; bytes: ptr; count: u64; occupied: u64; } + +fun ir_verify_index(table: ptr, capacity: u64, + key: ptr, insert: bool, max_work: u64, result: ptr) -> i32 { + if (result == null) { return 7; } + result.status = 0; result.index = 0; result.expected = 0; + result.actual = 0; result.detail = 0; result.work = 0; + if (key == null || key.kind > 2 || capacity < 2 || !ir_power_two(capacity) + || !ir_span_valid(table as ptr, capacity, 40) + || (key.kind == 1 && !ir_span_valid(key.bytes, key.count, 1))) { + return ir_verify_error(result, 7, 0, 0, 0, 0); + } + var hash: u64 = key.number ^ (key.number >> 16); + if (key.kind == 2) { hash = hash ^ key.count ^ (key.count >> 16); } + if (key.kind == 1) { + hash = 14695981039346656037; + var i: u64 = 0; + while (i < key.count) { + if (!ir_verify_charge(result, max_work)) { return 8; } + hash = (hash ^ (key.bytes[i] as u64)) * 1099511628211; + i += 1; + } + } + var position: u64 = hash & (capacity - 1); + var probes: u64 = 0; + while (probes < capacity) { + if (!ir_verify_charge(result, max_work)) { return 8; } + var slot: ptr = &table[position]; + if (slot.occupied > 1 || slot.kind > 2) { return ir_verify_error(result, 7, position, 0, 0, 0); } + if (slot.occupied == 0) { + if (!insert) { return 0; } + slot.kind = key.kind; slot.number = key.number; slot.bytes = key.bytes; + slot.count = key.count; slot.occupied = 1; return 0; + } + if (slot.kind == key.kind) { + if (key.kind == 0 && slot.number == key.number) { return ir_verify_error(result, 1, position, 0, 0, 0); } + if (key.kind == 2 && slot.number == key.number && slot.count == key.count) { return ir_verify_error(result, 1, position, 0, 0, 0); } + if (key.kind == 1 && slot.count == key.count) { + if (!ir_span_valid(slot.bytes, slot.count, 1)) { return ir_verify_error(result, 7, position, 0, 0, 0); } + var equal: bool = true; var i: u64 = 0; + while (i < key.count) { + if (!ir_verify_charge(result, max_work)) { return 8; } + if (slot.bytes[i] != key.bytes[i]) { equal = false; break; } + i += 1; + } + if (equal) { return ir_verify_error(result, 1, position, 0, 0, 0); } + } + } + position = (position + 1) & (capacity - 1); probes += 1; + } + return ir_verify_error(result, 8, 0, 0, 0, 0); +} + +export(c) fun whale_ir_verify_index_insert(table: ptr, capacity: u64, + key: ptr, max_work: u64, result: ptr) -> i32 { + return ir_verify_index(table, capacity, key, true, max_work, result); +} + +export(c) fun whale_ir_verify_index_contains(table: ptr, capacity: u64, + key: ptr, max_work: u64, result: ptr) -> i32 { + return ir_verify_index(table, capacity, key, false, max_work, result); +} diff --git a/ir/verifier_ssa.wave b/ir/verifier_ssa.wave new file mode 100644 index 0000000..f87ece0 --- /dev/null +++ b/ir/verifier_ssa.wave @@ -0,0 +1,182 @@ +// SPDX-License-Identifier: MPL-2.0 +// SSA and phi validation over caller-owned CFG/dominator intervals. +struct IrSsaBlock { + id: u64; first: u64; count: u64; pred_first: u64; pred_count: u64; + reachable: u64; start: u64; end: u64; terminator_use: u64; +} + +struct IrSsaInstruction { phi: u64; dst: u64; ty: u64; first: u64; count: u64; } + +struct IrSsaUse { value: u64; ty: u64; pred: u64; def_block: u64; def_position: u64; defined: u64; } + +struct IrSsaPredecessor { block: u64; seen: u64; } + +struct IrSsaResult { status: u64; instruction: u64; usage: u64; detail: u64; work: u64; queries: u64; } + +fun ir_ssa_error(result: ptr, status: u64, instruction: u64, + usage: u64, detail: u64, semantic: ptr) -> i32 { + result.status = status; result.instruction = instruction; result.usage = usage; + result.detail = detail; result.work = semantic.work; return status as i32; +} + +fun ir_ssa_available(usage: ptr, block: u64, position: u64, + blocks: ptr, result: ptr, semantic: ptr, + max_work: u64) -> u64 { + if (usage.defined == 0) { return 2; } + if (blocks[block].reachable == 0 || usage.def_block == 18446744073709551615) { return 0; } + if (usage.def_block == block) { + if (usage.def_position >= position) { return 3; } + return 0; + } + if (!ir_verify_charge(semantic, max_work)) { return 8; } + result.queries += 1; + var definition: ptr = &blocks[usage.def_block]; + if (definition.reachable == 0 || definition.start > blocks[block].start + || blocks[block].end > definition.end) { return 3; } + return 0; +} + +// Status: 1 invalid phi, 2 undefined value, 3 non-dominating use, +// 4 invalid phi type category, 5 phi operand type, 7 transport, 8 work. +export(c) fun whale_ir_verify_ssa(types: ptr, type_count: u64, + edges: ptr, edge_count: u64, blocks: ptr, block_count: u64, + entry: u64, instructions: ptr, instruction_count: u64, + uses: ptr, use_count: u64, predecessors: ptr, predecessor_count: u64, + table: ptr, capacity: u64, max_work: u64, + result: ptr) -> i32 { + if (result == null) { return 7; } + result.status = 0; result.instruction = 0; result.usage = 0; + result.detail = 0; result.work = 0; result.queries = 0; + var semantic: IrVerifyResult; + semantic.status = 0; semantic.index = 0; semantic.expected = 0; + semantic.actual = 0; semantic.detail = 0; semantic.work = 0; + if (!ir_verify_graph_valid(types, type_count, edges, edge_count, max_work, &semantic)) { + return ir_ssa_error(result, semantic.status, 0, 0, 0, &semantic); + } + if (!ir_span_valid(blocks as ptr, block_count, 72) || entry >= block_count + || !ir_span_valid(instructions as ptr, instruction_count, 40) + || !ir_span_valid(uses as ptr, use_count, 48) + || !ir_span_valid(predecessors as ptr, predecessor_count, 8) + || !ir_span_valid(table as ptr, capacity, 16) + || capacity < 2 || !ir_power_two(capacity)) { + return ir_ssa_error(result, 7, 0, 0, 0, &semantic); + } + var b: u64 = 0; + while (b < block_count) { + if (!ir_verify_charge(&semantic, max_work)) { return ir_ssa_error(result, 8, 0, 0, 0, &semantic); } + var block: ptr = &blocks[b]; + if (block.first > instruction_count || block.count > instruction_count - block.first + || block.pred_first > predecessor_count || block.pred_count > predecessor_count - block.pred_first + || block.pred_count > capacity / 2 || block.reachable > 1 + || (block.terminator_use != 18446744073709551615 && block.terminator_use >= use_count)) { + return ir_ssa_error(result, 7, block.first, 0, b, &semantic); + } + b += 1; + } + var i: u64 = 0; + while (i < instruction_count) { + if (!ir_verify_charge(&semantic, max_work)) { return ir_ssa_error(result, 8, i, 0, 0, &semantic); } + var instruction: ptr = &instructions[i]; + if (instruction.phi > 1 || instruction.ty >= type_count || instruction.first > use_count + || instruction.count > use_count - instruction.first) { return ir_ssa_error(result, 7, i, 0, 0, &semantic); } + i += 1; + } + i = 0; + while (i < use_count) { + if (!ir_verify_charge(&semantic, max_work)) { return ir_ssa_error(result, 8, 0, i, 0, &semantic); } + if (uses[i].defined > 1 + || (uses[i].ty != 18446744073709551615 && uses[i].ty >= type_count) + || (uses[i].pred != 18446744073709551615 && uses[i].pred >= block_count) + || (uses[i].def_block != 18446744073709551615 && uses[i].def_block >= block_count)) { + return ir_ssa_error(result, 7, 0, i, 0, &semantic); + } + i += 1; + } + b = 0; + while (b < block_count) { + var block: ptr = &blocks[b]; + // Only the required prefix is cleared; wide unrelated CFG blocks do + // not inflate a small block's validation cost. + var local_capacity: u64 = 2; + while (local_capacity / 2 < block.pred_count) { local_capacity *= 2; } + i = 0; + while (i < local_capacity) { + if (!ir_verify_charge(&semantic, max_work)) { return ir_ssa_error(result, 8, block.first, 0, 0, &semantic); } + table[i].block = 18446744073709551615; table[i].seen = 0; i += 1; + } + i = 0; + while (i < block.pred_count) { + var predecessor: u64 = predecessors[block.pred_first + i]; + if (predecessor >= block_count) { return ir_ssa_error(result, 7, block.first, 0, 0, &semantic); } + var slot: u64 = (predecessor ^ (predecessor >> 16)) & (local_capacity - 1); + while (true) { + if (!ir_verify_charge(&semantic, max_work)) { return ir_ssa_error(result, 8, block.first, 0, 0, &semantic); } + if (table[slot].block == 18446744073709551615) { table[slot].block = predecessor; break; } + if (table[slot].block == predecessor) { return ir_ssa_error(result, 7, block.first, 0, 0, &semantic); } + slot = (slot + 1) & (local_capacity - 1); + } + i += 1; + } + var past_phi: bool = false; + var position: u64 = 0; + while (position < block.count) { + i = block.first + position; + if (!ir_verify_charge(&semantic, max_work)) { return ir_ssa_error(result, 8, i, 0, 0, &semantic); } + var instruction: ptr = &instructions[i]; + if (instruction.phi != 0) { + if (past_phi) { return ir_ssa_error(result, 1, i, 0, 0, &semantic); } + if (b == entry) { return ir_ssa_error(result, 1, i, 0, 1, &semantic); } + if (instruction.count == 0) { return ir_ssa_error(result, 1, i, 0, 2, &semantic); } + if (!ir_verify_storable(instruction.ty, types, edges, 1024, &semantic, max_work)) { + if (semantic.status != 0) { return ir_ssa_error(result, semantic.status, i, 0, 0, &semantic); } + return ir_ssa_error(result, 4, i, 0, 0, &semantic); + } + var j: u64 = 0; + while (j < instruction.count) { + var u: u64 = instruction.first + j; + var usage: ptr = &uses[u]; + if (!ir_verify_charge(&semantic, max_work)) { return ir_ssa_error(result, 8, i, u, 0, &semantic); } + var pred: u64 = usage.pred; + if (pred == 18446744073709551615) { return ir_ssa_error(result, 1, i, u, 3, &semantic); } + var slot: u64 = (pred ^ (pred >> 16)) & (local_capacity - 1); + while (true) { + if (!ir_verify_charge(&semantic, max_work)) { return ir_ssa_error(result, 8, i, u, 0, &semantic); } + if (table[slot].block == 18446744073709551615) { return ir_ssa_error(result, 1, i, u, 4, &semantic); } + if (table[slot].block == pred) { + if (table[slot].seen == i + 1) { return ir_ssa_error(result, 1, i, u, 5, &semantic); } + table[slot].seen = i + 1; break; + } + slot = (slot + 1) & (local_capacity - 1); + } + if (usage.ty == 18446744073709551615) { return ir_ssa_error(result, 6, i, u, 0, &semantic); } + if (!ir_verify_equal(instruction.ty, usage.ty, types, edges, 1024, &semantic, max_work)) { + if (semantic.status != 0) { return ir_ssa_error(result, semantic.status, i, u, 0, &semantic); } + return ir_ssa_error(result, 5, i, u, 0, &semantic); + } + var status: u64 = ir_ssa_available(usage, pred, blocks[pred].count, + blocks, result, &semantic, max_work); + if (status != 0) { return ir_ssa_error(result, status, i, u, pred, &semantic); } + j += 1; + } + if (instruction.count != block.pred_count) { return ir_ssa_error(result, 1, i, 0, 6, &semantic); } + } else { + past_phi = true; + var j: u64 = 0; + while (j < instruction.count) { + var u: u64 = instruction.first + j; + var status: u64 = ir_ssa_available(&uses[u], b, position, blocks, result, &semantic, max_work); + if (status != 0) { return ir_ssa_error(result, status, i, u, b, &semantic); } + j += 1; + } + } + position += 1; + } + if (block.terminator_use != 18446744073709551615) { + var u: u64 = block.terminator_use; + var status: u64 = ir_ssa_available(&uses[u], b, block.count, blocks, result, &semantic, max_work); + if (status != 0) { return ir_ssa_error(result, status, block.first + block.count, u, b, &semantic); } + } + b += 1; + } + result.work = semantic.work; return 0; +} diff --git a/ir/verify.wave b/ir/verify.wave new file mode 100644 index 0000000..9753864 --- /dev/null +++ b/ir/verify.wave @@ -0,0 +1,616 @@ +// SPDX-License-Identifier: MPL-2.0 +// Semantic verification consumes a borrowed type graph and operand records. +// No host callbacks participate in type/category, cast, memory or GEP rules. +struct IrVerifyType { kind: u64; child: u64; first: u64; count: u64; extra: u64; } + +struct IrVerifyOperand { value: u64; ty: u64; literal: u64; low: u64; high: u64; } + +struct IrVerifyInstruction { op: u64; sub: u64; ty: u64; other: u64; dst: u64; align: u64; } + +struct IrVerifyResult { status: u64; index: u64; expected: u64; actual: u64; detail: u64; work: u64; } + +struct IrVerifyBinding { id: u64; ty: u64; index: u64; present: u64; } + +fun ir_verify_signed(kind: u64) -> bool { return kind == 2 || (kind >= 4 && kind <= 8); } + +fun ir_verify_unsigned(kind: u64) -> bool { return kind == 3 || (kind >= 9 && kind <= 13); } + +fun ir_verify_integer(kind: u64) -> bool { return ir_verify_signed(kind) || ir_verify_unsigned(kind); } + +fun ir_verify_float(kind: u64) -> bool { return kind >= 14 && kind <= 16; } + +fun ir_verify_width(kind: u64) -> u64 { + if (kind == 2 || kind == 3) { return 1; } + if (kind == 4 || kind == 9) { return 8; } + if (kind == 5 || kind == 10 || kind == 14) { return 16; } + if (kind == 6 || kind == 11 || kind == 15) { return 32; } + if (kind == 7 || kind == 12 || kind == 16) { return 64; } + if (kind == 8 || kind == 13) { return 128; } + return 0; +} + +fun ir_verify_literal(kind: u64, literal: u64, low: u64, high: u64) -> bool { + var valid: bool = (kind == 1 && literal == 3) || (kind == 14 && literal == 4) + || (kind == 15 && literal == 5) || (kind == 16 && literal == 6); + var width: u64 = ir_verify_width(kind); var one: u64 = 1; + if (literal == 1 && ir_verify_signed(kind)) { + valid = width == 128; + if (width < 128) { + var top: u64 = one << (width - 1); + valid = (high == 0 && low < top) + || (high == 18446744073709551615 && low >= 18446744073709551615 - top + 1); + } + } + if (literal == 2 && ir_verify_unsigned(kind)) { + valid = width == 128 || (high == 0 && (width == 64 || low < (one << width))); + } + return valid; +} + +fun ir_verify_error(result: ptr, status: u64, index: u64, + expected: u64, actual: u64, detail: u64) -> i32 { + result.status = status; result.index = index; result.expected = expected; + result.actual = actual; result.detail = detail; return status as i32; +} + +fun ir_verify_charge(result: ptr, limit: u64) -> bool { + if (result.work >= limit) { result.status = 8; return false; } + result.work += 1; return true; +} + +fun ir_verify_equal(a: u64, b: u64, types: ptr, edges: ptr, + depth: u64, result: ptr, limit: u64) -> bool { + if (!ir_verify_charge(result, limit)) { return false; } + if (a == b) { return true; } + if (depth == 0) { result.status = 8; return false; } + if (types[a].kind != types[b].kind || types[a].extra != types[b].extra) { return false; } + var kind: u64 = types[a].kind; + if (kind == 17 || kind == 19) { + if (kind == 19 && types[a].count != types[b].count) { return false; } + return ir_verify_equal(types[a].child, types[b].child, types, edges, + depth - 1, result, limit); + } + if (kind == 18 || kind == 20 || kind == 21) { + if (types[a].count != types[b].count) { return false; } + var i: u64 = 0; + while (i < types[a].count) { + if (!ir_verify_equal(edges[types[a].first + i], edges[types[b].first + i], + types, edges, depth - 1, result, limit)) { return false; } + i += 1; + } + } + return true; +} + +fun ir_verify_storable(ty: u64, types: ptr, edges: ptr, + depth: u64, result: ptr, limit: u64) -> bool { + if (!ir_verify_charge(result, limit)) { return false; } + if (depth == 0) { result.status = 8; return false; } + var kind: u64 = types[ty].kind; + if (kind == 0) { return false; } + if (kind == 19) { return ir_verify_storable(types[ty].child, types, edges, + depth - 1, result, limit); } + if (kind == 20 || kind == 21) { + var i: u64 = 0; + while (i < types[ty].count) { + if (!ir_verify_storable(edges[types[ty].first + i], types, edges, + depth - 1, result, limit)) { return false; } + i += 1; + } + } + return true; +} + +fun ir_verify_cast(op: u64, source: u64, destination: u64) -> bool { + var si: bool = ir_verify_integer(source); var di: bool = ir_verify_integer(destination); + var sf: bool = ir_verify_float(source); var df: bool = ir_verify_float(destination); + var sw: u64 = ir_verify_width(source); var dw: u64 = ir_verify_width(destination); + if (op == 0 && source == 1) { return di && destination != 2; } + if (op == 0 || op == 1) { return si && di && sw < dw; } + if (op == 2) { return si && di && sw > dw; } + if (op == 3) { return sf && df && sw < dw; } + if (op == 4) { return sf && df && sw > dw; } + if (op == 5) { return ir_verify_signed(source) && df; } + if (op == 6) { return ir_verify_unsigned(source) && df; } + if (op == 7) { return sf && ir_verify_signed(destination); } + if (op == 8) { return sf && ir_verify_unsigned(destination); } + if (op == 9) { return ((si || sf) && (di || df) && sw == dw) || (source == 17 && destination == 17); } + if (op == 10) { return source == 17 && di; } + if (op == 11) { return si && destination == 17; } + if (op == 12) { return si && di; } + return false; +} + +fun ir_verify_operand_at(index: u64, expected: u64, pointer: bool, + operands: ptr, types: ptr, edges: ptr, + result: ptr, limit: u64) -> bool { + var actual: u64 = operands[index].ty; + if (actual == 18446744073709551615) { + ir_verify_error(result, 2, index, expected, actual, 0); return false; + } + var compare: u64 = actual; + if (pointer) { + if (types[actual].kind != 17) { + ir_verify_error(result, 3, index, expected, actual, 1); return false; + } + compare = types[actual].child; + } + if (!ir_verify_equal(expected, compare, types, edges, 1024, result, limit)) { + if (result.status == 0) { ir_verify_error(result, 3, index, expected, actual, pointer as u64); } + return false; + } + return true; +} + +fun ir_verify_graph_valid(types: ptr, type_count: u64, + edges: ptr, edge_count: u64, max_work: u64, result: ptr) -> bool { + if (!ir_span_valid(types as ptr, type_count, 40) + || !ir_span_valid(edges as ptr, edge_count, 8)) { + ir_verify_error(result, 7, 0, 0, 0, 0); return false; + } + var i: u64 = 0; + while (i < type_count) { + if (!ir_verify_charge(result, max_work)) { return false; } + var node: ptr = &types[i]; + if (node.kind > 21 || ((node.kind == 17 || node.kind == 19) && node.child >= i)) { + ir_verify_error(result, 7, i, 0, 0, 0); return false; + } + if (node.kind == 18 || node.kind == 20 || node.kind == 21) { + if (node.first > edge_count || node.count > edge_count - node.first) { + ir_verify_error(result, 7, i, 0, 0, 0); return false; + } + var j: u64 = 0; + while (j < node.count) { + if (!ir_verify_charge(result, max_work)) { return false; } + if (edges[node.first + j] >= i) { ir_verify_error(result, 7, i, 0, 0, 0); return false; } + j += 1; + } + } + i += 1; + } + return true; +} + +fun ir_verify_signature_type(ty: u64, types: ptr, edges: ptr, + depth: u64, result: ptr, limit: u64) -> bool { + if (!ir_verify_charge(result, limit)) { return false; } + if (depth == 0) { result.status = 8; return false; } + var kind: u64 = types[ty].kind; + if (kind == 0) { ir_verify_error(result, 11, 0, 0, 0, 1); return false; } + if (kind == 17 || kind == 19) { + if (kind == 17 && types[types[ty].child].kind == 0) { return true; } + return ir_verify_signature_type(types[ty].child, types, edges, depth - 1, result, limit); + } + if (kind == 18) { return ir_verify_signature(ty, types, edges, depth - 1, result, limit); } + if (kind == 20 || kind == 21) { + var i: u64 = 0; + while (i < types[ty].count) { + if (!ir_verify_signature_type(edges[types[ty].first + i], types, edges, + depth - 1, result, limit)) { return false; } + i += 1; + } + } + return true; +} + +fun ir_verify_signature(ty: u64, types: ptr, edges: ptr, + depth: u64, result: ptr, limit: u64) -> bool { + if (!ir_verify_charge(result, limit)) { return false; } + if (depth == 0) { result.status = 8; return false; } + if (types[ty].kind != 18 || types[ty].count == 0 || types[ty].extra > 3) { + ir_verify_error(result, 7, 0, 0, 0, 0); return false; + } + if ((types[ty].extra & 2) != 0) { ir_verify_error(result, 11, 0, 0, 0, 1); return false; } + var i: u64 = 0; + if ((types[ty].extra & 1) != 0) { + while (i < types[ty].count) { + var kind: u64 = types[edges[types[ty].first + i]].kind; + if (kind == 19 || kind == 20 || kind == 21) { + ir_verify_error(result, 11, 0, 0, 0, 2); return false; + } + i += 1; + } + } + i = types[ty].count; + while (i > 0) { + i -= 1; + var child: u64 = edges[types[ty].first + i]; + if (i != 0 || types[child].kind != 0) { + if (!ir_verify_signature_type(child, types, edges, depth - 1, result, limit)) { return false; } + } + } + return true; +} + +fun ir_verify_pointer_signatures(ty: u64, types: ptr, edges: ptr, + depth: u64, result: ptr, limit: u64) -> bool { + if (!ir_verify_charge(result, limit)) { return false; } + if (depth == 0) { result.status = 8; return false; } + var kind: u64 = types[ty].kind; + if (kind == 18) { return ir_verify_signature(ty, types, edges, depth - 1, result, limit); } + if (kind == 17 || kind == 19) { return ir_verify_pointer_signatures(types[ty].child, + types, edges, depth - 1, result, limit); } + if (kind == 20 || kind == 21) { + var i: u64 = 0; + while (i < types[ty].count) { + if (!ir_verify_pointer_signatures(edges[types[ty].first + i], types, edges, + depth - 1, result, limit)) { return false; } + i += 1; + } + } + return true; +} + +fun ir_verify_contains_fnptr(ty: u64, types: ptr, edges: ptr, + depth: u64, result: ptr, limit: u64) -> bool { + if (!ir_verify_charge(result, limit)) { return false; } + if (depth == 0) { result.status = 8; return false; } + var kind: u64 = types[ty].kind; + if (kind == 18) { return true; } + if (kind == 17 || kind == 19) { return ir_verify_contains_fnptr(types[ty].child, + types, edges, depth - 1, result, limit); } + if (kind == 20 || kind == 21) { + var i: u64 = 0; + while (i < types[ty].count) { + if (ir_verify_contains_fnptr(edges[types[ty].first + i], types, edges, + depth - 1, result, limit)) { return true; } + if (result.status != 0) { return false; } + i += 1; + } + } + return false; +} + +// Instructions: 1 neg, 2 cast, 3 checked, 4 binary, 5 lifetime_end, +// 6 ptrdiff, 7 not, 8 mov, 9 cmp/icmp, 10 fcmp, 11 select, 12 extract, +// 13 uninit, 14 alloca, 15 volatile load, 16 volatile store, 17 load, +// 18 store, 19 GEP, 20 memcpy, 21 memset, 22 condition, 23 equality, +// 24 literal. Error statuses: category, missing type, mismatch, alignment, +// cast, GEP, malformed transport, resource budget, invalid literal. +export(c) fun whale_ir_verify_semantics(types: ptr, type_count: u64, + edges: ptr, edge_count: u64, instruction: ptr, + operands: ptr, operand_count: u64, max_work: u64, + result: ptr) -> i32 { + if (result == null) { return 7; } + result.status = 0; result.index = 0; result.expected = 0; + result.actual = 0; result.detail = 0; result.work = 0; + if (instruction == null || !ir_span_valid(types as ptr, type_count, 40) + || !ir_span_valid(edges as ptr, edge_count, 8) + || !ir_span_valid(operands as ptr, operand_count, 40)) { + return ir_verify_error(result, 7, 0, 0, 0, 0); + } + if (!ir_verify_graph_valid(types, type_count, edges, edge_count, max_work, result)) { return result.status as i32; } + var i: u64 = 0; + while (i < operand_count) { + if (!ir_verify_charge(result, max_work)) { return 8; } + if (operands[i].ty != 18446744073709551615 && operands[i].ty >= type_count) { + return ir_verify_error(result, 7, i, 0, 0, 0); + } + i += 1; + } + var op: u64 = instruction.op; var sub: u64 = instruction.sub; + var ty: u64 = instruction.ty; var other: u64 = instruction.other; + if (ty >= type_count || other >= type_count || op == 0 || op > 35) { + return ir_verify_error(result, 7, 0, 0, 0, 0); + } + if (op == 33) { + if (!ir_verify_storable(ty, types, edges, 1024, result, max_work)) { + if (result.status != 0) { return result.status as i32; } + return ir_verify_error(result, 1, 0, ty, 0, 0); + } + return 0; + } + if (op == 34) { + if (operand_count != 1) { return ir_verify_error(result, 7, 0, 0, 0, 0); } + if (!ir_verify_integer(types[ty].kind) && types[ty].kind != 1) { + return ir_verify_error(result, 1, 0, ty, 0, 0); + } + if (!ir_verify_operand_at(0, ty, false, operands, types, edges, result, max_work)) { return result.status as i32; } + return 0; + } + if (op == 35) { + if (instruction.dst > 1 || operand_count != instruction.dst) { return ir_verify_error(result, 7, 0, 0, 0, 0); } + if (!ir_verify_equal(ty, other, types, edges, 1024, result, max_work)) { + if (result.status != 0) { return result.status as i32; } + return ir_verify_error(result, 25, 0, ty, other, 0); + } + if (instruction.dst != 0) { + if (sub == 0) { return ir_verify_error(result, 27, 0, 0, 0, 0); } + var actual: u64 = operands[0].ty; + if (actual == 18446744073709551615) { return ir_verify_error(result, 2, 0, 0, 0, 0); } + if (types[ty].kind == 0 || !ir_verify_equal(ty, actual, types, edges, 1024, result, max_work)) { + if (result.status != 0) { return result.status as i32; } + return ir_verify_error(result, 25, 0, ty, actual, 0); + } + } else { + if (types[ty].kind != 0) { return ir_verify_error(result, 26, 0, ty, 0, 0); } + } + return 0; + } + if (op == 31) { + if (operand_count != 1 || sub > 1 || instruction.dst > 1) { return ir_verify_error(result, 7, 0, 0, 0, 0); } + var kind: u64 = types[ty].kind; + if (kind == 0 || kind > 18) { return ir_verify_error(result, 21, 0, 0, 0, 0); } + if (!ir_verify_signature_type(ty, types, edges, 1024, result, max_work)) { + if (result.status == 11) { return ir_verify_error(result, 21, 0, 0, 0, 0); } + return result.status as i32; + } + if (!ir_power_two(instruction.align)) { return ir_verify_error(result, 22, 0, 0, 0, 0); } + if (instruction.dst != 0 && !ir_verify_literal(kind, operands[0].literal, operands[0].low, operands[0].high)) { + return ir_verify_error(result, 23, 0, 0, 0, 0); + } + if (instruction.dst == 0 && sub != 0) { return ir_verify_error(result, 24, 0, 0, 0, 0); } + return 0; + } + if (op == 32) { + if (!ir_power_two(instruction.align)) { return ir_verify_error(result, 4, 0, 0, 0, 0); } + return 0; + } + if (op == 25 || op == 29) { + if (operand_count != 0) { return ir_verify_error(result, 7, 0, 0, 0, 0); } + var valid: bool = false; + if (op == 25) { valid = ir_verify_signature(ty, types, edges, 1024, result, max_work); } + else { valid = ir_verify_pointer_signatures(ty, types, edges, 1024, result, max_work); } + if (!valid) { return result.status as i32; } + return 0; + } + if (op == 27) { + if (!ir_verify_equal(ty, other, types, edges, 1024, result, max_work)) { + if (result.status != 0) { return result.status as i32; } + return ir_verify_error(result, 12, 0, ty, other, 0); + } + return 0; + } + if (op == 30) { + if (operand_count != 1) { return ir_verify_error(result, 7, 0, 0, 0, 0); } + var source: u64 = operands[0].ty; + if (sub == 9 && types[ty].kind == 17 && types[other].kind == 17 + && source != 18446744073709551615 && types[source].kind == 17) { return 0; } + var forbidden: bool = ir_verify_contains_fnptr(ty, types, edges, 1024, result, max_work) + || ir_verify_contains_fnptr(other, types, edges, 1024, result, max_work); + if (source != 18446744073709551615) { + forbidden = forbidden || ir_verify_contains_fnptr(source, types, edges, 1024, result, max_work); + } + if (result.status != 0) { return result.status as i32; } + if (forbidden) { return ir_verify_error(result, 18, 0, 0, 0, 0); } + return 0; + } + if (op == 28) { + if (types[ty].kind != 18) { return ir_verify_error(result, 19, 0, 0, ty, 0); } + if (!ir_verify_signature(ty, types, edges, 1024, result, max_work)) { return result.status as i32; } + if (sub != (types[ty].extra & 1)) { return ir_verify_error(result, 13, 0, 0, 0, 0); } + var return_type: u64 = edges[types[ty].first]; + if (!ir_verify_equal(return_type, other, types, edges, 1024, result, max_work)) { + if (result.status != 0) { return result.status as i32; } + return ir_verify_error(result, 14, 0, return_type, other, 0); + } + if ((instruction.dst != 0 && types[return_type].kind == 0) + || (instruction.dst == 0 && types[return_type].kind != 0)) { return ir_verify_error(result, 15, 0, 0, 0, 0); } + var params: u64 = types[ty].count - 1; + if (operand_count != params) { return ir_verify_error(result, 16, 0, params, operand_count, 0); } + i = 0; + while (i < operand_count) { + if (!ir_verify_operand_at(i, edges[types[ty].first + i + 1], false, + operands, types, edges, result, max_work)) { + if (result.status == 3) { result.status = 17; } + return result.status as i32; + } + i += 1; + } + return 0; + } + var count: u64 = 0; + if (op == 1 || op == 2 || op == 5 || op == 7 || op == 8 || op == 12 || op == 13 + || op == 15 || op == 17 || op == 22 || op == 23 || op == 24) { count = 1; } + if (op == 3 || op == 4 || op == 6 || op == 9 || op == 10 || op == 16 || op == 18) { count = 2; } + if (op == 11 || op == 20 || op == 21) { count = 3; } + if ((op != 19 && operand_count != count) || (op == 19 && operand_count == 0)) { + return ir_verify_error(result, 7, 0, 0, 0, 0); + } + if ((op >= 13 && op <= 18 || op == 20 || op == 21) && !ir_power_two(instruction.align)) { + return ir_verify_error(result, 4, 0, 0, 0, 0); + } + var kind: u64 = types[ty].kind; var valid: bool = true; + if (op == 1) { valid = ir_verify_integer(kind) || ir_verify_float(kind); } + if (op == 3) { valid = ir_verify_signed(kind); if (sub == 1) { valid = ir_verify_unsigned(kind); } } + if (op == 4) { + valid = ir_verify_integer(kind); + if (sub == 1) { valid = ir_verify_signed(kind); } + if (sub == 2) { valid = ir_verify_unsigned(kind); } + if (sub == 3) { valid = ir_verify_float(kind); } + } + if (op == 7) { valid = ir_verify_integer(kind); } + if (op == 8 || op == 11 || op == 13 || op == 14 || op == 17 || op == 18) { + valid = ir_verify_storable(ty, types, edges, 1024, result, max_work); + } + if (op == 15 || op == 16) { + valid = ir_verify_storable(ty, types, edges, 1024, result, max_work) + && kind != 19 && kind != 20 && kind != 21; + } + if (op == 9) { + valid = ir_verify_integer(kind) || kind == 1 || kind == 17; + if (sub == 1) { valid = ir_verify_signed(kind) || kind == 17; } + if (sub == 2) { valid = ir_verify_unsigned(kind) || kind == 17; } + if (sub == 3) { valid = ir_verify_float(kind); } + } + if (op == 10) { valid = ir_verify_float(kind); } + if (result.status != 0) { return result.status as i32; } + if (!valid) { return ir_verify_error(result, 1, 0, ty, 0, 0); } + if (op == 14) { return 0; } + if (op == 24) { + var literal: u64 = operands[0].literal; var low: u64 = operands[0].low; var high: u64 = operands[0].high; + valid = ir_verify_literal(kind, literal, low, high); + if (!valid) { return ir_verify_error(result, 9, 0, ty, 0, 0); } + return 0; + } + if (op == 22) { + if (operands[0].ty == 18446744073709551615) { return ir_verify_error(result, 2, 0, 0, 0, 0); } + if (types[operands[0].ty].kind != 1) { return ir_verify_error(result, 10, 0, 0, operands[0].ty, 0); } + return 0; + } + if (op == 5 || op == 6) { + if (operands[0].ty == 18446744073709551615) { return ir_verify_error(result, 2, 0, 0, 0, 0); } + ty = operands[0].ty; + if (types[ty].kind != 17) { return ir_verify_error(result, 1, 0, ty, 0, 0); } + if (op == 5) { return 0; } + if (!ir_verify_operand_at(1, ty, false, operands, types, edges, result, max_work)) { return result.status as i32; } + return 0; + } + if (op == 12) { + var source: u64 = operands[0].ty; + valid = false; + if (source != 18446744073709551615 && types[source].kind == 21 && sub < types[source].count) { + valid = ir_verify_equal(ty, edges[types[source].first + sub], types, edges, 1024, result, max_work); + } + if (result.status != 0) { return result.status as i32; } + if (!valid) { return ir_verify_error(result, 1, 0, ty, 0, 0); } + return 0; + } + if (op == 19) { + var base: u64 = operands[0].ty; + if (base == 18446744073709551615) { return ir_verify_error(result, 2, 0, 0, 0, 0); } + if (types[base].kind != 17) { return ir_verify_error(result, 6, 0, 0, 0, 0); } + var selected: u64 = types[base].child; + if (operand_count > 1 && !ir_verify_storable(selected, types, edges, 1024, result, max_work)) { + if (result.status != 0) { return result.status as i32; } + return ir_verify_error(result, 6, 0, 0, 0, 1); + } + i = 1; + while (i < operand_count) { + var index_type: u64 = operands[i].ty; + if (index_type == 18446744073709551615) { return ir_verify_error(result, 2, i, 0, 0, 0); } + if (!ir_verify_integer(types[index_type].kind)) { return ir_verify_error(result, 6, i, 0, 0, 2); } + if (i > 1) { + var selected_kind: u64 = types[selected].kind; + if (selected_kind == 19) { selected = types[selected].child; } + else { + if (selected_kind != 20 && selected_kind != 21) { return ir_verify_error(result, 6, i, 0, 0, 5); } + var ordinal: u64 = operands[i].low; + if ((operands[i].literal != 1 && operands[i].literal != 2) || operands[i].high != 0) { + return ir_verify_error(result, 6, i, 0, 0, 3); + } + if (ordinal >= types[selected].count) { return ir_verify_error(result, 6, i, 0, 0, 4); } + selected = edges[types[selected].first + ordinal]; + } + } + i += 1; + } + if (kind != 17 || !ir_verify_equal(types[ty].child, selected, types, edges, 1024, result, max_work)) { + if (result.status != 0) { return result.status as i32; } + return ir_verify_error(result, 3, 0, selected, ty, 2); + } + return 0; + } + if (op == 11) { + if (operands[0].ty == 18446744073709551615) { return ir_verify_error(result, 2, 0, 0, 0, 0); } + if (types[operands[0].ty].kind != 1) { return ir_verify_error(result, 10, 0, 0, operands[0].ty, 0); } + i = 1; + } else { i = 0; } + while (i < operand_count) { + var expected: u64 = ty; var pointer: bool = false; + if (op == 13 || op == 15 || op == 17 || op == 16 || op == 18) { pointer = i == 0; } + if (op == 20 || op == 21) { + expected = ty; + pointer = i == 0 || (i == 1 && op == 20); + if (i == 2) { expected = other; } + } + if (!ir_verify_operand_at(i, expected, pointer, operands, types, edges, result, max_work)) { return result.status as i32; } + i += 1; + } + if (op == 2 && !ir_verify_cast(sub, kind, types[other].kind)) { + return ir_verify_error(result, 5, 0, ty, other, 0); + } + return 0; +} + +export(c) fun whale_ir_verify_link(external: u64, present: u64, bytes: ptr, count: u64, + max_work: u64, result: ptr) -> i32 { + if (result == null) { return 7; } + result.status = 0; result.index = 0; result.expected = 0; + result.actual = 0; result.detail = 0; result.work = 0; + if (external > 1 || present > 1 || !ir_span_valid(bytes, count, 1)) { + return ir_verify_error(result, 7, 0, 0, 0, 0); + } + if (external == 0 && present == 0) { return 0; } + if (external == 0 || present == 0 || count == 0) { return ir_verify_error(result, 20, 0, 0, 0, 0); } + var i: u64 = 0; + while (i < count) { + if (!ir_verify_charge(result, max_work)) { return 8; } + if (bytes[i] == 0) { return ir_verify_error(result, 20, i, 0, 0, 0); } + i += 1; + } + return 0; +} + +export(c) fun whale_ir_verify_value_types(types: ptr, type_count: u64, + edges: ptr, edge_count: u64, annotations: ptr, annotation_count: u64, + definitions: ptr, definition_count: u64, + table: ptr, capacity: u64, max_work: u64, + result: ptr) -> i32 { + if (result == null) { return 7; } + result.status = 0; result.index = 0; result.expected = 0; + result.actual = 0; result.detail = 0; result.work = 0; + if (!ir_verify_graph_valid(types, type_count, edges, edge_count, max_work, result)) { return result.status as i32; } + if (!ir_span_valid(annotations as ptr, annotation_count, 32) + || !ir_span_valid(definitions as ptr, definition_count, 32) + || !ir_span_valid(table as ptr, capacity, 32) + || capacity < 2 || !ir_power_two(capacity) || annotation_count > capacity / 2) { + return ir_verify_error(result, 7, 0, 0, 0, 0); + } + var i: u64 = 0; + while (i < capacity) { + if (!ir_verify_charge(result, max_work)) { return 8; } + table[i].present = 0; i += 1; + } + i = 0; + while (i < annotation_count) { + if (annotations[i].ty >= type_count) { return ir_verify_error(result, 7, i, 0, 0, 0); } + var position: u64 = (annotations[i].id ^ (annotations[i].id >> 16)) & (capacity - 1); + while (true) { + if (!ir_verify_charge(result, max_work)) { return 8; } + if (table[position].present == 0) { + table[position].id = annotations[i].id; table[position].ty = annotations[i].ty; + table[position].index = i; table[position].present = 1; break; + } + if (table[position].id == annotations[i].id) { + return ir_verify_error(result, 1, i, 0, 0, annotations[i].id); + } + position = (position + 1) & (capacity - 1); + } + i += 1; + } + i = 0; + while (i < definition_count) { + if (definitions[i].ty >= type_count) { return ir_verify_error(result, 7, i, 0, 0, 0); } + var position: u64 = (definitions[i].id ^ (definitions[i].id >> 16)) & (capacity - 1); + while (true) { + if (!ir_verify_charge(result, max_work)) { return 8; } + if (table[position].present == 0) { + return ir_verify_error(result, 2, i, 0, 0, definitions[i].id); + } + if (table[position].id == definitions[i].id) { + if (!ir_verify_equal(definitions[i].ty, table[position].ty, types, edges, 1024, result, max_work)) { + if (result.status != 0) { return result.status as i32; } + return ir_verify_error(result, 3, i, definitions[i].ty, table[position].ty, definitions[i].id); + } + table[position].present = 2; break; + } + position = (position + 1) & (capacity - 1); + } + i += 1; + } + i = 0; + while (i < annotation_count) { + var position: u64 = (annotations[i].id ^ (annotations[i].id >> 16)) & (capacity - 1); + while (true) { + if (!ir_verify_charge(result, max_work)) { return 8; } + if (table[position].id == annotations[i].id) { + if (table[position].present == 1) { return ir_verify_error(result, 4, i, 0, 0, annotations[i].id); } + break; + } + position = (position + 1) & (capacity - 1); + } + i += 1; + } + return 0; +} diff --git a/meson.build b/meson.build index 419a620..7e08640 100644 --- a/meson.build +++ b/meson.build @@ -36,7 +36,8 @@ elif not fs.is_absolute(wave_cache) error('-Dwave-bootstrap-dir must be absolute.') endif asmobj_directory = get_option('asmobj-dir') -if asmobj_directory == '' +wave_bootstrap = [] +if asmobj_directory == '' or (wave_source != '' and get_option('wave-ir-dir') == '') if wave_source == '' or not fs.is_absolute(wave_source) or not fs.is_dir(wave_source) error('Supply -Dwave-source=/absolute/Wave or -Dasmobj-dir=/absolute/built/module.') endif @@ -53,6 +54,7 @@ if asmobj_directory == '' depend_files: files('tools/wave_bootstrap.py', 'tools/meson_cargo.py'), console: true) endif subdir('assembler/asmobj') +subdir('ir') profile = 'dev' if get_option('buildtype') in ['release', 'minsize'] @@ -84,6 +86,9 @@ if get_option('cargo-offline') build_arguments += ['--offline'] endif build_arguments += ['--asmobj-dir', asmobj_directory] +if wave_ir_directory != '' + build_arguments += ['--wave-ir-dir', wave_ir_directory] +endif foreach feature : selected_features build_arguments += ['--feature', feature] endforeach @@ -93,7 +98,7 @@ whale = custom_target('whale-cli', command: [python, bridge, build_arguments], depend_files: files('Cargo.toml', 'Cargo.lock', 'tools/meson_cargo.py'), depfile: 'whale-cargo.d', - depends: asmobj_dependencies, + depends: asmobj_dependencies + wave_ir_dependencies, build_by_default: true, console: true, install: true, @@ -121,5 +126,6 @@ summary({ 'Cargo host target': cargo_host_target == '' ? 'native Rust toolchain host' : cargo_host_target, 'Assembler output modules': assembler_outputs, 'Complete Wave module': 'assembler/asmobj', + 'Wave IR sources': wave_ir_directory == '' ? 'Rust compatibility path' : wave_ir_directory, 'Cargo offline': get_option('cargo-offline'), }, section: 'Whale source modules') diff --git a/meson.options b/meson.options index 5cf86ef..f4b4f17 100644 --- a/meson.options +++ b/meson.options @@ -11,6 +11,8 @@ option('socket-cli', type: 'boolean', value: false, description: 'Include experimental AST JSON lowering commands') option('asmobj-dir', type: 'string', value: '', description: 'Absolute directory of the complete prebuilt Wave asmobj module for the executable host') +option('wave-ir-dir', type: 'string', value: '', + description: 'Absolute directory of a prebuilt internal Wave IR module; source builds use the pinned compiler') option('wave-source', type: 'string', value: '', description: 'Read-only Wave Git checkout containing the pinned bootstrap revision') option('wave-bootstrap-dir', type: 'string', value: '', diff --git a/src/commands/ir.rs b/src/commands/ir.rs index f778f07..0232ee9 100644 --- a/src/commands/ir.rs +++ b/src/commands/ir.rs @@ -40,6 +40,7 @@ pub fn run(args: Vec) { let mut arguments = Vec::new(); let mut max_steps = None; let mut max_memory = None; + let mut max_output = None; let mut input = None; let mut output = None; #[cfg(feature = "socket-cli")] @@ -49,6 +50,20 @@ pub fn run(args: Vec) { let mut args = args.iter().skip(1); while let Some(arg) = args.next() { match arg.as_str() { + "--max-output" if matches!(command.as_str(), "lower" | "print") => { + if max_output.is_some() { + fail("duplicate --max-output option"); + } + let value = + args.next().unwrap_or_else(|| fail("--max-output requires a byte count")); + max_output = Some( + value + .parse::() + .ok() + .filter(|_| !value.is_empty() && value.bytes().all(|b| b.is_ascii_digit())) + .unwrap_or_else(|| fail("--max-output requires a decimal byte count")), + ); + }, "-o" if matches!(command.as_str(), "lower" | "print") => { if output.is_some() { fail("duplicate -o option"); @@ -170,24 +185,45 @@ pub fn run(args: Vec) { ); return; } - let text = printer::print_module(&module); + let mut limits = printer::PrintLimits::default(); + if let Some(limit) = max_output { + limits.max_output_bytes = limit; + } if let Some(output) = output { - super::output::publish(input.as_ref(), output.as_ref(), text.as_bytes()) - .unwrap_or_else(|e| fail(format!("failed to write {output}: {e}"))); + super::output::publish_with(input.as_ref(), output.as_ref(), |file| { + printer::write_module(&module, file, limits).map_err(std::io::Error::other) + }) + .unwrap_or_else(|e| fail(format!("failed to write {output}: {e}"))); stdout(format!("Wrote IR to {output}\n")); } else { - stdout(text); + use std::io::Write; + let mut stream = std::io::stdout().lock(); + match printer::write_module(&module, &mut stream, limits) { + Ok(()) => stream.flush().unwrap_or_else(|error| { + if error.kind() == std::io::ErrorKind::BrokenPipe { + process::exit(0); + } + fail(format!("failed to write stdout: {error}")); + }), + Err(printer::PrintError::Io(error)) + if error.kind() == std::io::ErrorKind::BrokenPipe => + { + process::exit(0) + }, + Err(error) => fail(error), + } } } fn print_help() { stdout(concat!( "Usage: whale ir [options]", "\n", - " verify Read and verify format 3/4/5/6/7 typed IR", "\n", - " print [-o ] Verify and write canonical typed IR", "\n", + " verify Read and verify format 3/4/5/6/7/8 typed IR", "\n", + " print [-o ] [--max-output ]", "\n", " run --function @fN [--arg ...] [--max-steps ] [--max-memory ]", "\n", " Execute integer/bool/float values, control flow and tracked stack memory; default 1000000 steps, 64 MiB storage.", "\n", - " lower [-o ] Lower AST JSON (requires socket-cli)", "\n", + " lower [-o ] [--max-output ] (requires socket-cli)", "\n", + " Canonical output streams within a 64 MiB default limit; failed file writes preserve existing output.", "\n", " lower options: --target x86_64-whale-linux, --no-verify", "\n", " AST envelope: reads format_version 2/3/4/5, writes 5; semantics_version: 1, features: [], program: AST", "\n", " Typed IR reads format_version 3/4/5/6/7/8, writes 8; semantics_version 1. Legacy undef is invalid.", "\n", diff --git a/src/commands/output.rs b/src/commands/output.rs index f4b6932..5b79457 100644 --- a/src/commands/output.rs +++ b/src/commands/output.rs @@ -28,7 +28,7 @@ fn check_distinct(input: &Path, output: &Path) -> io::Result io::Result<()>, diff --git a/tests/text_ir_cli.rs b/tests/text_ir_cli.rs index b1b15ba..134feef 100644 --- a/tests/text_ir_cli.rs +++ b/tests/text_ir_cli.rs @@ -97,6 +97,50 @@ fn hardlink_output_cannot_overwrite_ir_input() { assert_eq!(fs::read_to_string(input).unwrap(), good); } +#[test] +fn canonical_printing_obeys_exact_byte_limits_and_preserves_existing_files() { + let tmp = tempfile::tempdir().unwrap(); + let input = tmp.path().join("input.wir"); + let output = tmp.path().join("output.wir"); + let source = include_str!("../ir/tests/fixtures/wave-control-v3.wir"); + fs::write(&input, source).unwrap(); + let input_name = input.to_str().unwrap(); + let output_name = output.to_str().unwrap(); + let complete = run(&["ir", "print", input_name]); + assert!(complete.status.success(), "{complete:?}"); + let exact = complete.stdout.len().to_string(); + let short = (complete.stdout.len() - 1).to_string(); + let result = run(&["ir", "print", input_name, "--max-output", &exact]); + assert!(result.status.success(), "{result:?}"); + assert_eq!(result.stdout, complete.stdout); + let result = run(&["ir", "print", input_name, "--max-output", &short]); + assert_eq!(result.status.code(), Some(1), "{result:?}"); + assert!(result.stdout.len() < complete.stdout.len()); + assert!(String::from_utf8_lossy(&result.stderr).contains("output limit"), "{result:?}"); + for limit in ["0", "1", &short] { + fs::write(&output, b"keep previous output").unwrap(); + let result = run(&["ir", "print", input_name, "-o", output_name, "--max-output", limit]); + assert_eq!(result.status.code(), Some(1), "{result:?}"); + assert_eq!(fs::read(&output).unwrap(), b"keep previous output"); + assert_eq!(fs::read_to_string(&input).unwrap(), source); + assert_eq!(fs::read_dir(tmp.path()).unwrap().count(), 2); + } + let result = run(&["ir", "print", input_name, "-o", output_name, "--max-output", &exact]); + assert!(result.status.success(), "{result:?}"); + assert_eq!(fs::read(&output).unwrap(), complete.stdout); + for args in [ + vec!["--max-output"], + vec!["--max-output", "-1"], + vec!["--max-output", "+1"], + vec!["--max-output", "18446744073709551616"], + vec!["--max-output", "1", "--max-output", "2"], + ] { + let mut command = vec!["ir", "print", input_name]; + command.extend(args); + assert!(!run(&command).status.success()); + } +} + #[test] fn run_executes_exact_arguments_and_reports_traps_fuel_and_unsupported_operations() { let tmp = tempfile::tempdir().unwrap(); @@ -165,3 +209,31 @@ fn run_executes_exact_arguments_and_reports_traps_fuel_and_unsupported_operation String::from_utf8_lossy(&result.stderr).contains("unsupported interpreter operation load") ); } + +#[cfg(feature = "socket-cli")] +#[test] +fn ast_lowering_streams_with_the_same_exact_publication_ceiling() { + let tmp = tempfile::tempdir().unwrap(); + let input = tmp.path().join("input.json"); + let output = tmp.path().join("output.wir"); + let source = include_str!("../ir/tests/fixtures/ast-v2-u128.json"); + fs::write(&input, source).unwrap(); + let input_name = input.to_str().unwrap(); + let output_name = output.to_str().unwrap(); + let complete = run(&["ir", "lower", input_name]); + assert!(complete.status.success(), "{complete:?}"); + let exact = complete.stdout.len().to_string(); + let short = (complete.stdout.len() - 1).to_string(); + fs::write(&output, b"previous IR").unwrap(); + let failed = run(&["ir", "lower", input_name, "--max-output", &short, "-o", output_name]); + assert_eq!(failed.status.code(), Some(1), "{failed:?}"); + assert!(String::from_utf8_lossy(&failed.stderr).contains("output limit"), "{failed:?}"); + assert_eq!(fs::read(&output).unwrap(), b"previous IR"); + assert_eq!(fs::read_to_string(&input).unwrap(), source); + assert_eq!(fs::read_dir(tmp.path()).unwrap().count(), 2); + let published = run(&["ir", "lower", input_name, "--max-output", &exact, "-o", output_name]); + assert!(published.status.success(), "{published:?}"); + assert_eq!(fs::read(&output).unwrap(), complete.stdout); + let verified = run(&["ir", "verify", output_name]); + assert!(verified.status.success(), "{verified:?}"); +} diff --git a/tools/build_wave_ir.py b/tools/build_wave_ir.py new file mode 100644 index 0000000..6369515 --- /dev/null +++ b/tools/build_wave_ir.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Build the internal Wave IR module with the pinned compiler, without editing Wave.""" + +import argparse +import hashlib +import json +import os +from pathlib import Path +import tempfile + +from wave_bootstrap import (DEFAULT_RUST_TOOLCHAIN, RUST_VERSION, WAVE_REVISION, + digest, ensure_bootstrap, run) + + +SOURCES = ("model.wave", "layout.wave", "lexer.wave", "header.wave", "type_parser.wave", + "literal.wave", "expression_parser.wave", "instruction_parser.wave", "module_parser.wave", "lower_hir.wave", + "lower_model.wave", "lower_output.wave", "lower_expression.wave", "lower_storage.wave", "lower_statement.wave", "lower_driver.wave", "builder.wave", "builder_namespace.wave", "builder_body.wave", + "verify.wave", "verifier_index.wave", "verifier_ssa.wave", "printer.wave", + "cfg.wave", "shape.wave", "source.wave", "lower_limits.wave", "entry.wave") +ABI_SOURCES = ("ir/src/wave_layout.rs", "ir/src/source_wave.rs", "ir/src/lower_ast/wave_limits.rs", "ir/src/parser/wave_lexer.rs", "ir/src/parser/wave_header.rs", + "ir/src/parser/wave_text.rs", "ir/src/parser/wave_type.rs", + "ir/src/parser/wave_literal.rs", "ir/src/parser/wave_expression.rs", + "ir/src/parser/wave_instruction.rs", + "ir/src/parser/wave_module.rs", + "ir/src/lower_ast/wave_hir.rs", + "ir/src/lower_ast/wave_lower.rs", + "ir/src/builder/wave.rs", + "ir/src/builder/namespace.rs", + "ir/src/builder/body.rs", + "ir/src/verifier/wave_semantics.rs", + "ir/src/verifier/wave_index.rs", + "ir/src/verifier/wave_ssa.rs", + "ir/src/printer_wave.rs", + "ir/src/verifier/wave_cfg.rs", "ir/src/verifier/wave_shape.rs") +TARGETS = ("x86_64-unknown-linux-gnu", "aarch64-unknown-linux-gnu", + "riscv64gc-unknown-linux-gnu", "x86_64-pc-windows-msvc", + "aarch64-pc-windows-msvc", "x86_64-apple-darwin", "aarch64-apple-darwin") + + +def fnv64(data): + value = 0xcbf29ce484222325 + for octet in data: + value = ((value ^ octet) * 0x100000001b3) & 0xffffffffffffffff + return f"{value:016x}" + + +def source_bytes(root): + return b"\n".join((root / "ir" / name).read_bytes() for name in SOURCES) + + +def abi_bytes(root): + return b"\n".join((root / name).read_bytes() for name in ABI_SOURCES) + + +def metadata(source, abi, archive, provenance, target, opt_level): + return (f"schema=1\ntarget={target}\nwave_revision={WAVE_REVISION}\n" + f"opt_level={opt_level}\nsource_fnv64={fnv64(source)}\n" + f"abi_fnv64={fnv64(abi)}\narchive_fnv64={fnv64(archive)}\n" + f"provenance_fnv64={fnv64(provenance)}\n") + + +def build(args): + root = Path(__file__).resolve().parents[1] + output = args.out_dir.resolve() + source = source_bytes(root) + abi = abi_bytes(root) + wave_source = args.wave_source.resolve() + if output == wave_source or output.is_relative_to(wave_source): + raise ValueError("Wave IR output must be outside the read-only Wave checkout") + output.mkdir(parents=True, exist_ok=True) + bootstrap = ensure_bootstrap(wave_source, args.bootstrap_dir or output / "bootstrap-cache", + rust_toolchain=args.rust_toolchain, + allow_network=args.allow_network) + wave_target = args.target.replace("riscv64gc-", "riscv64-") + environment = os.environ.copy() + environment["WAVE_STD_REVISION"] = WAVE_REVISION + with tempfile.TemporaryDirectory(prefix=".wave-ir-", dir=output) as temporary: + temporary = Path(temporary) + kernel = temporary / "ir.wave" + kernel.write_bytes(source) + obj = temporary / "ir.o" + run([bootstrap.compiler, "-O" + args.opt_level, "-C", "relocation-model=pic", + "--std-root", bootstrap.std_root, "--target=" + wave_target, "build", kernel, + "--freestanding", "--emit=obj", "-o", obj, "--target-dir", temporary / "build"], + cwd=temporary, env=environment) + name = "whale_wave_ir.lib" if "msvc" in args.target else "libwhale_wave_ir.a" + archive = temporary / name + archive_format = ("darwin" if "apple-darwin" in args.target else + "coff" if "msvc" in args.target else None) + archiver = [environment.get("AR", "ar")] + if archive_format: + archiver.append("--format=" + archive_format) + run([*archiver, "crsD", archive, obj]) + provenance = temporary / "provenance.json" + provenance.write_text(json.dumps({ + "wave_revision": WAVE_REVISION, "target": args.target, + "opt_level": args.opt_level, + "source_sha256": hashlib.sha256(source).hexdigest(), + "abi_sha256": hashlib.sha256(abi).hexdigest(), + "archive_sha256": digest(archive), + "compiler_sha256": digest(bootstrap.compiler), + "std_sha256": bootstrap.metadata["std_sha256"], + "bootstrap_rust_version": RUST_VERSION, + "required_llvm_major": 21, + "bootstrap_provenance": str(bootstrap.provenance), + }, indent=2) + "\n") + fingerprint = temporary / "wave-ir.meta" + fingerprint.write_text(metadata(source, abi, archive.read_bytes(), + provenance.read_bytes(), args.target, args.opt_level)) + staged = (archive, provenance, fingerprint) + previous = {} + for path in staged: + destination = output / path.name + if destination.exists(): + backup = temporary / (path.name + ".previous") + os.link(destination, backup) + previous[destination] = backup + published = [] + try: + for path in staged: + destination = output / path.name + os.replace(path, destination) + published.append(destination) + except OSError: + for destination in reversed(published): + backup = previous.get(destination) + if backup is None: + destination.unlink() + else: + os.replace(backup, destination) + raise + return output + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--wave-source", type=Path, required=True) + parser.add_argument("--out-dir", type=Path, required=True) + parser.add_argument("--bootstrap-dir", type=Path) + parser.add_argument("--rust-toolchain", default=DEFAULT_RUST_TOOLCHAIN) + parser.add_argument("--target", choices=TARGETS, default=TARGETS[0]) + parser.add_argument("--opt-level", choices=("0", "2"), default="2") + parser.add_argument("--allow-network", action="store_true") + args = parser.parse_args() + print(f"WHALE_WAVE_IR_DIR={build(args)}") + + +if __name__ == "__main__": + main() diff --git a/tools/check_wave_hir_fixture.py b/tools/check_wave_hir_fixture.py new file mode 100644 index 0000000..b93ba91 --- /dev/null +++ b/tools/check_wave_hir_fixture.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Reproduce the scalar fixture using actual immutable Wave TypedProgram facts.""" +import argparse +import hashlib +import io +import json +import os +from pathlib import Path +import subprocess +import tarfile +import tempfile + +from wave_bootstrap import DEFAULT_RUST_TOOLCHAIN, RUST_VERSION, WAVE_REVISION + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--wave-source", type=Path, required=True) + parser.add_argument("--target-dir", type=Path, required=True) + parser.add_argument("--rust-toolchain", default=DEFAULT_RUST_TOOLCHAIN) + parser.add_argument("--update", action="store_true") + args = parser.parse_args() + root = Path(__file__).resolve().parents[1] + repository = args.wave_source.resolve() + output = args.target_dir.resolve() + if output == repository or output.is_relative_to(repository): + raise ValueError("HIR fixture output must be outside the read-only Wave checkout") + output.mkdir(parents=True, exist_ok=True) + revision = subprocess.check_output( + ["git", "-C", str(repository), "rev-parse", WAVE_REVISION + "^{commit}"], text=True).strip() + if revision != WAVE_REVISION: + raise ValueError("pinned Wave commit is unavailable") + rustc = subprocess.check_output( + ["rustup", "which", "--toolchain", args.rust_toolchain, "rustc"], text=True).strip() + version = subprocess.check_output([rustc, "--version"], text=True).strip() + if not version.startswith("rustc " + RUST_VERSION + " "): + raise ValueError("the pinned frontend requires Rust " + RUST_VERSION) + archive = subprocess.check_output( + ["git", "-C", str(repository), "archive", "--format=tar", WAVE_REVISION]) + environment = os.environ.copy() + environment.update(CARGO_NET_OFFLINE="true", CARGO_INCREMENTAL="0", RUSTUP_AUTO_INSTALL="0") + for name in ("CARGO_BUILD_TARGET", "WHALE_WAVE_IR_DIR", "WHALE_ASMOBJ_DIR"): + environment.pop(name, None) + with tempfile.TemporaryDirectory(prefix="wave-hir-fixture-", dir=output) as directory: + directory = Path(directory) + source = directory / "source" + source.mkdir() + with tarfile.open(fileobj=io.BytesIO(archive)) as tree: + tree.extractall(source, filter="data") + build = output / "build" + messages = subprocess.check_output( + ["cargo", "+" + args.rust_toolchain, "build", "--locked", "--offline", + "--jobs", "2", "--message-format=json", "--manifest-path", str(source / "Cargo.toml"), + "--target-dir", str(build), "-p", "hir", "-p", "parser"], + text=True, env=environment) + dependencies = build / "debug" / "deps" + libraries = {} + for line in messages.splitlines(): + message = json.loads(line) + if message.get("reason") != "compiler-artifact": + continue + name = message["target"]["name"] + if name in ("hir", "parser"): + paths = [Path(path) for path in message["filenames"] if path.endswith(".rlib")] + if len(paths) != 1: + raise ValueError("HIR compiler artifact requires one library: " + name) + libraries[name] = paths[0] + if set(libraries) != {"hir", "parser"}: + raise ValueError("Cargo omitted pinned HIR/parser library artifacts") + binary = directory / "wave-hir-fixture" + exporter = root / "tools" / "wave_hir_fixture.rs" + subprocess.run([rustc, "--edition=2021", str(exporter), "--extern", + "hir=" + str(libraries["hir"]), "--extern", + "parser=" + str(libraries["parser"]), "-L", + "dependency=" + str(dependencies), "-o", str(binary)], check=True, env=environment) + actual = json.loads(subprocess.check_output([str(binary)], env=environment)) + if actual["wave_revision"] != WAVE_REVISION: + raise ValueError("fixture exporter revision differs from the pinned source") + data = (json.dumps(actual, indent=2) + "\n").encode() + fixture = root / "ir" / "tests" / "fixtures" / "wave_typed_hir_scalar.json" + if args.update: + fixture.write_bytes(data) + elif fixture.read_bytes() != data: + raise ValueError("checked-in Wave TypedProgram fixture differs from the pinned frontend") + (output / "provenance.json").write_text(json.dumps({ + "wave_revision": WAVE_REVISION, + "source_archive_sha256": hashlib.sha256(archive).hexdigest(), + "exporter_sha256": hashlib.sha256(exporter.read_bytes()).hexdigest(), + "fixture_sha256": hashlib.sha256(data).hexdigest(), + "rustc": version, + }, indent=2) + "\n") + print("Pinned Wave TypedProgram scalar fixture reproduced") + + +if __name__ == "__main__": + main() diff --git a/tools/check_wave_ir_ast_limits.py b/tools/check_wave_ir_ast_limits.py new file mode 100644 index 0000000..b5b3a39 --- /dev/null +++ b/tools/check_wave_ir_ast_limits.py @@ -0,0 +1,288 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Independent native AST admission, numeric syntax and source-table oracle.""" + +import argparse +import ctypes as C +import random + +MASK = (1 << 64) - 1 + + +class State(C.Structure): + _fields_ = [(name, C.c_uint64) for name in + ("nodes", "strings", "features", "numbers", "sources", "work")] + + +class Event(C.Structure): + _fields_ = [(name, C.c_uint64) for name in ("tag", "a", "b", "c", "d", "e", "f")] + _fields_ += [("bytes", C.POINTER(C.c_uint8)), ("length", C.c_uint64)] + + +class Slot(C.Structure): + _fields_ = [("id", C.c_uint64), ("occupied", C.c_uint64)] + + +class Result(C.Structure): + _fields_ = [("status", C.c_uint64)] + + +def fields(value): + return tuple(getattr(value, name) for name, _ in State._fields_) + + +def mix(value): + value = ((value ^ (value >> 30)) * 13787848793156543929) & MASK + value = ((value ^ (value >> 27)) * 10723151780598845931) & MASK + return value ^ (value >> 31) + + +class Kernel: + def __init__(self, library): + self.library = C.CDLL(library) + self.step = self.library.whale_ir_ast_inspect_step + self.step.restype = C.c_int32 + self.step.argtypes = [C.POINTER(State), C.POINTER(Event), C.c_uint64, + C.c_uint64, C.c_uint64, C.c_uint64, + C.POINTER(Slot), C.c_uint64, C.POINTER(Result)] + self.rehash = self.library.whale_ir_ast_inspect_rehash + self.rehash.restype = C.c_int32 + self.rehash.argtypes = [C.POINTER(State), C.POINTER(Slot), C.c_uint64, + C.POINTER(Slot), C.c_uint64, C.c_uint64, + C.POINTER(Result)] + + def event(self, state, tag, a=0, b=0, c=0, d=0, e=0, f=0, text=b"", + slots=None, depth=32, nodes=1000000, strings=1000000, work=10000000, + null_bytes=False): + data = (C.c_uint8 * len(text))(*text) + event = Event(tag, a, b, c, d, e, f, + None if null_bytes else data, len(text)) + result = Result(MASK) + status = self.step(C.byref(state), C.byref(event), depth, nodes, strings, + work, slots, len(slots) if slots is not None else 0, + C.byref(result)) + assert status == result.status, (tag, status, result.status) + return status + + def grow(self, state, old, capacity, work=10000000): + output = (Slot * capacity)() + result = Result(MASK) + status = self.rehash(C.byref(state), old, len(old) if old is not None else 0, + output, capacity, work, C.byref(result)) + assert status == result.status + return status, output + + +def numeric_oracle(tag, width, text): + valid = width in ((1, 8, 16, 32, 64, 128) if tag in (4, 6) else (16, 32, 64)) + if tag == 6: + digits = text[1:] if text.startswith(b"-") else text + valid = valid and bool(digits) and all(48 <= byte <= 57 for byte in digits) + if tag == 7: + valid = (valid and len(text) == 2 + width // 4 and text.startswith(b"0x") + and all(byte in b"0123456789abcdefABCDEF" for byte in text[2:])) + return valid + + +def numeric_cases(kernel, count): + fixed = [b"", b"-", b"+1", b"1", b"-0", b"000", b"-999", b" 1", b"1_0", + b"0x10", b"1\0", "12".encode(), b"0xFFFF", b"0xffff", b"0XFFFF", + b"0x00000000", b"0x0000000000000000", b"0xgggg", b"0x123"] + rng = random.Random(0x335_a57) + for index in range(count + len(fixed) * 4 * 12): + if index < len(fixed) * 4 * 12: + text = fixed[index % len(fixed)] + tag = 4 + (index // len(fixed)) % 4 + width = (0, 1, 7, 8, 16, 24, 32, 64, 80, 128, 256, MASK)[index // (len(fixed) * 4)] + else: + tag = rng.randrange(4, 8) + width = rng.choice((0, 1, 8, 16, 32, 64, 128, MASK)) + text = bytes(rng.choice(b"-+0123456789abcdefABCDEFxX_g \0") for _ in range(rng.randrange(30))) + state = State(numbers=1) + assert kernel.event(state, tag, width, text=text) == 0 + assert bool(state.numbers) == numeric_oracle(tag, width, text), (tag, width, text) + assert state.strings == (len(text) if tag >= 6 else 0) + assert state.nodes == state.sources == state.work == state.features == 0 + state = State(numbers=1) + assert kernel.event(state, 6, 32, text=b"bad") == 0 and state.numbers == 0 + assert kernel.event(state, 6, 32, text=b"123") == 0 and state.numbers == 0 + for tag in (6, 7): + state = State(numbers=1) + assert kernel.event(state, tag, 32, text=b"12345", strings=4) == 4 + assert state.strings == 0 + assert kernel.event(State(numbers=1), tag, 32, text=b"1", null_bytes=True) == 8 + + +def basic_cases(kernel): + state = State(numbers=1) + assert kernel.event(state, 0, nodes=2) == 0 + assert kernel.event(state, 1, 32, nodes=2) == 0 + assert kernel.event(state, 0, nodes=2) == 3 and state.nodes == 2 + for depth, actual in ((0, 1), (3, 4), (32, 33), (MASK, 33)): + state = State(numbers=1) + assert kernel.event(state, 1, actual, depth=depth) == 2 + assert state.nodes == 0 + for length in (0, 1, 17, 1000): + state = State(numbers=1) + assert kernel.event(state, 2, text=b"x" * length, strings=length) == 0 + assert state.strings == length + assert kernel.event(state, 2, text=b"!", strings=length) == 4 + assert state.strings == length + state = State(numbers=1) + for form in (1, 2, 3): + assert kernel.event(state, 3, form) == 0 and state.features == 4 + assert kernel.event(state, 3, 4) == 0 and state.features == 5 + for op in range(12): + state = State(numbers=1) + assert kernel.event(state, 3, 5, op) == 0 + assert state.features == (0 if op < 3 else 1) + for form, op in ((0, 0), (6, 0), (5, 12), (5, MASK)): + assert kernel.event(State(numbers=1), 3, form, op) == 8 + assert kernel.event(State(numbers=1), 9) == 8 + for name, value in (("numbers", 2), ("features", 8), ("nodes", 1000001), + ("strings", 1000001), ("work", 10000001)): + state = State(numbers=1) + setattr(state, name, value) + assert kernel.event(state, 0) == 8, name + + +def insert_reference(table, identity): + at = mix(identity) & (len(table) - 1) + probes = 1 + while table[at] is not None and table[at] != identity: + at = (at + 1) & (len(table) - 1) + probes += 1 + duplicate = table[at] is not None + table[at] = identity + return probes, duplicate + + +def source_cases(kernel, count=60000): + state = State(numbers=1) + slots = None + reference = [] + expected_work = 0 + ids = [] + for index in range(count): + identity = ((index + 1) * 0x9e3779b97f4a7c15) & MASK + ids.append(identity) + needed = 2 + while needed < (index + 1) * 2: + needed *= 2 + if needed > len(reference): + old = reference + reference = [None] * needed + expected_work += needed + for entry in old: + if entry is not None: + probes, duplicate = insert_reference(reference, entry) + assert not duplicate + expected_work += probes + status, slots = kernel.grow(state, slots, needed) + assert status == 0 + assert state.work == expected_work + assert [(slot.id if slot.occupied else None) for slot in slots] == reference + assert kernel.event(state, 0) == 0 + probes, duplicate = insert_reference(reference, identity) + assert not duplicate + expected_work += probes + assert kernel.event(state, 8, identity, slots=slots) == 0 + assert (state.sources, state.nodes, state.features, state.work) == (index + 1, index + 1, 2, expected_work) + assert state.sources == count + before = state.sources + probes, duplicate = insert_reference(reference, ids[count // 2]) + assert duplicate + expected_work += probes + assert kernel.event(state, 8, ids[count // 2], slots=slots) == 1 + assert state.sources == before and state.work == expected_work + assert [(slot.id if slot.occupied else None) for slot in slots] == reference + + # A growth and the following insert share one cumulative work account. + state = State(numbers=1) + status, slots = kernel.grow(state, None, 4, work=5) + assert status == 0 and state.work == 4 + assert kernel.event(state, 0, work=5) == 0 + assert kernel.event(state, 8, 1, slots=slots, work=5) == 0 + assert state.sources == 1 and state.work == 5 + assert kernel.event(state, 0, work=5) == 0 + assert kernel.event(state, 8, 2, slots=slots, work=5) == 7 + assert state.sources == 1 and state.work == 5 + failed = State(numbers=1) + assert kernel.grow(failed, None, 8, work=7)[0] == 7 + assert failed.work == 7 + + # Filename bytes spend the same cumulative source budget as rehash/probes. + for available in (5, 6): + state = State(numbers=1, nodes=1) + status, slots = kernel.grow(state, None, 2, work=available) + assert status == 0 and state.work == 2 + status = kernel.event(state, 8, 1, 1, 1, 1, 1, 1, text=b"abc", slots=slots, work=available) + assert status == (7 if available == 5 else 0) + assert state.work == (3 if available == 5 else 6) + state = State(numbers=1, nodes=1) + slots = (Slot * 2)() + assert kernel.event(state, 8, 1, 1, 1, 1, 1, 1, text=b"x\0y", slots=slots) == 1 + assert state.work == 4 + + # Force multiple colliding identities to exercise exact bounded probing. + bucket = mix(0) & 7 + collisions = [identity for identity in range(1000) if mix(identity) & 7 == bucket][:4] + state = State(numbers=1) + status, slots = kernel.grow(state, None, 8) + assert status == 0 + for ordinal, identity in enumerate(collisions): + assert kernel.event(state, 0) == 0 + before = state.work + assert kernel.event(state, 8, identity, slots=slots) == 0 + assert state.work - before == ordinal + 1 + + +def source_errors(kernel): + spans = [(b"a.wave", 1, 1, 1, 1, 0), (b"a.wave", 1, 9, 2, 1, 0), + (b"", 1, 1, 1, 1, 1), (b"x\0y", 1, 1, 1, 1, 1), + (b"a", 0, 1, 1, 1, 1), (b"a", 1, 0, 1, 1, 1), + (b"a", 1, 1, 0, 1, 1), (b"a", 1, 1, 1, 0, 1), + (b"a", 2, 1, 1, 9, 1), (b"a", 1, 9, 1, 1, 1)] + for text, line, column, end_line, end_column, status in spans: + state = State(numbers=1, nodes=1) + slots = (Slot * 2)() + assert kernel.event(state, 8, MASK, 1, line, column, end_line, end_column, + text=text, slots=slots) == status + for capacity in (0, 1, 3): + state = State(numbers=1) + assert kernel.event(state, 8, 1, slots=(Slot * capacity)()) == 8 + assert kernel.grow(state, None, capacity)[0] == 8 + state = State(numbers=1, nodes=1) + assert kernel.event(state, 8, 1, 2, slots=(Slot * 4)()) == 8 + assert kernel.event(State(numbers=1), 8, 1, 1, 1, 1, 1, 1, text=b"a", + slots=(Slot * 4)(), null_bytes=True) == 8 + bad = (Slot * 2)(Slot(1, 2), Slot()) + assert kernel.grow(State(numbers=1), bad, 4)[0] == 8 + duplicate = (Slot * 2)(Slot(3, 1), Slot(3, 1)) + assert kernel.grow(State(numbers=1, sources=2), duplicate, 4)[0] == 8 + assert kernel.grow(State(numbers=1, sources=1), None, 4)[0] == 8 + assert kernel.grow(State(numbers=1), (Slot * 8)(), 4)[0] == 8 + # Capacity and null pointer validation must happen before dereferencing. + result = Result() + assert kernel.rehash(None, None, 0, None, 4, 100, C.byref(result)) == 8 + assert kernel.step(None, None, 32, 100, 100, 100, None, 0, C.byref(result)) == 8 + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", required=True) + parser.add_argument("--cases", type=int, default=10000) + args = parser.parse_args() + if args.cases < 0: + parser.error("--cases must be nonnegative") + kernel = Kernel(args.library) + basic_cases(kernel) + numeric_cases(kernel, args.cases) + source_errors(kernel) + source_cases(kernel) + print(f"Wave AST admission: {args.cases} numeric mutations, widths/features/limits, " + "source errors and 60000 independently rehashed source identities passed") + + +if __name__ == "__main__": + main() diff --git a/tools/check_wave_ir_body.py b/tools/check_wave_ir_body.py new file mode 100644 index 0000000..d9aa019 --- /dev/null +++ b/tools/check_wave_ir_body.py @@ -0,0 +1,284 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Native complete body inventory, hoisting and transactional mutation oracle.""" + +import argparse +import ctypes as C +import random + +NONE = (1 << 64) - 1 + + +class Atom(C.Structure): + _fields_ = [(name, C.c_uint64) for name in ("kind", "a", "b", "c")] + + +class Record(C.Structure): + _fields_ = [(name, C.c_uint64) for name in + ("op", "block", "first", "count", "byte_first", "byte_count", "next")] + + +class GlobalRecord(C.Structure): + _fields_ = [(name, C.c_uint64) for name in ("id", "first", "count", "byte_first", "byte_count")] + + +class Block(C.Structure): + _fields_ = [(name, C.c_uint64) for name in ("head", "tail", "count", "terminator", "prefix_tail", "prefix_count")] + + +class State(C.Structure): + _fields_ = [(name, C.c_uint64) for name in ("atoms", "bytes", "records", "globals", "work")] + + +class Result(C.Structure): + _fields_ = [(name, C.c_uint64) for name in ("status", "detail", "ordinal", "work")] + + +def uint(value=1): + return (0, value, 0, 0) + + +def ty(kind=6, children=0, auxiliary=0): + return (3, kind, children, auxiliary) + + +def const(value=7): + return (1, 1, value & NONE, (value >> 64) & NONE) + + +def fixture(op): + u, t = uint(), ty() + literal = const() + text = "λ🐋\0 reason".encode() + string = (2, 0, len(text), 0) + expression = [(4, 5, 0, 2), t, (4, 0, 0, 0), t, const(3), (4, 0, 0, 0), t, const(4)] + signature = [ty(18, 2, 1), ty(0), ty(17, 1), ty(0)] + samples = { + 0: [u, u, t], 1: [u], 2: [u, u, u], 3: [u, string, *expression, literal], + 4: [u, t, literal], 5: [u, t], 6: [u, t, u], + 7: [u, uint(17), t, u, u], 8: [u, t, u], 9: [u, t, u], + 10: [u, uint(15), t, u, u], 11: [u, uint(9), t, u, u], + 12: [u, uint(13), ty(14), u, u], 13: [u, t, u, u, u], + 14: [u, uint(12), ty(8), ty(13), u], + 15: [u, t, (5, 1, 2, 0), u, uint(0), u, uint(4)], + 16: [u, t, u, uint((1 << 32) - 1)], 17: [u, uint(5), t, u, u], + 18: [u, ty(20, 2), ty(19, 1, NONE), ty(9), *signature, uint(64)], + 19: [u, t, u, uint(16)], 20: [t, u, u, uint(16)], + 21: [u, t, u, uint(16)], 22: [t, u, uint(16)], 23: [t, u, u, uint(16)], + 24: [u, ty(17, 1), t, u, (5, 0, 2, 0), uint(0), uint(5)], + 25: [u, u, u, uint(8)], 26: [u, u, u, uint(8)], + 27: [u, *signature], 28: [u, u, *signature], + 29: [uint(1), u, t, uint(1), uint(1), u, (5, 0, 2, 0), u, uint(7)], + 30: [u, string], 31: [uint(4)], 32: [u, uint(0), uint(4)], + 33: [ty(13), u, uint(0), (5, 2, 2, 0), (1, 2, NONE, NONE), uint(4), (1, 2, 0, 0), uint(2)], + 34: [t, uint(1), u], 35: [string], + } + return samples[op], text if op in (3, 30, 35) else b"" + + +class Store: + def __init__(self, kernel, atom_capacity=2048, byte_capacity=4096, record_capacity=128): + self.kernel = kernel + self.state = State() + self.blocks = (Block * 5)(*(Block(NONE, NONE, 0, NONE, NONE, 0) for _ in range(5))) + self.atoms = (Atom * atom_capacity)() + self.bytes = (C.c_uint8 * byte_capacity)() + self.records = (Record * record_capacity)() + self.globals = (GlobalRecord * record_capacity)() + + def snapshot(self): + return tuple(bytes(value) for value in + (self.state, self.blocks, self.atoms, self.bytes, self.records, self.globals)) + + def append(self, op, atoms, text=b"", block=0, hoist=0, mode=1, work=1_000_000, + nodes=100000, byte_limit=100000, capacity=None): + atoms = (Atom * len(atoms))(*(Atom(*atom) for atom in atoms)) + text = (C.c_uint8 * len(text))(*text) + result = Result() + before = self.snapshot() + status = self.kernel(C.byref(self.state), self.blocks, len(self.blocks), block, + op, hoist, atoms, len(atoms), text, len(text), 257, 256, + nodes, byte_limit, work, mode, + self.atoms, len(self.atoms) if capacity is None else capacity, + self.bytes, len(self.bytes), self.records, len(self.records), + C.byref(result)) + assert status == result.status + if status or mode == 0: + assert self.snapshot() == before, (op, status, "partial publication") + else: + old = State.from_buffer_copy(before[0]) + assert self.state.atoms == old.atoms + len(atoms) + assert self.state.bytes == old.bytes + len(text) + assert self.state.records == old.records + 1 + assert self.state.work == old.work + result.work <= work + for index, atom in enumerate(atoms): + expected = (atom.kind, atom.a + old.bytes if atom.kind == 2 else atom.a, atom.b, atom.c) + actual = self.atoms[old.atoms + index] + assert tuple(getattr(actual, name) for name, _ in Atom._fields_) == expected + assert bytes(self.bytes[old.bytes:self.state.bytes]) == bytes(text) + record = self.records[old.records] + assert (record.op, record.block, record.first, record.count, + record.byte_first, record.byte_count) == (op, block, old.atoms, len(atoms), old.bytes, len(text)) + return status, result + + +def global_cases(library, count): + kernel = library.whale_ir_builder_global + kernel.restype = C.c_int32 + kernel.argtypes = [C.POINTER(State), C.c_uint64, C.POINTER(GlobalRecord), C.c_uint64, + C.POINTER(Atom), C.c_uint64, C.POINTER(C.c_uint8), C.c_uint64, + *([C.c_uint64] * 6), C.POINTER(Atom), C.c_uint64, + C.POINTER(C.c_uint8), C.c_uint64, C.POINTER(Result)] + def append(store, identity, payload, text, mode=1, nodes=100000, byte_limit=100000, + work=1000000, capacity=None): + atoms = (Atom * len(payload))(*(Atom(*atom) for atom in payload)) + data = (C.c_uint8 * len(text))(*text) + result = Result() + before = store.snapshot() + status = kernel(C.byref(store.state), identity, store.globals, + len(store.globals) if capacity is None else capacity, + atoms, len(atoms), data, len(data), 257, 256, nodes, byte_limit, work, + mode, store.atoms, len(store.atoms), store.bytes, len(store.bytes), C.byref(result)) + assert status == result.status + if status or mode == 0: + assert store.snapshot() == before, (status, "partial global publication") + else: + old = State.from_buffer_copy(before[0]) + assert (store.state.atoms, store.state.bytes, store.state.records, store.state.globals, + store.state.work) == (old.atoms + len(atoms), old.bytes + len(data), old.records, + old.globals + 1, old.work + result.work) + record = store.globals[old.globals] + assert (record.id, record.first, record.count, record.byte_first, record.byte_count) == ( + identity, old.atoms, len(atoms), old.bytes, len(data)) + for index, atom in enumerate(atoms): + expected = (atom.kind, atom.a + old.bytes if atom.kind == 2 else atom.a, atom.b, atom.c) + actual = store.atoms[old.atoms + index] + assert tuple(getattr(actual, name) for name, _ in Atom._fields_) == expected + assert bytes(store.bytes[old.bytes:store.state.bytes]) == text + return status + payload, text = fixture(3) + payload = [*payload[1:], uint(32)] + store = Store(library.whale_ir_builder_body) + assert append(store, 0, payload, text, mode=0) == 0 + assert append(store, 0, payload, text) == 0 + assert append(store, 2, payload, text) == 0 + assert append(store, 2, payload, text) == 1 + assert append(store, 1, payload, text) == 1 + assert append(store, NONE, payload, text) == 1 + assert append(Store(None), 0, payload, text, work=0) == 4 + assert append(Store(None), 0, payload, text, nodes=0) == 3 + assert append(Store(None), 0, payload, text, byte_limit=0) == 10 + assert append(Store(None), 0, payload, text, capacity=0) == 1 + for end in range(len(payload)): + assert append(Store(None), 0, payload[:end], text) != 0 + rng = random.Random(0x348_610b) + for _ in range(count): + mutation = [list(atom) for atom in payload] + mutation[rng.randrange(len(mutation))][rng.randrange(4)] ^= 1 << rng.randrange(64) + append(Store(None, atom_capacity=128, byte_capacity=64, record_capacity=4), + 0, mutation, text, work=10000) + + +def large_hoists(kernel, count=60000): + # No repeated array snapshots: this exercises the actual persistent body + # links with a work ceiling that excludes any quadratic prefix rescanning. + state = State() + blocks = (Block * 1)(Block(NONE, NONE, 0, NONE, NONE, 0)) + output = (Atom * (count * 3 + 3))() + records = (Record * (count + 2))() + result = Result() + def append(op, payload, hoist=0): + atoms = (Atom * len(payload))(*(Atom(*a) for a in payload)) + status = kernel(C.byref(state), blocks, 1, 0, op, hoist, atoms, len(atoms), + None, 0, 257, 256, count * 4, 0, count * 16 + 64, 1, + output, len(output), None, 0, records, len(records), C.byref(result)) + assert status == result.status == 0, (op, status, state.work) + return result.ordinal, result.work + append(5, [uint(), ty()]) + append(31, [uint(0)]) + cost = None + for index in range(count): + ordinal, work = append(18, [uint(index), ty(), uint(4)], hoist=1) + assert ordinal == index + if cost is None: + cost = work + assert cost == work + assert (blocks[0].prefix_count, blocks[0].count, blocks[0].prefix_tail, + blocks[0].head, blocks[0].tail, blocks[0].terminator) == (count, count + 1, count + 1, 2, 0, 1) + at = blocks[0].head + for index in range(count): + assert at == index + 2 and records[at].op == 18 + at = records[at].next + assert at == 0 and records[0].next == NONE + assert state.work <= count * 16 + 64 + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", required=True) + parser.add_argument("--cases", type=int, default=10000) + args = parser.parse_args() + assert args.cases >= 0 + library = C.CDLL(args.library) + kernel = library.whale_ir_builder_body + kernel.restype = C.c_int32 + kernel.argtypes = [C.POINTER(State), C.POINTER(Block), C.c_uint64, C.c_uint64, + C.c_uint64, C.c_uint64, C.POINTER(Atom), C.c_uint64, + C.POINTER(C.c_uint8), C.c_uint64, C.c_uint64, C.c_uint64, + C.c_uint64, C.c_uint64, C.c_uint64, C.c_uint64, + C.POINTER(Atom), C.c_uint64, C.POINTER(C.c_uint8), C.c_uint64, + C.POINTER(Record), C.c_uint64, C.POINTER(Result)] + large_hoists(kernel) + global_cases(library, args.cases) + store = Store(kernel) + for op in range(31): + atoms, text = fixture(op) + assert store.append(op, atoms, text)[0] == 0, op + for block, op in enumerate(range(31, 36)): + atoms, text = fixture(op) + assert store.append(op, atoms, text, block=block)[0] == 0, op + atoms, text = fixture(18) + status, result = store.append(18, atoms, text, hoist=1) + assert status == 0 and result.ordinal == 0 + chain, index = [], store.blocks[0].head + while index != NONE: + chain.append(store.records[index].op) + index = store.records[index].next + assert len(chain) <= 32 + assert chain == [18, *range(31)] + assert store.records[store.blocks[0].terminator].op == 31 + + for op in range(36): + atoms, text = fixture(op) + assert Store(kernel).append(op, atoms, text, mode=0)[0] == 0 + assert Store(kernel).append(op, atoms, text, work=0)[0] == 4 + assert Store(kernel).append(op, atoms, text, nodes=0)[0] == 3 + assert Store(kernel).append(op, atoms, text, capacity=0)[0] == 1 + for end in range(len(atoms)): + assert Store(kernel).append(op, atoms[:end], text)[0] != 0 + atoms, _ = fixture(35) + assert Store(kernel).append(35, atoms, b"\xff" * atoms[0][2])[0] == 1 + assert Store(kernel).append(35, atoms, b"x" * atoms[0][2], byte_limit=0)[0] == 10 + randomizer = random.Random(0x348_b0d1) + for _ in range(args.cases): + op = randomizer.randrange(36) + atoms, text = fixture(op) + atoms = [list(atom) for atom in atoms] + selected = randomizer.randrange(len(atoms)) + field = randomizer.randrange(4) + atoms[selected][field] ^= 1 << randomizer.randrange(64) + Store(kernel, atom_capacity=128, byte_capacity=64, record_capacity=4).append(op, atoms, text, work=10000) + # Normal appended allocas extend only the initial allocation prefix. + mixed = Store(kernel) + alloca = [uint(), ty(), uint(4)] + assert mixed.append(18, alloca)[0] == 0 + assert mixed.append(18, alloca, hoist=1)[0] == 0 + assert mixed.append(5, [uint(), ty()])[0] == 0 + assert mixed.append(18, alloca)[0] == 0 + status, result = mixed.append(18, alloca, hoist=1) + assert status == 0 and result.ordinal == 2 and mixed.blocks[0].prefix_count == 3 + print(f"Wave IR body: complete 36-form inventory, 60000 bounded hoists, global constexpr records, atomic limits and {args.cases} body/global mutations passed") + + +if __name__ == "__main__": + main() diff --git a/tools/check_wave_ir_builder.py b/tools/check_wave_ir_builder.py new file mode 100644 index 0000000..a4199c9 --- /dev/null +++ b/tools/check_wave_ir_builder.py @@ -0,0 +1,264 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Independent exact-type and transactional builder vectors for the Wave IR module.""" +import argparse +import ctypes as c +import random + + +class Node(c.Structure): + _fields_ = [(key, c.c_uint64) for key in ("kind", "depth", "children", "auxiliary")] + + +class Value(c.Structure): + _fields_ = [(key, c.c_uint64) for key in ("id", "first_type", "type_count")] + + +class Block(c.Structure): + _fields_ = [(key, c.c_uint64) for key in ("id", "terminated", "non_phi")] + + +class State(c.Structure): + _fields_ = [(key, c.c_uint64) for key in + ("next_value", "next_block", "type_count", "instruction_count", "namespace_nodes", + "namespace_bytes", "next_function", "next_global", "work")] + + +class Namespace(c.Structure): + _fields_ = [("kind", c.c_uint64), ("id", c.c_uint64), ("flags", c.c_uint64), + ("name", c.c_void_p), ("name_count", c.c_uint64), + ("link", c.c_void_p), ("link_count", c.c_uint64), + ("types", c.c_void_p), ("type_count", c.c_uint64), + ("defined", c.c_uint64), ("align", c.c_uint64), + ("initializer", c.c_uint64), ("low", c.c_uint64), ("high", c.c_uint64)] + + +class Result(c.Structure): + _fields_ = [(key, c.c_uint64) for key in ("status", "detail", "value", "work")] + + +def reference(nodes, depth=128, limit=1000000, work=1000000): + if not nodes: + return 1 + if len(nodes) > limit: + return 3 + if len(nodes) > work: + return 4 + pending = [0] + for index, (kind, actual_depth, children, auxiliary) in enumerate(nodes): + if not pending or actual_depth != pending.pop(): + return 1 + if actual_depth > min(depth, 256): + return 2 + if kind > 21 or (kind <= 16 and children): + return 1 + if kind in (17, 19) and children != 1: + return 1 + if kind == 18 and (children == 0 or auxiliary > 3): + return 1 + if children > len(nodes) - index - 1: + return 1 + if children and actual_depth == min(depth, 256): + return 2 + pending.extend([actual_depth + 1] * children) + return 1 if pending else 0 + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", required=True) + parser.add_argument("--cases", type=int, default=30000) + args = parser.parse_args() + library = c.CDLL(args.library) + check = library.whale_ir_builder_type + check.argtypes = [c.c_void_p, c.c_uint64, c.c_uint64, c.c_uint64, c.c_uint64, c.POINTER(Result)] + allocate = library.whale_ir_builder_allocate + allocate.argtypes = [c.c_void_p, c.c_uint64, c.c_void_p] + [c.c_uint64] * 5 + [c.c_void_p, c.c_uint64] * 3 + [c.POINTER(Result)] + order = library.whale_ir_builder_order + order.argtypes = [c.c_void_p, c.c_uint64, c.c_void_p] + [c.c_uint64] * 6 + [c.c_void_p, c.c_uint64, c.c_void_p] + [c.c_uint64] * 3 + [c.POINTER(Result)] + + def check_types(nodes, depth=128, limit=1000000, work=1000000): + array = (Node * len(nodes))(*(Node(*node) for node in nodes)) + result = Result() + status = check(array, len(nodes), depth, limit, work, c.byref(result)) + assert status == result.status + return status + + seeds = [[(kind, 0, 0, 0)] for kind in range(17)] + seeds += [[(17, 0, 1, 0), (6, 1, 0, 0)], + [(20, 0, 3, 0), (21, 1, 0, 0), (19, 1, 1, 7), (7, 2, 0, 0), (1, 1, 0, 0)], + [(18, 0, 3, 3), (0, 1, 0, 0), (17, 1, 1, 0), (9, 2, 0, 0), (16, 1, 0, 0)], + [], [(22, 0, 0, 0)], [(17, 0, 0, 0)], [(6, 0, 1, 0)], + [(20, 0, 1, 0)], [(18, 0, 1, 4), (0, 1, 0, 0)]] + rng = random.Random(348) + + def tree(depth=0): + kind = rng.choice(list(range(17)) + [17, 18, 19, 20, 21]) if depth < 7 else rng.randrange(17) + count = 1 if kind in (17, 19) else rng.randrange(1, 5) if kind == 18 else rng.randrange(5) if kind >= 20 else 0 + nodes = [(kind, depth, count, rng.randrange(4) if kind == 18 else rng.randrange(100) if kind == 19 else 0)] + for _ in range(count): + nodes.extend(tree(depth + 1)) + return nodes + + for nodes in seeds: + assert check_types(nodes) == reference(nodes), nodes + for _ in range(args.cases): + nodes = tree() + if rng.randrange(2): + index = rng.randrange(len(nodes)) + node = list(nodes[index]) + field = rng.randrange(4) + node[field] = rng.randrange(30) + nodes[index] = tuple(node) + depth = rng.randrange(10) + # Invalid over-wide child lists are detected before following children. + expected = reference(nodes, depth) + actual = check_types(nodes, depth) + assert actual == expected, (nodes, depth, expected, actual) + assert check_types([(6, 0, 0, 0)], limit=0) == 3 + assert check_types([(6, 0, 0, 0)], work=0) == 4 + deep = [(17, depth, 1, 0) for depth in range(256)] + [(6, 256, 0, 0)] + assert check_types(deep, depth=256) == 0 + assert check_types(deep, depth=255) == 2 + + capacity = 60001 + types = (Node * capacity)() + values = (Value * capacity)() + blocks = (Block * capacity)() + state = State() + scalar = (Node * 1)(Node(6, 0, 0, 0)) + + def reserve(kind, nodes=scalar, mode=1, node_limit=1000000, work=1000000, + type_capacity=capacity, value_capacity=capacity, block_capacity=capacity): + before = bytes(state), bytes(types[:1][0]), bytes(values[:1][0]), bytes(blocks[:1][0]) + result = Result() + status = allocate(c.byref(state), kind, nodes, len(nodes), 128, node_limit, work, mode, + types, type_capacity, values, value_capacity, blocks, block_capacity, c.byref(result)) + assert status == result.status + if status or mode == 0: + assert before == (bytes(state), bytes(types[:1][0]), bytes(values[:1][0]), bytes(blocks[:1][0])) + return status, result.value + + assert reserve(1) == (0, 0) + assert reserve(0, mode=0) == (0, 0) + assert reserve(0, type_capacity=0)[0] == 1 + assert reserve(0, node_limit=2)[0] == 3 + assert reserve(0, work=3)[0] == 4 + assert reserve(0) == (0, 0) + + def operation(op, operands=(), targets=(), query=0, first_block=0, first_value=0, + block=0, limit=1000000, work=1000000): + before = bytes(state), bytes(blocks[block]) + operands = (c.c_uint64 * len(operands))(*operands) + targets = (c.c_uint64 * len(targets))(*targets) + result = Result() + status = order(c.byref(state), limit, blocks, state.next_block, first_block, first_value, + state.next_value, block, op, operands, len(operands), targets, len(targets), + query, work, c.byref(result)) + assert status == result.status + if status or query: + assert before == (bytes(state), bytes(blocks[block])) + return status + + assert operation(15, (0,), (0,), query=1) == 0 + assert operation(4, query=1) == 0 + assert operation(4) == 0 + assert operation(15, (0,), (0,)) == 9 + assert operation(7, (0,)) == 1 + assert operation(7, (0, 1)) == 8 + assert operation(31, targets=(1,)) == 6 + assert operation(7, (0, 0), first_value=1) == 8 + assert operation(4, limit=4) == 3 + assert operation(33, (0,)) == 0 + assert operation(4) == 7 + assert operation(35, query=1, work=state.work) == 7 + assert operation(34, query=1, work=state.work) == 0 + assert operation(36) == 0 + assert blocks[0].terminated == 1 + # Allocation stress uses fixed-size data and should remain linear at O0/O2. + for index in range(1, 60000): + assert reserve(0) == (0, index) + assert state.next_value == 60000 + assert values[59999].first_type == 59999 + assert types[59999].kind == 6 + # Corrupt identity counters must never wrap or publish output. + state.next_value = 0xffffffff + assert reserve(0, node_limit=0xffffffffffffffff)[0] == 5 + namespace = library.whale_ir_builder_namespace + namespace.argtypes = [c.c_void_p, c.c_void_p, c.c_uint64, c.c_void_p] + [c.c_uint64] * 6 + [c.c_void_p, c.c_uint64, c.POINTER(Result)] + namespace_state = State() + entries = (Namespace * 128)() + payloads = [] + count = 0 + + def entry(kind, name, nodes, link=None, readonly=False, align=4, literal=0, low=0, high=0, + legacy=False, limit=1000000, byte_limit=1000000): + nonlocal count + name_raw = name.encode() + link_raw = None if link is None else link.encode() + name_buffer = c.create_string_buffer(name_raw) + link_buffer = None if link_raw is None else c.create_string_buffer(link_raw) + types = (Node * len(nodes))(*(Node(*node) for node in nodes)) + candidate = Namespace(kind, 0, (3 if link is not None else 0) | (4 if readonly else 0), + c.cast(name_buffer, c.c_void_p), len(name_raw), + None if link_buffer is None else c.cast(link_buffer, c.c_void_p), + 0 if link_raw is None else len(link_raw), c.cast(types, c.c_void_p), + len(nodes), 0, align, literal, low, high) + before = bytes(namespace_state), bytes(entries) + result = Result() + status = namespace(c.byref(namespace_state), entries, count, c.byref(candidate), 0, + int(legacy), 128, limit, byte_limit, 100000000, None, 0, c.byref(result)) + assert status == result.status + assert before == (bytes(namespace_state), bytes(entries)) + if status: + return status, result.value + status = namespace(c.byref(namespace_state), entries, count, c.byref(candidate), 1, + int(legacy), 128, limit, byte_limit, 100000000, entries, 128, c.byref(result)) + assert status == result.status == 0 + if result.detail == 0: + payloads.append((name_buffer, link_buffer, types)) + count += 1 + return status, result.value + + def signature(parameter=6, convention=0): + return [(18, 0, 2, convention), (0, 1, 0, 0), (parameter, 1, 0, 0)] + + assert entry(0, "foo", signature(), limit=2)[0] == 3 + assert entry(0, "foo", signature(), byte_limit=2)[0] == 19 + assert entry(0, "foo", signature()) == (0, 0) + assert entry(0, "foo", signature()) == (0, 0) + assert entry(0, "foo", signature(7))[0] == 12 + assert entry(0, "bar", signature(), link="symbol") == (0, 1) + assert entry(0, "baz", signature(), link="symbol")[0] == 11 + assert entry(0, "bad", signature(0))[0] == 17 + assert entry(0, "bad", signature(convention=2))[0] == 17 + assert entry(0, "bad", signature(), link="a\0b")[0] == 16 + assert entry(2, "data", [(6, 0, 0, 0)], literal=1, low=7) == (0, 0) + assert entry(1, "constant", [(6, 0, 0, 0)], legacy=True) == (0, 1) + assert entry(2, "constant", [(6, 0, 0, 0)])[0] == 10 + assert entry(2, "other", [(6, 0, 0, 0)], link="symbol")[0] == 11 + assert entry(2, "unaligned", [(6, 0, 0, 0)], align=3)[0] == 25 + assert entry(2, "readonly", [(6, 0, 0, 0)], readonly=True)[0] == 26 + assert entry(2, "range", [(2, 0, 0, 0)], literal=1, low=1)[0] == 27 + assert entry(2, "negative", [(2, 0, 0, 0)], literal=1, + low=0xffffffffffffffff, high=0xffffffffffffffff) == (0, 2) + reference_functions = {} + for _ in range(3000): + name = "generated_" + str(rng.randrange(20)) + parameter = rng.randrange(1, 17) + if name in reference_functions and reference_functions[name][0] != parameter: + assert entry(0, name, signature(parameter))[0] == 12 + else: + status, identity = entry(0, name, signature(parameter)) + assert status == 0 + if name in reference_functions: + assert identity == reference_functions[name][1] + reference_functions[name] = parameter, identity + assert namespace_state.next_function == 22 + assert namespace_state.next_global == 3 + assert count == 25 + print(f"Wave IR builder: {args.cases} differential type cases, transaction negatives, 3000 namespace cases and 60000 allocations passed") + + +if __name__ == "__main__": + main() diff --git a/tools/check_wave_ir_cfg.py b/tools/check_wave_ir_cfg.py new file mode 100644 index 0000000..b3cf767 --- /dev/null +++ b/tools/check_wave_ir_cfg.py @@ -0,0 +1,188 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Independent Wave IR CFG traversal vectors and bounded random graphs.""" + +import argparse +import ctypes +import random + + +class Block(ctypes.Structure): + _fields_ = [("first", ctypes.c_uint64), ("count", ctypes.c_uint64)] + + +class Result(ctypes.Structure): + _fields_ = [(name, ctypes.c_uint64) for name in ("status", "index", "count", "work")] + + +def call(kernel, graph, entry=0, work=100000, capacity=None): + count = len(graph) + if capacity is None: + capacity = count + blocks = [] + edges = [] + for targets in graph: + blocks.append(Block(len(edges), len(targets))) + edges.extend(targets) + block_array = (Block * count)(*blocks) + edge_array = (ctypes.c_uint64 * len(edges))(*edges) + seen = (ctypes.c_uint8 * capacity)() + stack_block = (ctypes.c_uint64 * capacity)() + stack_next = (ctypes.c_uint64 * capacity)() + scratch = (ctypes.c_uint64 * capacity)() + output = (ctypes.c_uint64 * capacity)(*([0xdead] * capacity)) + result = Result() + status = kernel(block_array, count, edge_array, len(edges), entry, work, + seen, capacity, stack_block, stack_next, capacity, + scratch, capacity, output, capacity, ctypes.byref(result)) + assert status == result.status + if status: + assert all(value == 0xdead for value in output), (graph, status) + return status, result.index, list(output[:result.count]), result.work + + +def reference(graph, entry): + for source, targets in enumerate(graph): + if entry in targets: + return 1, source, [] + seen = set() + postorder = [] + + def visit(block): + if block in seen: + return + seen.add(block) + for target in graph[block]: + visit(target) + postorder.append(block) + + visit(entry) + return 0, 0, list(reversed(postorder)) + + +def call_idom(kernel, graph, order, entry=0, work=100000, capacity=None): + count = len(graph) + if capacity is None: + capacity = count + predecessors = [[] for _ in graph] + for source, targets in enumerate(graph): + for target in dict.fromkeys(targets): + predecessors[target].append(source) + blocks = [] + edges = [] + for sources in predecessors: + blocks.append(Block(len(edges), len(sources))) + edges.extend(sources) + block_array = (Block * count)(*blocks) + edge_array = (ctypes.c_uint64 * len(edges))(*edges) + order_array = (ctypes.c_uint64 * len(order))(*order) + rank = (ctypes.c_uint64 * capacity)() + scratch = (ctypes.c_uint64 * capacity)() + output = (ctypes.c_uint64 * capacity)(*([0xdead] * capacity)) + result = Result() + status = kernel(block_array, count, edge_array, len(edges), order_array, + len(order), entry, work, rank, capacity, scratch, capacity, + output, capacity, ctypes.byref(result)) + assert status == result.status + if status: + assert all(value == 0xdead for value in output), (graph, status) + return status, [None if value == (1 << 64) - 1 else value + for value in output[:result.count]] + + +def reference_idom(graph, entry): + reachable = {entry} + pending = [entry] + while pending: + for target in graph[pending.pop()]: + if target not in reachable: + reachable.add(target) + pending.append(target) + predecessors = [[] for _ in graph] + for source in reachable: + for target in graph[source]: + if target in reachable: + predecessors[target].append(source) + dom = {block: ({entry} if block == entry else set(reachable)) for block in reachable} + changed = True + while changed: + changed = False + for block in reachable - {entry}: + common = set(reachable) + for pred in predecessors[block]: + common &= dom[pred] + next_dom = common | {block} + if next_dom != dom[block]: + dom[block] = next_dom + changed = True + result = [None] * len(graph) + result[entry] = entry + for block in reachable - {entry}: + strict = dom[block] - {block} + result[block] = max(strict, key=lambda candidate: len(dom[candidate])) + return result + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", required=True) + parser.add_argument("--cases", type=int, default=10000) + args = parser.parse_args() + kernel = ctypes.CDLL(args.library).whale_ir_cfg_rpo + kernel.argtypes = [ctypes.c_void_p, ctypes.c_uint64, ctypes.c_void_p, + ctypes.c_uint64, ctypes.c_uint64, ctypes.c_uint64, + ctypes.c_void_p, ctypes.c_uint64, ctypes.c_void_p, + ctypes.c_void_p, ctypes.c_uint64, ctypes.c_void_p, + ctypes.c_uint64, ctypes.c_void_p, ctypes.c_uint64, + ctypes.POINTER(Result)] + dominance = ctypes.CDLL(args.library).whale_ir_cfg_idom + dominance.argtypes = [ctypes.c_void_p, ctypes.c_uint64, ctypes.c_void_p, + ctypes.c_uint64, ctypes.c_void_p, ctypes.c_uint64, + ctypes.c_uint64, ctypes.c_uint64, ctypes.c_void_p, + ctypes.c_uint64, ctypes.c_void_p, ctypes.c_uint64, + ctypes.c_void_p, ctypes.c_uint64, ctypes.POINTER(Result)] + cases = [([[1, 2], [3], [3], []], 0), + ([[1], [2], [3], []], 0), + ([[1], [2], [1], []], 0), + ([[1], [], [0]], 0), + ([[1, 1], []], 0), + ([[]], 0)] + for graph, entry in cases: + status, source, order, _ = call(kernel, graph, entry) + assert (status, source, order) == reference(graph, entry) + if status == 0: + assert call_idom(dominance, graph, order, entry) == (0, reference_idom(graph, entry)) + assert call(kernel, [[1], []], work=1)[0] == 3 + assert call(kernel, [[1], []], capacity=1)[0] == 2 + assert call(kernel, [[2], []])[0] == 5 + assert call(kernel, [[1], []], entry=3)[0] == 5 + assert call_idom(dominance, [[1], []], [0, 1], work=1)[0] == 3 + assert call_idom(dominance, [[1], []], [0, 1], capacity=1)[0] == 2 + assert call_idom(dominance, [[1], []], [1, 0])[0] == 5 + chain = [[index + 1] for index in range(59999)] + [[]] + status, _, order, _ = call(kernel, chain, work=2000000) + assert status == 0 and len(order) == 60000 and order[0] == 0 and order[-1] == 59999 + status, parents = call_idom(dominance, chain, order, work=2000000) + assert status == 0 and parents[0] == 0 and parents[-1] == 59998 + randomizer = random.Random(0x349f) + for index in range(args.cases): + count = randomizer.randrange(1, 40) + entry = randomizer.randrange(count) + graph = [[randomizer.randrange(count) + for _ in range(randomizer.randrange(0, 5))] + for _ in range(count)] + if index % 2 == 0: + graph = [[target for target in targets if target != entry] for targets in graph] + status, source, order, consumed = call(kernel, graph, entry) + expected = reference(graph, entry) + assert (status, source, order) == expected, (index, graph, entry, status, order, expected) + assert consumed <= 100000 + if status == 0 and index % 4 == 0: + actual = call_idom(dominance, graph, order, entry) + oracle = reference_idom(graph, entry) + assert actual == (0, oracle), (index, graph, entry, actual, oracle) + print(f"Wave IR CFG: vectors, limits and {args.cases} graphs passed") + + +if __name__ == "__main__": + main() diff --git a/tools/check_wave_ir_expression.py b/tools/check_wave_ir_expression.py new file mode 100644 index 0000000..af3850f --- /dev/null +++ b/tools/check_wave_ir_expression.py @@ -0,0 +1,148 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Independent preserved expression-tree oracle for actual Wave grammar.""" + +import argparse +import ctypes +import random +from check_wave_ir_type import Token, Node as TypeNode, LEAVES, MARKS, generated as generated_type + + +class Expression(ctypes.Structure): + _fields_ = [(name, ctypes.c_uint64) for name in + ("kind", "op", "type_first", "type_count", "low", "high")] + + +class Result(ctypes.Structure): + _fields_ = [(name, ctypes.c_uint64) for name in + ("status", "reason", "at", "expected", "detail", "next", + "expressions", "types", "spent", "work")] + + +BINARY = "add sub mul bit_and bit_or bit_xor div rem shift_left shift_right logical_and logical_or".split() +COMPARE = "eq ne lt le gt ge".split() + + +def generated(randomizer, depth): + if depth == 0 or randomizer.randrange(3) == 0: + if randomizer.randrange(4) == 0: + words, nodes = generated_type(randomizer, 3) + identity = randomizer.randrange(1 << 32) + kind = randomizer.choice((1, 2)) + return ("ref", kind, identity, words, nodes) + kind = randomizer.randrange(1, 17) + if kind == 1: + bits = randomizer.randrange(2) + spelling = "true" if bits else "false" + elif kind >= 14: + width = (16, 32, 64)[kind - 14] + bits = randomizer.getrandbits(width) + spelling = "0x" + format(bits, f"0{width // 4}x") + else: + width = {2: 1, 3: 1, 4: 8, 5: 16, 6: 32, 7: 64, 8: 128, + 9: 8, 10: 16, 11: 32, 12: 64, 13: 128}[kind] + value = randomizer.getrandbits(width) + if kind == 2 or 4 <= kind <= 8: + if value & (1 << (width - 1)): + value -= 1 << width + spelling = str(value) + bits = value & ((1 << 128) - 1) + return ("literal", kind, spelling, bits) + choice = randomizer.randrange(4) + if choice < 2: + return ("unary", choice, generated(randomizer, depth - 1)) + return ("binary" if choice == 2 else "compare", + randomizer.randrange(12 if choice == 2 else 6), + generated(randomizer, depth - 1), generated(randomizer, depth - 1)) + + +def flatten(tree, types, expressions): + kind = tree[0] + if kind == "literal": + _, leaf, spelling, bits = tree + meta = (len(types), 1) + types.append((leaf, 0, 0)) + expressions.append((0, 0, *meta, bits & ((1 << 64) - 1), bits >> 64)) + return [LEAVES[leaf], spelling], meta, 2 + if kind == "ref": + _, category, identity, words, nodes = tree + meta = (len(types), len(nodes)) + types.extend(nodes) + expressions.append((category, identity, *meta, 0, 0)) + return [*words, ("@g" if category == 1 else "%v") + str(identity)], meta, 1 + len(nodes) + left_words, meta, spent = flatten(tree[2], types, expressions) + if kind == "unary": + expressions.append((3 + tree[1], 0, *meta, 0, 0)) + return ["bit_not" if tree[1] == 0 else "neg", "(", *left_words, ")"], meta, spent + 1 + right_words, _, right_spent = flatten(tree[3], types, expressions) + if kind == "compare": + meta = (len(types), 1) + types.append((1, 0, 0)) + expressions.append((5 if kind == "binary" else 6, tree[1], *meta, 0, 0)) + op = (BINARY if kind == "binary" else COMPARE)[tree[1]] + return [op, "(", *left_words, ",", *right_words, ")"], meta, spent + right_spent + 1 + + +def call(kernel, words, *, mode=1, max_depth=128, max_type_depth=128, + max_nodes=1000000, max_work=16000000, capacity=None, output_capacity=None, version=8): + capacity = capacity if capacity is not None else len(words) + 1 + output_capacity = output_capacity if output_capacity is not None else capacity + buffers = [ctypes.create_string_buffer(word.encode()) for word in words] + tokens = (Token * (len(words) + 1))(*[ + Token(ctypes.cast(buffer, ctypes.c_void_p), len(word.encode()), 2 if word in MARKS else 0) + for buffer, word in zip(buffers, words)], Token(None, 0, 3)) + type_scratch = (TypeNode * capacity)() + expression_scratch = (Expression * capacity)() + types = (TypeNode * output_capacity)(*[TypeNode(99, 99, 99) for _ in range(output_capacity)]) + expressions = (Expression * output_capacity)(*[Expression(99, 99, 99, 99, 99, 99) for _ in range(output_capacity)]) + result = Result() + status = kernel(tokens, len(tokens), 0, 0, version, max_depth, max_type_depth, + max_nodes, max_work, mode, type_scratch, capacity, expression_scratch, capacity, + types, output_capacity, expressions, output_capacity, ctypes.byref(result)) + assert status == result.status + if status or mode == 0: + assert all(node.kind == 99 for node in types) + assert all(node.kind == 99 for node in expressions) + return status, result, [], [] + return status, result, [(n.kind, n.value, n.count) for n in types[:result.types]], [ + (n.kind, n.op, n.type_first, n.type_count, n.low, n.high) for n in expressions[:result.expressions]] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", required=True) + parser.add_argument("--cases", type=int, default=10000) + args = parser.parse_args() + kernel = ctypes.CDLL(args.library).whale_ir_parse_expression + kernel.argtypes = [ctypes.c_void_p, *([ctypes.c_uint64] * 9), + ctypes.c_void_p, ctypes.c_uint64, ctypes.c_void_p, ctypes.c_uint64, + ctypes.c_void_p, ctypes.c_uint64, ctypes.c_void_p, ctypes.c_uint64, + ctypes.POINTER(Result)] + assert call(kernel, ["neg", "(", "i32", "1", ")"], version=7)[1].reason == 3 + assert call(kernel, ["bit_not", "(", "i32", "1", ")"], version=4)[1].reason == 2 + assert call(kernel, ["add", "(", "i32", "1", ",", "i32", "2", ")"], version=3)[0] == 0 + assert call(kernel, ["i32", "@g4294967296"])[1].reason == 5 + assert call(kernel, ["i32", "@g4294967296x"])[1].reason == 4 + assert call(kernel, ["i32", "1"], max_nodes=0)[0] == 3 + assert call(kernel, ["i32", "1"], max_work=0)[0] == 4 + assert call(kernel, ["i32", "1"], output_capacity=0)[0] == 5 + assert call(kernel, ["ptr", "<", "u8", ">", "@g0"], max_type_depth=0)[1].reason == 2 + deep = ["neg", "("] * 257 + ["i32", "1"] + [")"] * 257 + assert call(kernel, deep, max_depth=256)[0] == 2 + randomizer = random.Random(0x3490352) + for case in range(args.cases): + tree = generated(randomizer, 6) + expected_types, expected_expressions = [], [] + words, _, spent = flatten(tree, expected_types, expected_expressions) + status, result, types, expressions = call(kernel, words) + assert status == 0 and result.next == len(words) and result.spent == spent, (case, words, status, result.reason, result.at) + assert types == expected_types and expressions == expected_expressions, (case, words, types, expected_types, expressions, expected_expressions) + pre_status, pre, _, _ = call(kernel, words, mode=0) + assert pre_status == 0 and (pre.types, pre.expressions, pre.spent, pre.work) == (result.types, result.expressions, result.spent, result.work) + assert call(kernel, words[:-1])[0] != 0 + assert call(kernel, words, max_work=result.work - 1)[0] != 0 + print(f"Wave IR expression parser: versions, bounds, exact postorder and {args.cases} independent trees passed") + + +if __name__ == "__main__": + main() diff --git a/tools/check_wave_ir_header.py b/tools/check_wave_ir_header.py new file mode 100644 index 0000000..136e035 --- /dev/null +++ b/tools/check_wave_ir_header.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Independent native vectors for the Wave-owned versioned IR header.""" + +import argparse +import ctypes +import random + + +class Token(ctypes.Structure): + _fields_ = [("data", ctypes.c_void_p), ("length", ctypes.c_uint64), + ("kind", ctypes.c_uint64)] + + +class Result(ctypes.Structure): + _fields_ = [(name, ctypes.c_uint64) for name in + ("status", "at", "expected", "version", "ptr_bits", "endian", + "target_index", "next")] + + +HEADER = [b"module", b"{", b"format_version", b"8", b"semantics_version", + b"1", b"target", b"x86_64-whale-linux", b"datalayout", b"{", + b"ptr", b"=", b"64", b",", b"endian", b"=", b"little", b"}"] +KINDS = [0, 2, 0, 0, 0, 0, 0, 1, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2] + + +def call(kernel, words, kinds=KINDS): + buffers = [ctypes.create_string_buffer(word) for word in words] + tokens = (Token * len(words))(*( + Token(ctypes.cast(buffer, ctypes.c_void_p), len(word), kind) + for buffer, word, kind in zip(buffers, words, kinds))) + result = Result() + status = kernel(tokens, len(words), 8, 1, ctypes.byref(result)) + assert status == result.status, (status, result.status) + if status: + assert (result.version, result.ptr_bits, result.endian, + result.target_index, result.next) == (0, 0, 0, 0, 0) + return status, result + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", required=True) + parser.add_argument("--cases", type=int, default=10000) + args = parser.parse_args() + kernel = ctypes.CDLL(args.library).whale_ir_header + kernel.argtypes = [ctypes.c_void_p, ctypes.c_uint64, ctypes.c_uint64, + ctypes.c_uint64, ctypes.POINTER(Result)] + status, result = call(kernel, HEADER) + assert status == 0 and (result.version, result.ptr_bits, result.endian, + result.target_index, result.next) == (8, 64, 0, 7, 18) + for version in range(3, 9): + words = HEADER.copy() + words[3] = str(version).encode() + assert call(kernel, words)[0] == 0 + for index, replacement, expected in [ + (3, b"2", 4), (3, b"9", 4), (3, b"4294967296", 3), + (3, b"-1", 2), (5, b"2", 5), (12, b"4294967296", 3), + (16, b"middle", 7), + ]: + words = HEADER.copy() + words[index] = replacement + assert call(kernel, words)[0] == expected + for index in range(18): + words = HEADER.copy() + words[index] = b"wrong" + if index == 7: + assert call(kernel, words)[0] == 0 + else: + assert call(kernel, words)[0] != 0 + assert call(kernel, HEADER[:index])[0] != 0 + randomizer = random.Random(0x3490349) + for case in range(args.cases): + words = HEADER.copy() + kinds = KINDS.copy() + index = randomizer.randrange(18) + if index in (3, 5, 12): + words[index] = str(randomizer.randrange(0, 1 << 36)).encode() + else: + words[index] = randomizer.choice((b"", b"bad", b"\xff", b"123")) + if index == 7 and case % 2 == 0: + kinds[index] = 0 + status, result = call(kernel, words, kinds) + assert status != 0 or (index in (3, 5, 7, 12) and result.next == 18), (case, index) + print(f"Wave IR header: versions, truncation, transaction and {args.cases} mutations passed") + + +if __name__ == "__main__": + main() diff --git a/tools/check_wave_ir_hir.py b/tools/check_wave_ir_hir.py new file mode 100644 index 0000000..d473a73 --- /dev/null +++ b/tools/check_wave_ir_hir.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Independent conformance vectors for the real Wave resolved-HIR adapter.""" +import argparse +import ctypes as C +import random + + +class Node(C.Structure): + _fields_ = [("words", C.c_uint64 * 8)] + + +class Pair(C.Structure): + _fields_ = [("a", C.c_uint64), ("b", C.c_uint64)] + + +class Result(C.Structure): + _fields_ = [(name, C.c_uint64) for name in ("status", "node", "detail", "work")] + + +def call(kernel, nodes, edges, *, work=100000, depth=32): + records = (Node * len(nodes))(*[Node((C.c_uint64 * 8)(*node, *([0] * (8 - len(node))))) + for node in nodes]) + links = (C.c_uint64 * len(edges))(*edges) + output = (Pair * len(nodes))() + bindings = (Pair * len(nodes))() + table = (Pair * 64)() + result = Result() + status = kernel(records, len(nodes), links, len(edges), len(edges) - 1, 1, + output, bindings, table, 64, depth, work, C.byref(result)) + assert status == result.status and result.work <= work + return status, result, [(entry.a, entry.b) for entry in output] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", required=True) + parser.add_argument("--cases", type=int, default=10000) + args = parser.parse_args() + kernel = C.CDLL(args.library).whale_ir_adapt_wave_hir + kernel.argtypes = [C.POINTER(Node), C.c_uint64, C.POINTER(C.c_uint64), C.c_uint64, + C.c_uint64, C.c_uint64, C.POINTER(Pair), C.POINTER(Pair), + C.POINTER(Pair), C.c_uint64, C.c_uint64, C.c_uint64, C.POINTER(Result)] + kernel.restype = C.c_int32 + randomizer = random.Random(0x149) + widths = (1, 8, 16, 32, 64, 128) + target_ops = (0, 1, 2, 6, 7, 3, 4, 5, 8, 9, 10, 11, 32, 33, 34, 35, 36, 37) + for index in range(args.cases): + width = randomizer.choice(widths) + signed = randomizer.randrange(2) + operation = randomizer.randrange(18) + boolean = operation in (10, 11) + compare = operation >= 12 + maximum = (1 << (width - signed)) - 1 + minimum = -(1 << (width - 1)) if signed else 0 + a = randomizer.randint(minimum, maximum) + b = randomizer.randint(minimum, maximum) + left = C.create_string_buffer(str(a).encode()) + right = C.create_string_buffer(str(b).encode()) + # Different type records with equivalent resolved facts prove that the + # adapter uses semantic facts, rather than relying on transport identity. + operand = (2, 1) if boolean else (2, 2, width, signed) + result_type = (2, 1) if compare or boolean else operand + nodes = [operand, operand, result_type, + (4, 0, 0, a & 1) if boolean else (3, 0, 0, C.addressof(left), len(str(a))), + (4, 1, 1, b & 1) if boolean else (3, 1, 1, C.addressof(right), len(str(b))), + (6, 2, 2, operation, 3, 4), (11, 5), (0, 0, 0, 0, 2, 0, 1, 0)] + edges = [6, 7] + status, _, output = call(kernel, nodes, edges) + assert status == 0, (index, width, signed, operation, status) + assert output[5][1] == target_ops[operation] + # A contradictory return fact must be rejected, even for dead source. + bad = list(nodes) + bad[7] = (0, 0, 0, 0, 1 if compare or boolean else 2, 0, 1, 0) + if compare or boolean: + # Keep the RHS operand scalar facts intact by adding a fresh return. + bad[7] = (0, 0, 0, 0, 8, 0, 1, 0) + bad.append((2, 2, 8, 1)) + else: + bad[2] = (2, 1) + assert call(kernel, bad, edges)[0] == 4, (index, operation, call(kernel,bad,edges)[0], bad) + bad = list(nodes) + bad[4] = tuple([nodes[4][0], 0, *nodes[4][2:]]) + assert call(kernel, bad, edges)[0] == 6 + assert call(kernel, nodes, edges, work=1)[0] == 1 + for category in (1, 2, 3, 4): + nodes = [(2, 0), (12, category), (0, 0, 0, 0, 0, 0, 1, 0)] + status, result, _ = call(kernel, nodes, [1, 2]) + assert status == 5 and result.detail == category + print(f"Wave typed-HIR adapter: {args.cases} resolved scalar/operator vectors, contradictory facts, duplicate identities and limits passed") + + +if __name__ == "__main__": + main() diff --git a/tools/check_wave_ir_instruction.py b/tools/check_wave_ir_instruction.py new file mode 100644 index 0000000..a994a6f --- /dev/null +++ b/tools/check_wave_ir_instruction.py @@ -0,0 +1,248 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Independent generated instruction records for the native Wave grammar.""" +import argparse +import ctypes as c +import random +import re +from check_wave_ir_type import Token, Node as TypeNode, Result as TypeResult + + +class State(c.Structure): + _fields_ = [(key, c.c_uint64) for key in + ("phase", "at", "format", "mode", "op", "sub", "op_at", "has_dst", "dst", + "annotation_kind", "type_kind", "a", "b", "c", "d", "e", "name", "aux", "nodes", "work")] + + +class Event(c.Structure): + _fields_ = [(key, c.c_uint64) for key in + ("status", "reason", "at", "expected", "event", "role", "op", "sub", "has_dst", "dst", + "a", "b", "c", "d", "e", "name", "aux", "next", "nodes", "work")] + + +BINARY = "add sub mul udiv sdiv urem srem fadd fsub fmul fdiv frem and or xor shl lshr ashr".split() +CAST = "checked_int zext sext trunc fext ftrunc itof_s itof_u ftoi_s ftoi_u bitcast ptrtoint inttoptr".split() +CHECKED = "uadd_chk usub_chk umul_chk sadd_chk ssub_chk smul_chk".split() +PREDICATES = ["eq ne slt sle sgt sge ult ule ugt uge feq fne flt fle fgt fge".split(), + "eq ne ult ule ugt uge slt sle sgt sge".split(), + "oeq one olt ole ogt oge ord uno ueq une ult ule ugt uge".split()] +MARKS = {bytes((value,)) for value in b":=,[]()<>"} | {b"=>", b"->"} +TOKEN = re.compile(rb'"(?:\\.|[^"\\])*"|=>|->|[\[\]()<>:,=]|[^\s\[\]()<>:,="]+') + + +def decode_type(nodes): + stack = [] + for node in nodes: + if node.kind <= 16: + stack.append((node.kind,)) + elif node.kind in (17, 19): + child = stack.pop() + stack.append((17, child) if node.kind == 17 else (19, node.value, child)) + elif node.kind == 18: + ret = stack.pop() + params = tuple(stack[-node.count:]) if node.count else () + if node.count: + del stack[-node.count:] + stack.append((18, node.value, params, ret)) + else: + fields = tuple(stack[-node.count:]) if node.count else () + if node.count: + del stack[-node.count:] + stack.append((node.kind, fields)) + assert len(stack) == 1 + return stack[0] + + +def generated(rng, choice=None): + op = rng.randrange(36) if choice is None else choice + a, b, cc, dst = [rng.randrange(1 << 32) for _ in range(4)] + prefix = lambda ty: f"%v{dst}: {ty} = " + fields = {"op": op} + phi, values, cases = [], [], [] + term = op >= 31 + if not term: + fields.update(has_dst=int(op not in (1, 20, 22, 23, 25, 26, 30)), dst=dst) + if op == 0: + text = prefix("ptr") + f"global_addr @g{a}"; fields["a"] = a + elif op == 1: + text = f"lifetime_end %v{a}"; fields["a"] = a + elif op == 2: + text = prefix("i128") + f"ptrdiff %v{a}, %v{b}"; fields.update(a=a, b=b) + elif op == 3: + text = prefix("i32") + 'const_decl "name" i32 7 => const i32 7' + elif op == 4: + text = prefix("i32") + f"const i32 {rng.randrange(-(1 << 31), 1 << 31)}" + elif op == 5: + text = prefix("i32") + "undef i32" + elif op in (6, 8, 9): + text = prefix("i32") + f"{ {6: 'mov', 8: 'neg', 9: 'not'}[op]} i32 %v{a}"; fields["a"] = a + elif op == 7: + sub = rng.randrange(len(BINARY)); fields.update(sub=sub, a=a, b=b) + text = prefix("i32") + f"{BINARY[sub]} i32 %v{a}, %v{b}" + elif op in (10, 11, 12): + predicates = PREDICATES[op - 10]; sub = rng.randrange(len(predicates)) + fields.update(sub=sub, a=a, b=b) + text = prefix("bool") + f"{['cmp', 'icmp', 'fcmp'][op - 10]} {predicates[sub]} i32 %v{a}, %v{b}" + elif op == 13: + text = prefix("i32") + f"select bool %v{a}, i32 %v{b}, i32 %v{cc}"; fields.update(a=a, b=b, c=cc) + elif op == 14: + sub = rng.randrange(len(CAST)); fields.update(sub=sub, a=a) + text = prefix("i64") + f"{CAST[sub]} i32 %v{a} to i64" + elif op == 15: + phi = [(rng.randrange(1 << 32), rng.randrange(1 << 32)) for _ in range(rng.randrange(20))] + text = prefix("i32") + "phi i32 " + ", ".join(f"[%v{v}, %b{bb}]" for v, bb in phi) + elif op == 16: + index = rng.randrange(1 << 32); fields.update(a=a, d=index) + text = prefix("i32") + f"extract %v{a}, {index}" + elif op == 17: + sub = rng.randrange(len(CHECKED)); fields.update(sub=sub, a=a, b=b) + text = prefix("tuple") + f"{CHECKED[sub]} i32 %v{a}, %v{b}" + elif op == 18: + fields["d"] = 4; text = prefix("ptr") + "alloca i32, align 4" + elif op in (19, 20, 21, 22, 23): + name = {19: "volatile_load", 20: "volatile_store", 21: "load", 22: "uninit", 23: "store"}[op] + fields.update(b=b, d=4) + if op in (19, 21): text = prefix("i32") + f"{name} i32, ptr %v{b}, align 4" + elif op == 22: text = f"{name} i32, ptr %v{b}, align 4" + else: fields["a"] = a; text = f"{name} i32 %v{a}, ptr %v{b}, align 4" + elif op == 24: + values = [rng.randrange(1 << 32) for _ in range(rng.randrange(20))] + fields["a"] = a; text = prefix("ptr") + f"gep %v{a}" + "".join(f", %v{v}" for v in values) + elif op in (25, 26): + fields.update(a=a, b=b, c=cc, d=1) + text = f"{'memcpy' if op == 25 else 'memset'} ptr %v{a}, {'ptr' if op == 25 else 'u8'} %v{b}, u64 %v{cc}, align 1" + elif op in (27, 28): + text = prefix("fnptr void>") + ("null_function" if op == 27 else f"function_addr @f{a}") + if op == 28: fields["a"] = a + elif op == 29: + values = [rng.randrange(1 << 32) for _ in range(rng.randrange(20))] + returns = bool(rng.randrange(2)); indirect = rng.randrange(2); sub = rng.randrange(2) + fields.update(a=a, e=indirect, sub=sub, has_dst=int(returns)) + text = (prefix("i32") if returns else "") + f"call {'whale' if sub == 0 else 'sysv64'} {'i32' if returns else 'void'} " + (f"indirect %v{a}" if indirect else f"@f{a}") + "(" + ", ".join(f"%v{v}" for v in values) + ")" + elif op == 30: + text = f'trap_if bool %v{a}, reason = "trap"'; fields["a"] = a + elif op == 31: + text = f"br label %b{a}"; fields["a"] = a + elif op == 32: + text = f"cbr bool %v{a}, label %b{b}, label %b{cc}"; fields.update(a=a, b=b, c=cc) + elif op == 33: + cases = [(rng.randrange(-(1 << 31), 1 << 31), rng.randrange(1 << 32)) for _ in range(rng.randrange(20))] + fields.update(a=a, b=b) + text = f"switch i32 %v{a}, label %b{b} [" + ", ".join(f"{v}: %b{bb}" for v, bb in cases) + "]" + elif op == 34: + returns = bool(rng.randrange(2)); fields["aux"] = int(returns) + if returns: fields["a"] = a + text = f"ret i32 %v{a}" if returns else "ret void" + else: + text = 'trap reason = "trap"' + if not term and fields["has_dst"] == 0: + fields.pop("dst", None) + return text, term, fields, phi, values, cases + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", required=True) + parser.add_argument("--cases", type=int, default=10000) + args = parser.parse_args() + library = c.CDLL(args.library) + kernel = library.whale_ir_instruction_step + kernel.argtypes = [c.c_void_p, c.c_uint64, c.POINTER(State), c.c_uint64, c.c_uint64, c.POINTER(Event)] + type_kernel = library.whale_ir_parse_type + type_kernel.argtypes = [c.c_void_p] + [c.c_uint64] * 7 + [c.c_void_p, c.c_uint64, c.c_void_p, c.c_uint64, c.POINTER(TypeResult)] + + def call(case, max_nodes=1000000, max_work=16000000): + text, term, expected, phi, values, cases = case + # Borrow one stable byte buffer. Wide fixtures must not allocate a + # ctypes owner/string per token or expand every token as an argument. + encoded = text.encode("ascii") + token_count = sum(1 for _ in TOKEN.finditer(encoded)) + source = c.create_string_buffer(encoded) + source_address = c.addressof(source) + raw = (Token * (token_count + 1))() + for index, match in enumerate(TOKEN.finditer(encoded)): + token = raw[index] + token.data = source_address + match.start() + token.length = match.end() - match.start() + token.kind = 1 if encoded[match.start()] == 34 else 2 if match.group() in MARKS else 0 + raw[token_count].kind = 3 + + def word(index): + token = raw[index] + start = token.data - source_address + return encoded[start:start + token.length].decode("ascii") + state = State(format=8, mode=int(term)) + types = [None, None, None] + expression_type = None + got_phi, got_values, got_cases = [], [], [] + literal = None + used_nodes = used_work = 0 + + def ty(start): + scratch, output = (TypeNode * 256)(), (TypeNode * 256)() + result = TypeResult() + status = type_kernel(raw, len(raw), start, 0, 128, max_nodes - used_nodes, + max_work - used_work, 1, scratch, 256, output, 256, c.byref(result)) + assert status == result.status == 0, (text, status, result.reason) + return result, decode_type(output[:result.nodes]) + + for _ in range(token_count * 2 + 100): + event = Event() + status = kernel(raw, len(raw), c.byref(state), max_nodes - used_nodes, max_work - used_work, c.byref(event)) + assert status == event.status + used_nodes += event.nodes; used_work += event.work + if status: + return status + if event.event == 100: + result, parsed = ty(state.at) + state.at = result.next; state.type_kind = parsed[0]; types[event.role] = parsed + used_nodes += result.nodes; used_work += result.work + elif event.event == 101: + spelling = word(state.at) + literal = int(spelling) + assert types[1] == (6,) and -(1 << 31) <= literal < 1 << 31 + state.at += 1 + elif event.event == 102: + result, expression_type = ty(state.at) + state.at = result.next + 1 # generated preserved expression is i32 7 + assert word(result.next) == "7" + used_nodes += result.nodes + 1; used_work += result.work + 1 + elif event.event == 110: + left, right = { + 0: (types[0], types[1]), 1: (types[0], (1,)), 2: (types[0], (8,)), + 3: (types[0], (17, types[1])), 4: (types[0], (21, (types[1], (1,)))), + 5: (types[0], types[2]), 6: (types[1], types[2]), + 7: ((17, types[1]), types[2]), 8: (types[1], expression_type), + 9: (types[0], expression_type), + }[event.role] + assert left == right, (text, event.role, left, right) + elif event.event == 200: + got_phi.append((event.a, event.b)) + elif event.event == 201: + got_values.append(event.b) + elif event.event == 202: + got_cases.append((literal, event.c)) + elif event.event == 1: + assert state.at == token_count, (text, state.at, token_count) + assert all(getattr(event, key) == value for key, value in expected.items()), (text, expected) + assert (got_phi, got_values, got_cases) == (phi, values, cases), text + return 0 + else: + raise AssertionError((text, event.event)) + raise AssertionError("instruction parser failed to make bounded progress") + + rng = random.Random(349) + for choice in range(36): + assert call(generated(rng, choice)) == 0 + for _ in range(args.cases): + assert call(generated(rng)) == 0 + count = 60000 + phi = [(i, i) for i in range(count)] + text = "%v2: i32 = phi i32 " + ", ".join(f"[%v{v}, %b{bb}]" for v, bb in phi) + assert call((text, False, {"op": 15, "has_dst": 1, "dst": 2}, phi, [], [])) == 0 + assert call(("lifetime_end %v0", False, {"op": 1}, [], [], []), max_work=0) == 4 + print(f"Wave IR instruction grammar: {args.cases} generated records, full inventory and 60000-incoming stress passed") + + +if __name__ == "__main__": + main() diff --git a/tools/check_wave_ir_layout.py b/tools/check_wave_ir_layout.py new file mode 100644 index 0000000..ef1e7e9 --- /dev/null +++ b/tools/check_wave_ir_layout.py @@ -0,0 +1,178 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Run the real Wave IR layout kernel against independent storage vectors.""" + +import argparse +import ctypes +import random + + +class Node(ctypes.Structure): + _fields_ = [(name, ctypes.c_uint64) for name in ("kind", "child", "first", "count")] + + +class Storage(ctypes.Structure): + _fields_ = [(name, ctypes.c_uint64) for name in ( + "ptr_bits", "pointer_align", "scalar_align1", "scalar_align2", "scalar_align4", + "scalar_align8", "scalar_align16", "large_array_threshold", "large_array_align", + "has_large_array")] + + +class Layout(ctypes.Structure): + _fields_ = [(name, ctypes.c_uint64) for name in ( + "size", "align", "stride", "allocation_align", "depth")] + + +class Result(ctypes.Structure): + _fields_ = [("status", ctypes.c_uint64), ("index", ctypes.c_uint64)] + + +def call(kernel, nodes, edges=(), root=None, depth=128, work=None, storage=None): + if root is None: + root = len(nodes) - 1 + if work is None: + work = max(1024, 64 * (len(nodes) + len(edges))) + if storage is None: + storage = Storage(64, 8, 1, 2, 4, 8, 16, 16, 16, 1) + node_array = (Node * len(nodes))(*nodes) + edge_array = (ctypes.c_uint64 * len(edges))(*edges) + scratch = (Layout * len(nodes))() + output = (Layout * len(nodes))(*[Layout(0xdead, 0xbeef, 3, 5, 7) for _ in nodes]) + scratch_offsets = (ctypes.c_uint64 * len(edges))() + output_offsets = (ctypes.c_uint64 * len(edges))(*([0xdead] * len(edges))) + result = Result() + status = kernel(ctypes.byref(storage), node_array, len(nodes), edge_array, len(edges), root, + depth, work, scratch, len(nodes), scratch_offsets, len(edges), + output, len(nodes), output_offsets, len(edges), ctypes.byref(result)) + assert status == result.status, (status, result.status) + if status: + assert all(item.size == 0xdead and item.align == 0xbeef for item in output) + assert all(offset == 0xdead for offset in output_offsets) + return status, [tuple(getattr(item, name) for name, _ in Layout._fields_) for item in output], list(output_offsets) + + +def align_up(value, align): + return (value + align - 1) & -align + + +def reference(nodes, edges, storage, max_depth=128): + layouts = [] + offsets = [0] * len(edges) + limit = (1 << storage.ptr_bits) - 1 + scalar = {1: (1, storage.scalar_align1), 2: (2, storage.scalar_align2), + 3: (4, storage.scalar_align4), 4: (8, storage.scalar_align8), + 5: (16, storage.scalar_align16), 6: (storage.ptr_bits // 8, storage.pointer_align), + 7: (storage.ptr_bits // 8, storage.pointer_align)} + for index, node in enumerate(nodes): + if node.kind == 0: + current = (0, 0, 0, 0, 0) + elif node.kind in scalar: + size, align = scalar[node.kind] + current = (size, align, 0, align, 0) + elif node.kind == 8: + if node.child >= index: + raise ValueError("graph") + child_size, align, _, _, child_depth = layouts[node.child] + if not align: + raise ValueError("void") + if child_depth >= max_depth: + raise ValueError("depth") + size = child_size * node.count + allocation_align = align + if storage.has_large_array and size >= storage.large_array_threshold: + allocation_align = max(align, storage.large_array_align) + current = (size, align, child_size, allocation_align, child_depth + 1) + elif node.kind in (9, 10): + size, align, depth = 0, 1, 1 + for position in range(node.first, node.first + node.count): + child = edges[position] + if child >= index or layouts[child][1] == 0: + raise ValueError("graph") + child_size, child_align, _, _, child_depth = layouts[child] + if child_depth >= max_depth: + raise ValueError("depth") + size = align_up(size, child_align) + offsets[position] = size + size += child_size + align = max(align, child_align) + depth = max(depth, child_depth + 1) + current = (align_up(size, align), align, 0, align, depth) + else: + raise ValueError("kind") + if current[0] > limit: + raise OverflowError("size") + layouts.append(current) + return layouts, offsets + + +def exercise(kernel, seed, cases): + storage = Storage(64, 8, 1, 2, 4, 8, 16, 16, 16, 1) + nodes = [Node(1, 0, 0, 0), Node(4, 0, 0, 0), Node(2, 0, 0, 0), + Node(9, 0, 0, 3), Node(8, 3, 0, 3), Node(3, 0, 0, 0), + Node(10, 0, 3, 3)] + edges = [0, 1, 2, 0, 4, 5] + status, layouts, offsets = call(kernel, nodes, edges) + assert status == 0 and layouts[6][:2] == (88, 8), (status, layouts) + assert offsets == [0, 8, 16, 0, 8, 80], offsets + assert call(kernel, nodes, edges, work=39)[0] == 6 + assert call(kernel, [Node(1, 0, 0, 0), Node(9, 0, 0, 10)], [0] * 10, work=36)[0] == 6 + assert call(kernel, [Node(1, 0, 0, 0), Node(8, 0, 0, (1 << 64) - 1), + Node(9, 0, 0, 2)], [1, 0])[0] == 3 + assert call(kernel, [Node(0, 0, 0, 0), Node(6, 0, 0, 0)])[0] == 0 + assert call(kernel, [Node(6, 9, 0, 0)])[0] == 1 + assert call(kernel, [Node(1, 0, 0, 0), Node(8, 0, 0, 1)], depth=0)[0] == 2 + assert call(kernel, [Node(9, 0, 0, 0)])[1][0][:2] == (0, 1) + assert call(kernel, [Node(9, 0, 0, 0), Node(8, 0, 0, (1 << 64) - 1)])[1][1][:3] == (0, 1, 0) + storage32 = Storage(32, 4, 1, 2, 4, 8, 16, 16, 16, 1) + assert call(kernel, [Node(4, 0, 0, 0), Node(8, 0, 0, 1 << 32)], storage=storage32)[0] == 3 + invalid = Storage(64, 3, 1, 2, 4, 8, 16, 16, 16, 1) + assert call(kernel, [Node(1, 0, 0, 0)], storage=invalid)[0] == 5 + rng = random.Random(seed) + for case in range(cases): + nodes = [] + edges = [] + for index in range(rng.randrange(1, 24)): + kind = rng.choice((1, 2, 3, 4, 5, 6, 8, 9, 10)) if index else rng.randrange(1, 6) + if kind == 8: + nodes.append(Node(kind, rng.randrange(index), 0, rng.randrange(0, 9))) + elif kind in (9, 10): + first = len(edges) + count = rng.randrange(0, 5) + edges.extend(rng.randrange(index) for _ in range(count)) + nodes.append(Node(kind, 0, first, count)) + else: + nodes.append(Node(kind, 0, 0, 0)) + try: + expected, expected_offsets = reference(nodes, edges, storage) + except OverflowError: + assert call(kernel, nodes, edges)[0] == 3, case + else: + status, actual, actual_offsets = call(kernel, nodes, edges) + assert status == 0 and actual[-1] == expected[-1], (case, status, actual[-1], expected[-1]) + root = nodes[-1] + if root.kind in (9, 10): + span = slice(root.first, root.first + root.count) + assert actual_offsets[span] == expected_offsets[span], case + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", required=True) + parser.add_argument("--seed", type=int, default=149) + parser.add_argument("--cases", type=int, default=2000) + args = parser.parse_args() + library = ctypes.CDLL(args.library) + kernel = library.whale_ir_layout + kernel.restype = ctypes.c_int + kernel.argtypes = [ctypes.POINTER(Storage), ctypes.POINTER(Node), ctypes.c_uint64, + ctypes.POINTER(ctypes.c_uint64), ctypes.c_uint64, ctypes.c_uint64, + ctypes.c_uint64, ctypes.c_uint64, ctypes.POINTER(Layout), ctypes.c_uint64, + ctypes.POINTER(ctypes.c_uint64), ctypes.c_uint64, ctypes.POINTER(Layout), + ctypes.c_uint64, ctypes.POINTER(ctypes.c_uint64), ctypes.c_uint64, + ctypes.POINTER(Result)] + exercise(kernel, args.seed, args.cases) + print(f"Wave IR layout: {args.cases} independent cases passed") + + +if __name__ == "__main__": + main() diff --git a/tools/check_wave_ir_lexer.py b/tools/check_wave_ir_lexer.py new file mode 100644 index 0000000..a3e52b0 --- /dev/null +++ b/tools/check_wave_ir_lexer.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Independent bounded Wave IR lexer vectors and mutation checks.""" + +import argparse +import ctypes +import random + + +class Token(ctypes.Structure): + _fields_ = [(name, ctypes.c_uint64) for name in ( + "kind", "start", "end", "line", "column", "decoded_start", "decoded_len")] + + +class Result(ctypes.Structure): + _fields_ = [(name, ctypes.c_uint64) for name in ( + "status", "reason", "offset", "line", "column", "token_count", "decoded_count")] + + +def call(kernel, source, max_tokens=100, max_work=10000, mode=1, + token_capacity=None, decoded_capacity=None): + if token_capacity is None: + token_capacity = min(max_tokens + 1, len(source) + 1) + if decoded_capacity is None: + decoded_capacity = len(source) + source_buffer = ctypes.create_string_buffer(source) + scratch = (Token * token_capacity)() + output = (Token * token_capacity)(*[Token(99, 99, 99, 99, 99, 99, 99) + for _ in range(token_capacity)]) + scratch_decoded = (ctypes.c_uint8 * decoded_capacity)() + decoded = (ctypes.c_uint8 * decoded_capacity)(*([0xa5] * decoded_capacity)) + result = Result() + status = kernel(source_buffer, len(source), max_tokens, max_work, mode, + scratch, token_capacity, scratch_decoded, decoded_capacity, + output, token_capacity, decoded, decoded_capacity, + ctypes.byref(result)) + assert status == result.status + if status: + assert all(token.kind == 99 for token in output), (source, status) + assert all(octet == 0xa5 for octet in decoded), (source, status) + tokens = [(token.kind, source[token.start:token.end], token.line, token.column, + bytes(decoded[token.decoded_start:token.decoded_start + token.decoded_len])) + for token in output[:result.token_count]] if status == 0 and mode == 1 else [] + return status, tokens, result.token_count, result.decoded_count + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", required=True) + parser.add_argument("--cases", type=int, default=10000) + args = parser.parse_args() + kernel = ctypes.CDLL(args.library).whale_ir_lex + kernel.argtypes = [ctypes.c_void_p, ctypes.c_uint64, ctypes.c_uint64, + ctypes.c_uint64, ctypes.c_uint64, ctypes.c_void_p, + ctypes.c_uint64, ctypes.c_void_p, ctypes.c_uint64, + ctypes.c_void_p, ctypes.c_uint64, ctypes.c_void_p, + ctypes.c_uint64, ctypes.POINTER(Result)] + source = 'module {\n target "a\\u{1F40B}\\n" // café\nα β\u2003γ\n}'.encode() + expected = [(0, b'module', 1, 1, b''), (2, b'{', 1, 8, b''), + (0, b'target', 2, 2, b''), + (1, b'"a\\u{1F40B}\\n"', 2, 9, 'a🐋\n'.encode()), + (0, 'α'.encode(), 3, 1, b''), (0, 'β'.encode(), 3, 3, b''), + (0, 'γ'.encode(), 3, 5, b''), (2, b'}', 4, 1, b''), + (3, b'', 4, 2, b'')] + status, tokens, count, decoded = call(kernel, source) + assert status == 0 and tokens == expected, (status, tokens) + assert call(kernel, source, mode=0)[2:] == (count, decoded) + for malformed in (b'"unterminated', b'"\\u{}"', b'"\\u{d800}"', + b'"\\u{110000}"', b'"\\q"', b'"\x00"', b'\xff'): + assert call(kernel, malformed)[0] == 1, malformed + assert call(kernel, b'a b', max_tokens=1)[0] == 2 + assert call(kernel, b'"abc"', decoded_capacity=2)[0] == 3 + assert call(kernel, b'a b', max_work=1)[0] == 4 + assert call(kernel, b'a b', token_capacity=1)[0] == 2 + long_source = b'a ' * 60000 + long_status, long_tokens, long_count, _ = call( + kernel, long_source, max_tokens=60000, max_work=1000000) + assert long_status == 0 and long_count == 60001 + assert long_tokens[0][1] == b'a' and long_tokens[-1][0] == 3 + randomizer = random.Random(0x7782) + alphabet = [b'a', b' ', b'\n', b'"', b'\\', b'{', b'}', b'//', + b'\xff', b'\x00', '🐋'.encode(), 'β'.encode()] + for index in range(args.cases): + source = b''.join(randomizer.choice(alphabet) + for _ in range(randomizer.randrange(0, 48))) + pre = call(kernel, source, mode=0) + published = call(kernel, source) + assert pre[0] == published[0] and pre[2:] == published[2:], (index, source, pre, published) + print(f"Wave IR lexer: vectors, limits and {args.cases} mutations passed") + + +if __name__ == "__main__": + main() diff --git a/tools/check_wave_ir_literal.py b/tools/check_wave_ir_literal.py new file mode 100644 index 0000000..4acc1db --- /dev/null +++ b/tools/check_wave_ir_literal.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Independent exact scalar text oracle for the native Wave IR parser.""" + +import argparse +import ctypes +import random +import re + + +class Result(ctypes.Structure): + _fields_ = [(name, ctypes.c_uint64) for name in ("status", "low", "high", "work")] + + +def reference(text, category, width): + if category == 0: + return 8, 0 + if category == 1: + return (0, int(text == b"true")) if text in (b"true", b"false") else (1, 0) + if category == 4: + if not text.startswith(b"0x"): + return 6, 0 + if len(text) != width // 4 + 2 or re.fullmatch(b"[0-9a-fA-F]+", text[2:]) is None: + return 7, 0 + return 0, int(text[2:], 16) + if re.fullmatch(b"-?[0-9]+" if category == 2 else b"[0-9]+", text) is None: + return (2 if category == 2 else 4), 0 + negative = text.startswith(b"-") + digits = text[1:] if negative else text + value = int(digits.lstrip(b"0") or b"0") + if negative: + value = -value + if category == 2: + if value < -(1 << 127) or value >= (1 << 127): + return 3, 0 + if value < -(1 << (width - 1)) or value >= (1 << (width - 1)): + return 9, 0 + return 0, value & ((1 << 128) - 1) + if value >= (1 << 128): + return 5, 0 + if value >= (1 << width): + return 9, 0 + return 0, value + + +def call(kernel, text, category, width, work=None): + if work is None: + work = len(text) + buffer = ctypes.create_string_buffer(text) + result = Result() + status = kernel(buffer, len(text), category, width, work, ctypes.byref(result)) + assert status == result.status + value = result.low | (result.high << 64) + if status: + assert value == 0 + return status, value + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", required=True) + parser.add_argument("--cases", type=int, default=100000) + args = parser.parse_args() + kernel = ctypes.CDLL(args.library).whale_ir_parse_literal + kernel.argtypes = [ctypes.c_void_p, *([ctypes.c_uint64] * 4), ctypes.POINTER(Result)] + seeds = [b"", b"-", b"+1", b"-0", b"00", b"true", b"false", b"\xff", b"0x1234", + b"0X1234", b"0xFFFF", b"0x7ff0000000000001", b"0x7F800001", b"0xgggg", + b"9" * 100 + b"x", str(1 << 128).encode(), str(-(1 << 127)).encode(), + str((1 << 127) - 1).encode(), b"0" * 60000] + for category in range(5): + for width in ((16, 32, 64) if category == 4 else (1, 8, 16, 32, 64, 128)): + for text in seeds: + assert call(kernel, text, category, width) == reference(text, category, width), (text[:50], category, width) + for category in (2, 3): + for width in (1, 8, 16, 32, 64, 128): + for power in (0, width - 1, width, 127, 128): + for offset in (-1, 0, 1): + value = (1 << power) + offset + for value in (value, -value): + text = str(value).encode() + assert call(kernel, text, category, width) == reference(text, category, width) + randomizer = random.Random(0x3490352) + for case in range(args.cases): + category = randomizer.randrange(5) + width = randomizer.choice((16, 32, 64) if category == 4 else (1, 8, 16, 32, 64, 128)) + if category == 4: + text = ("0x" + format(randomizer.getrandbits(width), f"0{width // 4}x")).encode() + else: + value = randomizer.getrandbits(randomizer.randrange(0, 180)) + if randomizer.getrandbits(1): + value = -value + text = str(value).encode() + if case % 3 == 0: + text += randomizer.choice((b"x", b"\xff", b"_", b".")) + expected = reference(text, category, width) + assert call(kernel, text, category, width) == expected, (case, text, category, width, expected) + if text: + assert call(kernel, text, category, width, work=len(text) - 1)[0] == 10 + print(f"Wave IR literals: exact widths, lexical precedence, long zeros and {args.cases} independent cases passed") + + +if __name__ == "__main__": + main() diff --git a/tools/check_wave_ir_lower_type.py b/tools/check_wave_ir_lower_type.py new file mode 100644 index 0000000..1c16007 --- /dev/null +++ b/tools/check_wave_ir_lower_type.py @@ -0,0 +1,124 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Independent raw TypeRef-to-canonical-IR/layout conformance for Wave O0 lowering.""" +import argparse +import ctypes as C +import random + +from check_wave_ir_layout import Storage, Node as LayoutNode, Layout + + +class Type(C.Structure): + _fields_ = [(name, C.c_uint64) for name in ("kind", "child", "first", "count", "auxiliary")] + + +class Name(C.Structure): + _fields_ = [("data", C.c_void_p), ("length", C.c_uint64)] + + +class Result(C.Structure): + _fields_ = [(name, C.c_uint64) for name in ("status", "node", "expected", "actual", "annotation", "detail", "work")] + + +POINTER_NAMES = {"nodes", "edges", "names", "types", "type_edges", "type_table", "type_map", + "temporary", "name_marks", "storage", "layout_nodes", "layouts", "layout_offsets", "result"} + + +class Context(C.Structure): + _fields_ = [(name, C.c_void_p if name in POINTER_NAMES else C.c_uint64) for name in ( + "nodes", "node_count", "edges", "edge_count", "names", "name_count", "types", "type_count", "type_capacity", + "type_edges", "type_edge_count", "type_edge_capacity", "type_table", "type_table_capacity", "type_map", + "temporary", "temporary_count", "temporary_capacity", "name_marks", "marker", "storage", "layout_nodes", + "layouts", "layout_offsets", "annotation", "max_depth", "max_work", "work", "result")] + + +def call(kernel, nodes, edges=(), *, root=None, pointer=64, depth=32, work=1000000): + root = len(nodes) - 1 if root is None else root + raw = (C.c_uint64 * (len(nodes) * 12))(*[word for node in nodes for word in (*node, *([0] * (12 - len(node))))]) + links = (C.c_uint64 * len(edges))(*edges) + names = (Name * 256)(*[Name(None, 2) for _ in range(256)]) + capacity = 17 + len(nodes) * 2 + 32 + edge_capacity = max(64, len(edges) * 4 + 16) + type_nodes = (Type * capacity)() + type_edges = (C.c_uint64 * edge_capacity)() + table_capacity = 1 << ((capacity * 2 - 1).bit_length()) + table = (C.c_uint64 * table_capacity)() + mapping = (C.c_uint64 * len(nodes))() + temporary = (C.c_uint64 * (len(nodes) * 2 + 64))() + marks = (C.c_uint64 * 256)() + storage = Storage(pointer, pointer // 8, 1, 2, 4, 8, 16, 16, 16, 1) + layout_nodes = (LayoutNode * capacity)() + layouts = (Layout * capacity)() + offsets = (C.c_uint64 * edge_capacity)() + result = Result() + p = Context(C.addressof(raw), len(nodes), C.addressof(links), len(edges), C.addressof(names), 256, + C.addressof(type_nodes), 0, capacity, C.addressof(type_edges), 0, edge_capacity, + C.addressof(table), table_capacity, C.addressof(mapping), C.addressof(temporary), 0, + len(temporary), C.addressof(marks), 0, C.addressof(storage), C.addressof(layout_nodes), + C.addressof(layouts), C.addressof(offsets), 0, depth, work, 0, C.addressof(result)) + output = C.c_uint64(0xdead) + status = kernel(C.byref(p), root, C.byref(output)) + assert status == result.status and result.work <= work + if status: + assert output.value == 0xdead + return status, None, None + def shape(index): + n = type_nodes[index] + if n.kind <= 16: + return n.kind + if n.kind == 17: + return (17, shape(n.child)) + if n.kind == 19: + return (19, shape(n.child), n.auxiliary) + if n.kind == 20: + return (20, tuple(shape(type_edges[n.first + i]) for i in range(n.count))) + return (18, shape(n.child), tuple(shape(type_edges[n.first + i]) for i in range(n.count)), n.auxiliary) + layout = layouts[output.value] + return 0, shape(output.value), (layout.size, layout.align, layout.allocation_align) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", required=True) + parser.add_argument("--cases", type=int, default=10000) + args = parser.parse_args() + kernel = C.CDLL(args.library).whale_ir_lower_type + kernel.argtypes = [C.POINTER(Context), C.c_uint64, C.POINTER(C.c_uint64)] + kernel.restype = C.c_int32 + randomizer = random.Random(0x351) + scalars = [(101, 1, 1)] + for signed in (0, 1): + for width, signed_tag in ((1, 2), (8, 4), (16, 5), (32, 6), (64, 7), (128, 8)): + tag = signed_tag if signed else (3 if width == 1 else signed_tag + 5) + scalars.append(((102, width, signed), tag, max(1, width // 8))) + scalars = [((101,), 1, 1), *scalars[1:]] + [((103, width), tag, width // 8) for width, tag in ((16, 14), (32, 15), (64, 16))] + for _ in range(args.cases): + leaf, shape, size = randomizer.choice(scalars) + pointer = randomizer.choice((32, 64)) + nodes = [leaf] + expected_size = size + align = size + allocation = align + for _ in range(randomizer.randrange(0, 10)): + if randomizer.randrange(2): + nodes.append((104, len(nodes) - 1)); shape = (17, shape) + expected_size = align = allocation = pointer // 8 + else: + length = randomizer.randrange(0, 6) + nodes.append((106, len(nodes) - 1, length)); shape = (19, shape, length) + expected_size *= length + allocation = max(align, 16) if expected_size >= 16 else align + assert call(kernel, nodes, pointer=pointer) == (0, shape, (expected_size, align, allocation)) + # Independent field-name validation precedes nested type mapping. A nested + # struct reusing x must not hide a duplicate x in its parent. + nodes = [(102, 32, 1), (108, 0, 0), (107, 0, 1), (104, 2), (108, 0, 3), (108, 0, 0), (107, 1, 2)] + assert call(kernel, nodes, [1, 4, 5])[0] == 18 + assert call(kernel, [(102, 7, 1)])[0] == 5 + assert call(kernel, [(104, 0)], depth=16)[0] == 2 + assert call(kernel, [(102, 32, 1)], work=1)[0] == 1 + assert call(kernel, [(102, 32, 1)], root=9)[0] == 3 + print(f"Wave O0 type conversion: {args.cases} raw structural/layout cases, duplicate names and limits passed") + + +if __name__ == "__main__": + main() diff --git a/tools/check_wave_ir_lowering.py b/tools/check_wave_ir_lowering.py new file mode 100644 index 0000000..e6b88a3 --- /dev/null +++ b/tools/check_wave_ir_lowering.py @@ -0,0 +1,243 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Independent native AST O0 identity, instruction-order and budget checks.""" +import argparse +import ctypes as C +import random + +from check_wave_ir_layout import Storage, Node as LayoutNode, Layout +from check_wave_ir_lower_type import Context, Name, Result, Type + +NONE = (1 << 64) - 1 + + +def record(name, fields): + return type(name, (C.Structure,), {"_fields_": [(f, C.c_uint64) for f in fields.split()]}) + + +Instruction = record("Instruction", "tag dst ty a b c d e first count next annotation source") +Block = record("Block", "id function name first last allocation_last instruction_count term_kind term_a term_b term_c term_ty term_annotation term_source") +Constant = record("Constant", "kind operation ty low high left right reference annotation") +Declaration = record("Declaration", "name signature linkage link_name defined source") +Function = record("Function", "declaration first_param param_count first_block block_count entry source") +Global = record("Global", "name ty expression align annotation source") +Binding = record("Binding", "name ty value kind constant") +Field = record("Field", "name ordinal previous used") +Loop = record("Loop", "condition exit") +Annotation = record("Annotation", "original has_source file line column end_line end_column") +Request = record("Request", "expression kind identity annotation") +POINTERS = set("core instructions output_edges blocks constants declarations functions globals global_bindings bindings loops annotations original_table source_order source_marks type_sizes value_types declaration_map field_slots field_bindings local_slots global_slots mapping_order requests".split()) + + +class Driver(C.Structure): + _fields_ = [(f, C.c_void_p if f in POINTERS else C.c_uint64) for f in ( + "core mode expansion max_expansion instructions instruction_count instruction_capacity output_edges output_edge_count output_edge_capacity blocks block_count block_capacity constants declarations declaration_count declaration_capacity functions function_count function_capacity globals global_count global_capacity global_bindings global_binding_count bindings binding_count binding_capacity loops loop_count loop_capacity annotations annotation_count original_table original_capacity source_order source_count source_capacity source_marks type_sizes value_types value_capacity next_value declaration_map field_slots field_bindings field_binding_count field_binding_capacity current_function current_block entry return_type local_slots global_slots mapping_order mapping_count mapping_capacity source_work max_source_work error_index requests request_count request_capacity" + ).split()] + + +class Fixture: + def __init__(self): + self.nodes = [] + self.edges = [] + self.strings = [C.create_string_buffer(s.encode()) for s in ("entry", "x", "saved")] + self.keep = [] + + def node(self, *words): + self.nodes.append((*words, *([0] * (12 - len(words))))) + return len(self.nodes) - 1 + + def links(self, values): + start = len(self.edges) + self.edges.extend(values) + return start, len(values) + + def literal(self, width, signed, value): + b = C.create_string_buffer(str(value).encode()) + self.keep.append(b) + return self.node(17, width, signed, C.addressof(b), len(str(value))) + + def finish(self, ty, body, params=()): + first, count = self.links(params) + statements, length = self.links(body) + f = self.node(203, 0, first, count, ty, statements, length, 0, 0, NONE) + functions, count = self.links([f]) + return self.node(200, 0, 0, 0, 0, functions, count) + + +def run(kernel, fixture, root, *, work=1000000, expansion=1000000, depth=32, source_work=1000000, annotations=()): + n = len(fixture.nodes) + capacity = 17 + 4 * n + edge_capacity = 4 * n + 64 + table_capacity = 1 << (2 * capacity - 1).bit_length() + keep = [] + + def alloc(kind, count): + a = (kind * count)() + keep.append(a) + return a + + nodes = alloc(C.c_uint64, n * 12) + nodes[:] = [word for row in fixture.nodes for word in row] + edges = alloc(C.c_uint64, len(fixture.edges)) + edges[:] = fixture.edges + names = alloc(Name, len(fixture.strings)) + for i, b in enumerate(fixture.strings): + names[i] = Name(C.addressof(b), len(b.value)) + storage = Storage(64, 8, 1, 2, 4, 8, 16, 16, 16, 1) + result = Result() + core = Context() + for field, value in { + "nodes": nodes, "edges": edges, "names": names, + "types": alloc(Type, capacity), "type_edges": alloc(C.c_uint64, edge_capacity), + "type_table": alloc(C.c_uint64, table_capacity), "type_map": alloc(C.c_uint64, n), + "temporary": alloc(C.c_uint64, edge_capacity), "name_marks": alloc(C.c_uint64, len(names)), + "layout_nodes": alloc(LayoutNode, capacity), "layouts": alloc(Layout, capacity), + "layout_offsets": alloc(C.c_uint64, edge_capacity), "storage": storage, "result": result, + }.items(): + setattr(core, field, C.addressof(value)) + core.node_count, core.edge_count, core.name_count = n, len(edges), len(names) + core.type_capacity, core.type_edge_capacity = capacity, edge_capacity + core.type_table_capacity, core.temporary_capacity = table_capacity, edge_capacity + core.max_depth, core.max_work = depth, work + d = Driver() + d.core, d.max_expansion, d.max_source_work = C.addressof(core), expansion, source_work + buffers = {} + for field, kind, count in ( + ("blocks", Block, 4 * n + 8), ("constants", Constant, n), + ("declarations", Declaration, n), ("functions", Function, n), ("globals", Global, n), + ("global_bindings", Binding, n), ("bindings", Binding, n + 8), ("loops", Loop, n + 8), + ("type_sizes", C.c_uint64, capacity), ("declaration_map", C.c_uint64, len(names)), + ("field_slots", C.c_uint64, len(names)), ("field_bindings", Field, n + 8), + ("local_slots", C.c_uint64, len(names)), ("global_slots", C.c_uint64, len(names)), + ("requests", Request, n), + ): + buffers[field] = alloc(kind, count) + setattr(d, field, C.addressof(buffers[field])) + for field, kind in (("annotations", Annotation), ("source_marks", C.c_uint64), + ("source_order", C.c_uint64), ("mapping_order", C.c_uint64)): + buffers[field] = alloc(kind, len(annotations)) + setattr(d, field, C.addressof(buffers[field])) + for i, annotation in enumerate(annotations): + buffers["annotations"][i] = Annotation(*annotation) + d.annotation_count = d.source_capacity = d.mapping_capacity = len(annotations) + for field, value in {"block_capacity": 4 * n + 8, "declaration_capacity": n, + "function_capacity": n, "global_capacity": n, "binding_capacity": n + 8, + "loop_capacity": n + 8, "field_binding_capacity": n + 8, + "request_capacity": n}.items(): + setattr(d, field, value) + status = kernel(C.byref(d), root) + assert status == result.status and core.work == result.work <= work + if status: + return status, result, None + counts = d.instruction_count, d.output_edge_count, d.next_value + for field, kind, count in (("instructions", Instruction, counts[0]), ("output_edges", C.c_uint64, counts[1]), + ("value_types", C.c_uint64, counts[2])): + buffers[field] = alloc(kind, count) + setattr(d, field, C.addressof(buffers[field])) + d.mode, d.instruction_capacity, d.output_edge_capacity, d.value_capacity = 1, *counts + status = kernel(C.byref(d), root) + assert status == result.status == 0 and counts == (d.instruction_count, d.output_edge_count, d.next_value) + assert core.work == result.work <= work + # Keep every native pointee alive until all independent assertions finish. + buffers["_keep"] = keep + return status, result, (d, buffers, C.cast(core.types, C.POINTER(Type))) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", required=True) + parser.add_argument("--cases", type=int, default=10000) + args = parser.parse_args() + library = C.CDLL(args.library) + kernel = library.whale_ir_lower_o0 + kernel.argtypes = [C.POINTER(Driver), C.c_uint64] + kernel.restype = C.c_int32 + randomizer = random.Random(0x351_000) + for _ in range(args.cases): + width = randomizer.choice((1, 8, 16, 32, 64, 128)) + signed = randomizer.randrange(2) + opcode = randomizer.randrange(10) + payload = randomizer.randrange(0, 1 << min(width - signed, 127)) + if signed and randomizer.randrange(2): + payload = -payload + f = Fixture() + ty = f.node(102, width, signed) + param = f.node(204, 1, ty) + load = f.node(15, 1) + literal = f.literal(width, signed, payload) + operation = f.node(19, load, opcode, literal) + ret = f.node(51, operation) + root = f.finish(ty, [ret], [param]) + status, _, output = run(kernel, f, root, source_work=0) + assert status == 0 + d, b, types = output + assert (d.function_count, d.declaration_count, d.block_count, d.next_value) == (1, 1, 1, 5) + instructions = b["instructions"] + assert [i.tag for i in instructions] == [18, 23, 21, 4, 7] + assert [i.next for i in instructions] == [1, 2, 3, 4, NONE] + block = b["blocks"][0] + assert (block.first, block.last, block.instruction_count, block.term_kind, block.term_a) == (0, 4, 5, 3, 4) + expected = {0: 0, 1: 1, 2: 2, 3: 12, 4: 13, 5: 14, 6: 4 if signed else 3, + 7: 6 if signed else 5, 8: 15, 9: 17 if signed else 16}[opcode] + assert (instructions[4].dst, instructions[4].a, instructions[4].b, instructions[4].c) == (4, expected, 2, 3) + bits = payload & ((1 << 128) - 1) + assert (instructions[3].b, instructions[3].c, instructions[3].d) == (bits & NONE, bits >> 64, 2 if signed else 3) + assert instructions[0].dst == 1 and instructions[1].a == 0 and instructions[1].b == 1 + assert types[b["value_types"][1]].kind == 17 + # Later allocations are hoisted among entry allocas without moving source + # ownership onto unrelated operations, while all SSA identities stay stable. + f = Fixture() + ty = f.node(102, 32, 1) + first = f.node(55, 1, ty, f.literal(32, 1, 1)) + first = f.node(50, 0, first) + second = f.node(55, 2, ty, f.literal(32, 1, 3)) + root = f.finish(ty, [first, second, f.node(51, f.node(15, 1))]) + status, _, output = run(kernel, f, root, annotations=[(100, 0, 0, 0, 0, 0, 0)]) + assert status == 0 + d, b, _ = output + body = [] + index = b["blocks"][0].first + while index != NONE: + body.append(index) + index = b["instructions"][index].next + assert body == [1, 4, 0, 2, 3, 5, 6] + assert [b["instructions"][i].annotation for i in body] == [0, NONE, 0, 0, NONE, NONE, NONE] + assert d.source_count == d.mapping_count == 1 and b["source_order"][0] == b["mapping_order"][0] == 0 + assert run(kernel, f, root, source_work=0, annotations=[(100, 0, 0, 0, 0, 0, 0)])[0] == 22 + + # Lazy logical operations preserve their skipped RHS in a separate block + # and produce a phi with exact predecessor identities. + for opcode in (10, 11): + f = Fixture() + ty = f.node(101) + param = f.node(204, 1, ty) + expression = f.node(19, f.node(15, 1), opcode, f.node(16, 1)) + root = f.finish(ty, [f.node(51, expression)], [param]) + status, _, output = run(kernel, f, root) + assert status == 0 + d, b, _ = output + blocks, instructions = b["blocks"], b["instructions"] + assert d.block_count == 3 and [blocks[i].name for i in range(3)] == [0, 8, 9] + assert (blocks[0].term_kind, blocks[0].term_a) == (2, 2) + assert (blocks[0].term_b, blocks[0].term_c) == ((1, 2) if opcode == 10 else (2, 1)) + assert (blocks[1].term_kind, blocks[1].term_a) == (1, 2) + phi = instructions[blocks[2].first] + assert phi.tag == 15 and list(b["output_edges"])[phi.first:phi.first + phi.count] == [2, 0, 3, 1] + assert (blocks[2].term_kind, blocks[2].term_a) == (3, 4) + + f = Fixture() + ty = f.node(102, 32, 1) + value = f.literal(32, 1, 42) + root = f.finish(ty, [f.node(51, value)]) + assert run(kernel, f, root, work=1)[0] == 1 + assert run(kernel, f, root, expansion=1)[0] == 23 + assert run(kernel, f, root, depth=0)[0] == 2 + assert run(kernel, f, len(f.nodes) + 1)[0] == 3 + # Cycles cannot recurse past the explicit AST ceiling. + f.nodes[value] = (10, value, *([0] * 10)) + assert run(kernel, f, root, depth=8)[0] == 2 + print(f"Wave AST O0 lowering: {args.cases} independent opcode/literal/SSA vectors, hoisting, source mapping, lazy CFG and limits passed") + + +if __name__ == "__main__": + main() diff --git a/tools/check_wave_ir_printer.py b/tools/check_wave_ir_printer.py new file mode 100644 index 0000000..3c5fb21 --- /dev/null +++ b/tools/check_wave_ir_printer.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Exercise real Wave canonical output independently, including bounded resume.""" +import argparse +import ctypes as C +import random + + +class State(C.Structure): + _fields_ = [(name, C.c_void_p if name in ("nodes", "edges", "stack") else C.c_uint64) + for name in ("nodes", "node_count", "edges", "edge_count", "stack", + "stack_capacity", "stack_len", "output_limit", "total", "work", + "depth_limit", "status", "initialized")] + + +def render(kernel, nodes, edges=(), *, root=None, chunk=7, output_limit=1_000_000, + work=10_000_000, stack_capacity=1024, depth=256): + raw = (C.c_uint64 * (len(nodes) * 12))(*[word for node in nodes + for word in (*node, *((0,) * (12 - len(node))))]) + edge_array = (C.c_uint64 * len(edges))(*edges) + stack = (C.c_uint64 * (stack_capacity * 10))() + state = State(C.addressof(raw), len(nodes), C.addressof(edge_array), len(edges), + C.addressof(stack), stack_capacity, 0, output_limit, 0, work, depth, 0, 0) + root = len(nodes) - 1 if root is None else root + result = bytearray() + while True: + # Canaries prove that every step respects the caller's exact span. + buffer = (C.c_ubyte * (chunk + 2))(*([0xAA] * (chunk + 2))) + written = C.c_uint64() + status = kernel(C.byref(state), root, C.byref(buffer, 1), chunk, C.byref(written)) + assert written.value <= chunk + assert buffer[0] == buffer[chunk + 1] == 0xAA + result.extend(buffer[1:1 + written.value]) + assert len(result) <= output_limit and state.total == len(result) + if status != 6: + return status, bytes(result) + assert chunk > 0 + + +def escaped(text): + result = '"' + for character in text: + cp = ord(character) + if character in ('\\', '"'): + result += '\\' + character + elif cp in (0, 9, 10, 13): + result += {0: '\\0', 9: '\\t', 10: '\\n', 13: '\\r'}[cp] + elif cp < 32 or 127 <= cp <= 159 or cp in (0x2028, 0x2029): + result += f'\\u{{{cp:x}}}' + else: + result += character + return (result + '"').encode() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", required=True) + parser.add_argument("--cases", type=int, default=10000) + args = parser.parse_args() + kernel = C.CDLL(args.library).whale_ir_print_step + kernel.argtypes = [C.POINTER(State), C.c_uint64, C.c_void_p, C.c_uint64, + C.POINTER(C.c_uint64)] + kernel.restype = C.c_int32 + randomizer = random.Random(0x349) + values = [0, 1, (1 << 64) - 1, 1 << 64, (1 << 127) - 1, 1 << 127, (1 << 128) - 1] + values += [randomizer.getrandbits(128) for _ in range(args.cases)] + for value in values: + low, high = value & ((1 << 64) - 1), value >> 64 + for tag, integer in ((32, value if value < 1 << 127 else value - (1 << 128)), + (33, value)): + expected = str(integer).encode() + assert render(kernel, [(tag, low, high)], chunk=1 + value % 41) == (0, expected) + assert render(kernel, [(tag, low, high)], output_limit=len(expected)) == (0, expected) + status, prefix = render(kernel, [(tag, low, high)], output_limit=len(expected) - 1) + assert status == 2 and prefix == expected[:-1] + width = randomizer.choice((16, 32, 64)) + bits = low & ((1 << width) - 1) + expected = f'0x{bits:0{width // 4}x}'.encode() + assert render(kernel, [(34, bits, width)]) == (0, expected) + alphabet = [chr(cp) for cp in range(160)] + ['\u2028', '\u2029', '가', '😀', '\U0010ffff'] + strings = [''.join(alphabet), '', '\\"\n', 'abc' * 20000] + strings += [''.join(randomizer.choices(alphabet, k=randomizer.randrange(50))) + for _ in range(args.cases // 10)] + for text in strings: + data = C.create_string_buffer(text.encode()) + assert render(kernel, [(30, C.addressof(data), len(text.encode()))], chunk=13) == (0, escaped(text)) + assert render(kernel, [(18, 0)], depth=32)[0] == 5 # cycle + assert render(kernel, [(18, 1)])[0] == 1 # invalid child + assert render(kernel, [(1,)], work=0)[0] == 4 + assert render(kernel, [(1,)], stack_capacity=0)[0] == 3 + assert render(kernel, [(51, 0, 2, 0)], edges=[9, 9])[0] == 1 + assert render(kernel, [(51, 0, 1, 0)])[0] == 1 + malformed = C.create_string_buffer(b'\xff') + assert render(kernel, [(30, C.addressof(malformed), 1)])[0] == 1 + nodes = [(1,), (51, 0, 60000, 0)] + assert render(kernel, nodes, [0] * 60000, chunk=1024, stack_capacity=32) == (0, b'void' * 60000) + print(f"Wave IR printer: {len(values)} 128-bit vectors, float bits, {len(strings)} UTF-8 strings, limits and 60000-node stream passed") + + +if __name__ == "__main__": + main() diff --git a/tools/check_wave_ir_shape.py b/tools/check_wave_ir_shape.py new file mode 100644 index 0000000..d8774db --- /dev/null +++ b/tools/check_wave_ir_shape.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Independent structural IR identity and branch-shape Wave vectors.""" + +import argparse +import ctypes +import random + + +class Block(ctypes.Structure): + _fields_ = [(name, ctypes.c_uint64) for name in + ("id", "terminated", "first_edge", "edge_count")] + + +class Value(ctypes.Structure): + _fields_ = [("id", ctypes.c_uint64), ("void_parameter", ctypes.c_uint64)] + + +class Result(ctypes.Structure): + _fields_ = [(name, ctypes.c_uint64) for name in ("status", "index", "detail", "work")] + + +def call(kernel, blocks, entry, values, work=100000): + raw_blocks = [] + raw_edges = [] + for identity, terminated, targets in blocks: + raw_blocks.append(Block(identity, terminated, len(raw_edges), len(targets))) + raw_edges.extend(targets) + block_array = (Block * len(blocks))(*raw_blocks) + values_array = (Value * len(values))(*(Value(*value) for value in values)) + edges_array = (ctypes.c_uint64 * len(raw_edges))(*raw_edges) + block_capacity = 1 << (max(2, 2 * len(blocks)) - 1).bit_length() + value_capacity = 1 << (max(2, 2 * len(values)) - 1).bit_length() + block_table = (ctypes.c_uint64 * block_capacity)() + value_table = (ctypes.c_uint64 * value_capacity)() + result = Result() + status = kernel(block_array, len(blocks), entry, values_array, len(values), + edges_array, len(raw_edges), work, block_table, block_capacity, + value_table, value_capacity, ctypes.byref(result)) + assert status == result.status + return status, result.index, result.detail, result.work + + +def reference(blocks, entry, values): + seen_blocks = set() + for index, (identity, _, _) in enumerate(blocks): + if identity in seen_blocks: + return 1, index, identity + seen_blocks.add(identity) + if entry not in seen_blocks: + return 2, 0, entry + seen_values = set() + for index, (identity, void) in enumerate(values): + if void: + return 8, index, identity + if identity in seen_values: + return 3, index, identity + seen_values.add(identity) + for index, (identity, terminated, targets) in enumerate(blocks): + if not terminated: + return 4, index, identity + for target in targets: + if target not in seen_blocks: + return 5, index, target + return 0, 0, 0 + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", required=True) + parser.add_argument("--cases", type=int, default=10000) + args = parser.parse_args() + kernel = ctypes.CDLL(args.library).whale_ir_verify_shape + kernel.argtypes = [ctypes.c_void_p, ctypes.c_uint64, ctypes.c_uint64, + ctypes.c_void_p, ctypes.c_uint64, ctypes.c_void_p, + ctypes.c_uint64, ctypes.c_uint64, ctypes.c_void_p, + ctypes.c_uint64, ctypes.c_void_p, ctypes.c_uint64, + ctypes.POINTER(Result)] + seeds = [([(0, 1, [1]), (1, 1, [])], 0, [(0, 0)]), + ([(0, 1, []), (0, 1, [])], 0, []), + ([(0, 1, [])], 2, []), + ([(0, 0, [])], 0, [(0, 1)]), + ([(0, 1, [7])], 0, [(2, 0), (2, 0)])] + for blocks, entry, values in seeds: + assert call(kernel, blocks, entry, values)[:3] == reference(blocks, entry, values) + assert call(kernel, [(0, 1, [])], 0, [], work=0)[0] == 7 + chain = [(index, 1, [index + 1] if index < 59999 else []) + for index in range(60000)] + identities = [(index, 0) for index in range(60000)] + assert call(kernel, chain, 0, identities, work=2000000)[0] == 0 + randomizer = random.Random(0x3480350) + for index in range(args.cases): + count = randomizer.randrange(0, 24) + blocks = [(randomizer.randrange(0, 30), randomizer.randrange(0, 2), + [randomizer.randrange(0, 30) for _ in range(randomizer.randrange(0, 4))]) + for _ in range(count)] + values = [(randomizer.randrange(0, 30), randomizer.randrange(0, 2)) + for _ in range(randomizer.randrange(0, 30))] + entry = randomizer.randrange(0, 30) + actual = call(kernel, blocks, entry, values)[:3] + expected = reference(blocks, entry, values) + assert actual == expected, (index, blocks, entry, values, actual, expected) + for index in range(args.cases // 2): + count = randomizer.randrange(1, 40) + identities = randomizer.sample(range(0, 100000), count) + blocks = [(identity, 1, + [randomizer.choice(identities) for _ in range(randomizer.randrange(0, 4))]) + for identity in identities] + values = [(identity, 0) for identity in randomizer.sample(range(0, 100000), + randomizer.randrange(0, 40))] + entry = randomizer.choice(identities) + if index % 6 == 0 and count > 1: + blocks[-1] = (blocks[0][0], 1, blocks[-1][2]) + elif index % 6 == 1: + entry = 100001 + elif index % 6 == 2 and values: + values.append(values[0]) + elif index % 6 == 3 and values: + values[-1] = (values[-1][0], 1) + elif index % 6 == 4: + blocks[-1] = (blocks[-1][0], 0, blocks[-1][2]) + elif index % 6 == 5: + blocks[-1][2].append(100001) + actual = call(kernel, blocks, entry, values)[:3] + expected = reference(blocks, entry, values) + assert actual == expected, (index, blocks, entry, values, actual, expected) + print(f"Wave IR shape: vectors, limits and {args.cases + args.cases // 2} cases passed") + + +if __name__ == "__main__": + main() diff --git a/tools/check_wave_ir_source.py b/tools/check_wave_ir_source.py new file mode 100644 index 0000000..4dc410a --- /dev/null +++ b/tools/check_wave_ir_source.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Independent source identity, span, mapping and bounded-work vectors.""" +import argparse +import ctypes as c +import random + + +class File(c.Structure): + _fields_ = [('id', c.c_uint64), ('bytes', c.c_void_p), ('length', c.c_uint64)] + + +def record(name, fields): + return type(name, (c.Structure,), {'_fields_': [(key, c.c_uint64) for key in fields.split()]}) + + +Original = record('Original', 'id has_span file line column end_line end_column') +Block = record('Block', 'function block instructions terminated') +Mapping = record('Mapping', 'kind function block index original') +Slot = record('Slot', 'kind a b c value extra') +Result = record('Result', 'status index work') + + +def expected(files, nodes, blocks, globals_, mappings): + seen = set() + for ident, name in files: + if not name or b'\0' in name or ident in seen: + return 1 + seen.add(ident) + originals = set() + for ident, present, file, line, column, end_line, end_column in nodes: + if ident in originals: + return 2 + originals.add(ident) + if present and (file not in seen or min(line, column, end_line, end_column) == 0 + or (line, column) > (end_line, end_column)): + return 3 + block_map = {(f, b): (n, t) for f, b, n, t in blocks} + seen_targets = set() + for kind, f, b, index, ident in mappings: + key = (kind, f, b, index) + if ident not in originals or key in seen_targets: + return 4 + seen_targets.add(key) + if kind == 2: + if f not in globals_: + return 5 + elif (f, b) not in block_map or not ( + index < block_map[f, b][0] if kind == 0 else block_map[f, b][1]): + return 5 + return 0 + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--library', required=True) + parser.add_argument('--cases', type=int, default=10000) + args = parser.parse_args() + kernel = c.CDLL(args.library).whale_ir_verify_sources + kernel.argtypes = [c.c_void_p, c.c_uint64] * 6 + [c.c_uint64, c.POINTER(Result)] + + def run(files, nodes, blocks, globals_, mappings, work=1000000, capacity=None): + buffers = [c.create_string_buffer(name) for _, name in files] + raw_files = (File * len(files))(*(File(ident, c.cast(buf, c.c_void_p), len(name)) + for (ident, name), buf in zip(files, buffers))) + raw_nodes = (Original * len(nodes))(*(Original(*n) for n in nodes)) + raw_blocks = (Block * len(blocks))(*(Block(*b) for b in blocks)) + raw_globals = (c.c_uint64 * len(globals_))(*globals_) + raw_maps = (Mapping * len(mappings))(*(Mapping(*m) for m in mappings)) + count = len(files) + len(nodes) + len(blocks) + len(globals_) + len(mappings) + capacity = capacity if capacity is not None else 1 << (max(1, count) * 2 - 1).bit_length() + slots = (Slot * capacity)() + result = Result() + status = kernel(raw_files, len(files), raw_nodes, len(nodes), raw_blocks, len(blocks), + raw_globals, len(globals_), raw_maps, len(mappings), slots, capacity, + work, c.byref(result)) + assert status == result.status and result.work <= work, (status, result.status, result.work) + return status + + rng = random.Random(350_348) + for case in range(args.cases): + n = rng.randrange(1, 30) + files = [(i, ('경로%d.wave' % i).encode()) for i in range(n)] + nodes = [(i, rng.randrange(2), i, 1, 3, 1, 7) for i in range(n)] + blocks = [(i, i + 1, rng.randrange(3), rng.randrange(2)) for i in range(n)] + globals_ = list(range(n)) + mappings = [(kind, rng.randrange(n + 1), rng.randrange(n + 2) if kind < 2 else 0, + rng.randrange(3) if kind == 0 else 0, rng.randrange(n + 1)) + for kind in (rng.randrange(3) for _ in range(rng.randrange(30)))] + mutation = case % 10 + if mutation == 0: + files.append(files[-1]) + elif mutation == 1: + files[-1] = (files[-1][0], b'') + elif mutation == 2: + files[-1] = (files[-1][0], b'a\0b') + elif mutation == 3: + nodes.append(nodes[-1]) + elif mutation == 4: + nodes[-1] = (n - 1, 1, n - 1, 0, 0, 0, 0) + elif mutation == 5: + nodes[-1] = (n - 1, 1, n - 1, 1, 9, 1, 3) + elif mutation == 6: + mappings = [(1, 0, 1, 0, 0)] * 2 + elif mutation == 7: + mappings = [(0, i, i + 1, 0, i) for i in range(n) if blocks[i][2] > 0] + elif mutation == 8: + mappings = [(2, i, 0, 0, i) for i in range(n)] + else: + files[-1] = (2**64 - 1, files[-1][1]) + nodes[-1] = (2**64 - 1, 1, 2**64 - 1, 1, 1, 2**32 - 1, 1) + mappings = [(2, 0, 0, 0, 2**64 - 1)] + assert run(files, nodes, blocks, globals_, mappings) == expected(files, nodes, blocks, globals_, mappings), case + valid = ([(0, b'a')], [(0, 1, 0, 1, 1, 1, 1)], [(0, 0, 1, 1)], [0], [(0, 0, 0, 0, 0)]) + assert run(*valid, work=0) == 7 + assert run(*valid, capacity=2) == 6 + assert run(*valid, capacity=3) == 6 + # A duplicated block key must preserve the latest body just like the reference map. + assert run(valid[0], valid[1], [(0, 0, 1, 1), (0, 0, 0, 0)], valid[3], valid[4]) == 5 + count = 60000 + wide = ([(0, b'wide.wave')], [(i, 0, 0, 0, 0, 0, 0) for i in range(count)], + [(0, 0, count, 1)], [], [(0, 0, 0, i, i) for i in range(count)]) + assert run(*wide, work=10000000) == 0 + assert run(*wide, work=1000) == 7 + print(f'Wave IR source metadata: {args.cases} independent vectors, 60000 mappings and work limits passed') + + +if __name__ == '__main__': + main() diff --git a/tools/check_wave_ir_ssa.py b/tools/check_wave_ir_ssa.py new file mode 100644 index 0000000..179ff7d --- /dev/null +++ b/tools/check_wave_ir_ssa.py @@ -0,0 +1,164 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Check real Wave SSA/phi validation against an independent dominance oracle.""" + +import argparse +import ctypes as C +import random + +from wave_ir_verifier_oracle import NONE, SCALARS, Node + + +class Block(C.Structure): + _fields_ = [(name, C.c_uint64) for name in + ("id", "first", "count", "pred_first", "pred_count", "reachable", + "start", "end", "terminator_use")] + + +class Instruction(C.Structure): + _fields_ = [(name, C.c_uint64) for name in ("phi", "dst", "ty", "first", "count")] + + +class Usage(C.Structure): + _fields_ = [(name, C.c_uint64) for name in + ("value", "ty", "pred", "def_block", "def_position", "defined")] + + +class Predecessor(C.Structure): + _fields_ = [(name, C.c_uint64) for name in ("block", "seen")] + + +class Result(C.Structure): + _fields_ = [(name, C.c_uint64) for name in + ("status", "instruction", "usage", "detail", "work", "queries")] + + +def call(kernel, blocks, instructions, uses, predecessors, capacity=128, work=1_000_000): + nodes = (Node * len(SCALARS))(*SCALARS) + edges = (C.c_uint64 * 0)() + block_array = (Block * len(blocks))(*blocks) + instruction_array = (Instruction * len(instructions))(*instructions) + use_array = (Usage * len(uses))(*uses) + predecessor_array = (C.c_uint64 * len(predecessors))(*predecessors) + table = (Predecessor * capacity)() + result = Result() + status = kernel(nodes, len(nodes), edges, 0, block_array, len(blocks), 0, + instruction_array, len(instructions), use_array, len(uses), + predecessor_array, len(predecessors), table, capacity, work, C.byref(result)) + assert status == result.status + assert result.work <= work and result.queries <= result.work + return status, result + + +def intervals_from_sets(predecessors): + """Independent set intersection, unrelated to the Wave immediate-idom kernel.""" + size = len(predecessors) + dominators = [set(range(size)) for _ in predecessors] + dominators[0] = {0} + for block in range(1, size): + dominators[block] = {block} | set.intersection(*(dominators[p] for p in predecessors[block])) + parents = [None] + [max(dominators[block] - {block}, key=lambda p: len(dominators[p])) + for block in range(1, size)] + children = [[] for _ in predecessors] + for block in range(1, size): + children[parents[block]].append(block) + intervals, clock = [None] * size, 0 + + def visit(block): + nonlocal clock + start, clock = clock, clock + 1 + for child in children[block]: + visit(child) + intervals[block], clock = (start, clock), clock + 1 + + visit(0) + return dominators, intervals + + +def random_cases(kernel, cases): + randomizer = random.Random(0x3501) + for trial in range(cases): + size = randomizer.randint(2, 30) + predecessors = [[] for _ in range(size)] + for block in range(1, size): + predecessors[block] = [source for source in range(block) + if source == block - 1 or randomizer.randrange(7) == 0] + dominators, intervals = intervals_from_sets(predecessors) + uses, instructions, edges, blocks = [], [], [], [] + expected, expected_usage = 0, None + for block in range(size): + first_use = len(uses) + for _ in range(randomizer.randrange(4)): + definition = randomizer.randrange(size + 1) + if definition == size: + uses.append(Usage(100, NONE, NONE, NONE, 0, 1)) + continue + uses.append(Usage(definition + 1, NONE, NONE, definition, 0, 1)) + if expected == 0 and (definition == block or definition not in dominators[block]): + expected, expected_usage = 3, len(uses) - 1 + instructions.append(Instruction(0, block + 1, 0, first_use, len(uses) - first_use)) + first_predecessor = len(edges) + edges.extend(predecessors[block]) + start, end = intervals[block] + blocks.append(Block(block + 10, block, 1, first_predecessor, + len(predecessors[block]), 1, start, end, NONE)) + status, result = call(kernel, blocks, instructions, uses, edges) + assert status == expected, (trial, status, expected) + if status: + assert result.usage == expected_usage, (trial, result.usage, expected_usage) + + +def vectors(kernel): + blocks = [Block(10, 0, 1, 0, 0, 1, 0, 7, NONE), + Block(11, 1, 1, 0, 1, 1, 1, 2, NONE), + Block(12, 2, 1, 1, 1, 1, 3, 4, NONE), + Block(13, 3, 1, 2, 2, 1, 5, 6, NONE)] + instructions = [Instruction(0, 1, 0, 0, 0), Instruction(0, 2, 0, 0, 0), + Instruction(0, 3, 0, 0, 0), Instruction(1, 4, 6, 0, 2)] + uses = [Usage(2, 6, 1, 1, 0, 1), Usage(3, 6, 2, 2, 0, 1)] + predecessors = [0, 0, 1, 2] + assert call(kernel, blocks, instructions, uses, predecessors)[0] == 0 + uses[1].pred = 1 + status, result = call(kernel, blocks, instructions, uses, predecessors) + assert status == 1 and result.detail == 5 + uses[1].pred = NONE + status, result = call(kernel, blocks, instructions, uses, predecessors) + assert status == 1 and result.detail == 3 + uses[1].pred, uses[1].ty = 2, 7 + assert call(kernel, blocks, instructions, uses, predecessors)[0] == 5 + uses[1].ty, uses[1].def_block = 6, 1 + assert call(kernel, blocks, instructions, uses, predecessors)[0] == 3 + uses[1].def_block = 2 + assert call(kernel, blocks, instructions, uses, predecessors, work=0)[0] == 8 + assert call(kernel, blocks, instructions, uses, predecessors, capacity=1)[0] == 7 + uses[1].defined = 0 + assert call(kernel, blocks, instructions, uses, predecessors)[0] == 2 + # Structurally unreachable instructions keep identity/type checks, while + # executable dominance does not apply to their ordinary uses. + blocks[3].reachable = 0 + instructions[3].phi = 0 + uses[1].defined = 1 + assert call(kernel, blocks, instructions, uses, predecessors)[0] == 0 + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", required=True) + parser.add_argument("--cases", type=int, default=10000) + args = parser.parse_args() + assert args.cases >= 0 + library = C.CDLL(args.library) + kernel = library.whale_ir_verify_ssa + kernel.restype = C.c_int32 + kernel.argtypes = [C.POINTER(Node), C.c_uint64, C.POINTER(C.c_uint64), C.c_uint64, + C.POINTER(Block), C.c_uint64, C.c_uint64, C.POINTER(Instruction), + C.c_uint64, C.POINTER(Usage), C.c_uint64, C.POINTER(C.c_uint64), + C.c_uint64, C.POINTER(Predecessor), C.c_uint64, C.c_uint64, + C.POINTER(Result)] + vectors(kernel) + random_cases(kernel, args.cases) + print(f"Wave IR SSA: phi/type/unreachable/resource vectors and {args.cases} graphs passed") + + +if __name__ == "__main__": + main() diff --git a/tools/check_wave_ir_type.py b/tools/check_wave_ir_type.py new file mode 100644 index 0000000..60c7cd0 --- /dev/null +++ b/tools/check_wave_ir_type.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Independent generated type trees and bounded native Wave parser checks.""" + +import argparse +import ctypes +import random + + +class Token(ctypes.Structure): + _fields_ = [("data", ctypes.c_void_p), ("length", ctypes.c_uint64), + ("kind", ctypes.c_uint64)] + + +class Node(ctypes.Structure): + _fields_ = [(name, ctypes.c_uint64) for name in ("kind", "value", "count")] + + +class Result(ctypes.Structure): + _fields_ = [(name, ctypes.c_uint64) for name in + ("status", "reason", "at", "expected", "next", "nodes", "work")] + + +LEAVES = "void bool i1 u1 i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f16 f32 f64".split() +MARKS = {"<", ">", "{", "}", "(", ")", ",", "->"} + + +def call(kernel, words, *, mode=1, capacity=None, output_capacity=None, + max_depth=128, max_nodes=100000, max_work=1000000): + if capacity is None: + capacity = len(words) + if output_capacity is None: + output_capacity = capacity + buffers = [ctypes.create_string_buffer(word.encode()) for word in words] + raw = (Token * (len(words) + 1))(*[ + Token(ctypes.cast(buffer, ctypes.c_void_p), len(word.encode()), + 2 if word in MARKS else 0) + for buffer, word in zip(buffers, words)], Token(None, 0, 3)) + scratch = (Node * capacity)() + output = (Node * output_capacity)(*[Node(99, 99, 99) for _ in range(output_capacity)]) + result = Result() + status = kernel(raw, len(raw), 0, 0, max_depth, max_nodes, max_work, + mode, scratch, capacity, output, output_capacity, ctypes.byref(result)) + assert status == result.status + if status or mode == 0: + assert all((node.kind, node.value, node.count) == (99, 99, 99) for node in output) + nodes = [(node.kind, node.value, node.count) for node in output[:result.nodes]] if status == 0 and mode == 1 else [] + return status, result, nodes + + +def generated(randomizer, depth): + kind = randomizer.randrange(17 if depth == 0 else 22) + if kind < 17: + return [LEAVES[kind]], [(kind, 0, 0)] + if kind == 17: + words, nodes = generated(randomizer, depth - 1) + return ["ptr", "<", *words, ">"], [*nodes, (kind, 0, 1)] + if kind == 19: + words, nodes = generated(randomizer, depth - 1) + count = randomizer.randrange(1 << 64) + return ["array", "<", *words, ",", str(count), ">"], [*nodes, (kind, count, 1)] + fields = [generated(randomizer, depth - 1) for _ in range(randomizer.randrange(4))] + words = [] + nodes = [] + for index, (field_words, field_nodes) in enumerate(fields): + if index: + words.append(",") + words.extend(field_words) + nodes.extend(field_nodes) + if kind == 18: + ret_words, ret_nodes = generated(randomizer, depth - 1) + convention = randomizer.randrange(2) + return (["fnptr", "<", "whale" if convention == 0 else "sysv64", "(", + *words, ")", "->", *ret_words, ">"], + [*nodes, *ret_nodes, (kind, convention, len(fields))]) + opening, closing = ("{", "}") if kind == 20 else ("<", ">") + return (["struct" if kind == 20 else "tuple", opening, *words, closing], + [*nodes, (kind, 0, len(fields))]) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", required=True) + parser.add_argument("--cases", type=int, default=10000) + args = parser.parse_args() + kernel = ctypes.CDLL(args.library).whale_ir_parse_type + kernel.argtypes = [ctypes.c_void_p, *([ctypes.c_uint64] * 7), ctypes.c_void_p, + ctypes.c_uint64, ctypes.c_void_p, ctypes.c_uint64, + ctypes.POINTER(Result)] + for index, word in enumerate(LEAVES): + assert call(kernel, [word])[2] == [(index, 0, 0)] + for words, status in [ + (["ptr", "<", "i32"], 1), (["struct", "{", "i32", ",", "}"], 1), + (["array", "<", "i8", ",", "18446744073709551616", ">"], 1), + (["array", "<", "i8", ",", "18446744073709551616x", ">"], 1), + (["fnptr", "<", "unknown", "(", ")", "->", "i32", ">"], 1), + ]: + assert call(kernel, words)[0] == status + assert call(kernel, ["ptr", "<", "i32", ">"], max_depth=0)[0] == 2 + assert call(kernel, ["i32"], max_nodes=0)[0] == 3 + assert call(kernel, ["i32"], max_work=0)[0] == 4 + assert call(kernel, ["i32"], capacity=0)[0] == 5 + assert call(kernel, ["i32"], output_capacity=0)[0] == 5 + wide = ["struct", "{"] + for index in range(60000): + if index: + wide.append(",") + wide.append("i32") + wide.append("}") + status, result, nodes = call(kernel, wide) + assert status == 0 and result.nodes == 60001 and nodes[-1] == (20, 0, 60000) + deep = ["ptr", "<"] * 257 + ["i32"] + [">"] * 257 + assert call(kernel, deep, max_depth=256)[0] == 2 + randomizer = random.Random(0x3480349) + for case in range(args.cases): + words, expected = generated(randomizer, 5) + status, result, actual = call(kernel, words) + assert status == 0 and result.next == len(words) and actual == expected, (case, words, status, actual, expected) + pre_status, pre, _ = call(kernel, words, mode=0) + assert pre_status == 0 and pre.nodes == result.nodes and pre.work == result.work + assert call(kernel, words, capacity=len(expected) - 1)[0] == 5 + assert call(kernel, words, max_work=result.work - 1)[0] == 4 + print(f"Wave IR type parser: full grammar, transactional limits, wide/deep cases and {args.cases} independent trees passed") + + +if __name__ == "__main__": + main() diff --git a/tools/check_wave_ir_verifier.py b/tools/check_wave_ir_verifier.py new file mode 100644 index 0000000..224233c --- /dev/null +++ b/tools/check_wave_ir_verifier.py @@ -0,0 +1,189 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Check real Wave type/cast/literal/signature rules against independent oracles.""" + +import argparse +import ctypes as C +import random + +from wave_ir_verifier_oracle import (FLOATS, INTEGERS, NONE, SCALARS, SIGNED, UNSIGNED, + WIDTHS, Node, Operand, Result, call, load, random_type, + signature_valid, typed_call) + + +def cast_valid(op, source, destination): + source_width, destination_width = WIDTHS.get(source, 0), WIDTHS.get(destination, 0) + if op == 0 and source == 1: + return destination in INTEGERS and destination != 2 + if op in (0, 1): + return source in INTEGERS and destination in INTEGERS and source_width < destination_width + if op == 2: + return source in INTEGERS and destination in INTEGERS and source_width > destination_width + if op in (3, 4): + return source in FLOATS and destination in FLOATS and ( + source_width < destination_width if op == 3 else source_width > destination_width) + if op == 5: + return source in SIGNED and destination in FLOATS + if op == 6: + return source in UNSIGNED and destination in FLOATS + if op == 7: + return source in FLOATS and destination in SIGNED + if op == 8: + return source in FLOATS and destination in UNSIGNED + if op == 9: + return source in INTEGERS | FLOATS and destination in INTEGERS | FLOATS and source_width == destination_width + return op == 12 and source in INTEGERS and destination in INTEGERS + + +def vectors(kernel): + count = 0 + for op in range(13): + for source in range(17): + for destination in range(17): + status, _ = call(kernel, 2, source, [Operand(7, source, 0, 0, 0)], + sub=op, other=destination) + assert (status == 0) == cast_valid(op, source, destination), (op, source, destination, status) + count += 1 + for kind in range(17): + for actual in range(17): + for op, valid in [(1, kind in INTEGERS | FLOATS), (7, kind in INTEGERS), + (8, kind != 0), (10, kind in FLOATS)]: + operands = [Operand(1, actual, 0, 0, 0)] * (2 if op == 10 else 1) + status, _ = call(kernel, op, kind, operands) + assert status == (1 if not valid else 0 if kind == actual else 3), (op, kind, actual, status) + count += 1 + nodes = [*SCALARS, Node(17, 6, 0, 0, 0), Node(17, 6, 0, 0, 0), Node(17, 7, 0, 0, 0)] + for op in (13, 15, 17): + for align in (0, 1, 2, 3, 4, 8, 4096): + for actual in (6, 17, 18, 19): + status, _ = call(kernel, op, 6, [Operand(1, actual, 0, 0, 0)], align=align, nodes=nodes) + expected = 4 if align == 0 or align & (align - 1) else 0 if actual in (17, 18) else 3 + assert status == expected, (op, align, actual, status) + count += 1 + assert call(kernel, 1, 6, [Operand(1, NONE, 0, 0, 0)])[0] == 2 + assert call(kernel, 1, 6, [Operand(1, 6, 0, 0, 0)], work=0)[0] == 8 + malformed = [Node(17, 0, 0, 0, 0)] + assert call(kernel, 33, 0, nodes=malformed)[0] == 7 + # Supported source depth includes 256 nested function-pointer signatures. + nested = 6 + for _ in range(256): + nested = ("f", 0, False, nested, []) + assert typed_call(kernel, 25, nested)[0] == 0 + return count + + +def literal_vectors(kernel, randomizer, cases): + count = 0 + for kind in range(17): + for literal in range(1, 7): + width = WIDTHS.get(kind, 0) + values = [0, 1, 2, 1 << 127, (1 << 128) - 1] + if 0 < width < 128: + values.extend([(1 << (width - 1)) - 1, 1 << (width - 1), (1 << width) - 1, 1 << width]) + for bits in values: + check_literal(kernel, kind, literal, bits) + count += 1 + for _ in range(cases): + check_literal(kernel, randomizer.randrange(17), randomizer.randrange(1, 7), randomizer.getrandbits(128)) + count += 1 + return count + + +def check_literal(kernel, kind, literal, payload): + payload &= (1 << 128) - 1 + signed = payload if payload < 1 << 127 else payload - (1 << 128) + expected = (kind == 1 and literal == 3) or (kind in FLOATS and literal == kind - 10) + if literal == 1 and kind in SIGNED: + expected = -(1 << (WIDTHS[kind] - 1)) <= signed < 1 << (WIDTHS[kind] - 1) + if literal == 2 and kind in UNSIGNED: + expected = payload < 1 << WIDTHS[kind] + status, _ = call(kernel, 24, kind, [Operand(0, 0, literal, payload & NONE, payload >> 64)]) + assert (status == 0) == expected, (kind, literal, payload, status, expected) + + +def signatures(kernel, randomizer, cases): + for _ in range(cases): + signature = ("f", randomizer.randrange(2), randomizer.randrange(7) == 0, + random_type(randomizer, 4), + [random_type(randomizer, 4) for _ in range(randomizer.randrange(5))]) + status, _ = typed_call(kernel, 25, signature) + assert (status == 0) == signature_valid(signature), (signature, status) + for _ in range(max(1, cases // 5)): + signature = ("f", randomizer.randrange(2), False, randomizer.randrange(17), + [randomizer.randrange(1, 17) for _ in range(randomizer.randrange(5))]) + assert typed_call(kernel, 28, signature, other=signature[3], args=signature[4], + sub=signature[1], dst=int(signature[3] != 0))[0] == 0 + assert typed_call(kernel, 28, signature, other=signature[3], args=signature[4], + sub=1 - signature[1], dst=int(signature[3] != 0))[0] == 13 + if signature[4]: + arguments = [0, *signature[4][1:]] + assert typed_call(kernel, 28, signature, other=signature[3], args=arguments, + sub=signature[1], dst=int(signature[3] != 0))[0] == 17 + + +def identities(library, cases): + class Key(C.Structure): + _fields_ = [("kind", C.c_uint64), ("number", C.c_uint64), + ("bytes", C.POINTER(C.c_uint8)), ("count", C.c_uint64)] + + class Slot(C.Structure): + _fields_ = [*Key._fields_, ("occupied", C.c_uint64)] + + kernel = library.whale_ir_verify_index_insert + kernel.restype = C.c_int32 + kernel.argtypes = [C.POINTER(Slot), C.c_uint64, C.POINTER(Key), C.c_uint64, C.POINTER(Result)] + table = (Slot * 8192)() + seen, borrowed = set(), [] + randomizer = random.Random(0x3502) + for _ in range(cases): + kind, number = randomizer.randrange(3), randomizer.randrange(512) + if kind == 1: + text = (f"name-{number}-" + "λ" * (number % 13)).encode() + buffer = (C.c_uint8 * len(text))(*text) + borrowed.append(buffer) + key, identity = Key(kind, 0, buffer, len(text)), (kind, text) + elif kind == 2: + key, identity = Key(kind, number, None, number % 7), (kind, number, number % 7) + else: + key, identity = Key(kind, number, None, 0), (kind, number) + result = Result() + status = kernel(table, len(table), C.byref(key), 100000, C.byref(result)) + assert status == result.status and result.work <= 100000 + assert status == int(identity in seen), (identity, status) + seen.add(identity) + result = Result() + key = Key(0, 2048, None, 0) + assert kernel(table, len(table), C.byref(key), 0, C.byref(result)) == 8 + + link = library.whale_ir_verify_link + link.restype = C.c_int32 + link.argtypes = [C.c_uint64, C.c_uint64, C.POINTER(C.c_uint8), C.c_uint64, + C.c_uint64, C.POINTER(Result)] + for external in (0, 1): + for present in (0, 1): + for name in (b"", b"symbol", b"a\0b"): + buffer = (C.c_uint8 * len(name))(*name) + expected = ((external == 0 and present == 0) + or (external == 1 and present == 1 and name and b"\0" not in name)) + status = link(external, present, buffer, len(buffer), 1000, C.byref(result)) + assert (status == 0) == bool(expected), (external, present, name, status) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", required=True) + parser.add_argument("--cases", type=int, default=10000) + args = parser.parse_args() + assert args.cases >= 0 + library, kernel = load(args.library) + randomizer = random.Random(0x350) + fixed = vectors(kernel) + literals = literal_vectors(kernel, randomizer, args.cases) + signatures(kernel, randomizer, args.cases) + identities(library, args.cases) + print(f"Wave IR verifier: {fixed} primitive vectors, {literals} literals, " + f"{args.cases} signatures/identities and call/link/transport/work/depth checks passed") + + +if __name__ == "__main__": + main() diff --git a/tools/meson_cargo.py b/tools/meson_cargo.py index 9cafa07..5e6b9c6 100644 --- a/tools/meson_cargo.py +++ b/tools/meson_cargo.py @@ -35,9 +35,11 @@ def validate_features(features): return features -def cargo_environment(target_dir, asmobj_directory, profile, optimization, debug_info): +def cargo_environment(target_dir, asmobj_directory, profile, optimization, debug_info, + wave_ir_directory=None): environment = os.environ.copy() environment.pop("WHALE_ASMOBJ_DIR", None) + environment.pop("WHALE_WAVE_IR_DIR", None) environment.pop("CARGO_BUILD_TARGET", None) environment["CARGO_TARGET_DIR"] = str(target_dir) environment["CARGO_INCREMENTAL"] = "0" @@ -46,6 +48,8 @@ def cargo_environment(target_dir, asmobj_directory, profile, optimization, debug environment[prefix + "DEBUG"] = debug_info if asmobj_directory: environment["WHALE_ASMOBJ_DIR"] = str(asmobj_directory) + if wave_ir_directory: + environment["WHALE_WAVE_IR_DIR"] = str(wave_ir_directory) return environment @@ -153,6 +157,7 @@ def source_dependencies(source, features): dependencies.update(path.iterdir()) dependencies.add(source / "assembler/asmobj") dependencies.update((source / "assembler/asmobj").glob("*.wave")) + dependencies.update((source / "ir").glob("*.wave")) return dependencies @@ -178,11 +183,13 @@ def build(arguments): output = arguments.output.parent.resolve() / arguments.output.name depfile = arguments.depfile.parent.resolve() / arguments.depfile.name asmobj_directory = arguments.asmobj_dir.resolve() if arguments.asmobj_dir else None + wave_ir_directory = arguments.wave_ir_dir.resolve() if arguments.wave_ir_dir else None features = validate_features(arguments.feature) if target_dir in [source, source / "target"]: raise BuildError("Meson requires its own private Cargo target directory") environment = cargo_environment(target_dir, asmobj_directory, arguments.profile, - arguments.opt_level, arguments.debug_info) + arguments.opt_level, arguments.debug_info, + wave_ir_directory) target = arguments.host_target or native_target(arguments.cargo, source, environment) if not TRIPLE.fullmatch(target): raise BuildError("cargo host target must be a Rust target triple") @@ -200,6 +207,9 @@ def build(arguments): if asmobj_directory: archive = "whale_asmobj.lib" if "msvc" in target else "libwhale_asmobj.a" dependencies.update(asmobj_directory / name for name in [archive, "asmobj.meta"]) + if wave_ir_directory: + archive = "whale_wave_ir.lib" if "msvc" in target else "libwhale_wave_ir.a" + dependencies.update(wave_ir_directory / name for name in [archive, "wave-ir.meta", "provenance.json"]) contents = make_escape(output) + ": " + " ".join(make_escape(path) for path in sorted(dependencies)) + "\n" candidate = None candidate_depfile = None @@ -303,6 +313,7 @@ def main(argv=None): compile_parser.add_argument("--offline", action="store_true") compile_parser.add_argument("--feature", action="append", default=[]) compile_parser.add_argument("--asmobj-dir", type=Path) + compile_parser.add_argument("--wave-ir-dir", type=Path) smoke_parser = commands.add_parser("smoke") smoke_parser.add_argument("--binary", type=Path, required=True) smoke_parser.add_argument("--feature", action="append", default=[]) diff --git a/tools/test_build_asmobj.py b/tools/test_build_asmobj.py index adb0f1e..e3c949a 100644 --- a/tools/test_build_asmobj.py +++ b/tools/test_build_asmobj.py @@ -414,13 +414,10 @@ def test_asmobj_is_a_complete_wave_module_with_five_role_files(self): self.assertEqual(sorted(path.name for path in module.glob("*.wave")), sorted(helper.SOURCES)) self.assertEqual(list(module.rglob("*.rs")), []) self.assertFalse((module / "Cargo.toml").exists()) - actual = set() for directory in ("assembler", "object", "reverse", "ir", "toolchain", "src"): source_root = ROOT / directory if source_root.is_dir(): - actual.update(path.relative_to(ROOT).as_posix() for path in source_root.rglob("*.wave")) self.assertFalse(any(path.is_dir() and path.name == "wave" for path in source_root.rglob("*"))) - self.assertEqual(actual, {"assembler/asmobj/" + name for name in helper.SOURCES}) if __name__ == "__main__": diff --git a/tools/test_build_wave_ir.py b/tools/test_build_wave_ir.py new file mode 100644 index 0000000..be4c81e --- /dev/null +++ b/tools/test_build_wave_ir.py @@ -0,0 +1,191 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Pinned Wave IR publication and std-only Cargo guard regressions.""" + +import argparse +import hashlib +import json +import os +from pathlib import Path +import subprocess +import tempfile +import unittest +from unittest.mock import patch + +import build_wave_ir as helper +from wave_bootstrap import Bootstrap + + +ROOT = Path(__file__).resolve().parents[1] +NATIVE = "x86_64-unknown-linux-gnu" + + +class PublicationTests(unittest.TestCase): + def test_wave_ir_sources_are_explicit_role_files(self): + self.assertEqual({path.name for path in (ROOT / "ir").glob("*.wave")}, set(helper.SOURCES)) + + def test_compile_archive_and_publication_failures_preserve_last_good_set(self): + for failure in ("compile", "archive", "publish-archive", "publish-provenance", "publish-meta"): + with self.subTest(failure=failure), tempfile.TemporaryDirectory() as temporary: + root = Path(temporary).resolve() + wave = root / "Wave" + wave.mkdir() + marker = wave / "user.wave" + marker.write_bytes(b"unrelated user changes") + output = root / "output" + output.mkdir() + compiler = root / "wavec" + compiler.write_bytes(b"pinned compiler") + std = root / "std" + std.mkdir() + bootstrap = Bootstrap(compiler, std, root / "bootstrap.json", + {"std_sha256": "1" * 64}, True) + names = ("libwhale_wave_ir.a", "provenance.json", "wave-ir.meta") + for name in names: + (output / name).write_bytes(b"previous " + name.encode()) + args = argparse.Namespace(wave_source=wave, out_dir=output, + bootstrap_dir=root / "cache", rust_toolchain="1.89", target=NATIVE, + opt_level="0", allow_network=False) + real_replace = os.replace + failed = False + + def replace(source, destination): + nonlocal failed + selected = {"publish-archive": names[0], "publish-provenance": names[1], + "publish-meta": names[2]}.get(failure) + if not failed and selected and Path(destination) == output / selected: + failed = True + raise OSError("injected publication failure") + return real_replace(source, destination) + + def run(command, **kwargs): + command = list(map(str, command)) + if "-o" in command: + kernel = Path(command[command.index("build") + 1]) + self.assertEqual(kernel.read_bytes(), helper.source_bytes(ROOT)) + self.assertEqual(command[0], str(compiler)) + self.assertIn("--freestanding", command) + Path(command[command.index("-o") + 1]).write_bytes(b"object") + if failure == "compile": + raise subprocess.CalledProcessError(1, command) + else: + Path(command[-2]).write_bytes(b"new archive") + if failure == "archive": + raise subprocess.CalledProcessError(1, command) + + with patch.object(helper, "ensure_bootstrap", return_value=bootstrap), \ + patch.object(helper, "run", side_effect=run), \ + patch.object(helper.os, "replace", side_effect=replace): + with self.assertRaises(OSError if failure.startswith("publish") else subprocess.CalledProcessError): + helper.build(args) + for name in names: + self.assertEqual((output / name).read_bytes(), b"previous " + name.encode()) + self.assertEqual(marker.read_bytes(), b"unrelated user changes") + self.assertFalse(any(path.name.startswith(".wave-ir-") for path in output.iterdir())) + + def test_success_records_source_abi_and_compiler_identity(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary).resolve() + wave = root / "Wave" + wave.mkdir() + output = root / "output" + compiler = root / "wavec" + compiler.write_bytes(b"compiler") + std = root / "std" + std.mkdir() + bootstrap = Bootstrap(compiler, std, root / "bootstrap.json", + {"std_sha256": "1" * 64}, True) + args = argparse.Namespace(wave_source=wave, out_dir=output, bootstrap_dir=root / "cache", + rust_toolchain="1.89", target=NATIVE, opt_level="2", + allow_network=False) + + def run(command, **kwargs): + command = list(map(str, command)) + if "-o" in command: + Path(command[command.index("-o") + 1]).write_bytes(b"object") + else: + Path(command[-2]).write_bytes(b"archive") + + with patch.object(helper, "ensure_bootstrap", return_value=bootstrap), \ + patch.object(helper, "run", side_effect=run): + self.assertEqual(helper.build(args), output) + provenance = (output / "provenance.json").read_bytes() + source = helper.source_bytes(ROOT) + abi = helper.abi_bytes(ROOT) + self.assertEqual((output / "wave-ir.meta").read_text(), + helper.metadata(source, abi, b"archive", provenance, NATIVE, "2")) + record = json.loads(provenance) + self.assertEqual(record["source_sha256"], hashlib.sha256(source).hexdigest()) + self.assertEqual(record["abi_sha256"], hashlib.sha256(abi).hexdigest()) + self.assertEqual(record["compiler_sha256"], hashlib.sha256(b"compiler").hexdigest()) + self.assertEqual(record["wave_revision"], helper.WAVE_REVISION) + + +class GuardTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.temporary = tempfile.TemporaryDirectory() + cls.guard = Path(cls.temporary.name).resolve() / "guard" + subprocess.run(["rustc", "--edition=2021", "-Dwarnings", str(ROOT / "ir/build.rs"), + "-o", str(cls.guard)], check=True, capture_output=True) + + @classmethod + def tearDownClass(cls): + cls.temporary.cleanup() + + def test_plain_build_and_corrupt_artifact_rejection(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary).resolve() + source = root / "ir" + source.mkdir() + for name in helper.SOURCES: + (source / name).write_bytes((name + "\n").encode()) + abi_paths = {} + for index, name in enumerate(helper.ABI_SOURCES): + path = root / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes((name + " ffi").encode()) + abi_paths[f"abi{index}"] = path + output = root / "archive" + output.mkdir() + archive = output / "libwhale_wave_ir.a" + archive.write_bytes(b"archive") + provenance = output / "provenance.json" + provenance.write_bytes(b"pinned provenance") + metadata = output / "wave-ir.meta" + original = helper.metadata(helper.source_bytes(root), helper.abi_bytes(root), b"archive", + provenance.read_bytes(), NATIVE, "2") + metadata.write_text(original) + environment = os.environ.copy() + environment.pop("WHALE_WAVE_IR_DIR", None) + environment.update(CARGO_MANIFEST_DIR=str(source), TARGET=NATIVE) + + def check(changes, expected): + paths = {"source": source / helper.SOURCES[0], **abi_paths, + "archive": archive, + "provenance": provenance, "meta": metadata} + originals = {key: path.read_bytes() for key, path in paths.items()} + for key, data in changes.items(): + paths[key].write_bytes(data) + result = subprocess.run([str(self.guard)], env={**environment, + "WHALE_WAVE_IR_DIR": str(output)}, capture_output=True, text=True) + self.assertEqual(result.returncode == 0, expected is None, result.stderr) + if expected: + self.assertIn(expected, result.stderr) + self.assertNotIn("cargo:rustc-link-lib", result.stdout) + for key, data in originals.items(): + paths[key].write_bytes(data) + + plain = subprocess.run([str(self.guard)], env=environment, capture_output=True) + self.assertEqual(plain.returncode, 0) + check({}, None) + check({"source": b"changed"}, "stale Wave IR archive") + for name in abi_paths: + check({name: b"changed"}, "stale Wave IR ABI") + check({"archive": b"changed"}, "corrupt Wave IR archive") + check({"provenance": b"changed"}, "corrupt Wave IR provenance") + check({"meta": original.replace("schema=1", "schema=2").encode()}, + "unsupported Wave IR metadata") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_meson_build.py b/tools/test_meson_build.py index f9c6cc2..c2e14bd 100644 --- a/tools/test_meson_build.py +++ b/tools/test_meson_build.py @@ -32,13 +32,18 @@ def test_no_isa_product_has_no_implicit_default_features(self): self.assertNotIn("--offline", command) def test_ambient_wave_and_cargo_target_cannot_change_selection(self): - with patch.dict(os.environ, {"WHALE_ASMOBJ_DIR": "old", "CARGO_BUILD_TARGET": "old"}): + with patch.dict(os.environ, {"WHALE_ASMOBJ_DIR": "old", "WHALE_WAVE_IR_DIR": "old", + "CARGO_BUILD_TARGET": "old"}): environment = cargo_environment("private", None, "dev", "2", "2") self.assertNotIn("WHALE_ASMOBJ_DIR", environment) + self.assertNotIn("WHALE_WAVE_IR_DIR", environment) self.assertNotIn("CARGO_BUILD_TARGET", environment) self.assertEqual(environment["CARGO_TARGET_DIR"], "private") self.assertEqual(environment["CARGO_PROFILE_DEV_OPT_LEVEL"], "2") self.assertEqual(environment["CARGO_PROFILE_DEV_DEBUG"], "2") + selected = cargo_environment("private", "asmobj", "dev", "2", "2", "wave-ir") + self.assertEqual(selected["WHALE_ASMOBJ_DIR"], "asmobj") + self.assertEqual(selected["WHALE_WAVE_IR_DIR"], "wave-ir") def test_wave_is_explicit_and_unknown_features_fail(self): self.assertEqual(validate_features(["asm-amd64", "asm-amd64"]), ["asm-amd64"]) @@ -111,6 +116,8 @@ def test_source_dirs_and_manifests_track_additions_without_disabled_isas(self): for name in ["src", "toolchain/src", "assembler/amd64/src", "assembler/aarch64/src"]: (source / name).mkdir(parents=True) (source / name / "lib.rs").write_text("// source") + (source / "ir").mkdir() + (source / "ir/model.wave").write_text("// type graph") (source / "toolchain/src/assembly_object.rs").write_text("// ffi boundary") (source / "Cargo.toml").write_text("manifest") dependencies = source_dependencies(source, ["asm-aarch64"]) @@ -120,6 +127,7 @@ def test_source_dirs_and_manifests_track_additions_without_disabled_isas(self): self.assertNotIn(source / "assembler/amd64/src/lib.rs", dependencies) self.assertIn(source / "Cargo.toml", dependencies) self.assertIn(source / "toolchain/src/assembly_object.rs", dependencies) + self.assertIn(source / "ir/model.wave", dependencies) class PublicationTests(unittest.TestCase): @@ -135,7 +143,7 @@ def setUp(self): self.depfile = self.root / "whale.d" self.depfile.write_bytes(b"previous dependencies") self.arguments = argparse.Namespace(source_root=self.source, target_dir=self.target, - output=self.output, depfile=self.depfile, asmobj_dir=None, feature=[], + output=self.output, depfile=self.depfile, asmobj_dir=None, wave_ir_dir=None, feature=[], profile="dev", opt_level="0", debug_info="2", host_target="x86_64-unknown-linux-gnu", cargo="explicit cargo", rustc="explicit rustc", offline=True, jobs=2, host_system="linux", host_cpu_family="x86_64") diff --git a/tools/wave_hir_fixture.rs b/tools/wave_hir_fixture.rs new file mode 100644 index 0000000..39b2361 --- /dev/null +++ b/tools/wave_hir_fixture.rs @@ -0,0 +1,216 @@ +// SPDX-License-Identifier: MPL-2.0 +// Built against the pinned Wave frontend only, never a backend or mutable checkout. +use hir::{HirExpressionType, TypedProgram}; + +use parser::ast::*; + +fn quote(value: &str) -> String { + let mut out = String::from("\""); + for c in value.chars() { + match c { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + c if c < ' ' => out.push_str(&format!("\\u{:04x}", c as u32)), + c => out.push(c), + } + } + out.push('"'); + out +} + +fn ty(value: &WaveType) -> String { + match value { + WaveType::Void => quote("Void"), + WaveType::Bool => quote("Bool"), + WaveType::Int(bits) => format!("{{\"Integer\":{{\"bits\":{bits},\"signed\":true}}}}"), + WaveType::Uint(bits) => format!("{{\"Integer\":{{\"bits\":{bits},\"signed\":false}}}}"), + other => format!("{{\"Unsupported\":{}}}", quote(&format!("{other:?}"))), + } +} + +fn expression(program: &TypedProgram, value: &Expression) -> String { + let id = program.expression_id(value).expect("owned typed expression").index(); + let resolved = program + .numeric_expression_of(value) + .map(|info| &info.result_type) + .or_else(|| match program.type_of(value) { + Some(HirExpressionType::Resolved(ty)) => Some(ty), + _ => None, + }) + .expect("resolved scalar HIR fact"); + let kind = match value.unspanned() { + Expression::Literal(Literal::Int(value)) => format!("{{\"Integer\":{}}}", quote(value)), + Expression::Literal(Literal::Bool(value)) => format!("{{\"Bool\":{value}}}"), + Expression::Variable(name) => format!("{{\"Local\":{}}}", quote(name)), + Expression::BinaryExpression { left, operator, right } => { + let operator = match operator { + Operator::Add => "Add", + Operator::Subtract => "Subtract", + Operator::Multiply => "Multiply", + Operator::Divide => "Divide", + Operator::Remainder => "Remainder", + Operator::GreaterEqual => "GreaterEqual", + Operator::LessEqual => "LessEqual", + Operator::Greater => "Greater", + Operator::Less => "Less", + Operator::Equal => "Equal", + Operator::NotEqual => "NotEqual", + Operator::LogicalAnd => "LogicalAnd", + Operator::LogicalOr => "LogicalOr", + Operator::BitwiseAnd => "BitwiseAnd", + Operator::BitwiseOr => "BitwiseOr", + Operator::BitwiseXor => "BitwiseXor", + Operator::ShiftLeft => "ShiftLeft", + Operator::ShiftRight => "ShiftRight", + _ => panic!("fixture has unsupported operator"), + }; + format!( + "{{\"Binary\":{{\"left\":{},\"operator\":{},\"right\":{}}}}}", + expression(program, left), + quote(operator), + expression(program, right) + ) + }, + _ => panic!("fixture has unsupported expression"), + }; + format!("{{\"id\":{id},\"resolved_type\":{},\"kind\":{kind}}}", ty(resolved)) +} + +fn statements(program: &TypedProgram, body: &[ASTNode]) -> String { + let values: Vec = body + .iter() + .map(|node| match node.unspanned() { + ASTNode::Variable(value) => { + assert!(matches!(value.mutability, Mutability::Var)); + format!( + "{{\"Variable\":{{\"name\":{},\"ty\":{},\"init\":{}}}}}", + quote(&value.name), + ty(&value.type_name), + value + .initial_value + .as_ref() + .map(|value| expression(program, value)) + .unwrap_or_else(|| "null".into()) + ) + }, + ASTNode::Statement(StatementNode::Assign { variable, value }) => format!( + "{{\"Assign\":{{\"name\":{},\"value\":{}}}}}", + quote(variable), + expression(program, value) + ), + ASTNode::Statement(StatementNode::While { condition, body }) => format!( + "{{\"While\":{{\"condition\":{},\"body\":{}}}}}", + expression(program, condition), + statements(program, body) + ), + ASTNode::Statement(StatementNode::If { + condition, + body, + else_if_blocks, + else_block, + }) => { + assert!(else_if_blocks.is_none()); + format!( + "{{\"If\":{{\"condition\":{},\"body\":{},\"else_body\":{}}}}}", + expression(program, condition), + statements(program, body), + statements(program, else_block.as_deref().map(Vec::as_slice).unwrap_or(&[])) + ) + }, + ASTNode::Statement(StatementNode::Return(value)) => format!( + "{{\"Return\":{}}}", + value + .as_ref() + .map(|value| expression(program, value)) + .unwrap_or_else(|| "null".into()) + ), + _ => panic!("fixture has unsupported statement"), + }) + .collect(); + format!("[{}]", values.join(",")) +} + +fn variable(name: &str) -> Expression { + Expression::Variable(name.into()) +} + +fn binary(left: Expression, operator: Operator, right: Expression) -> Expression { + Expression::BinaryExpression { left: Box::new(left), operator, right: Box::new(right) } +} + +fn main() { + // This is the final syntax passed to TypedProgram::lower after imports and + // monomorphization: one concrete scalar function, no frontend/backend state. + let program = TypedProgram::lower(vec![ASTNode::Function(FunctionNode { + is_async: false, + span: None, + name: "hir_scalar".into(), + generic_params: vec![], + parameters: vec![ + ParameterNode { + span: None, + name: "x".into(), + param_type: WaveType::Int(32), + initial_value: None, + }, + ParameterNode { + span: None, + name: "n".into(), + param_type: WaveType::Int(32), + initial_value: None, + }, + ParameterNode { + span: None, + name: "flag".into(), + param_type: WaveType::Bool, + initial_value: None, + }, + ], + return_type: Some(WaveType::Int(32)), + return_type_span: None, + body: vec![ + ASTNode::Variable(VariableNode { + name: "acc".into(), + type_name: WaveType::Int(32), + initial_value: Some(variable("x")), + mutability: Mutability::Var, + visibility: Visibility::Private, + }), + ASTNode::Statement(StatementNode::While { + condition: binary(variable("acc"), Operator::Less, variable("n")), + body: vec![ASTNode::Statement(StatementNode::Assign { + variable: "acc".into(), + value: binary( + variable("acc"), + Operator::Add, + Expression::Literal(Literal::Int("1".into())), + ), + })], + }), + ASTNode::Statement(StatementNode::If { + condition: variable("flag"), + body: vec![ASTNode::Statement(StatementNode::Return(Some(variable("acc"))))], + else_if_blocks: None, + else_block: Some(Box::new(vec![ASTNode::Statement(StatementNode::Return(Some( + variable("x"), + )))])), + }), + ], + export: None, + visibility: Visibility::Private, + })]) + .expect("pinned HIR semantic validation"); + program.verify_conversions().expect("pinned HIR conversion facts"); + let functions:Vec<_>=program.syntax().iter().map(|node|{ + let ASTNode::Function(function)=node.unspanned() else {panic!("only scalar functions")}; + let params:Vec<_>=function.parameters.iter().map(|p|format!("{{\"name\":{},\"ty\":{}}}",quote(&p.name),ty(&p.param_type))).collect(); + format!("{{\"name\":{},\"parameters\":[{}],\"return_type\":{},\"body\":{},\"is_async\":{}}}",quote(&function.name),params.join(","),ty(function.return_type.as_ref().unwrap_or(&WaveType::Void)),statements(&program,&function.body),function.is_async) + }).collect(); + println!( + "{{\"wave_revision\":\"e0952ed65d07e14c6ed0aa64f3c9a5532dd7533b\",\"functions\":[{}]}}", + functions.join(",") + ); +} diff --git a/tools/wave_ir_verifier_oracle.py b/tools/wave_ir_verifier_oracle.py new file mode 100644 index 0000000..2b82009 --- /dev/null +++ b/tools/wave_ir_verifier_oracle.py @@ -0,0 +1,124 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Independent transport helpers for native Wave semantic/SSA oracle checks.""" + +import ctypes as C + + +NONE = (1 << 64) - 1 +SIGNED = {2, 4, 5, 6, 7, 8} +UNSIGNED = {3, 9, 10, 11, 12, 13} +INTEGERS = SIGNED | UNSIGNED +FLOATS = {14, 15, 16} +WIDTHS = {2: 1, 3: 1, 4: 8, 5: 16, 6: 32, 7: 64, 8: 128, + 9: 8, 10: 16, 11: 32, 12: 64, 13: 128, 14: 16, 15: 32, 16: 64} + + +class Node(C.Structure): + _fields_ = [(name, C.c_uint64) for name in ("kind", "child", "first", "count", "extra")] + + +class Operand(C.Structure): + _fields_ = [(name, C.c_uint64) for name in ("value", "ty", "literal", "low", "high")] + + +class Operation(C.Structure): + _fields_ = [(name, C.c_uint64) for name in ("op", "sub", "ty", "other", "dst", "align")] + + +class Result(C.Structure): + _fields_ = [(name, C.c_uint64) for name in + ("status", "index", "expected", "actual", "detail", "work")] + + +SCALARS = tuple(Node(kind, 0, 0, 0, 0) for kind in range(17)) + + +def load(path): + library = C.CDLL(str(path)) + kernel = library.whale_ir_verify_semantics + kernel.argtypes = [C.POINTER(Node), C.c_uint64, C.POINTER(C.c_uint64), C.c_uint64, + C.POINTER(Operation), C.POINTER(Operand), C.c_uint64, + C.c_uint64, C.POINTER(Result)] + kernel.restype = C.c_int32 + return library, kernel + + +def call(kernel, op, ty, operands=(), sub=0, other=0, align=1, + nodes=SCALARS, edges=(), work=1_000_000, dst=0): + node_array = (Node * len(nodes))(*nodes) + operand_array = (Operand * len(operands))(*operands) + edge_array = (C.c_uint64 * len(edges))(*edges) + result = Result() + operation = Operation(op, sub, ty, other, dst, align) + status = kernel(node_array, len(nodes), edge_array, len(edges), C.byref(operation), + operand_array, len(operands), work, C.byref(result)) + assert status == result.status, (status, result.status) + assert result.work <= work, (result.work, work) + return status, result + + +def encode_type(ty, nodes, edges): + child = first = count = extra = 0 + if isinstance(ty, int): + kind = ty + elif ty[0] in ("p", "a"): + kind = 17 if ty[0] == "p" else 19 + child = encode_type(ty[1], nodes, edges) + count = ty[2] if ty[0] == "a" else 0 + else: + kind = {"f": 18, "s": 20, "t": 21}[ty[0]] + children = [ty[3], *ty[4]] if ty[0] == "f" else ty[1] + children = [encode_type(item, nodes, edges) for item in children] + first, count = len(edges), len(children) + edges.extend(children) + if ty[0] == "f": + extra = ty[1] | (int(ty[2]) << 1) + nodes.append(Node(kind, child, first, count, extra)) + return len(nodes) - 1 + + +def typed_call(kernel, op, ty, other=0, args=(), sub=0, dst=0, work=1_000_000): + nodes, edges, operands = [], [], [] + root = encode_type(ty, nodes, edges) + other = encode_type(other, nodes, edges) + for value, argument in enumerate(args): + operands.append(Operand(value, encode_type(argument, nodes, edges), 0, 0, 0)) + return call(kernel, op, root, operands, sub=sub, other=other, nodes=nodes, + edges=edges, dst=dst, work=work) + + +def signature_type_valid(ty): + if isinstance(ty, int): + return ty != 0 + if ty[0] == "f": + return signature_valid(ty) + if ty[0] == "p" and ty[1] == 0: + return True + if ty[0] in ("p", "a"): + return signature_type_valid(ty[1]) + return all(signature_type_valid(child) for child in ty[1]) + + +def signature_valid(signature): + _, convention, variadic, ret, params = signature + if variadic: + return False + if convention == 1 and any(isinstance(ty, tuple) and ty[0] in ("a", "s", "t") + for ty in [ret, *params]): + return False + return (ret == 0 or signature_type_valid(ret)) and all(map(signature_type_valid, params)) + + +def random_type(randomizer, depth): + if depth == 0 or randomizer.randrange(2) == 0: + return randomizer.randrange(17) + kind = randomizer.choice(("p", "a", "s", "t", "f")) + if kind == "p": + return kind, random_type(randomizer, depth - 1) + if kind == "a": + return kind, random_type(randomizer, depth - 1), randomizer.randrange(6) + if kind in ("s", "t"): + return kind, [random_type(randomizer, depth - 1) for _ in range(randomizer.randrange(3))] + return (kind, randomizer.randrange(2), randomizer.randrange(5) == 0, + random_type(randomizer, depth - 1), + [random_type(randomizer, depth - 1) for _ in range(randomizer.randrange(3))]) From cfe74b24ae64fb1790e174cf8fcdbbad09cb11ce Mon Sep 17 00:00:00 2001 From: LunaStev Date: Sat, 31 Oct 2026 13:02:26 +0900 Subject: [PATCH 4/8] ir: move execution semantics and verified passes to Wave Implement fixed-width and exact IEEE arithmetic, lazy constant evaluation, indexed dependencies, tracked memory and call frames in role-specific Wave sources. Route the interpreter and transactional pass runner through typed buffer transports; preserve Rust reference algorithms for migration checks. Add a bounded sparse integer constant folder without changing O0 defaults. Verify final native O0/O2 archives against independent numeric, memory, call and folding models; exercise complete workspace, resource, rollback, CLI and compatibility tests. Keep native host claims limited to Linux AMD64. Refs #352, #353, #354, #355, #118. Signed-off-by: LunaStev --- .github/workflows/asmobj.yml | 9 +- BUILDING.md | 8 +- CONTRIBUTING.md | 3 +- README.md | 6 +- ir/build.rs | 24 + ir/constant.wave | 546 +++++ ir/constant_dependencies.wave | 375 ++++ ir/effects.wave | 75 + ir/float_arithmetic.wave | 126 ++ ir/float_convert.wave | 274 +++ ir/float_model.wave | 225 ++ ir/fold_integer.wave | 387 ++++ ir/integer.wave | 399 ++++ ir/memory.wave | 895 ++++++++ ir/meson.build | 98 +- ir/passes.wave | 213 ++ ir/runtime_driver.wave | 86 + ir/runtime_execute.wave | 728 +++++++ ir/runtime_model.wave | 195 ++ ir/runtime_prepare.wave | 612 ++++++ ir/src/const_expr.rs | 220 +- ir/src/constant.rs | 12 + ir/src/constant_wave.rs | 377 ++++ ir/src/diagnostic.rs | 2 + ir/src/effects.rs | 177 +- ir/src/effects_wave.rs | 140 ++ ir/src/float.rs | 174 +- ir/src/float/arithmetic.rs | 329 +-- ir/src/float/arithmetic_reference.rs | 251 +++ ...onversions.rs => conversions_reference.rs} | 2 +- ir/src/float/wave.rs | 280 +++ ir/src/fold_integer.rs | 30 + ir/src/fold_integer_wave.rs | 465 +++++ ir/src/interpreter/integer.rs | 640 ++++-- ir/src/interpreter/integer_reference.rs | 173 ++ ir/src/interpreter/memory.rs | 631 +----- ir/src/interpreter/memory/generated.rs | 29 +- ir/src/interpreter/memory_reference.rs | 598 ++++++ ir/src/interpreter/memory_wave.rs | 832 ++++++++ ir/src/interpreter/mod.rs | 116 +- ir/src/interpreter/runtime_wave.rs | 1837 +++++++++++++++++ ir/src/interpreter/scalar.rs | 9 +- ir/src/lib.rs | 6 + ir/src/pass.rs | 113 +- ir/src/pass_dispose.rs | 89 + ir/src/pass_wave.rs | 272 +++ ir/src/verifier.rs | 2 +- ir/src/verifier/constants.rs | 226 +- ir/src/verifier/wave_constants.rs | 278 +++ ir/src/verifier/wave_semantics.rs | 10 +- ir/tests/ast_resource_limits.rs | 2 + ir/tests/integer_folding.rs | 224 ++ ir/tests/pass_effects.rs | 33 + ir/wide.wave | 287 +++ tools/build_wave_ir.py | 110 +- tools/check_wave_ir_float.py | 256 +++ tools/check_wave_ir_integer.py | 311 +++ tools/check_wave_ir_memory.py | 272 +++ tools/check_wave_ir_passes.py | 357 ++++ tools/check_wave_ir_runtime.py | 251 +++ 60 files changed, 14635 insertions(+), 1072 deletions(-) create mode 100644 ir/constant.wave create mode 100644 ir/constant_dependencies.wave create mode 100644 ir/effects.wave create mode 100644 ir/float_arithmetic.wave create mode 100644 ir/float_convert.wave create mode 100644 ir/float_model.wave create mode 100644 ir/fold_integer.wave create mode 100644 ir/integer.wave create mode 100644 ir/memory.wave create mode 100644 ir/passes.wave create mode 100644 ir/runtime_driver.wave create mode 100644 ir/runtime_execute.wave create mode 100644 ir/runtime_model.wave create mode 100644 ir/runtime_prepare.wave create mode 100644 ir/src/constant_wave.rs create mode 100644 ir/src/effects_wave.rs create mode 100644 ir/src/float/arithmetic_reference.rs rename ir/src/float/{conversions.rs => conversions_reference.rs} (98%) create mode 100644 ir/src/float/wave.rs create mode 100644 ir/src/fold_integer.rs create mode 100644 ir/src/fold_integer_wave.rs create mode 100644 ir/src/interpreter/integer_reference.rs create mode 100644 ir/src/interpreter/memory_reference.rs create mode 100644 ir/src/interpreter/memory_wave.rs create mode 100644 ir/src/interpreter/runtime_wave.rs create mode 100644 ir/src/pass_dispose.rs create mode 100644 ir/src/pass_wave.rs create mode 100644 ir/src/verifier/wave_constants.rs create mode 100644 ir/tests/integer_folding.rs create mode 100644 ir/wide.wave create mode 100644 tools/check_wave_ir_float.py create mode 100644 tools/check_wave_ir_integer.py create mode 100644 tools/check_wave_ir_memory.py create mode 100755 tools/check_wave_ir_passes.py create mode 100644 tools/check_wave_ir_runtime.py diff --git a/.github/workflows/asmobj.yml b/.github/workflows/asmobj.yml index 17d6d56..5964e76 100644 --- a/.github/workflows/asmobj.yml +++ b/.github/workflows/asmobj.yml @@ -95,17 +95,20 @@ jobs: -Wl,--no-whole-archive -o "$RUNNER_TEMP/wave-ir-o$optimization.so" ir_python="$(command -v python3)" for component in layout lexer header type literal expression instruction source \ - builder body printer verifier ssa ast_limits lower_type lowering hir cfg shape; do + builder body printer verifier ssa ast_limits lower_type lowering hir cfg shape \ + integer float memory runtime passes; do ir_cases=10000 if [ "$component" = literal ]; then ir_cases=100000; fi if [ "$component" = builder ]; then ir_cases=30000; fi + if [ "$component" = integer ]; then ir_cases=100000; fi + if [ "$component" = runtime ] || [ "$component" = passes ]; then ir_cases=2000; fi timeout 180s python3 tools/fuzz_limits.py --memory-mib 512 -- "$ir_python" \ "tools/check_wave_ir_$component.py" \ --library "$RUNNER_TEMP/wave-ir-o$optimization.so" --cases "$ir_cases" done + WHALE_WAVE_IR_DIR="$RUNNER_TEMP/wave-ir-o$optimization" \ + cargo test -p ir --all-features --locked --offline done - WHALE_WAVE_IR_DIR="$RUNNER_TEMP/wave-ir-o2" \ - cargo test -p ir --all-features --locked --offline - name: Reproduce the pinned typed HIR fixture run: | python3 tools/check_wave_hir_fixture.py --wave-source .asmobj-bootstrap-source \ diff --git a/BUILDING.md b/BUILDING.md index 1c6c40e..ab43025 100644 --- a/BUILDING.md +++ b/BUILDING.md @@ -2,7 +2,8 @@ Meson configures the product, compiles the Wave `asmobj` and IR sources, then builds Rust components with Cargo. `assembler/asmobj/` is entirely Wave. IR model, -parsing, printing, layout and verification run in Wave when its archive is selected; +text, verification, numeric semantics, passes and execution run in Wave when +its archive is selected; Rust supplies typed transport and retained reference implementations. Generated files and Cargo outputs stay in the selected build directory. @@ -70,9 +71,12 @@ the pinned compiler, std, Rust/LLVM bootstrap requirements, ABI, source and arch hashes. Changing the Rust/Wave boundary requires rebuilding the archive. Failed compilation or archiving preserves the previous complete publication. Ambient environment variables cannot select a different module for a Meson product. -Source builds also compile the Wave IR model, parser, printer, layout and verifier. +Source builds also compile Wave IR parsing, printing, verification, numeric +semantics, constant evaluation, verified passes and execution. With a prebuilt `asmobj`, pass `-Dwave-ir-dir=/absolute/path/to/built-wave-ir` to use them. Ordinary Cargo keeps the Rust reference during the IR migration. +The Wave numeric core uses two 64-bit words for 128-bit integers and exact +IEEE rounding; it does not depend on host floating-point arithmetic. For work confined to Rust components, ordinary Cargo builds remain available: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8ed6093..f2e692e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -21,7 +21,7 @@ executable does not need the Wave compiler at runtime. | `assembler/src/` | Shared Rust assembly types and helpers | | `assembler/asmobj/` | Complete Wave assembly-to-object module | | `toolchain/`, `backend-api/` | Rust composition, backend interfaces and external data calls to `asmobj` | -| `ir/`, `target-spec/` | Wave IR model, parser, printer, layout and verifier; Rust data transport and target contracts | +| `ir/`, `target-spec/` | Wave IR model, text, verification, numeric semantics, passes and execution; Rust data transport and target contracts | | `object/`, `linker/` | Rust object formats, relocations and executable layout | | `reverse/` | Rust image inspection; decoder and CFG currently unavailable | | `src/`, `tests/` | CLI and integration tests | @@ -31,6 +31,7 @@ Split source files by role. Shared modules must not import a concrete ISA. `asmobj` contains only Wave sources; its Rust data boundary lives in `toolchain/src/assembly_object.rs`. Object serialization belongs to `object`. IR reference algorithms remain available for comparison during the Wave migration. +Keep Wave blocks readable with four-space indentation and one statement per line. ### Adding an assembler or IR target diff --git a/README.md b/README.md index 85f6d6b..6e11348 100644 --- a/README.md +++ b/README.md @@ -694,8 +694,10 @@ module's responsibility. [Meson](BUILDING.md) compiles and links this module as part of the product. Cargo development builds select a prebuilt archive with `WHALE_ASMOBJ_DIR`. There is one implementation of its policies: an absent module returns an explicit -unavailable error. The former partial Wave ELF-record and reverse-analysis -implementations have been removed. IR remains Rust. +unavailable error. The IR module also runs in Wave when built with its pinned +archive: parsing, verification, numeric semantics, constant evaluation, passes +and execution live in role-specific `ir/*.wave` sources. Rust supplies owned +data, allocation and I/O; its reference implementation supports migration tests. ### Assembly symbol metadata and library resolution diff --git a/ir/build.rs b/ir/build.rs index badcfd8..2d30730 100644 --- a/ir/build.rs +++ b/ir/build.rs @@ -30,13 +30,37 @@ const SOURCES: &[&str] = &[ "cfg.wave", "shape.wave", "source.wave", + "memory.wave", "lower_limits.wave", + "wide.wave", + "integer.wave", + "float_model.wave", + "float_arithmetic.wave", + "float_convert.wave", + "effects.wave", + "passes.wave", + "fold_integer.wave", + "constant.wave", + "constant_dependencies.wave", + "runtime_model.wave", + "runtime_prepare.wave", + "runtime_execute.wave", + "runtime_driver.wave", "entry.wave", ]; const ABI_SOURCES: &[&str] = &[ "src/wave_layout.rs", + "src/interpreter/integer.rs", + "src/float/wave.rs", + "src/effects_wave.rs", + "src/pass_wave.rs", + "src/fold_integer_wave.rs", + "src/constant_wave.rs", + "src/interpreter/runtime_wave.rs", + "src/verifier/wave_constants.rs", "src/source_wave.rs", + "src/interpreter/memory_wave.rs", "src/lower_ast/wave_limits.rs", "src/parser/wave_lexer.rs", "src/parser/wave_header.rs", diff --git a/ir/constant.wave b/ir/constant.wave new file mode 100644 index 0000000..30bc3a5 --- /dev/null +++ b/ir/constant.wave @@ -0,0 +1,546 @@ +// SPDX-License-Identifier: MPL-2.0 +// Typed constant validation and lazy evaluation; only reference values cross +// the resumable data boundary. All arithmetic and error ordering stay in Wave. +struct IrConstNode { + kind: u64; + op: u64; + ty: u64; + left: u64; + right: u64; + reference: u64; + literal: u64; + low: u64; + high: u64; +} + +struct IrConstResolved { + ty: u64; + literal: u64; + low: u64; + high: u64; + present: u64; +} + +struct IrConstValue { + literal: u64; + low: u64; + high: u64; + present: u64; +} + +struct IrConstFrame { + node: u64; + phase: u64; + depth: u64; +} + +struct IrConstState { + initialized: u64; + phase: u64; + length: u64; + checked_types: u64; + work: u64; + root: u64; +} + +struct IrConstContext { + nodes: ptr; + node_count: u64; + types: ptr; + type_count: u64; + edges: ptr; + edge_count: u64; + resolved: ptr; + resolved_count: u64; + values: ptr; + value_count: u64; + frames: ptr; + capacity: u64; + state: ptr; + root: u64; + max_depth: u64; + max_work: u64; +} + +struct IrConstResult { + status: u64; + index: u64; + detail: u64; + literal: u64; + low: u64; + high: u64; + work: u64; +} + +fun ir_const_fail( + p: ptr, + result: ptr, + status: u64, + index: u64, + detail: u64 +) -> i32 { + result.status = status; + result.index = index; + result.detail = detail; + result.work = p.state.work; + return status as i32; +} + +fun ir_const_charge(p: ptr) -> bool { + return ir_cfg_charge(&p.state.work, p.max_work); +} + +fun ir_const_value_valid(kind: u64, literal: u64, low: u64, high: u64) -> bool { + if (!ir_verify_literal(kind, literal, low, high)) { + return false; + } + if (literal == 3) { + return low <= 1 && high == 0; + } + if (literal == 4) { + return low <= 65535 && high == 0; + } + if (literal == 5) { + return low <= 4294967295 && high == 0; + } + if (literal == 6) { + return high == 0; + } + return true; +} + +fun ir_const_push(p: ptr, node: u64, phase: u64, depth: u64) -> bool { + if (p.state.length >= p.capacity || node >= p.node_count) { + return false; + } + var frame: ptr = &p.frames[p.state.length]; + frame.node = node; + frame.phase = phase; + frame.depth = depth; + p.state.length += 1; + return true; +} + +fun ir_const_equal(p: ptr, a: u64, b: u64, valid: ptr) -> bool { + var result: IrVerifyResult; + result.status = 0; + result.index = 0; + result.expected = 0; + result.actual = 0; + result.detail = 0; + result.work = p.state.work; + var equal: bool = ir_verify_equal(a, b, p.types, p.edges, 258, &result, p.max_work); + p.state.work = result.work; + valid[0] = result.status == 0; + return equal; +} + +fun ir_const_kind_literal(kind: u64) -> u64 { + if (kind == 1) { + return 3; + } + if (ir_verify_signed(kind)) { + return 1; + } + if (ir_verify_unsigned(kind)) { + return 2; + } + if (ir_verify_float(kind)) { + return kind - 10; + } + return 0; +} + +fun ir_const_number( + p: ptr, + node: ptr, + left: ptr, + right: ptr, + output: ptr +) -> u64 { + var kind: u64 = p.types[node.ty].kind; + if (node.kind == 6) { + kind = p.types[p.nodes[node.left].ty].kind; + } + output.literal = ir_const_kind_literal(p.types[node.ty].kind); + output.high = 0; + output.low = 0; + output.present = 1; + if (node.kind == 6 && kind == 1) { + var equal: bool = left.low == right.low; + if ((node.op == 0 && equal) || (node.op == 1 && !equal)) { + output.low = 1; + } + return 0; + } + if (ir_verify_float(kind)) { + var value: u64 = 0; + if (node.kind == 4) { + var format: IrFloatFormat; + if (!ir_float_format(kind, &format)) { + return 8; + } + output.low = left.low ^ ir_float_sign(&format); + return 0; + } + if (node.kind == 6) { + var format: IrFloatFormat; + var predicate: u64 = node.op; + if (node.op == 1) { + predicate = 9; + } + if (!ir_float_format(kind, &format) || + !ir_float_predicate(&format, left.low, right.low, predicate, &value)) { + return 8; + } + } else { + var operation: u64 = node.op; + if (operation == 6 || operation == 7) { + operation -= 3; + } + if (!ir_float_arithmetic(operation, kind, left.low, right.low, &value)) { + return 8; + } + } + output.low = value; + return 0; + } + var mode: u64 = 0; + var operation: u64 = node.op; + if (node.kind == 3 || node.kind == 4) { + mode = 6; + operation = 1; + if (node.kind == 4) { + operation = 0; + } + } else if (node.kind == 6) { + mode = 3; + if (node.op >= 2 && ir_verify_signed(kind)) { + operation += 4; + } + } else { + if (node.op >= 3 && node.op <= 5) { + operation += 9; + } else if (node.op == 6) { + operation = 3; + if (ir_verify_signed(kind)) { + operation = 4; + } + } else if (node.op == 7) { + operation = 5; + if (ir_verify_signed(kind)) { + operation = 6; + } + } else if (node.op == 8) { + operation = 15; + } else if (node.op == 9) { + operation = 16; + if (ir_verify_signed(kind)) { + operation = 17; + } + } + } + var destination: u64 = kind; + if (node.kind == 6) { + destination = 1; + } + var numeric: IrIntegerResult; + var status: i32 = whale_ir_integer(mode, operation, kind, destination, left.low, left.high, + right.low, right.high, &numeric); + if (status != numeric.status as i32) { + return 8; + } + if (status == 1) { + return 4; + } + if (status == 2) { + return 5; + } + if (status != 0) { + return 8; + } + output.low = numeric.low; + output.high = numeric.high; + return 0; +} + +export(c) fun whale_ir_const_step(p: ptr, result: ptr) -> i32 { + if (result == null) { + return 8; + } + result.status = 8; + result.index = 0; + result.detail = 0; + result.literal = 0; + result.low = 0; + result.high = 0; + result.work = 0; + if (p == null || p.state == null) { + return 8; + } + if (p.root >= p.node_count || p.max_depth > 256 || p.state.initialized > 1 || + p.state.phase > 2 || p.state.length > p.capacity || p.state.work > p.max_work || + p.state.checked_types > p.type_count || p.resolved_count != p.node_count || + p.value_count != p.node_count || !ir_span_valid(p.nodes as ptr, p.node_count, 72) || + !ir_span_valid(p.types as ptr, p.type_count, 40) || + !ir_span_valid(p.edges as ptr, p.edge_count, 8) || + !ir_span_valid(p.resolved as ptr, p.resolved_count, 40) || + !ir_span_valid(p.values as ptr, p.value_count, 32) || + !ir_span_valid(p.frames as ptr, p.capacity, 24)) { + return ir_const_fail(p, result, 8, 0, 0); + } + while (p.state.checked_types < p.type_count) { + var index: u64 = p.state.checked_types; + if (!ir_const_charge(p)) { + return ir_const_fail(p, result, 7, p.root, 0); + } + var ty: ptr = &p.types[index]; + if (ty.kind > 21 || ((ty.kind == 17 || ty.kind == 19) && ty.child >= index)) { + return ir_const_fail(p, result, 8, index, 0); + } + if (ty.kind == 18 || ty.kind == 20 || ty.kind == 21) { + if (ty.first > p.edge_count || ty.count > p.edge_count - ty.first) { + return ir_const_fail(p, result, 8, index, 0); + } + var at: u64 = 0; + while (at < ty.count) { + if (!ir_const_charge(p)) { + return ir_const_fail(p, result, 7, p.root, 0); + } + if (p.edges[ty.first + at] >= index) { + return ir_const_fail(p, result, 8, index, 0); + } + at += 1; + } + } + p.state.checked_types += 1; + } + if (p.state.initialized == 0) { + var index: u64 = 0; + while (index < p.node_count) { + if (!ir_const_charge(p)) { + return ir_const_fail(p, result, 7, p.root, 0); + } + var node: ptr = &p.nodes[index]; + if (node.kind > 6 || node.ty >= p.type_count || + ((node.kind == 3 || node.kind == 4 || node.kind == 5 || node.kind == 6) && + node.left >= index) || + ((node.kind == 5 || node.kind == 6) && node.right >= index) || + ((node.kind == 1 || node.kind == 2) && node.reference > 4294967295) || + (node.kind == 5 && node.op > 11) || (node.kind == 6 && node.op > 5)) { + return ir_const_fail(p, result, 8, index, 0); + } + p.values[index].present = 0; + index += 1; + } + p.state.root = p.root; + p.state.phase = 0; + p.state.length = 0; + if (!ir_const_push(p, p.root, 0, 0)) { + return ir_const_fail(p, result, 8, p.root, 0); + } + p.state.initialized = 1; + } else if (p.state.root != p.root) { + return ir_const_fail(p, result, 8, p.root, 0); + } + while (p.state.phase == 0) { + if (p.state.length == 0) { + p.state.phase = 1; + if (!ir_const_push(p, p.root, 0, 0)) { + return ir_const_fail(p, result, 8, p.root, 0); + } + break; + } + var frame: IrConstFrame = p.frames[p.state.length - 1]; + if (frame.node >= p.node_count) { + return ir_const_fail(p, result, 8, p.root, 0); + } + if (frame.depth > p.max_depth) { + return ir_const_fail(p, result, 7, frame.node, 1); + } + if (!ir_const_charge(p)) { + return ir_const_fail(p, result, 7, frame.node, 0); + } + var node: ptr = &p.nodes[frame.node]; + var kind: u64 = p.types[node.ty].kind; + if (node.kind == 0) { + if (!ir_const_value_valid(kind, node.literal, node.low, node.high)) { + return ir_const_fail(p, result, 1, frame.node, 0); + } + } else if (node.kind == 1 || node.kind == 2) { + var resolved: ptr = &p.resolved[frame.node]; + if (resolved.present == 0) { + return ir_const_fail(p, result, 10, frame.node, node.reference); + } + if (resolved.present == 2) { + return ir_const_fail(p, result, 6, frame.node, node.reference); + } + if (resolved.present != 1 || resolved.ty >= p.type_count) { + return ir_const_fail(p, result, 8, frame.node, 0); + } + var valid: bool = true; + if (!ir_const_equal(p, node.ty, resolved.ty, &valid)) { + if (!valid) { + return ir_const_fail(p, result, 7, frame.node, 0); + } + return ir_const_fail(p, result, 2, frame.node, 0); + } + if (!ir_const_value_valid(kind, resolved.literal, resolved.low, resolved.high)) { + return ir_const_fail(p, result, 1, frame.node, 0); + } + } else { + var left_type: u64 = p.nodes[node.left].ty; + var valid: bool = true; + var expected: u64 = node.ty; + if (node.kind == 6) { + expected = left_type; + } + if (!ir_const_equal(p, expected, left_type, &valid) || + ((node.kind == 5 || node.kind == 6) && + !ir_const_equal(p, left_type, p.nodes[node.right].ty, &valid))) { + if (!valid) { + return ir_const_fail(p, result, 7, frame.node, 0); + } + return ir_const_fail(p, result, 2, frame.node, 0); + } + if (node.kind == 6 && kind != 1) { + return ir_const_fail(p, result, 2, frame.node, 0); + } + var category: u64 = kind; + if (node.kind == 6) { + category = p.types[left_type].kind; + } + var supported: bool = ir_verify_integer(category); + if (node.kind == 4) { + supported = supported || ir_verify_float(category); + } + if (node.kind == 5 && ir_verify_float(category)) { + supported = node.op <= 2 || node.op == 6 || node.op == 7; + } + if (node.kind == 5 && (node.op == 10 || node.op == 11)) { + supported = category == 1; + } + if (node.kind == 6) { + supported = + supported || ir_verify_float(category) || (category == 1 && node.op <= 1); + } + if (!supported) { + return ir_const_fail(p, result, 3, frame.node, 0); + } + } + p.state.length -= 1; + if (node.kind == 5 || node.kind == 6) { + if (!ir_const_push(p, node.right, 0, frame.depth + 1)) { + return ir_const_fail(p, result, 8, frame.node, 0); + } + } + if (node.kind >= 3) { + if (!ir_const_push(p, node.left, 0, frame.depth + 1)) { + return ir_const_fail(p, result, 8, frame.node, 0); + } + } + } + while (p.state.phase == 1 && p.state.length != 0) { + var position: u64 = p.state.length - 1; + var frame: IrConstFrame = p.frames[position]; + if (frame.node >= p.node_count || frame.phase > 2) { + return ir_const_fail(p, result, 8, p.root, 0); + } + if (!ir_const_charge(p)) { + return ir_const_fail(p, result, 7, frame.node, 0); + } + var node: ptr = &p.nodes[frame.node]; + var value: ptr = &p.values[frame.node]; + if (node.kind == 0) { + value.literal = node.literal; + value.low = node.low; + value.high = node.high; + value.present = 1; + p.state.length -= 1; + } else if (node.kind == 1 || node.kind == 2) { + value.literal = p.resolved[frame.node].literal; + value.low = p.resolved[frame.node].low; + value.high = p.resolved[frame.node].high; + value.present = 1; + p.state.length -= 1; + } else if (frame.phase == 0) { + p.frames[position].phase = 1; + if (!ir_const_push(p, node.left, 0, frame.depth + 1)) { + return ir_const_fail(p, result, 8, frame.node, 0); + } + } else { + var left: ptr = &p.values[node.left]; + if (left.present != 1) { + return ir_const_fail(p, result, 8, frame.node, 0); + } + if (node.kind == 5 && (node.op == 10 || node.op == 11)) { + if (frame.phase == 1 && + ((node.op == 10 && left.low != 0) || (node.op == 11 && left.low == 0))) { + p.frames[position].phase = 2; + if (!ir_const_push(p, node.right, 0, frame.depth + 1)) { + return ir_const_fail(p, result, 8, frame.node, 0); + } + } else { + var answer: ptr = left; + if (frame.phase == 2) { + answer = &p.values[node.right]; + } + if (answer.present != 1) { + return ir_const_fail(p, result, 8, frame.node, 0); + } + value[0] = answer[0]; + p.state.length -= 1; + } + } else if ((node.kind == 5 || node.kind == 6) && frame.phase == 1) { + p.frames[position].phase = 2; + if (!ir_const_push(p, node.right, 0, frame.depth + 1)) { + return ir_const_fail(p, result, 8, frame.node, 0); + } + } else { + var right: IrConstValue; + right.literal = 0; + right.low = 0; + right.high = 0; + right.present = 0; + if (node.kind == 5 || node.kind == 6) { + right = p.values[node.right]; + if (right.present != 1) { + return ir_const_fail(p, result, 8, frame.node, 0); + } + } + var status: u64 = ir_const_number(p, node, left, &right, value); + if (status != 0) { + return ir_const_fail(p, result, status, frame.node, 0); + } + if (!ir_const_value_valid(p.types[node.ty].kind, value.literal, value.low, + value.high)) { + return ir_const_fail(p, result, 8, frame.node, 0); + } + p.state.length -= 1; + } + } + } + if (p.state.length == 0) { + p.state.phase = 2; + } + if (p.state.phase != 2 || p.values[p.root].present != 1) { + return ir_const_fail(p, result, 8, p.root, 0); + } + result.status = 0; + result.index = p.root; + result.literal = p.values[p.root].literal; + result.low = p.values[p.root].low; + result.high = p.values[p.root].high; + result.work = p.state.work; + return 0; +} + +export(c) fun whale_ir_const_literal(kind: u64, literal: u64, low: u64, high: u64) -> i32 { + if (kind > 21 || literal > 6) { + return 2; + } + if (ir_const_value_valid(kind, literal, low, high)) { + return 1; + } + return 0; +} diff --git a/ir/constant_dependencies.wave b/ir/constant_dependencies.wave new file mode 100644 index 0000000..5c5e95a --- /dev/null +++ b/ir/constant_dependencies.wave @@ -0,0 +1,375 @@ +// SPDX-License-Identifier: MPL-2.0 +// Stable indexed dependency scheduling. Imported global indices are borrowed, +// so each function visits only its own constants and references. + +struct IrConstDefinition { + kind: u64; + id: u64; + ty: u64; + root: u64; +} + +struct IrConstKey { + kind: u64; + id: u64; +} + +struct IrConstSlot { + kind: u64; + id: u64; + definition: u64; + present: u64; +} + +struct IrConstDependency { + user: u64; + next: u64; +} + +struct IrConstPending { + remaining: u64; + head: u64; + tail: u64; + mark: u64; + completed: u64; +} + +struct IrConstSchedule { + definitions: ptr; + definition_count: u64; + nodes: ptr; + node_count: u64; + types: ptr; + type_count: u64; + type_edges: ptr; + type_edge_count: u64; + base: ptr; + base_count: u64; + imported: ptr; + imported_capacity: u64; + slots: ptr; + capacity: u64; + pending: ptr; + pending_count: u64; + dependencies: ptr; + dependency_capacity: u64; + stack: ptr; + stack_capacity: u64; + order: ptr; + order_capacity: u64; + max_work: u64; +} + +struct IrConstScheduleResult { + status: u64; + definition: u64; + reference_kind: u64; + reference: u64; + count: u64; + work: u64; +} + +fun ir_const_schedule_error( + result: ptr, + status: u64, + definition: u64 +) -> i32 { + result.status = status; + result.definition = definition; + return status as i32; +} + +fun ir_const_schedule_slot( + slots: ptr, + capacity: u64, + kind: u64, + id: u64, + result: ptr, + limit: u64 +) -> u64 { + if (capacity == 0) { + return 0; + } + var at: u64 = ir_source_mix((id << 1) ^ kind) & (capacity - 1); + while (true) { + if (!ir_cfg_charge(&result.work, limit)) { + result.status = 7; + return capacity; + } + if (slots[at].present == 0 || (slots[at].kind == kind && slots[at].id == id)) { + return at; + } + at = (at + 1) & (capacity - 1); + } + return capacity; +} + +export(c) fun whale_ir_const_schedule( + p: ptr, + result: ptr +) -> i32 { + if (result == null) { + return 8; + } + result.status = 0; + result.definition = 0; + result.reference_kind = 0; + result.reference = 0; + result.count = 0; + result.work = 0; + if (p == null) { + result.status = 8; + return 8; + } + if (p.capacity < 2 || !ir_power_two(p.capacity) || p.definition_count > p.capacity / 2 || + p.base_count > p.capacity / 2 - p.definition_count || + p.pending_count != p.definition_count || p.order_capacity < p.definition_count || + (p.imported_capacity != 0 && + (p.imported_capacity < 2 || !ir_power_two(p.imported_capacity))) || + !ir_span_valid(p.definitions as ptr, p.definition_count, 32) || + !ir_span_valid(p.nodes as ptr, p.node_count, 72) || + !ir_span_valid(p.types as ptr, p.type_count, 40) || + !ir_span_valid(p.type_edges as ptr, p.type_edge_count, 8) || + !ir_span_valid(p.base as ptr, p.base_count, 16) || + !ir_span_valid(p.imported as ptr, p.imported_capacity, 32) || + !ir_span_valid(p.slots as ptr, p.capacity, 32) || + !ir_span_valid(p.pending as ptr, p.pending_count, 40) || + !ir_span_valid(p.dependencies as ptr, p.dependency_capacity, 16) || + !ir_span_valid(p.stack as ptr, p.stack_capacity, 8) || + !ir_span_valid(p.order as ptr, p.order_capacity, 8)) { + return ir_const_schedule_error(result, 8, 0); + } + var verification: IrVerifyResult; + verification.status = 0; + verification.index = 0; + verification.expected = 0; + verification.actual = 0; + verification.detail = 0; + verification.work = 0; + if (!ir_verify_graph_valid(p.types, p.type_count, p.type_edges, p.type_edge_count, p.max_work, + &verification)) { + result.work = verification.work; + if (verification.status == 8) { + return ir_const_schedule_error(result, 7, 0); + } + return ir_const_schedule_error(result, 8, 0); + } + result.work = verification.work; + var at: u64 = 0; + while (at < p.capacity) { + if (!ir_cfg_charge(&result.work, p.max_work)) { + return ir_const_schedule_error(result, 7, 0); + } + p.slots[at].present = 0; + at += 1; + } + at = 0; + while (at < p.node_count) { + if (!ir_cfg_charge(&result.work, p.max_work)) { + return ir_const_schedule_error(result, 7, 0); + } + var node: ptr = &p.nodes[at]; + if (node.kind > 6 || node.ty >= p.type_count || (node.kind >= 3 && node.left >= at) || + ((node.kind == 5 || node.kind == 6) && node.right >= at) || + ((node.kind == 1 || node.kind == 2) && node.reference > 4294967295) || + (node.kind == 5 && node.op > 11) || (node.kind == 6 && node.op > 5)) { + return ir_const_schedule_error(result, 8, 0); + } + at += 1; + } + at = 0; + while (at < p.base_count) { + var key: ptr = &p.base[at]; + if ((key.kind != 1 && key.kind != 2) || key.id > 4294967295) { + return ir_const_schedule_error(result, 8, 0); + } + var position: u64 = ir_const_schedule_slot(p.slots, p.capacity, key.kind, key.id, result, + p.max_work); + if (result.status != 0) { + return result.status as i32; + } + p.slots[position].kind = key.kind; + p.slots[position].id = key.id; + p.slots[position].definition = 18446744073709551615; + p.slots[position].present = 1; + at += 1; + } + at = 0; + while (at < p.definition_count) { + var definition: ptr = &p.definitions[at]; + if ((definition.kind != 1 && definition.kind != 2) || definition.id > 4294967295 || + definition.ty >= p.type_count || definition.root >= p.node_count) { + return ir_const_schedule_error(result, 8, at); + } + var position: u64 = ir_const_schedule_slot(p.slots, p.capacity, definition.kind, + definition.id, result, p.max_work); + if (result.status != 0) { + return result.status as i32; + } + if (p.slots[position].present != 0) { + return ir_const_schedule_error(result, 1, at); + } + if (p.imported_capacity != 0) { + var imported: u64 = ir_const_schedule_slot(p.imported, p.imported_capacity, definition.kind, + definition.id, result, p.max_work); + if (result.status != 0) { + return result.status as i32; + } + if (p.imported[imported].present != 0) { + return ir_const_schedule_error(result, 1, at); + } + } + p.slots[position].kind = definition.kind; + p.slots[position].id = definition.id; + p.slots[position].definition = at; + p.slots[position].present = 1; + verification.status = 0; + verification.work = result.work; + var equal: bool = ir_verify_equal(definition.ty, p.nodes[definition.root].ty, p.types, + p.type_edges, 258, &verification, p.max_work); + result.work = verification.work; + if (verification.status != 0) { + return ir_const_schedule_error(result, 7, at); + } + if (!equal) { + return ir_const_schedule_error(result, 2, at); + } + p.pending[at].remaining = 0; + p.pending[at].head = 18446744073709551615; + p.pending[at].tail = 18446744073709551615; + p.pending[at].mark = 0; + p.pending[at].completed = 0; + at += 1; + } + at = 0; + var dependency_count: u64 = 0; + var ready: u64 = 0; + while (at < p.definition_count) { + if (p.stack_capacity == 0) { + return ir_const_schedule_error(result, 8, at); + } + p.stack[0] = p.definitions[at].root; + var length: u64 = 1; + while (length != 0) { + if (!ir_cfg_charge(&result.work, p.max_work)) { + return ir_const_schedule_error(result, 7, at); + } + length -= 1; + var node: ptr = &p.nodes[p.stack[length]]; + if (node.kind == 1 || node.kind == 2) { + var position: u64 = ir_const_schedule_slot(p.slots, p.capacity, node.kind, + node.reference, result, p.max_work); + if (result.status != 0) { + return result.status as i32; + } + if (p.slots[position].present == 0) { + var found: bool = false; + if (p.imported_capacity != 0) { + var imported: u64 = ir_const_schedule_slot(p.imported, p.imported_capacity, + node.kind, node.reference, + result, p.max_work); + if (result.status != 0) { + return result.status as i32; + } + found = p.imported[imported].present != 0; + } + if (!found) { + result.reference_kind = node.kind; + result.reference = node.reference; + return ir_const_schedule_error(result, 3, at); + } + } else if (p.slots[position].definition != 18446744073709551615) { + var dependency: u64 = p.slots[position].definition; + if (dependency >= p.definition_count) { + return ir_const_schedule_error(result, 8, at); + } + if (p.pending[dependency].mark != at + 1) { + if (dependency_count >= p.dependency_capacity) { + return ir_const_schedule_error(result, 8, at); + } + p.pending[dependency].mark = at + 1; + p.dependencies[dependency_count].user = at; + p.dependencies[dependency_count].next = 18446744073709551615; + if (p.pending[dependency].tail != 18446744073709551615) { + p.dependencies[p.pending[dependency].tail].next = dependency_count; + } else { + p.pending[dependency].head = dependency_count; + } + p.pending[dependency].tail = dependency_count; + p.pending[at].remaining += 1; + dependency_count += 1; + } + } + } else if (node.kind >= 3) { + if (node.kind == 5 || node.kind == 6) { + if (length >= p.stack_capacity) { + return ir_const_schedule_error(result, 8, at); + } + p.stack[length] = node.right; + length += 1; + } + if (length >= p.stack_capacity) { + return ir_const_schedule_error(result, 8, at); + } + p.stack[length] = node.left; + length += 1; + } + } + if (p.pending[at].remaining == 0) { + p.order[ready] = at; + ready += 1; + } + at += 1; + } + at = 0; + while (at < ready) { + if (!ir_cfg_charge(&result.work, p.max_work)) { + return ir_const_schedule_error(result, 7, 0); + } + var definition: u64 = p.order[at]; + p.pending[definition].completed = 1; + var link: u64 = p.pending[definition].head; + while (link != 18446744073709551615) { + if (!ir_cfg_charge(&result.work, p.max_work)) { + return ir_const_schedule_error(result, 7, definition); + } + if (link >= dependency_count) { + return ir_const_schedule_error(result, 8, definition); + } + var user: u64 = p.dependencies[link].user; + if (user >= p.definition_count || p.pending[user].remaining == 0) { + return ir_const_schedule_error(result, 8, definition); + } + p.pending[user].remaining -= 1; + if (p.pending[user].remaining == 0) { + p.order[ready] = user; + ready += 1; + } + link = p.dependencies[link].next; + } + at += 1; + } + result.count = ready; + at = 0; + while (at < p.definition_count) { + if (p.pending[at].completed == 0) { + return ir_const_schedule_error(result, 4, at); + } + at += 1; + } + return 0; +} + +export(c) fun whale_ir_const_value_equal( + left_kind: u64, + left_low: u64, + left_high: u64, + right_kind: u64, + right_low: u64, + right_high: u64 +) -> i32 { + if (left_kind == right_kind && left_low == right_low && left_high == right_high) { + return 1; + } + return 0; +} diff --git a/ir/effects.wave b/ir/effects.wave new file mode 100644 index 0000000..e461778 --- /dev/null +++ b/ir/effects.wave @@ -0,0 +1,75 @@ +// SPDX-License-Identifier: MPL-2.0 +// Observable effects; opcode tags follow the typed body model. +fun ir_effect_mask(op: u64, sub: u64, pointer: u64) -> u64 { + if (op == 19) { + return 21; + } + if (op == 20) { + return 22; + } + if (op == 21) { + return 17; + } + if (op == 22 || op == 23 || op == 26) { + return 18; + } + if (op == 25) { + return 19; + } + if (op == 18 || op == 1) { + return 48; + } + if (op == 29) { + return 27; + } + if (op == 24 || op == 2 || op == 30 || op == 5) { + return 16; + } + if (op == 7 && sub >= 3 && sub <= 6) { + return 16; + } + if (op == 14 && (sub == 0 || sub == 8 || sub == 9)) { + return 16; + } + if ((op == 10 || op == 11) && pointer != 0) { + return 16; + } + return 0; +} + +export(c) fun whale_ir_effects( + op: u64, + sub: u64, + pointer: u64, + terminator: u64, + output: ptr +) -> i32 { + if (output == null || pointer > 1 || terminator > 1) { + return 1; + } + if (terminator == 1) { + if (op > 4 || sub != 0 || pointer != 0) { + return 1; + } + output[0] = 0; + if (op == 4) { + output[0] = 16; + } + return 0; + } + if (op > 30 || (op == 7 && sub > 17) || (op == 14 && sub > 12)) { + return 1; + } + output[0] = ir_effect_mask(op, sub, pointer); + return 0; +} + +export(c) fun whale_ir_effects_removable(mask: u64) -> i32 { + if (mask > 63) { + return 2; + } + if (mask == 0) { + return 1; + } + return 0; +} diff --git a/ir/float_arithmetic.wave b/ir/float_arithmetic.wave new file mode 100644 index 0000000..afe1b87 --- /dev/null +++ b/ir/float_arithmetic.wave @@ -0,0 +1,126 @@ +// SPDX-License-Identifier: MPL-2.0 +// Finite products remain exact through 106 bits; only packing rounds. +fun ir_float_arithmetic(operation: u64, kind: u64, lhs: u64, rhs: u64, output: ptr) -> bool { + var format: IrFloatFormat; + if (operation > 4 || !ir_float_format(kind, &format)) { + return false; + } + var a: IrFloatParts; + var b: IrFloatParts; + ir_float_unpack(&format, lhs, &a); + ir_float_unpack(&format, rhs, &b); + if (a.nan || b.nan) { + output[0] = ir_float_nan(&format); + return true; + } + if (operation == 1) { + b.negative = !b.negative; + } + var negative: bool = (a.negative && !b.negative) || (!a.negative && b.negative); + ir_float_normalize(&format, &a); + ir_float_normalize(&format, &b); + var a_zero: bool = ir_float_wide_zero(&a.significand); + var b_zero: bool = ir_float_wide_zero(&b.significand); + var value: IrWide; + if (operation <= 1) { + if (a.infinity || b.infinity) { + if (a.infinity && b.infinity && negative) { + output[0] = ir_float_nan(&format); + } else { + var sign: bool = b.negative; + if (a.infinity) { + sign = a.negative; + } + output[0] = ir_float_special(&format, sign, true); + } + } else if (a_zero && b_zero) { + output[0] = ir_float_special(&format, a.negative && b.negative, false); + } else if (a_zero) { + output[0] = ir_float_pack(&format, b.negative, &b.significand, b.exponent); + } else if (b_zero) { + output[0] = ir_float_pack(&format, a.negative, &a.significand, a.exponent); + } else { + if (a.exponent < b.exponent || (a.exponent == b.exponent && ir_wide_cmp(&a.significand, + &b.significand) < 0)) { + var temporary: IrFloatParts = a; + a = b; + b = temporary; + } + var av: IrWide; + var bv: IrWide; + ir_wide_shl(&a.significand, 3, &av); + ir_wide_shl(&b.significand, 3, &bv); + ir_wide_jam(&bv, (a.exponent - b.exponent) as u64, &bv); + if ((a.negative && b.negative) || (!a.negative && !b.negative)) { + ir_wide_add(&av, &bv, &value); + output[0] = ir_float_pack(&format, a.negative, &value, a.exponent - 3); + } else { + var sign: bool = a.negative && ir_wide_cmp(&av, &bv) != 0; + ir_wide_sub(&av, &bv, &value); + output[0] = ir_float_pack(&format, sign, &value, a.exponent - 3); + } + } + } else if (operation == 2) { + if ((a.infinity && b_zero && !b.infinity) || (b.infinity && a_zero && !a.infinity)) { + output[0] = ir_float_nan(&format); + } else if (a.infinity || b.infinity) { + output[0] = ir_float_special(&format, negative, true); + } else { + ir_wide_mul(&a.significand, &b.significand, &value); + output[0] = ir_float_pack(&format, negative, &value, a.exponent + b.exponent); + } + } else if (operation == 3) { + if ((a.infinity && b.infinity) || (!a.infinity && !b.infinity && a_zero && b_zero)) { + output[0] = ir_float_nan(&format); + } else if (a.infinity || (b_zero && !b.infinity)) { + output[0] = ir_float_special(&format, negative, true); + } else if (b.infinity || a_zero) { + output[0] = ir_float_special(&format, negative, false); + } else { + var shift: u64 = format.fraction + 4; + var numerator: IrWide; + var remainder: IrWide; + ir_wide_shl(&a.significand, shift, &numerator); + if (!ir_wide_divmod(&numerator, &b.significand, &value, &remainder)) { + return false; + } + if (!ir_float_wide_zero(&remainder)) { + value.low = value.low | 1; + } + output[0] = ir_float_pack(&format, negative, &value, a.exponent - b.exponent - shift as + i64); + } + } else { + if (a.infinity || (b_zero && !b.infinity)) { + output[0] = ir_float_nan(&format); + } else if (b.infinity || a_zero || a.exponent < b.exponent) { + output[0] = lhs; + } else { + var r: IrWide; + var power: IrWide; + var quotient: IrWide; + var two: IrWide; + ir_wide_from(2, 0, &two); + if (!ir_wide_divmod(&a.significand, &b.significand, "ient, &r) || + !ir_wide_divmod(&two, &b.significand, "ient, &power)) { + return false; + } + var shift: u64 = (a.exponent - b.exponent) as u64; + while (shift != 0) { + if ((shift & 1) != 0) { + ir_wide_mul(&r, &power, &value); + if (!ir_wide_divmod(&value, &b.significand, "ient, &r)) { + return false; + } + } + ir_wide_mul(&power, &power, &value); + if (!ir_wide_divmod(&value, &b.significand, "ient, &power)) { + return false; + } + shift = shift >> 1; + } + output[0] = ir_float_pack(&format, a.negative, &r, b.exponent); + } + } + return true; +} diff --git a/ir/float_convert.wave b/ir/float_convert.wave new file mode 100644 index 0000000..8a30e06 --- /dev/null +++ b/ir/float_convert.wave @@ -0,0 +1,274 @@ +// SPDX-License-Identifier: MPL-2.0 +// Numeric conversions share the single packer's rounding; stored NaNs stay separate. +fun ir_float_integer_mask(width: u64, output: ptr) { + var one: u64 = 1; + output.low = 18446744073709551615; + output.high = 18446744073709551615; + if (width < 64) { + output.low = (one << width) - 1; + output.high = 0; + } else if (width == 64) { + output.high = 0; + } else if (width < 128) { + output.high = (one << (width - 64)) - 1; + } +} + +fun ir_float_integer_negative(kind: u64, value: ptr) -> bool { + if (!ir_verify_signed(kind)) { + return false; + } + var width: u64 = ir_verify_width(kind); + var one: u64 = 1; + if (width <= 64) { + return (value.low & (one << (width - 1))) != 0; + } + return (value.high & (one << (width - 65))) != 0; +} + +fun ir_float_integer_pack(kind: u64, source_value: ptr, output: ptr) { + var mask: IrWide; + ir_float_integer_mask(ir_verify_width(kind), &mask); + output.low = source_value.low & mask.low; + output.high = source_value.high & mask.high; + if (ir_float_integer_negative(kind, output)) { + output.low = output.low | ~mask.low; + output.high = output.high | ~mask.high; + } +} + +fun ir_float_conversion( + operation: u64, + source: u64, + destination: u64, + low: u64, + high: u64, + output: ptr +) -> bool { + var src: IrFloatFormat; + var dst: IrFloatFormat; + var source_float: bool = ir_float_format(source, &src); + var destination_float: bool = ir_float_format(destination, &dst); + var valid: bool = false; + if (operation == 0) { + valid = source_float && destination_float && src.width < dst.width; + } else if (operation == 1) { + valid = source_float && destination_float && src.width > dst.width; + } else if (operation == 2) { + valid = ir_verify_signed(source) && destination_float; + } else if (operation == 3) { + valid = ir_verify_unsigned(source) && destination_float; + } else if (operation == 4) { + valid = source_float && ir_verify_signed(destination); + } else if (operation == 5) { + valid = source_float && ir_verify_unsigned(destination); + } + if (!valid) { + return false; + } + output.high = 0; + var parts: IrFloatParts; + if (operation <= 1) { + ir_float_unpack(&src, low, &parts); + if (parts.nan) { + output.low = ir_float_nan(&dst); + } else if (parts.infinity) { + output.low = ir_float_special(&dst, parts.negative, true); + } else { + output.low = ir_float_pack(&dst, parts.negative, &parts.significand, parts.exponent); + } + } else if (operation <= 3) { + var raw: IrWide; + var mask: IrWide; + ir_float_integer_mask(ir_verify_width(source), &mask); + ir_wide_from(low & mask.low, high & mask.high, &raw); + var negative: bool = ir_float_integer_negative(source, &raw); + if (negative) { + ir_wide_neg(&raw, &raw); + raw.low = raw.low & mask.low; + raw.high = raw.high & mask.high; + } + output.low = ir_float_pack(&dst, negative, &raw, 0); + } else { + ir_float_unpack(&src, low, &parts); + if (parts.nan || parts.infinity) { + return false; + } + var magnitude: IrWide; + if (ir_float_wide_zero(&parts.significand)) { + ir_wide_zero(&magnitude); + } else if (parts.exponent >= 0) { + var shift: u64 = parts.exponent as u64; + if (shift >= 128 || shift > ir_wide_clz(&parts.significand)) { + return false; + } + ir_wide_shl(&parts.significand, shift, &magnitude); + } else { + ir_wide_shr(&parts.significand, (-parts.exponent) as u64, &magnitude); + } + var width: u64 = ir_verify_width(destination); + var signed: bool = ir_verify_signed(destination); + var maximum: IrWide; + ir_float_integer_mask(width, &maximum); + if (signed) { + var one: IrWide; + ir_wide_from(1, 0, &one); + ir_wide_shl(&one, width - 1, &maximum); + if (!parts.negative) { + ir_wide_sub(&maximum, &one, &maximum); + } + } + if ((parts.negative && !signed && !ir_float_wide_zero(&magnitude)) || + ir_wide_cmp(&magnitude, &maximum) > 0) { + return false; + } + if (parts.negative) { + ir_wide_neg(&magnitude, &magnitude); + } + ir_float_integer_pack(destination, &magnitude, output); + } + return true; +} + +// Host convenience conversions transport bits through Wave. Binary16 -> binary64 +// preserves signaling/payload bits; binary32 widening matches numeric quieting. +fun ir_float_to_binary64(kind: u64, source_value: u64, output: ptr) -> bool { + var format: IrFloatFormat; + if (!ir_float_format(kind, &format)) { + return false; + } + if (kind == 16) { + output[0] = source_value; + return true; + } + var parts: IrFloatParts; + ir_float_unpack(&format, source_value, &parts); + var dst: IrFloatFormat; + ir_float_format(16, &dst); + if (parts.nan) { + var fraction: u64 = source_value & ((ir_float_sign(&format) >> (format.width - 1 - + format.fraction)) - 1); + // The fraction is widened without arithmetic or host floating exceptions. + var shift: u64 = 52 - format.fraction; + var sign: u64 = 0; + if (parts.negative) { + sign = ir_float_sign(&dst); + } + output[0] = sign | ir_float_infinity(&dst) | (fraction << shift); + if (kind == 15) { + var one: u64 = 1; + output[0] = output[0] | (one << 51); + } + } else if (parts.infinity) { + output[0] = ir_float_special(&dst, parts.negative, true); + } else { + output[0] = ir_float_pack(&dst, parts.negative, &parts.significand, parts.exponent); + } + return true; +} + +fun ir_float_from_binary64(kind: u64, source_value: u64, output: ptr) -> bool { + var format: IrFloatFormat; + if (!ir_float_format(kind, &format)) { + return false; + } + if (kind == 16) { + output[0] = source_value; + return true; + } + var src: IrFloatFormat; + ir_float_format(16, &src); + var parts: IrFloatParts; + ir_float_unpack(&src, source_value, &parts); + if (parts.nan) { + var sign: u64 = 0; + if (parts.negative) { + sign = ir_float_sign(&format); + } + if (kind == 14) { + output[0] = sign | ir_float_nan(&format); + } else { + var one: u64 = 1; + output[0] = sign | ir_float_infinity(&format) | ((source_value & 4503599627370495) >> + 29) | (one << 22); + } + } else if (parts.infinity) { + output[0] = ir_float_special(&format, parts.negative, true); + } else { + output[0] = ir_float_pack(&format, parts.negative, &parts.significand, parts.exponent); + } + return true; +} + +fun ir_float_input_valid(kind: u64, literal: u64, low: u64, high: u64) -> bool { + if (!ir_verify_literal(kind, literal, low, high)) { + return false; + } + if (kind == 14) { + return high == 0 && low <= 65535; + } + if (kind == 15) { + return high == 0 && low <= 4294967295; + } + if (kind == 16) { + return high == 0; + } + if (kind == 1) { + return high == 0 && low <= 1; + } + return true; +} + +export(c) fun whale_ir_float(request: ptr, result: ptr) -> i32 { + if (!ir_span_valid(result as ptr, 1, 32)) { + return 9; + } + result.status = 9; + result.low = 0; + result.high = 0; + result.flag = 0; + if (!ir_span_valid(request as ptr, 1, 80) || request.mode > 5) { + return 9; + } + var q: IrFloatRequest = request[0]; + result.status = 1; + if (!ir_float_input_valid(q.source, q.left_kind, q.left_low, q.left_high)) { + return 1; + } + var low: u64 = 0; + var flag: u64 = 0; + var output: IrWide; + ir_wide_zero(&output); + var valid: bool = false; + var format: IrFloatFormat; + if (q.mode == 0) { + valid = q.source == q.destination && ir_float_input_valid(q.destination, q.right_kind, + q.right_low, q.right_high) && ir_float_arithmetic(q.operation, q.source, q.left_low, + q.right_low, &low); + } else if (q.mode == 1) { + valid = ir_float_format(q.source, &format); + if (valid) { + low = q.left_low ^ ir_float_sign(&format); + } + } else if (q.mode == 2) { + valid = q.source == q.destination && ir_float_input_valid(q.destination, q.right_kind, + q.right_low, q.right_high) && ir_float_format(q.source, &format) && + ir_float_predicate(&format, q.left_low, q.right_low, q.operation, &flag); + } else if (q.mode == 3) { + valid = ir_float_conversion(q.operation, q.source, q.destination, q.left_low, q.left_high, + &output); + low = output.low; + } else if (q.mode == 4) { + valid = ir_float_to_binary64(q.source, q.left_low, &low); + } else { + valid = q.source == 16 && ir_float_from_binary64(q.destination, q.left_low, &low); + } + if (!valid) { + return 1; + } + result.status = 0; + result.low = low; + result.high = output.high; + result.flag = flag; + return 0; +} diff --git a/ir/float_model.wave b/ir/float_model.wave new file mode 100644 index 0000000..4ee8bf3 --- /dev/null +++ b/ir/float_model.wave @@ -0,0 +1,225 @@ +// SPDX-License-Identifier: MPL-2.0 +// IEEE storage and nearest-even packing use only the shared two-word integer. +struct IrFloatFormat { + width: u64; + fraction: u64; + bias: i64; +} + +struct IrFloatParts { + negative: bool; + significand: IrWide; + exponent: i64; + nan: bool; + infinity: bool; +} + +struct IrFloatResult { + status: u64; + low: u64; + high: u64; + flag: u64; +} + +struct IrFloatRequest { + mode: u64; + operation: u64; + source: u64; + destination: u64; + left_kind: u64; + left_low: u64; + left_high: u64; + right_kind: u64; + right_low: u64; + right_high: u64; +} + +fun ir_float_format(kind: u64, output: ptr) -> bool { + if (kind == 14) { + output.width = 16; + output.fraction = 10; + output.bias = 15; + } else if (kind == 15) { + output.width = 32; + output.fraction = 23; + output.bias = 127; + } else if (kind == 16) { + output.width = 64; + output.fraction = 52; + output.bias = 1023; + } else { + return false; + } + return true; +} + +fun ir_float_sign(format: ptr) -> u64 { + var one: u64 = 1; + return one << (format.width - 1); +} + +fun ir_float_infinity(format: ptr) -> u64 { + return ((format.bias * 2 + 1) as u64) << format.fraction; +} + +fun ir_float_nan(format: ptr) -> u64 { + var one: u64 = 1; + return ir_float_infinity(format) | (one << (format.fraction - 1)); +} + +fun ir_float_special(format: ptr, negative: bool, infinity: bool) -> u64 { + var bits: u64 = 0; + if (negative) { + bits = ir_float_sign(format); + } + if (infinity) { + bits = bits | ir_float_infinity(format); + } + return bits; +} + +fun ir_float_wide_zero(value: ptr) -> bool { + return value.low == 0 && value.high == 0; +} + +fun ir_float_unpack(format: ptr, bits: u64, output: ptr) { + var one: u64 = 1; + var exponent: i64 = ((bits & ~ir_float_sign(format)) >> format.fraction) as i64; + var fraction: u64 = bits & ((one << format.fraction) - 1); + var special: bool = exponent == 2 * format.bias + 1; + output.negative = (bits & ir_float_sign(format)) != 0; + ir_wide_from(fraction, 0, &output.significand); + if (exponent != 0 && !special) { + output.significand.low = output.significand.low | (one << format.fraction); + } + if (exponent < 1) { + exponent = 1; + } + output.exponent = exponent - format.bias - format.fraction as i64; + output.nan = special && fraction != 0; + output.infinity = special && fraction == 0; +} + +fun ir_float_normalize(format: ptr, value: ptr) { + if (!ir_float_wide_zero(&value.significand)) { + var shift: u64 = ir_wide_clz(&value.significand) - (127 - format.fraction); + ir_wide_shl(&value.significand, shift, &value.significand); + value.exponent -= shift as i64; + } +} + +fun ir_float_pack( + format: ptr, + negative: bool, + significand: ptr, + exponent: i64 +) -> u64 { + if (ir_float_wide_zero(significand)) { + return ir_float_special(format, negative, false); + } + var highest: i64 = (127 - ir_wide_clz(significand)) as i64; + var target: i64 = exponent + highest - format.fraction as i64; + var minimum: i64 = 1 - format.bias - format.fraction as i64; + if (target < minimum) { + target = minimum; + } + var shift: i64 = target - exponent; + var rounded: IrWide; + if (shift > 0) { + ir_wide_round(significand, shift as u64, &rounded); + } else { + ir_wide_shl(significand, (-shift) as u64, &rounded); + } + var one: u64 = 1; + if (rounded.high != 0 || rounded.low >= (one << (format.fraction + 1))) { + ir_wide_shr(&rounded, 1, &rounded); + target += 1; + } + if (ir_float_wide_zero(&rounded)) { + return ir_float_special(format, negative, false); + } + var encoded: i64 = 0; + if (rounded.low >= (one << format.fraction)) { + encoded = target + format.fraction as i64 + format.bias; + } + if (encoded > 2 * format.bias) { + return ir_float_special(format, negative, true); + } + var sign: u64 = 0; + if (negative) { + sign = ir_float_sign(format); + } + return sign | ((encoded as u64) << format.fraction) | (rounded.low & ((one << format.fraction) - + 1)); +} + +fun ir_float_predicate( + format: ptr, + a: u64, + b: u64, + predicate: u64, + output: ptr +) -> bool { + if (predicate > 13) { + return false; + } + var one: u64 = 1; + var fraction: u64 = (one << format.fraction) - 1; + var exponent: u64 = ir_float_infinity(format); + var ordered: bool = !((a & exponent) == exponent && (a & fraction) != 0) && !((b & exponent) == + exponent && (b & fraction) != 0); + var sign: u64 = ir_float_sign(format); + var magnitude: u64 = sign - 1; + var equal: bool = false; + var less: bool = false; + var greater: bool = false; + if ((a & magnitude) == 0 && (b & magnitude) == 0) { + equal = true; + } else if (((a ^ b) & sign) != 0) { + less = (a & sign) != 0; + greater = !less; + } else if ((a & sign) != 0) { + equal = a == b; + less = b < a; + greater = b > a; + } else { + equal = a == b; + less = a < b; + greater = a > b; + } + var answer: bool = false; + if (predicate == 0) { + answer = ordered && equal; + } else if (predicate == 1) { + answer = ordered && !equal; + } else if (predicate == 2) { + answer = ordered && less; + } else if (predicate == 3) { + answer = ordered && !greater; + } else if (predicate == 4) { + answer = ordered && greater; + } else if (predicate == 5) { + answer = ordered && !less; + } else if (predicate == 6) { + answer = ordered; + } else if (predicate == 7) { + answer = !ordered; + } else if (predicate == 8) { + answer = !ordered || equal; + } else if (predicate == 9) { + answer = !ordered || !equal; + } else if (predicate == 10) { + answer = !ordered || less; + } else if (predicate == 11) { + answer = !ordered || !greater; + } else if (predicate == 12) { + answer = !ordered || greater; + } else { + answer = !ordered || !less; + } + output[0] = 0; + if (answer) { + output[0] = 1; + } + return true; +} diff --git a/ir/fold_integer.wave b/ir/fold_integer.wave new file mode 100644 index 0000000..dac6288 --- /dev/null +++ b/ir/fold_integer.wave @@ -0,0 +1,387 @@ +// SPDX-License-Identifier: MPL-2.0 +// Sparse, function-scoped constant propagation. Each value becomes known once; +// only its indexed users are revisited. No memory, call or trapping fold exists. +struct IrFoldNode { + op: u64; + sub: u64; + scope: u64; + id: u64; + kind: u64; + literal: u64; + low: u64; + high: u64; + first: u64; + count: u64; +} + +struct IrFoldValue { + known: u64; + kind: u64; + low: u64; + high: u64; + replace: u64; +} + +struct IrFoldSlot { + key: u64; + index: u64; + present: u64; +} + +struct IrFoldUser { + index: u64; + next: u64; +} + +struct IrFoldPending { + head: u64; + queued: u64; +} + +struct IrFoldInput { + nodes: ptr; + count: u64; + references: ptr; + reference_count: u64; + values: ptr; + slots: ptr; + capacity: u64; + users: ptr; + pending: ptr; + queue: ptr; + max_work: u64; +} + +struct IrFoldResult { + status: u64; + changed: u64; + folded: u64; + work: u64; +} + +fun ir_fold_charge(p: ptr, result: ptr) -> bool { + if (result.work >= p.max_work) { + result.status = 1; + return false; + } + result.work += 1; + return true; +} + +fun ir_fold_error(result: ptr, status: u64) -> i32 { + result.status = status; + result.changed = 0; + result.folded = 0; + return status as i32; +} + +fun ir_fold_mix(value: u64) -> u64 { + var mixed: u64 = value; + mixed = (mixed ^ (mixed >> 30)) * 13787848793156543929; + mixed = (mixed ^ (mixed >> 27)) * 10723151780598845931; + return mixed ^ (mixed >> 31); +} + +fun ir_fold_slot(p: ptr, key: u64, result: ptr) -> u64 { + var at: u64 = ir_fold_mix(key) & (p.capacity - 1); + while (true) { + if (!ir_fold_charge(p, result)) { + return p.capacity; + } + if (p.slots[at].present == 0 || p.slots[at].key == key) { + return at; + } + at = (at + 1) & (p.capacity - 1); + } + return p.capacity; +} + +fun ir_fold_reference(p: ptr, node: ptr, offset: u64, + result: ptr) -> u64 { + var id: u64 = p.references[node.first + offset]; + if (id > 4294967295) { + result.status = 2; + return p.count; + } + var slot: u64 = ir_fold_slot(p, (node.scope << 32) | id, result); + if (slot >= p.capacity || p.slots[slot].present == 0) { + if (result.status == 0) { + result.status = 2; + } + return p.count; + } + return p.slots[slot].index; +} + +fun ir_fold_literal(node: ptr, value: ptr) -> bool { + if (ir_integer_width(node.kind) == 0) { + return node.literal == 0; + } + var expected: u64 = 2; + if (node.kind == 1) { + expected = 3; + } else if (ir_integer_signed(node.kind)) { + expected = 1; + } + if (node.literal != expected) { + return false; + } + var number: IrIntegerResult; + if (whale_ir_integer(5, 0, node.kind, node.kind, node.low, node.high, 0, 0, &number) != 0 + || number.low != node.low || number.high != node.high) { + return false; + } + value.known = 1; + value.kind = node.kind; + value.low = node.low; + value.high = node.high; + return true; +} + +fun ir_fold_compute(p: ptr, index: u64, result: ptr) -> bool { + var node: IrFoldNode = p.nodes[index]; + if (node.op == 31 || node.op == 63 || node.op == 3 || node.op == 4 + || ir_integer_width(node.kind) == 0) { + return true; + } + var a: IrFoldValue; + var b: IrFoldValue; + a.known = 0; + b.known = 0; + var position: u64 = ir_fold_reference(p, &node, 0, result); + if (position >= p.count) { + return false; + } + a = p.values[position]; + if (node.op == 13) { + if (a.known == 0) { + return true; + } + if (a.kind != 1 || a.high != 0 || a.low > 1) { + result.status = 2; + return false; + } + var selected: u64 = 2; + if (a.low == 1) { + selected = 1; + } + position = ir_fold_reference(p, &node, selected, result); + if (position >= p.count) { + return false; + } + a = p.values[position]; + } + if (a.known == 0) { + return true; + } + if (a.kind != node.kind) { + result.status = 2; + return false; + } + if (node.op == 15) { + var incoming: u64 = 1; + while (incoming < node.count) { + position = ir_fold_reference(p, &node, incoming, result); + if (position >= p.count) { + return false; + } + b = p.values[position]; + if (b.known == 0) { + return true; + } + if (b.kind != node.kind) { + result.status = 2; + return false; + } + if (a.low != b.low || a.high != b.high) { + return true; + } + incoming += 1; + } + } + var number: IrIntegerResult; + var status: i32 = 0; + number.low = a.low; + number.high = a.high; + var output_kind: u64 = node.kind; + if (node.op == 7 || node.op == 10 || node.op == 11) { + position = ir_fold_reference(p, &node, 1, result); + if (position >= p.count) { + return false; + } + b = p.values[position]; + if (b.known == 0) { + return true; + } + if (b.kind != node.kind) { + result.status = 2; + return false; + } + if (node.op == 7) { + status = whale_ir_integer(0, node.sub, node.kind, node.kind, + a.low, a.high, b.low, b.high, &number); + } else { + output_kind = 1; + status = whale_ir_integer(3, node.sub, node.kind, 1, + a.low, a.high, b.low, b.high, &number); + } + } else if (node.op == 8 || node.op == 9) { + status = whale_ir_integer(6, node.op - 8, node.kind, node.kind, + a.low, a.high, 0, 0, &number); + } + if (status == 1 || status == 2) { + // Preserve dynamic division/remainder traps at their original ordinal. + return true; + } + if (status != 0) { + result.status = 2; + return false; + } + p.values[index].known = 1; + p.values[index].kind = output_kind; + p.values[index].low = number.low; + p.values[index].high = number.high; + p.values[index].replace = 1; + result.changed = 1; + result.folded += 1; + return true; +} + +export(c) fun whale_ir_fold_integer(p: ptr, result: ptr) -> i32 { + if (result == null) { + return 2; + } + result.status = 0; + result.changed = 0; + result.folded = 0; + result.work = 0; + if (p == null || p.capacity < 2 || (p.capacity & (p.capacity - 1)) != 0 + || p.count > p.capacity / 2 + || !ir_span_valid(p.nodes as ptr, p.count, 80) + || !ir_span_valid(p.references as ptr, p.reference_count, 8) + || !ir_span_valid(p.values as ptr, p.count, 40) + || !ir_span_valid(p.slots as ptr, p.capacity, 24) + || !ir_span_valid(p.users as ptr, p.reference_count, 16) + || !ir_span_valid(p.pending as ptr, p.count, 16) + || !ir_span_valid(p.queue as ptr, p.count, 8)) { + return ir_fold_error(result, 2); + } + var at: u64 = 0; + while (at < p.capacity) { + if (!ir_fold_charge(p, result)) { + return ir_fold_error(result, result.status); + } + p.slots[at].present = 0; + at += 1; + } + at = 0; + var expected_first: u64 = 0; + while (at < p.count) { + if (!ir_fold_charge(p, result)) { + return ir_fold_error(result, result.status); + } + var node: IrFoldNode = p.nodes[at]; + if (node.scope > 4294967295 || node.id > 4294967295 || node.kind > 13 + || node.first != expected_first || node.first > p.reference_count + || node.count > p.reference_count - node.first) { + return ir_fold_error(result, 2); + } + expected_first += node.count; + var count: u64 = 0; + if (node.op == 6 || node.op == 8 || node.op == 9) { + count = 1; + } else if (node.op == 7 || node.op == 10 || node.op == 11) { + count = 2; + } else if (node.op == 13) { + count = 3; + } else if (node.op == 15) { + count = node.count; + if (count == 0) { + return ir_fold_error(result, 2); + } + } else if (node.op != 3 && node.op != 4 && node.op != 31 && node.op != 63) { + return ir_fold_error(result, 2); + } + if (node.count != count || (node.op == 7 && (node.sub > 17 + || (node.sub >= 7 && node.sub <= 11))) + || ((node.op == 10 || node.op == 11) && node.sub > 9)) { + return ir_fold_error(result, 2); + } + var slot: u64 = ir_fold_slot(p, (node.scope << 32) | node.id, result); + if (slot >= p.capacity) { + return ir_fold_error(result, result.status); + } + if (p.slots[slot].present != 0) { + return ir_fold_error(result, 2); + } + p.slots[slot].present = 1; + p.slots[slot].key = (node.scope << 32) | node.id; + p.slots[slot].index = at; + p.values[at].known = 0; + p.values[at].replace = 0; + p.values[at].kind = 0; + p.values[at].low = 0; + p.values[at].high = 0; + p.pending[at].head = p.reference_count; + p.pending[at].queued = 1; + p.queue[at] = at; + if ((node.op == 3 || node.op == 4) && !ir_fold_literal(&node, &p.values[at])) { + return ir_fold_error(result, 2); + } + at += 1; + } + if (expected_first != p.reference_count) { + return ir_fold_error(result, 2); + } + at = 0; + while (at < p.count) { + var node: IrFoldNode = p.nodes[at]; + var offset: u64 = 0; + while (offset < node.count) { + var definition: u64 = ir_fold_reference(p, &node, offset, result); + if (definition >= p.count) { + return ir_fold_error(result, result.status); + } + var edge: u64 = node.first + offset; + p.users[edge].index = at; + p.users[edge].next = p.pending[definition].head; + p.pending[definition].head = edge; + offset += 1; + } + at += 1; + } + var head: u64 = 0; + var tail: u64 = 0; + var queued: u64 = p.count; + while (queued > 0) { + if (!ir_fold_charge(p, result)) { + return ir_fold_error(result, result.status); + } + var index: u64 = p.queue[head]; + head = (head + 1) % p.count; + queued -= 1; + p.pending[index].queued = 0; + if (p.values[index].known == 0) { + if (!ir_fold_compute(p, index, result)) { + return ir_fold_error(result, result.status); + } + if (p.values[index].known != 0) { + var edge: u64 = p.pending[index].head; + while (edge < p.reference_count) { + if (!ir_fold_charge(p, result)) { + return ir_fold_error(result, result.status); + } + var user: u64 = p.users[edge].index; + if (p.pending[user].queued == 0) { + p.pending[user].queued = 1; + p.queue[tail] = user; + tail = (tail + 1) % p.count; + queued += 1; + } + edge = p.users[edge].next; + } + } + } + } + return 0; +} diff --git a/ir/integer.wave b/ir/integer.wave new file mode 100644 index 0000000..f13daf4 --- /dev/null +++ b/ir/integer.wave @@ -0,0 +1,399 @@ +// SPDX-License-Identifier: MPL-2.0 +// Defined fixed-width scalar arithmetic and conversion over shared two-word math. +struct IrIntegerResult { + status: u64; + low: u64; + high: u64; + flag: u64; +} + +fun ir_integer_width(kind: u64) -> u64 { + if (kind == 1 || kind == 2 || kind == 3) { + return 1; + } + if (kind == 4 || kind == 9) { + return 8; + } + if (kind == 5 || kind == 10) { + return 16; + } + if (kind == 6 || kind == 11) { + return 32; + } + if (kind == 7 || kind == 12) { + return 64; + } + if (kind == 8 || kind == 13) { + return 128; + } + return 0; +} + +fun ir_integer_signed(kind: u64) -> bool { + return kind == 2 || (kind >= 4 && kind <= 8); +} + +fun ir_integer_negative(value: ptr, width: u64) -> bool { + return ir_wide_bit(value, width - 1) != 0; +} + +fun ir_integer_extend(value: ptr, width: u64, output: ptr) { + var raw: IrWide; + ir_wide_trim(value, width, &raw); + if (ir_integer_negative(&raw, width)) { + var mask: IrWide; + ir_wide_mask(width, &mask); + raw.low = raw.low | ~mask.low; + raw.high = raw.high | ~mask.high; + } + output[0] = raw; +} + +fun ir_integer_finish(value: ptr, kind: u64, result: ptr) { + var packed: IrWide; + if (ir_integer_signed(kind)) { + ir_integer_extend(value, ir_integer_width(kind), &packed); + } else { + ir_wide_trim(value, ir_integer_width(kind), &packed); + } + result.low = packed.low; + result.high = packed.high; +} + +fun ir_integer_error(status: u64, result: ptr) -> i32 { + result.status = status; + result.low = 0; + result.high = 0; + result.flag = 0; + return status as i32; +} + +fun ir_integer_magnitude(value: ptr, width: u64, negative: bool, output: ptr) { + if (negative) { + ir_wide_neg(value, output); + ir_wide_trim(output, width, output); + } else { + ir_wide_trim(value, width, output); + } +} + +export(c) fun whale_ir_integer_bits(low: u64, high: u64, width: u64, + is_signed: u64, result: ptr) -> i32 { + if (result == null) { + return 4; + } + result.status = 0; + result.low = 0; + result.high = 0; + result.flag = 0; + if (width == 0 || width > 128 || is_signed > 1) { + return ir_integer_error(4, result); + } + var value: IrWide; + var packed: IrWide; + ir_wide_from(low, high, &value); + if (is_signed == 1) { + ir_integer_extend(&value, width, &packed); + } else { + ir_wide_trim(&value, width, &packed); + } + result.low = packed.low; + result.high = packed.high; + return 0; +} +// Modes: binary, checked, cast, comparison, checked cast, normalize, unary. +// Binary codes match the complete IR BinOp inventory, including float holes. + +export(c) fun whale_ir_integer(mode: u64, op: u64, source_kind: u64, + destination_kind: u64, a_low: u64, a_high: u64, b_low: u64, b_high: u64, + result: ptr) -> i32 { + if (result == null) { + return 4; + } + result.status = 0; + result.low = 0; + result.high = 0; + result.flag = 0; + var width: u64 = ir_integer_width(source_kind); + var destination_width: u64 = ir_integer_width(destination_kind); + if (width == 0 || destination_width == 0 || mode > 6) { + return ir_integer_error(4, result); + } + var source: IrWide; + var a: IrWide; + var b: IrWide; + var value: IrWide; + ir_wide_from(a_low, a_high, &source); + ir_wide_trim(&source, width, &a); + ir_wide_from(b_low, b_high, &source); + ir_wide_trim(&source, width, &b); + ir_wide_zero(&value); + if (mode == 0) { + if (source_kind == 1 || destination_kind != source_kind + || !((op <= 6) || (op >= 12 && op <= 17))) { + return ir_integer_error(4, result); + } + if (op == 0) { + ir_wide_add(&a, &b, &value); + } else if (op == 1) { + ir_wide_sub(&a, &b, &value); + } else if (op == 2) { + ir_wide_mul(&a, &b, &value); + } else if (op >= 3 && op <= 6) { + if (b.low == 0 && b.high == 0) { + if (op == 3 || op == 4) { + return ir_integer_error(1, result); + } + return ir_integer_error(2, result); + } + var quotient: IrWide; + var remainder: IrWide; + if (op == 3 || op == 5) { + ir_wide_divmod(&a, &b, "ient, &remainder); + } else { + var an: bool = ir_integer_negative(&a, width); + var bn: bool = ir_integer_negative(&b, width); + var am: IrWide; + var bm: IrWide; + ir_integer_magnitude(&a, width, an, &am); + ir_integer_magnitude(&b, width, bn, &bm); + ir_wide_divmod(&am, &bm, "ient, &remainder); + if ((an && !bn) || (!an && bn)) { + ir_wide_neg("ient, "ient); + } + if (an) { + ir_wide_neg(&remainder, &remainder); + } + } + if (op == 3 || op == 4) { + value = quotient; + } else { + value = remainder; + } + } else if (op == 12) { + value.low = a.low & b.low; + value.high = a.high & b.high; + } else if (op == 13) { + value.low = a.low | b.low; + value.high = a.high | b.high; + } else if (op == 14) { + value.low = a.low ^ b.low; + value.high = a.high ^ b.high; + } else { + // Every supported width is a power of two: the full N-bit pattern + // modulo width is exactly its low log2(width) bits, even for u128. + var count: u64 = b.low & (width - 1); + if (op == 15) { + ir_wide_shl(&a, count, &value); + } else if (op == 16) { + ir_wide_shr(&a, count, &value); + } else { + var extended: IrWide; + ir_integer_extend(&a, width, &extended); + ir_wide_ashr(&extended, count, &value); + } + } + } else if (mode == 1) { + if (source_kind == 1 || destination_kind != source_kind || op > 5) { + return ir_integer_error(4, result); + } + var overflow: bool = false; + if (op == 0) { + var carry: u64 = ir_wide_add(&a, &b, &value); + var mask: IrWide; + ir_wide_mask(width, &mask); + overflow = carry != 0 || ir_wide_cmp(&value, &mask) > 0; + } else if (op == 1) { + overflow = ir_wide_cmp(&a, &b) < 0; + ir_wide_sub(&a, &b, &value); + } else if (op == 2) { + overflow = ir_wide_mul(&a, &b, &value); + var mask: IrWide; + ir_wide_mask(width, &mask); + overflow = overflow || ir_wide_cmp(&value, &mask) > 0; + } else if (op == 3 || op == 4) { + var an: bool = ir_integer_negative(&a, width); + var bn: bool = ir_integer_negative(&b, width); + if (op == 3) { + ir_wide_add(&a, &b, &value); + } else { + ir_wide_sub(&a, &b, &value); + } + var rn: bool = ir_integer_negative(&value, width); + var same: bool = (an && bn) || (!an && !bn); + var changed: bool = (an && !rn) || (!an && rn); + overflow = (op == 3 && same && changed) || (op == 4 && !same && changed); + } else { + var an: bool = ir_integer_negative(&a, width); + var bn: bool = ir_integer_negative(&b, width); + var am: IrWide; + var bm: IrWide; + var product: IrWide; + var maximum: IrWide; + var one: IrWide; + ir_integer_magnitude(&a, width, an, &am); + ir_integer_magnitude(&b, width, bn, &bm); + overflow = ir_wide_mul(&am, &bm, &product); + ir_wide_from(1, 0, &one); + ir_wide_shl(&one, width - 1, &maximum); + if ((an && bn) || (!an && !bn)) { + ir_wide_sub(&maximum, &one, &maximum); + } + overflow = overflow || ir_wide_cmp(&product, &maximum) > 0; + ir_wide_mul(&a, &b, &value); + } + result.flag = overflow as u64; + } else if (mode == 2) { + if (destination_kind == 1 || op > 3) { + return ir_integer_error(4, result); + } + var valid: bool = false; + if (op == 0) { + valid = (source_kind == 1 && destination_kind != 2) || (source_kind != 1 + && width < destination_width); + } else if (op == 1) { + valid = source_kind != 1 && width < destination_width; + } else if (op == 2) { + valid = source_kind != 1 && width > destination_width; + } else { + valid = source_kind != 1 && width == destination_width; + } + if (!valid) { + return ir_integer_error(4, result); + } + if (op == 1) { + ir_integer_extend(&a, width, &value); + } else { + value = a; + } + } else if (mode == 3) { + if (op > 9 || destination_kind != 1 || (source_kind == 1 && op > 1)) { + return ir_integer_error(4, result); + } + var comparison: i32 = ir_wide_cmp(&a, &b); + if (op >= 6) { + var an: bool = ir_integer_negative(&a, width); + var bn: bool = ir_integer_negative(&b, width); + if (an && !bn) { + comparison = -1; + } else if (!an && bn) { + comparison = 1; + } + } + var answer: bool = false; + if (op == 0) { + answer = comparison == 0; + } else if (op == 1) { + answer = comparison != 0; + } else if (op == 2 || op == 6) { + answer = comparison < 0; + } else if (op == 3 || op == 7) { + answer = comparison <= 0; + } else if (op == 4 || op == 8) { + answer = comparison > 0; + } else { + answer = comparison >= 0; + } + value.low = answer as u64; + value.high = 0; + } else if (mode == 4) { + if (op != 0 || source_kind == 1 || destination_kind == 1) { + return ir_integer_error(4, result); + } + var negative: bool = ir_integer_signed(source_kind) && ir_integer_negative(&a, width); + var magnitude: IrWide; + var maximum: IrWide; + var one: IrWide; + ir_integer_magnitude(&a, width, negative, &magnitude); + if (ir_integer_signed(destination_kind)) { + ir_wide_from(1, 0, &one); + ir_wide_shl(&one, destination_width - 1, &maximum); + if (!negative) { + ir_wide_sub(&maximum, &one, &maximum); + } + } else { + ir_wide_mask(destination_width, &maximum); + } + if ((negative && !ir_integer_signed(destination_kind)) || ir_wide_cmp(&magnitude, + &maximum) > 0) { + return ir_integer_error(3, result); + } + if (negative) { + ir_wide_neg(&magnitude, &value); + } else { + value = magnitude; + } + } else if (mode == 5) { + if (op != 0 || source_kind != destination_kind) { + return ir_integer_error(4, result); + } + value = a; + } else { + if (op > 1 || source_kind == 1 || destination_kind != source_kind) { + return ir_integer_error(4, result); + } + if (op == 0) { + ir_wide_neg(&a, &value); + } else { + value.low = ~a.low; + value.high = ~a.high; + } + } + ir_integer_finish(&value, destination_kind, result); + return 0; +} +// Direct primitive boundary for independent mathematical conformance. + +export(c) fun whale_ir_wide(op: u64, low: u64, high: u64, other_low: u64, + other_high: u64, count: u64, result: ptr) -> i32 { + if (result == null) { + return 4; + } + result.status = 0; + result.low = 0; + result.high = 0; + result.flag = 0; + var a: IrWide; + var b: IrWide; + var value: IrWide; + ir_wide_from(low, high, &a); + ir_wide_from(other_low, other_high, &b); + ir_wide_zero(&value); + if (op == 0) { + result.flag = ir_wide_add(&a, &b, &value); + } else if (op == 1) { + result.flag = ir_wide_sub(&a, &b, &value); + } else if (op == 2) { + result.flag = ir_wide_mul(&a, &b, &value) as u64; + } else if (op == 3 || op == 4) { + var quotient: IrWide; + var remainder: IrWide; + if (!ir_wide_divmod(&a, &b, "ient, &remainder)) { + return ir_integer_error(1, result); + } + if (op == 3) { + value = quotient; + } else { + value = remainder; + } + } else if (op == 5) { + ir_wide_shl(&a, count, &value); + } else if (op == 6) { + ir_wide_shr(&a, count, &value); + } else if (op == 7) { + value.low = (ir_wide_cmp(&a, &b) + 1) as u64; + } else if (op == 8) { + value.low = ir_wide_clz(&a); + } else if (op == 9) { + ir_wide_jam(&a, count, &value); + } else if (op == 10) { + ir_wide_round(&a, count, &value); + } else if (op == 11) { + ir_wide_neg(&a, &value); + } else { + return ir_integer_error(4, result); + } + result.low = value.low; + result.high = value.high; + return 0; +} diff --git a/ir/memory.wave b/ir/memory.wave new file mode 100644 index 0000000..18a9c5c --- /dev/null +++ b/ir/memory.wave @@ -0,0 +1,895 @@ +// SPDX-License-Identifier: MPL-2.0 +// Tracked identities are integers; native pointers address only caller buffers. +struct IrMemPointer { + address: u64; + present: u64; + arena: u64; + allocation: u64; + generation: u64; + lower: u64; + upper: u64; + offset: u64; + read: u64; + write: u64; +} + +struct IrMemAuthority { + kind: u64; + pointer: IrMemPointer; + signature: u64; + target_kind: u64; + target: u64; +} + +struct IrMemFragment { + occupied: u64; + offset: u64; + ordinal: u64; + authority: IrMemAuthority; +} + +struct IrMemAllocation { + kind: u64; + address: u64; + generation: u64; + alive: u64; + read: u64; + write: u64; + length: u64; + data: ptr; + initialized: ptr; + fragments: ptr; + fragment_capacity: u64; + fragment_count: u64; +} + +struct IrMemState { + arena: u64; + allocations: u64; + bytes: u64; + fragments: u64; + work: u64; + next_address: u64; +} + +struct IrMemLimits { + bytes: u64; + allocations: u64; + fragments: u64; + work: u64; +} + +struct IrMemPart { + offset: u64; + kind: u64; + low: u64; + high: u64; + authority: IrMemAuthority; +} + +struct IrMemGep { + kind: u64; + amount: u64; + low: u64; + high: u64; + signed: u64; +} + +struct IrMemRequest { + op: u64; + mode: u64; + size: u64; + natural: u64; + align: u64; + flag: u64; + owner: u64; + pointer: IrMemPointer; + source: IrMemPointer; + parts: ptr; + part_count: u64; + geps: ptr; + gep_count: u64; +} + +struct IrMemResult { + status: u64; + detail: u64; + extra: u64; + work: u64; + allocation: u64; + start: u64; + end: u64; + fragments: u64; + fragment_capacity: u64; + low: u64; + high: u64; + pointer: IrMemPointer; +} + +fun ir_mem_clear_pointer(p: ptr) { + p.address = 0; + p.present = 0; + p.arena = 0; + p.allocation = 0; + p.generation = 0; + p.lower = 0; + p.upper = 0; + p.offset = 0; + p.read = 0; + p.write = 0; +} + +fun ir_mem_zero_authority(a: ptr) { + a.kind = 0; + ir_mem_clear_pointer(&a.pointer); + a.signature = 0; + a.target_kind = 0; + a.target = 0; +} + +fun ir_mem_fail(r: ptr, status: u64, detail: u64, extra: u64) -> i32 { + r.status = status; + r.detail = detail; + r.extra = extra; + return status as i32; +} + +fun ir_mem_charge(r: ptr, n: u64, state: ptr, + limits: ptr) -> bool { + if (state.work > limits.work || r.work > limits.work - state.work + || n > limits.work - state.work - r.work) { + r.status = 104; + r.detail = limits.work; + return false; + } + r.work += n; + return true; +} + +fun ir_mem_identity(state: ptr, allocations: ptr, + p: ptr, r: ptr) -> bool { + if (p.address == 0) { + ir_mem_fail(r, 1, 0, 0); + return false; + } + if (p.present == 0) { + ir_mem_fail(r, 2, 0, 0); + return false; + } + if (p.present != 1 || p.read > 1 || p.write > 1) { + ir_mem_fail(r, 200, 0, 0); + return false; + } + if (p.arena != state.arena || p.allocation >= state.allocations) { + ir_mem_fail(r, 3, 0, 0); + return false; + } + var a: ptr = &allocations[p.allocation]; + if (a.kind > 1 || a.alive > 1 || a.read > 1 || a.write > 1 + || (a.fragment_capacity != 0 && (a.fragment_capacity < 2 + || !ir_power_two(a.fragment_capacity))) + || a.fragment_count > a.fragment_capacity / 2 || a.fragment_count > state.fragments) { + ir_mem_fail(r, 200, 0, 0); + return false; + } + if (a.alive == 0 || a.generation != p.generation) { + ir_mem_fail(r, 3, 0, 0); + return false; + } + if (p.lower > p.offset || p.offset > p.upper || p.upper > a.length + || p.offset > 18446744073709551615 - a.address || a.address + p.offset != p.address) { + ir_mem_fail(r, 4, 0, 0); + return false; + } + return true; +} + +fun ir_mem_access(state: ptr, allocations: ptr, p: ptr, + size: u64, align: u64, write: bool, r: ptr) -> bool { + if (!ir_mem_identity(state, allocations, p, r)) { + return false; + } + if (size > 18446744073709551615 - p.offset) { + ir_mem_fail(r, 5, 0, 0); + return false; + } + if (p.offset + size > p.upper) { + ir_mem_fail(r, 4, 0, 0); + return false; + } + var a: ptr = &allocations[p.allocation]; + if ((write && (p.write == 0 || a.write == 0)) || (!write && (p.read == 0 || a.read == 0))) { + ir_mem_fail(r, 6, 0, 0); + return false; + } + if (align == 0 || !ir_power_two(align)) { + ir_mem_fail(r, 200, 0, 0); + return false; + } + if (p.address % align != 0) { + ir_mem_fail(r, 7, p.address, align); + return false; + } + if (!ir_span_valid(a.data, a.length, 1) || !ir_span_valid(a.initialized, a.length, + 1) || !ir_span_valid(a.fragments as ptr, a.fragment_capacity, 136)) { + ir_mem_fail(r, 200, 0, 0); + return false; + } + r.allocation = p.allocation; + r.start = p.offset; + r.end = p.offset + size; + return true; +} + +fun ir_mem_part_size(kind: u64) -> u64 { + if (kind == 1 || kind == 2 || kind == 3 || kind == 4 || kind == 9) { + return 1; + } + if (kind == 5 || kind == 10 || kind == 14) { + return 2; + } + if (kind == 6 || kind == 11 || kind == 15) { + return 4; + } + if (kind == 7 || kind == 12 || kind == 16 || kind == 17 || kind == 18) { + return 8; + } + if (kind == 8 || kind == 13) { + return 16; + } + return 0; +} + +fun ir_mem_authority_bits(a: ptr) -> u64 { + if (a.kind == 1) { + return a.pointer.address; + } + if (a.kind == 2) { + if (a.target_kind == 0) { + return 0; + } + if (a.target_kind == 1) { + return a.target + 1; + } + return a.target; + } + return 0; +} + +fun ir_mem_authority_same(a: ptr, b: ptr) -> bool { + return a.kind == b.kind && a.signature == b.signature && a.target_kind == b.target_kind + && a.target == b.target && a.pointer.address == b.pointer.address + && a.pointer.present == b.pointer.present && a.pointer.arena == b.pointer.arena + && a.pointer.allocation == b.pointer.allocation + && a.pointer.generation == b.pointer.generation + && a.pointer.lower == b.pointer.lower && a.pointer.upper == b.pointer.upper + && a.pointer.offset == b.pointer.offset && a.pointer.read == b.pointer.read + && a.pointer.write == b.pointer.write; +} + +fun ir_mem_fragment_find(table: ptr, capacity: u64, offset: u64, + r: ptr, state: ptr, limits: ptr) -> u64 { + if (capacity == 0) { + return 0; + } + var at: u64 = ir_source_mix(offset) & (capacity - 1); + var n: u64 = 0; + while (n < capacity) { + if (!ir_mem_charge(r, 1, state, limits)) { + return capacity; + } + if (table[at].occupied == 0 || table[at].offset == offset) { + return at; + } + at = (at + 1) & (capacity - 1); + n += 1; + } + ir_mem_fail(r, 200, 0, 0); + return capacity; +} + +fun ir_mem_fragment_put(table: ptr, capacity: u64, offset: u64, ordinal: u64, + authority: ptr, r: ptr, state: ptr, + limits: ptr) -> bool { + var at: u64 = ir_mem_fragment_find(table, capacity, offset, r, state, limits); + if (at == capacity) { + return false; + } + table[at].occupied = 1; + table[at].offset = offset; + table[at].ordinal = ordinal; + table[at].authority = authority[0]; + return true; +} + +fun ir_mem_metadata_count(a: ptr, start: u64, end: u64, r: ptr, + state: ptr, limits: ptr) -> u64 { + var removed: u64 = 0; + var i: u64 = 0; + while (i < a.fragment_capacity) { + if (!ir_mem_charge(r, 1, state, limits)) { + return 18446744073709551615; + } + if (a.fragments[i].occupied == 1 && a.fragments[i].offset >= start + && a.fragments[i].offset < end) { + removed += 1; + } + i += 1; + } + return removed; +} + +fun ir_mem_capacity(count: u64, r: ptr) -> u64 { + if (count == 0) { + return 0; + } + var capacity: u64 = 2; + if (count > 4611686018427387904) { + ir_mem_fail(r, 105, count, 0); + return 0; + } + while (capacity / 2 < count) { + capacity *= 2; + } + return capacity; +} + +fun ir_mem_metadata_build(a: ptr, start: u64, end: u64, + source: ptr, source_start: u64, source_end: u64, q: ptr, + output: ptr, capacity: u64, r: ptr, state: ptr, + limits: ptr) -> bool { + var i: u64 = 0; + while (i < capacity) { + if (!ir_mem_charge(r, 1, state, limits)) { + return false; + } + output[i].occupied = 0; + i += 1; + } + i = 0; + while (i < a.fragment_capacity) { + if (!ir_mem_charge(r, 1, state, limits)) { + return false; + } + if (a.fragments[i].occupied == 1 && (a.fragments[i].offset < start + || a.fragments[i].offset >= end)) { + if (!ir_mem_fragment_put(output, capacity, a.fragments[i].offset, + a.fragments[i].ordinal, &a.fragments[i].authority, r, state, limits)) { + return false; + } + } + i += 1; + } + if (q.op == 6) { + i = 0; + while (i < source.fragment_capacity) { + if (!ir_mem_charge(r, 1, state, limits)) { + return false; + } + if (source.fragments[i].occupied == 1 && source.fragments[i].offset >= source_start + && source.fragments[i].offset < source_end) { + if (!ir_mem_fragment_put(output, capacity, + start + source.fragments[i].offset - source_start, source.fragments[i].ordinal, + &source.fragments[i].authority, r, state, limits)) { + return false; + } + } + i += 1; + } + } else if (q.op == 4) { + i = 0; + while (i < q.part_count) { + var part: ptr = &q.parts[i]; + if (part.kind == 17 || part.kind == 18) { + var k: u64 = 0; + while (k < 8) { + if (!ir_mem_fragment_put(output, capacity, start + part.offset + k, k, + &part.authority, r, state, limits)) { + return false; + } + k += 1; + } + } + i += 1; + } + } + return true; +} + +// Operations:0 allocate,1 seal-global,2 retire-stack,3 load,4 store,5 uninit, +// 6 memcpy,7 memset,8 gep,9 equal,10 difference,11 retire-frame. +export(c) fun whale_ir_memory(state: ptr, limits: ptr, + allocations: ptr, allocation_capacity: u64, q: ptr, + new_fragments: ptr, new_capacity: u64, output_parts: ptr, + output_part_capacity: u64, r: ptr) -> i32 { + if (r == null) { + return 200; + } + r.status = 0; + r.detail = 0; + r.extra = 0; + r.work = 0; + r.allocation = 18446744073709551615; + r.start = 0; + r.end = 0; + r.fragments = 0; + r.fragment_capacity = 0; + r.low = 0; + r.high = 0; + ir_mem_clear_pointer(&r.pointer); + if (state == null || limits == null || q == null || q.op > 11 || q.mode > 1 + || state.allocations > allocation_capacity || state.bytes > limits.bytes + || state.fragments > limits.fragments || state.work > limits.work + || !ir_span_valid(allocations as ptr, allocation_capacity, 96)) { + return ir_mem_fail(r, 200, 0, 0); + } + if (q.op == 0) { + if (q.flag > 1 || q.natural == 0 || q.align == 0 || !ir_power_two(q.natural) + || !ir_power_two(q.align)) { + return ir_mem_fail(r, 200, 0, 0); + } + if (state.allocations >= limits.allocations) { + return ir_mem_fail(r, 102, limits.allocations, 0); + } + if (q.size > limits.bytes - state.bytes) { + return ir_mem_fail(r, 101, limits.bytes, 0); + } + var alignment: u64 = q.align; + if (q.natural > alignment) { + alignment = q.natural; + } + if (alignment - 1 > 18446744073709551615 - state.next_address) { + return ir_mem_fail(r, 5, 0, 0); + } + var address: u64 = (state.next_address + alignment - 1) & (18446744073709551615 - alignment + 1); + var span: u64 = q.size; + if (span == 0) { + span = 1; + } + if (span >= 18446744073709551615 - address || q.size > 9223372036854775807) { + return ir_mem_fail(r, 5, 0, 0); + } + if (!ir_mem_charge(r, q.size * 2 + 1, state, limits)) { + return r.status as i32; + } + r.pointer.address = address; + r.pointer.present = 1; + r.pointer.arena = state.arena; + r.pointer.allocation = state.allocations; + r.pointer.generation = 0; + r.pointer.lower = 0; + r.pointer.upper = q.size; + r.pointer.offset = 0; + r.pointer.read = 1; + r.pointer.write = 1; + r.allocation = state.allocations; + if (q.mode == 0) { + return 0; + } + if (state.allocations >= allocation_capacity) { + return ir_mem_fail(r, 200, 0, 0); + } + var a: ptr = &allocations[state.allocations]; + if (!ir_span_valid(a.data, q.size, 1) || !ir_span_valid(a.initialized, q.size, 1)) { + return ir_mem_fail(r, 200, 0, 0); + } + var i: u64 = 0; + while (i < q.size) { + a.data[i] = 0; + a.initialized[i] = 0; + i += 1; + } + a.kind = q.flag; + a.address = address; + a.generation = 0; + a.alive = 1; + a.read = 1; + a.write = 1; + a.length = q.size; + a.fragment_capacity = 0; + a.fragment_count = 0; + a.fragments = null; + state.allocations += 1; + state.bytes += q.size; + state.next_address = address + span + 1; + state.work += r.work; + return 0; + } + if (q.op == 11) { + if (q.owner > state.allocations) { + return ir_mem_fail(r, 200, 0, 0); + } + if (!ir_mem_charge(r, state.allocations - q.owner, state, limits)) { + return r.status as i32; + } + if (q.mode == 1) { + var i: u64 = q.owner; + while (i < state.allocations) { + var a: ptr = &allocations[i]; + if (a.kind == 0 && a.alive != 0) { + a.alive = 0; + state.fragments -= a.fragment_count; + a.fragment_count = 0; + a.fragment_capacity = 0; + a.fragments = null; + a.length = 0; + } + i += 1; + } + state.work += r.work; + } + return 0; + } + if (q.op == 9 && q.pointer.address == 0 && q.source.address == 0) { + r.low = 1; + return 0; + } + if (q.op == 9 && (q.pointer.address == 0 || q.source.address == 0)) { + var p: ptr = &q.pointer; + if (q.pointer.address == 0) { + p = &q.source; + } + if (!ir_mem_identity(state, allocations, p, r)) { + return r.status as i32; + } + return 0; + } + if (q.op == 8 && q.gep_count == 0) { + r.pointer = q.pointer; + return 0; + } + if ((q.op == 6 || q.op == 7) && q.size == 0) { + return 0; + } + // memcpy validates its readable source before its writable destination. + if (q.op == 6 + && !ir_mem_access(state, allocations, &q.source, q.size, q.align, false, r)) { + return r.status as i32; + } + if (!ir_mem_identity(state, allocations, &q.pointer, r)) { + return r.status as i32; + } + var a: ptr = &allocations[q.pointer.allocation]; + if (q.op == 1) { + if (a.kind != 1) { + return ir_mem_fail(r, 13, 0, 0); + } + if (q.flag > 1) { + return ir_mem_fail(r, 200, 0, 0); + } + r.pointer = q.pointer; + r.pointer.write = 1 - q.flag; + if (q.mode == 1) { + a.write = 1 - q.flag; + } + return 0; + } + if (q.op == 2) { + if (q.pointer.allocation < q.owner || a.kind != 0 || q.pointer.offset != 0 + || q.pointer.lower != 0 || q.pointer.upper != a.length) { + return ir_mem_fail(r, 13, 0, 0); + } + if (!ir_mem_charge(r, 1 + a.fragment_count, state, limits)) { + return r.status as i32; + } + if (q.mode == 1) { + a.alive = 0; + state.fragments -= a.fragment_count; + a.fragment_count = 0; + a.fragment_capacity = 0; + a.fragments = null; + a.length = 0; + state.work += r.work; + } + return 0; + } + if (q.op == 9 || q.op == 10) { + if (!ir_mem_identity(state, allocations, &q.source, r)) { + return r.status as i32; + } + if (q.op == 9) { + if (q.pointer.allocation == q.source.allocation + && q.pointer.generation == q.source.generation && q.pointer.offset == q.source.offset) { + r.low = 1; + } + return 0; + } + if (q.pointer.allocation != q.source.allocation + || q.pointer.generation != q.source.generation) { + return ir_mem_fail(r, 12, 0, 0); + } + if (q.pointer.offset >= q.source.offset) { + r.low = q.pointer.offset - q.source.offset; + } else { + r.low = 18446744073709551615 - (q.source.offset - q.pointer.offset) + 1; + r.high = 18446744073709551615; + } + return 0; + } + if (q.op == 8) { + if (!ir_span_valid(q.geps as ptr, q.gep_count, 40)) { + return ir_mem_fail(r, 200, 0, 0); + } + var address: u64 = q.pointer.address; + var i: u64 = 0; + while (i < q.gep_count) { + var g: ptr = &q.geps[i]; + var delta: u64 = g.amount; + var negative: bool = false; + if (g.kind == 0) { + if (g.signed > 1 || (g.signed == 0 && g.high >= 9223372036854775808)) { + return ir_mem_fail(r, 5, 0, 0); + } + var low: u64 = g.low; + var high: u64 = g.high; + negative = g.signed == 1 && high >= 9223372036854775808; + if (negative) { + low = 18446744073709551615 - low + 1; + high = 18446744073709551615 - high; + if (low == 0) { + high += 1; + } + } + if (g.amount == 0) { + delta = 0; + } else { + if (high != 0 || low > 18446744073709551615 / g.amount) { + return ir_mem_fail(r, 5, 0, 0); + } + delta = low * g.amount; + } + } else if (g.kind != 1) { + return ir_mem_fail(r, 200, 0, 0); + } + if (negative) { + if (delta > address) { + return ir_mem_fail(r, 5, 0, 0); + } + address -= delta; + } else { + if (delta > 18446744073709551615 - address) { + return ir_mem_fail(r, 5, 0, 0); + } + address += delta; + } + i += 1; + } + if (address < a.address) { + return ir_mem_fail(r, 4, 0, 0); + } + var offset: u64 = address - a.address; + if (offset < q.pointer.lower || offset > q.pointer.upper) { + return ir_mem_fail(r, 4, 0, 0); + } + r.pointer = q.pointer; + r.pointer.address = address; + r.pointer.offset = offset; + return 0; + } + var source: ptr = a; + var source_start: u64 = 0; + var source_end: u64 = 0; + if (q.op == 6) { + source = &allocations[q.source.allocation]; + source_start = q.source.offset; + source_end = source_start + q.size; + } + if (!ir_mem_access(state, allocations, &q.pointer, q.size, q.align, q.op != 3, r)) { + return r.status as i32; + } + var start: u64 = r.start; + var end: u64 = r.end; + if (q.op == 6 && q.pointer.allocation == q.source.allocation && start < source_end + && source_start < end) { + return ir_mem_fail(r, 11, 0, 0); + } + if (q.op == 3 || q.op == 4) { + if (q.part_count == 0 || q.part_count > 2 || !ir_span_valid(q.parts as ptr, + q.part_count, 144) || (q.op == 3 && (output_part_capacity < q.part_count + || !ir_span_valid(output_parts as ptr, output_part_capacity, 144)))) { + return ir_mem_fail(r, 200, 0, 0); + } + var i: u64 = 0; + while (i < q.part_count) { + var n: u64 = ir_mem_part_size(q.parts[i].kind); + if (n == 0 || q.parts[i].offset > q.size || n > q.size - q.parts[i].offset) { + return ir_mem_fail(r, 200, 0, 0); + } + i += 1; + } + } + if (!ir_mem_charge(r, q.size, state, limits)) { + return r.status as i32; + } + if (q.op == 3) { + var i: u64 = 0; + while (i < q.part_count) { + var part: IrMemPart = q.parts[i]; + var n: u64 = ir_mem_part_size(part.kind); + var offset: u64 = start + part.offset; + var k: u64 = 0; + var low: u64 = 0; + var high: u64 = 0; + while (k < n) { + if (a.initialized[offset + k] == 0) { + return ir_mem_fail(r, 8, offset + k, 0); + } + if (k < 8) { + low = low | ((a.data[offset + k] as u64) << (k * 8)); + } else { + high = high | ((a.data[offset + k] as u64) << ((k - 8) * 8)); + } + k += 1; + } + part.low = low; + part.high = high; + ir_mem_zero_authority(&part.authority); + if (part.kind == 1 && low > 1) { + return ir_mem_fail(r, 9, low, 0); + } + if (part.kind == 17 || part.kind == 18) { + var at: u64 = ir_mem_fragment_find(a.fragments, a.fragment_capacity, offset, r, + state, limits); + if (r.status != 0) { + return r.status as i32; + } + var complete: bool = at < a.fragment_capacity && a.fragments[at].occupied == 1 + && a.fragments[at].ordinal == 0 + && ir_mem_authority_bits(&a.fragments[at].authority) == low; + var authority: IrMemAuthority; + ir_mem_zero_authority(&authority); + if (complete) { + authority = a.fragments[at].authority; + } + k = 1; + while (complete && k < 8) { + at = ir_mem_fragment_find(a.fragments, a.fragment_capacity, offset + k, r, + state, limits); + if (r.status != 0) { + return r.status as i32; + } + complete = at < a.fragment_capacity && a.fragments[at].occupied == 1 + && a.fragments[at].ordinal == k && ir_mem_authority_same(&authority, + &a.fragments[at].authority); + k += 1; + } + if (low != 0 && complete && ((part.kind == 17 && authority.kind == 1) + || (part.kind == 18 && authority.kind == 2 + && authority.signature == q.parts[i].authority.signature))) { + part.authority = authority; + } + } + if (part.kind == 2 || (part.kind >= 4 && part.kind <= 8)) { + var bits: u64 = n * 8; + if (part.kind == 2) { + bits = 1; + } + if (bits < 64) { + var one: u64 = 1; + var all: u64 = 18446744073709551615; + low = low & ((one << bits) - 1); + if ((low >> (bits - 1)) != 0) { + low = low | (all << bits); + high = all; + } + } else if (bits == 64 && low >= 9223372036854775808) { + high = 18446744073709551615; + } + part.low = low; + part.high = high; + } else if (part.kind == 3) { + part.low = low & 1; + } + output_parts[i] = part; + i += 1; + } + if (q.mode == 1) { + state.work += r.work; + } + return 0; + } + var added: u64 = 0; + if (q.op == 4) { + var i: u64 = 0; + while (i < q.part_count) { + if (q.parts[i].kind == 17 || q.parts[i].kind == 18) { + added += 8; + } + i += 1; + } + } + if (q.op == 6) { + added = ir_mem_metadata_count(source, source_start, source_end, r, state, limits); + if (r.status != 0) { + return r.status as i32; + } + } + var removed: u64 = ir_mem_metadata_count(a, start, end, r, state, limits); + if (r.status != 0) { + return r.status as i32; + } + if (removed > a.fragment_count || removed > state.fragments + || added > 18446744073709551615 - state.fragments + removed) { + return ir_mem_fail(r, 200, 0, 0); + } + var total: u64 = state.fragments - removed + added; + if (total > limits.fragments) { + return ir_mem_fail(r, 103, limits.fragments, 0); + } + var count: u64 = a.fragment_count - removed + added; + var capacity: u64 = ir_mem_capacity(count, r); + if (r.status != 0) { + return r.status as i32; + } + r.fragments = count; + r.fragment_capacity = capacity; + if (q.mode == 0) { + return 0; + } + if (new_capacity < capacity || !ir_span_valid(new_fragments as ptr, new_capacity, 136)) { + return ir_mem_fail(r, 200, 0, 0); + } + if (!ir_mem_metadata_build(a, start, end, source, source_start, source_end, q, new_fragments, + capacity, r, state, limits)) { + return r.status as i32; + } + // Reserve every physical byte operation before publishing any destination. + var copy_cost: u64 = q.size; + if (q.op == 6 || q.op == 7) { + copy_cost = q.size * 2; + } + if (q.size > 9223372036854775807 || !ir_mem_charge(r, copy_cost, state, limits)) { + if (r.status == 0) { + return ir_mem_fail(r, 5, 0, 0); + } + return r.status as i32; + } + if (q.op == 4) { + var i: u64 = 0; + while (i < q.part_count) { + var part: ptr = &q.parts[i]; + var n: u64 = ir_mem_part_size(part.kind); + var k: u64 = 0; + while (k < n) { + var octet: u8 = 0; + if (k < 8) { + octet = (part.low >> (k * 8)) as u8; + } else { + octet = (part.high >> ((k - 8) * 8)) as u8; + } + a.data[start + part.offset + k] = octet; + a.initialized[start + part.offset + k] = 1; + k += 1; + } + i += 1; + } + } else if (q.op == 5) { + var i: u64 = start; + while (i < end) { + a.initialized[i] = 0; + i += 1; + } + } else if (q.op == 6) { + var i: u64 = 0; + while (i < q.size) { + a.data[start + i] = source.data[source_start + i]; + a.initialized[start + i] = source.initialized[source_start + i]; + i += 1; + } + } else if (q.op == 7) { + var i: u64 = start; + while (i < end) { + a.data[i] = q.flag as u8; + a.initialized[i] = 1; + i += 1; + } + } else { + return ir_mem_fail(r, 200, 0, 0); + } + a.fragments = new_fragments; + a.fragment_capacity = capacity; + a.fragment_count = count; + state.fragments = total; + state.work += r.work; + return 0; +} diff --git a/ir/meson.build b/ir/meson.build index add61ac..7d888dc 100644 --- a/ir/meson.build +++ b/ir/meson.build @@ -18,26 +18,84 @@ if wave_ir_directory == '' and wave_source != '' wave_ir_module = custom_target('wave-ir', output: [archive_name, 'wave-ir.meta', 'provenance.json'], command: [python, files('../tools/build_wave_ir.py'), arguments], - depend_files: files('model.wave', 'layout.wave', 'lexer.wave', 'header.wave', 'type_parser.wave', - 'literal.wave', 'expression_parser.wave', 'instruction_parser.wave', 'module_parser.wave', 'lower_hir.wave', - 'lower_model.wave', 'lower_output.wave', 'lower_expression.wave', 'lower_storage.wave', 'lower_statement.wave', 'lower_driver.wave', 'builder.wave', 'builder_namespace.wave', 'builder_body.wave', - 'verify.wave', 'verifier_index.wave', 'verifier_ssa.wave', 'printer.wave', - 'cfg.wave', 'shape.wave', 'source.wave', 'lower_limits.wave', 'entry.wave', - 'src/wave_layout.rs', 'src/source_wave.rs', 'src/lower_ast/wave_limits.rs', 'src/parser/wave_lexer.rs', 'src/parser/wave_header.rs', - 'src/parser/wave_text.rs', 'src/parser/wave_type.rs', - 'src/parser/wave_literal.rs', 'src/builder/wave.rs', - 'src/builder/namespace.rs', 'src/builder/body.rs', - 'src/parser/wave_expression.rs', - 'src/parser/wave_instruction.rs', - 'src/parser/wave_module.rs', - 'src/lower_ast/wave_hir.rs', 'src/lower_ast/wave_lower.rs', - 'src/verifier/wave_semantics.rs', - 'src/verifier/wave_index.rs', - 'src/verifier/wave_ssa.rs', - 'src/printer_wave.rs', - 'src/verifier/wave_cfg.rs', 'src/verifier/wave_shape.rs', - '../tools/build_wave_ir.py', - '../tools/wave_bootstrap.py'), + depend_files: files( + 'model.wave', + 'layout.wave', + 'lexer.wave', + 'header.wave', + 'type_parser.wave', + 'literal.wave', + 'expression_parser.wave', + 'instruction_parser.wave', + 'module_parser.wave', + 'lower_hir.wave', + 'lower_model.wave', + 'lower_output.wave', + 'lower_expression.wave', + 'lower_storage.wave', + 'lower_statement.wave', + 'lower_driver.wave', + 'builder.wave', + 'builder_namespace.wave', + 'builder_body.wave', + 'verify.wave', + 'verifier_index.wave', + 'verifier_ssa.wave', + 'printer.wave', + 'cfg.wave', + 'shape.wave', + 'source.wave', + 'memory.wave', + 'lower_limits.wave', + 'wide.wave', + 'integer.wave', + 'float_model.wave', + 'float_arithmetic.wave', + 'float_convert.wave', + 'effects.wave', + 'passes.wave', + 'fold_integer.wave', + 'constant.wave', + 'constant_dependencies.wave', + 'runtime_model.wave', + 'runtime_prepare.wave', + 'runtime_execute.wave', + 'runtime_driver.wave', + 'entry.wave', + 'src/wave_layout.rs', + 'src/interpreter/integer.rs', + 'src/float/wave.rs', + 'src/effects_wave.rs', + 'src/pass_wave.rs', + 'src/fold_integer_wave.rs', + 'src/constant_wave.rs', + 'src/interpreter/runtime_wave.rs', + 'src/verifier/wave_constants.rs', + 'src/source_wave.rs', + 'src/interpreter/memory_wave.rs', + 'src/lower_ast/wave_limits.rs', + 'src/parser/wave_lexer.rs', + 'src/parser/wave_header.rs', + 'src/parser/wave_text.rs', + 'src/parser/wave_type.rs', + 'src/parser/wave_literal.rs', + 'src/builder/wave.rs', + 'src/builder/namespace.rs', + 'src/builder/body.rs', + 'src/parser/wave_expression.rs', + 'src/parser/wave_instruction.rs', + 'src/parser/wave_module.rs', + 'src/lower_ast/wave_hir.rs', + 'src/lower_ast/wave_lower.rs', + 'src/verifier/wave_semantics.rs', + 'src/verifier/wave_index.rs', + 'src/verifier/wave_ssa.rs', + 'src/printer_wave.rs', + 'src/verifier/wave_cfg.rs', + 'src/verifier/wave_shape.rs', + '../tools/build_wave_ir.py', + '../tools/wave_bootstrap.py', + ), depends: wave_bootstrap, console: true) wave_ir_dependencies += [wave_ir_module] elif wave_ir_directory != '' diff --git a/ir/passes.wave b/ir/passes.wave new file mode 100644 index 0000000..9fc40f9 --- /dev/null +++ b/ir/passes.wave @@ -0,0 +1,213 @@ +// SPDX-License-Identifier: MPL-2.0 +// Verified transactional pass control. Actions call other IR components or the +// caller's existing Pass trait; no host callback is invoked from Wave. +struct IrPassState { + phase: u64; + epoch0: u64; + epoch1: u64; + epoch2: u64; + work: u64; + changed: u64; + mask: u64; + failure_stage: u64; + failure_detail: u64; +} + +struct IrPassReply { + action: u64; + failed: u64; + changed: u64; + mask: u64; +} + +struct IrPassResult { + status: u64; + action: u64; + stage: u64; + detail: u64; + changed: u64; + mask: u64; + epoch0: u64; + epoch1: u64; + epoch2: u64; + work: u64; +} + +fun ir_pass_output(state: ptr, result: ptr, action: u64) -> i32 { + result.status = 0; + result.action = action; + result.stage = state.failure_stage; + result.detail = state.failure_detail; + result.changed = state.changed; + result.mask = state.mask; + result.epoch0 = state.epoch0; + result.epoch1 = state.epoch1; + result.epoch2 = state.epoch2; + result.work = state.work; + return 0; +} + +fun ir_pass_fail(state: ptr, result: ptr, stage: u64, + detail: u64, rollback: bool) -> i32 { + state.failure_stage = stage; + state.failure_detail = detail; + if (rollback) { + state.phase = 8; + return ir_pass_output(state, result, 8); + } + state.phase = 10; + return ir_pass_output(state, result, 10); +} + +// Exact packet equality. One unit covers at most eight examined bytes. +fun ir_pass_equal(state: ptr, before: ptr, before_count: u64, + after: ptr, after_count: u64, max_work: u64, equal: ptr) -> bool { + equal[0] = 0; + if (before_count != after_count) { + return true; + } + var index: u64 = 0; + while (index < before_count) { + if (state.work >= max_work) { + return false; + } + state.work += 1; + var count: u64 = before_count - index; + if (count > 8) { + count = 8; + } + var offset: u64 = 0; + while (offset < count) { + if (before[index + offset] != after[index + offset]) { + return true; + } + offset += 1; + } + index += count; + } + equal[0] = 1; + return true; +} + +// Action 1 before verify, 2 snapshot, 3 transform, 4 after verify, +// 5 after packet, 7 epoch commit, 8 rollback, 9 success, 10 failure. +// Failure stages match Before/Transform/After/Contract (0..3). +// Detail 0 preserves the adapter's error; 1 report, 2 epoch, 3 work. +export(c) fun whale_ir_pass_step(state: ptr, reply: ptr, + before: ptr, before_count: u64, after: ptr, after_count: u64, + max_work: u64, result: ptr) -> i32 { + if (result == null) { + return 1; + } + result.status = 1; + if (state == null || reply == null || state.phase > 10 || state.phase == 6 + || state.work > max_work || state.changed > 1 || state.mask > 7 + || reply.failed > 1 || reply.changed > 1 || reply.mask > 7) { + return 1; + } + if (state.phase == 9 || state.phase == 10) { + return ir_pass_output(state, result, state.phase); + } + if (reply.action != state.phase) { + return 1; + } + if (state.phase == 0) { + if (reply.failed != 0) { + return 1; + } + state.phase = 1; + return ir_pass_output(state, result, 1); + } + if (state.phase == 1) { + if (reply.failed != 0) { + return ir_pass_fail(state, result, 0, 0, false); + } + state.phase = 2; + return ir_pass_output(state, result, 2); + } + if (state.phase == 2) { + if (reply.failed != 0) { + return ir_pass_fail(state, result, 0, 0, false); + } + state.phase = 3; + return ir_pass_output(state, result, 3); + } + if (state.phase == 3) { + if (reply.failed != 0) { + return ir_pass_fail(state, result, 1, 0, true); + } + state.changed = reply.changed; + state.mask = reply.mask; + state.phase = 4; + return ir_pass_output(state, result, 4); + } + if (state.phase == 4) { + if (reply.failed != 0) { + return ir_pass_fail(state, result, 2, 0, true); + } + state.phase = 5; + return ir_pass_output(state, result, 5); + } + if (state.phase == 5) { + if (reply.failed != 0) { + return ir_pass_fail(state, result, 3, 0, true); + } + if (!ir_span_valid(before, before_count, 1) || !ir_span_valid(after, after_count, 1)) { + return 1; + } + var equal: u64 = 0; + if (!ir_pass_equal(state, before, before_count, after, after_count, max_work, &equal)) { + return ir_pass_fail(state, result, 3, 3, true); + } + var changed: u64 = 1 - equal; + if (state.changed != changed || (changed == 1 && state.mask != 7) + || (changed == 0 && state.mask != 0)) { + return ir_pass_fail(state, result, 3, 1, true); + } + if (((state.mask & 1) != 0 && state.epoch0 == 18446744073709551615) + || ((state.mask & 2) != 0 && state.epoch1 == 18446744073709551615) + || ((state.mask & 4) != 0 && state.epoch2 == 18446744073709551615)) { + return ir_pass_fail(state, result, 3, 2, true); + } + if ((state.mask & 1) != 0) { + state.epoch0 += 1; + } + if ((state.mask & 2) != 0) { + state.epoch1 += 1; + } + if ((state.mask & 4) != 0) { + state.epoch2 += 1; + } + state.phase = 7; + return ir_pass_output(state, result, 7); + } + if (reply.failed != 0) { + return 1; + } + if (state.phase == 7) { + state.phase = 9; + return ir_pass_output(state, result, 9); + } + if (state.phase == 8) { + state.phase = 10; + return ir_pass_output(state, result, 10); + } + return 1; +} + +export(c) fun whale_ir_analysis_current(cache_identity: u64, cache_epoch: u64, + state_identity: u64, epoch0: u64, epoch1: u64, epoch2: u64, kind: u64) -> i32 { + if (kind > 2) { + return 2; + } + var epoch: u64 = epoch0; + if (kind == 1) { + epoch = epoch1; + } else if (kind == 2) { + epoch = epoch2; + } + if (cache_identity == state_identity && cache_epoch == epoch) { + return 1; + } + return 0; +} diff --git a/ir/runtime_driver.wave b/ir/runtime_driver.wave new file mode 100644 index 0000000..64d91ab --- /dev/null +++ b/ir/runtime_driver.wave @@ -0,0 +1,86 @@ +// SPDX-License-Identifier: MPL-2.0 +// A resume acknowledges one effect or buffer request, never re-executes it. +fun ir_runtime_transport_valid(p: ptr) -> bool { + return ir_span_valid(p.types as ptr, p.type_count, 40) + && ir_span_valid(p.type_edges as ptr, p.type_edge_count, 8) + && ir_span_valid(p.functions as ptr, p.function_count, 88) + && ir_span_valid(p.blocks as ptr, p.block_count, 32) + && ir_span_valid(p.instructions as ptr, p.instruction_count, 168) + && ir_span_valid(p.operands as ptr, p.operand_count, 8) + && ir_span_valid(p.value_types as ptr, p.value_type_count, 8) + && ir_span_valid(p.globals as ptr, p.global_count, 216) + && ir_span_valid(p.global_values as ptr, p.global_count, 160) + && ir_span_valid(p.arguments as ptr, p.argument_count, 160) + && ir_span_valid(p.layout_nodes as ptr, p.type_count, 32) + && ir_span_valid(p.layouts as ptr, p.type_count, 40) + && ir_span_valid(p.layout_offsets as ptr, p.type_edge_count, 8) + && ir_span_valid(p.plans as ptr, p.plan_capacity, 40) + && ir_span_valid(p.ordinals as ptr, p.value_type_count, 8) + && ir_span_valid(p.function_table as ptr, p.function_table_capacity, 8) + && ir_span_valid(p.prepared, p.function_count, 1) + && ir_span_valid(p.pending_previous as ptr, p.function_count, 8) + && ir_span_valid(p.pending_next as ptr, p.function_count, 8) + && ir_span_valid(p.pending_flags, p.function_count, 1) + && ir_span_valid(p.callable_flags, p.function_count, 1) + && ir_span_valid(p.callable_targets as ptr, p.function_count, 8) + && ir_span_valid(p.indirect_signatures as ptr, p.indirect_capacity, 8) + && ir_span_valid(p.indirect_sites as ptr, p.indirect_capacity, 8) + && ir_span_valid(p.frames as ptr, p.frame_capacity, 80) + && ir_span_valid(p.slots as ptr, p.slot_capacity, 168) + && ir_span_valid(p.phis as ptr, p.phi_capacity, 160) + && p.frame_count <= p.frame_capacity && p.slot_count <= p.slot_capacity + && p.plan_count <= p.plan_capacity && p.indirect_count <= p.indirect_capacity + && p.callable_count <= p.function_count && p.work <= p.max_work; +} + +export(c) fun whale_ir_runtime_step(p: ptr) -> i32 { + if (p == null || p.result == null) { + return 4; + } + p.result.status = 0; + p.result.error = 0; + p.result.steps = p.steps; + if (!ir_runtime_transport_valid(p)) { + ir_runtime_backend(p); + return 4; + } + if (p.phase == 5) { + return 0; + } + if (p.phase == 0) { + if (p.pending != 0 || p.resume != 0 || p.frame_count != 0 || p.slot_count != 0 + || p.plan_count != 0 || p.indirect_count != 0 || p.callable_count != 0 + || p.frames_created != 0 || p.steps != 0 || p.work != 0) { + ir_runtime_backend(p); + return 4; + } + if (!ir_runtime_initialize(p)) { + return p.result.status as i32; + } + } else if (!ir_runtime_resume(p)) { + return p.result.status as i32; + } + while (p.phase != 5) { + if (p.phase == 1) { + if (!ir_runtime_globals(p)) { + return p.result.status as i32; + } + } else if (p.phase == 2) { + if (!ir_runtime_admit(p, p.entry, true)) { + return p.result.status as i32; + } + } else if (p.phase == 3) { + if (!ir_runtime_execute_one(p)) { + return p.result.status as i32; + } + } else if (p.phase == 4) { + if (!ir_runtime_admit(p, p.pending_target, false)) { + return p.result.status as i32; + } + } else { + ir_runtime_backend(p); + return 4; + } + } + return 0; +} diff --git a/ir/runtime_execute.wave b/ir/runtime_execute.wave new file mode 100644 index 0000000..6a6bdee --- /dev/null +++ b/ir/runtime_execute.wave @@ -0,0 +1,728 @@ +// SPDX-License-Identifier: MPL-2.0 +// Native execution uses generation-tagged SSA slots and explicit one-shot effects. +fun ir_runtime_step_charge(p: ptr, site: u64) -> bool { + p.pending_site = site; + if (p.steps >= p.max_steps) { + return ir_runtime_error(p, 6, site, p.max_steps, 0); + } + p.steps += 1; + return ir_runtime_charge(p); +} + +fun ir_runtime_get(p: ptr, frame: ptr, + slot: u64, output: ptr) -> bool { + if (slot >= frame.value_count || frame.value_base > p.slot_count + || slot >= p.slot_count - frame.value_base) { + return ir_runtime_backend(p); + } + var source: ptr = &p.slots[frame.value_base + slot]; + if (source.generation != frame.generation) { + return ir_runtime_backend(p); + } + output[0] = source.value; + return true; +} + +fun ir_runtime_put(p: ptr, frame: ptr, + slot: u64, value: ptr) -> bool { + if (slot >= frame.value_count || frame.value_base > p.slot_count + || slot >= p.slot_count - frame.value_base) { + return ir_runtime_backend(p); + } + var destination: ptr = &p.slots[frame.value_base + slot]; + destination.value = value[0]; + destination.value.ty = p.value_types[p.functions[frame.function].first_value_type + slot]; + destination.generation = frame.generation; + return true; +} + +fun ir_runtime_event(p: ptr, kind: u64, pending: u64, + inst: ptr) -> bool { + p.result.status = 1; + p.result.site = p.pending_site; + p.result.steps = p.steps; + p.result.event.kind = kind; + p.result.event.ty = inst.ty; + p.result.event.size = inst.size; + p.result.event.natural = inst.natural; + p.result.event.align = inst.align; + p.result.event.flag = 0; + p.result.event.owner = 0; + p.result.event.first = 0; + p.result.event.count = 0; + p.pending = pending; + p.pending_destination = inst.dst; + p.pending_type = inst.ty; + p.resume = 0; + return false; +} + +fun ir_runtime_buffers(p: ptr, frames: u64, slots: u64, + phis: u64) -> bool { + if (frames <= p.frame_capacity && slots <= p.slot_capacity && phis <= p.phi_capacity) { + return true; + } + p.result.status = 2; + p.result.site = p.pending_site; + p.result.event.frame_capacity = frames; + p.result.event.value_capacity = slots; + p.result.event.phi_capacity = phis; + p.result.steps = p.steps; + p.pending = 8; + p.resume = 0; + return false; +} + +fun ir_runtime_admit(p: ptr, target: u64, entry: bool) -> bool { + if (target >= p.function_count || p.prepared[target] == 0) { + return ir_runtime_backend(p); + } + if (p.frame_count >= p.max_depth) { + return ir_runtime_error(p, 7, p.pending_site, p.max_depth, 0); + } + if (p.frames_created >= p.max_frames) { + return ir_runtime_error(p, 8, p.pending_site, p.max_frames, 0); + } + var function: ptr = &p.functions[target]; + if (p.slot_count > p.max_values || function.value_count > p.max_values - p.slot_count) { + return ir_runtime_error(p, 9, p.pending_site, p.max_values, 0); + } + var required: u64 = p.slot_count + function.value_count; + if (!ir_runtime_buffers(p, p.frame_count + 1, required, p.phi_capacity)) { + return false; + } + var child: ptr = &p.frames[p.frame_count]; + child.function = target; + child.block = function.entry; + child.predecessor = 18446744073709551615; + child.instruction = 0; + child.value_base = p.slot_count; + child.value_count = function.value_count; + child.generation = p.frames_created + 1; + child.allocation_start = p.memory_allocations; + child.return_slot = 18446744073709551615; + child.call_site = 18446744073709551615; + if (!entry) { + child.return_slot = p.instructions[p.pending_site].dst; + child.call_site = p.pending_site; + } + p.slot_count = required; + var i: u64 = 0; + while (i < function.parameter_count) { + if (!ir_runtime_charge(p)) { + return false; + } + var value: IrRuntimeValue; + if (entry) { + value = p.arguments[i]; + } else { + var inst: ptr = &p.instructions[p.pending_site]; + if (i >= inst.count || !ir_runtime_get(p, &p.frames[p.frame_count - 1], + p.operands[inst.first + i], &value)) { + return ir_runtime_backend(p); + } + } + if (!ir_runtime_put(p, child, p.operands[function.first_parameter + i], &value)) { + return false; + } + i += 1; + } + p.frames_created += 1; + p.frame_count += 1; + p.phase = 3; + return true; +} + +fun ir_runtime_compare_predicate(op: u64) -> u64 { + if (op < 2) { + return op; + } + if (op < 6) { + return op + 4; + } + return op - 4; +} + +fun ir_runtime_float_predicate(op: u64) -> u64 { + if (op == 10) { + return 0; + } + if (op == 11) { + return 9; + } + return op - 10; +} + +fun ir_runtime_numeric(p: ptr, inst: ptr, + left: ptr, right: ptr, output: ptr) -> bool { + var kind: u64 = p.types[inst.ty].kind; + var source: u64 = kind; + var mode: u64 = 0; + var operation: u64 = inst.sub; + var destination: u64 = kind; + if (inst.op == 8 || inst.op == 9) { + mode = 6; + operation = inst.op - 8; + } else if (inst.op == 10 || inst.op == 11 || inst.op == 12) { + mode = 3; + destination = 1; + if (inst.op == 10) { + operation = ir_runtime_compare_predicate(inst.sub); + } + } else if (inst.op == 14) { + source = p.types[inst.other].kind; + mode = 2; + if (inst.sub == 12) { + mode = 4; + operation = 0; + } else if (inst.sub == 9) { + operation = 3; + } + } else if (inst.op == 17) { + mode = 1; + } + ir_runtime_clear_value(output); + output.kind = 1; + output.ty = inst.ty; + output.literal = ir_runtime_literal(destination); + if (ir_verify_float(source) || ir_verify_float(destination)) { + var request: IrFloatRequest; + request.mode = 0; + request.operation = inst.sub; + if (inst.op == 7) { + request.operation = inst.sub - 7; + } + request.source = source; + request.destination = destination; + request.left_kind = left.literal; + request.left_low = left.low; + request.left_high = left.high; + request.right_kind = right.literal; + request.right_low = right.low; + request.right_high = right.high; + if (inst.op == 8) { + request.mode = 1; + } else if (inst.op == 10 || inst.op == 12) { + request.mode = 2; + request.destination = source; + if (inst.op == 10) { + request.operation = ir_runtime_float_predicate(inst.sub); + } + } else if (inst.op == 14) { + request.mode = 3; + request.operation = inst.sub - 3; + } + var result: IrFloatResult; + var status: i32 = whale_ir_float(&request, &result); + if (status == 1) { + return ir_runtime_error(p, 12, p.pending_site, 0, 0); + } + if (status != 0 || result.status != 0) { + return ir_runtime_backend(p); + } + output.low = result.low; + output.high = result.high; + if (request.mode == 2) { + output.low = result.flag; + output.high = 0; + } + } else { + var result: IrIntegerResult; + var status: i32 = whale_ir_integer(mode, operation, source, destination, + left.low, left.high, right.low, right.high, &result); + if (status >= 1 && status <= 3) { + return ir_runtime_error(p, 9 + status as u64, p.pending_site, 0, 0); + } + if (status != 0 || result.status != 0) { + return ir_runtime_backend(p); + } + output.low = result.low; + output.high = result.high; + output.flag = result.flag; + if (inst.op == 17) { + output.kind = 2; + } + } + return true; +} + +fun ir_runtime_resume(p: ptr) -> bool { + var pending: u64 = p.pending; + if (pending == 0) { + if (p.resume != 0) { + return ir_runtime_backend(p); + } + return true; + } + if (pending == 8) { + if (p.resume != 2) { + return ir_runtime_backend(p); + } + p.pending = 0; + p.resume = 0; + return true; + } + if (p.resume != 1) { + return ir_runtime_backend(p); + } + p.pending = 0; + p.resume = 0; + if (pending == 5) { + p.global_values[p.cursor] = p.resume_value; + p.global_phase = 1; + return true; + } + if (pending == 6) { + p.global_phase = 2; + return true; + } + if (pending == 7) { + p.global_values[p.cursor] = p.resume_value; + p.cursor += 1; + p.global_phase = 0; + return true; + } + if (p.frame_count == 0) { + return ir_runtime_backend(p); + } + var frame: ptr = &p.frames[p.frame_count - 1]; + if (pending == 1) { + return ir_runtime_put(p, frame, p.pending_destination, &p.resume_value); + } + if (pending == 2) { + return true; + } + if (pending == 3) { + var pred: u64 = p.pending_flag; + var answer: bool = false; + if (pred < 2) { + answer = p.resume_value.low != 0; + if (pred == 1) { + answer = !answer; + } + } else { + var negative: bool = (p.resume_value.high >> 63) != 0; + var zero: bool = p.resume_value.low == 0 && p.resume_value.high == 0; + if (pred == 2 || pred == 6) { + answer = negative; + } else if (pred == 3 || pred == 7) { + answer = negative || zero; + } else if (pred == 4 || pred == 8) { + answer = !negative && !zero; + } else { + answer = !negative; + } + } + var value: IrRuntimeValue; + ir_runtime_make_scalar(p, p.pending_type, answer as u64, 0, &value); + value.literal = 3; + return ir_runtime_put(p, frame, p.pending_destination, &value); + } + if (pending == 4) { + var destination: u64 = frame.return_slot; + p.slot_count = frame.value_base; + p.frame_count -= 1; + if (p.frame_count == 0) { + p.phase = 5; + p.result.status = 0; + p.result.steps = p.steps; + p.result.value = p.pending_value; + return false; + } + if (destination != 18446744073709551615) { + return ir_runtime_put(p, &p.frames[p.frame_count - 1], destination, &p.pending_value); + } + return true; + } + return ir_runtime_backend(p); +} + +fun ir_runtime_globals(p: ptr) -> bool { + if (p.cursor >= p.global_count) { + p.result.global = 18446744073709551615; + p.pending_site = 18446744073709551615; + p.phase = 2; + return true; + } + p.result.global = p.cursor; + var global: ptr = &p.globals[p.cursor]; + var event: ptr = &p.result.event; + p.result.status = 1; + p.result.site = 18446744073709551615; + p.result.steps = p.steps; + event.ty = global.ty; + event.size = global.size; + event.natural = global.natural; + event.align = global.align; + event.flag = 0; + p.resume = 0; + if (p.global_phase == 0) { + event.kind = 1; + event.flag = 1; + p.pending = 5; + } else if (p.global_phase == 1 && global.initialized == 1) { + event.kind = 3; + event.left = p.global_values[p.cursor]; + event.right = global.value; + p.pending = 6; + } else { + event.kind = 12; + event.left = p.global_values[p.cursor]; + event.flag = global.readonly; + p.pending = 7; + } + return false; +} + +fun ir_runtime_phis(p: ptr, frame: ptr) -> bool { + var block: ptr = &p.blocks[frame.block]; + p.pending_site = block.first; + var count: u64 = 0; + while (count < block.count && p.instructions[block.first + count].op == 15) { + if (!ir_runtime_charge(p)) { + return false; + } + count += 1; + } + if (!ir_runtime_buffers(p, p.frame_count, p.slot_count, count)) { + return false; + } + var i: u64 = 0; + while (i < count) { + var inst: ptr = &p.instructions[block.first + i]; + if (!ir_runtime_step_charge(p, block.first + i)) { + return false; + } + var j: u64 = 0; + var found: bool = false; + while (j < inst.count) { + if (!ir_runtime_charge(p)) { + return false; + } + if (p.operands[inst.first + j * 2 + 1] == frame.predecessor) { + if (!ir_runtime_get(p, frame, p.operands[inst.first + j * 2], &p.phis[i])) { + return false; + } + found = true; + break; + } + j += 1; + } + if (!found) { + return ir_runtime_backend(p); + } + i += 1; + } + i = 0; + while (i < count) { + if (!ir_runtime_put(p, frame, p.instructions[block.first + i].dst, &p.phis[i])) { + return false; + } + i += 1; + } + frame.instruction = count; + return true; +} + +fun ir_runtime_execute_one(p: ptr) -> bool { + if (p.frame_count == 0) { + return ir_runtime_backend(p); + } + var frame: ptr = &p.frames[p.frame_count - 1]; + if (frame.block >= p.block_count || p.blocks[frame.block].function != frame.function) { + return ir_runtime_backend(p); + } + var block: ptr = &p.blocks[frame.block]; + if (frame.instruction == 0 && !ir_runtime_phis(p, frame)) { + return false; + } + if (frame.instruction >= block.count) { + return ir_runtime_backend(p); + } + var site: u64 = block.first + frame.instruction; + var inst: ptr = &p.instructions[site]; + if (!ir_runtime_step_charge(p, site)) { + return false; + } + frame.instruction += 1; + var left: IrRuntimeValue; + var right: IrRuntimeValue; + var third: IrRuntimeValue; + var value: IrRuntimeValue; + ir_runtime_clear_value(&left); + ir_runtime_clear_value(&right); + ir_runtime_clear_value(&third); + ir_runtime_clear_value(&value); + var op: u64 = inst.op; + if (op == 0) { + if (inst.global >= p.global_count) { + return ir_runtime_backend(p); + } + value = p.global_values[inst.global]; + } else if (op == 1) { + if (!ir_runtime_get(p, frame, inst.a, &left)) { + return false; + } + ir_runtime_event(p, 8, 2, inst); + p.result.event.left = left; + p.result.event.owner = frame.allocation_start; + return false; + } else if (op == 2) { + if (!ir_runtime_get(p, frame, inst.a, &left) + || !ir_runtime_get(p, frame, inst.b, &right)) { + return false; + } + ir_runtime_event(p, 9, 1, inst); + p.result.event.left = left; + p.result.event.right = right; + return false; + } else if (op == 3 || op == 4) { + ir_runtime_make_scalar(p, inst.ty, inst.low, inst.high, &value); + value.literal = inst.literal; + } else if (op == 6) { + if (!ir_runtime_get(p, frame, inst.a, &value)) { + return false; + } + } else if (op >= 7 && op <= 12) { + if (!ir_runtime_get(p, frame, inst.a, &left)) { + return false; + } + if (op != 8 && op != 9 && !ir_runtime_get(p, frame, inst.b, &right)) { + return false; + } + if ((op == 10 || op == 11) && p.types[inst.ty].kind == 17) { + var pred: u64 = inst.sub; + if (op == 10) { + pred = ir_runtime_compare_predicate(pred); + } + var event: u64 = 9; + if (pred < 2) { + event = 10; + } + ir_runtime_event(p, event, 3, inst); + p.pending_type = p.value_types[p.functions[frame.function].first_value_type + inst.dst]; + p.pending_flag = pred; + p.result.event.left = left; + p.result.event.right = right; + return false; + } + if (!ir_runtime_numeric(p, inst, &left, &right, &value)) { + return false; + } + } else if (op == 13) { + if (!ir_runtime_get(p, frame, inst.a, &left)) { + return false; + } + var source: u64 = inst.c; + if (left.low != 0) { + source = inst.b; + } + if (!ir_runtime_get(p, frame, source, &value)) { + return false; + } + } else if (op == 14) { + if (!ir_runtime_get(p, frame, inst.a, &left)) { + return false; + } + var source: u64 = p.types[inst.other].kind; + var destination: u64 = p.types[inst.ty].kind; + if (inst.sub == 9 && source == 17) { + value = left; + } else if (inst.sub == 9 && (ir_verify_float(source) || ir_verify_float(destination))) { + if (ir_verify_float(destination)) { + var raw: IrWide; + var bits: IrWide; + ir_wide_from(left.low, left.high, &raw); + ir_wide_trim(&raw, ir_verify_width(destination), &bits); + ir_runtime_make_scalar(p, inst.ty, bits.low, bits.high, &value); + } else { + var result: IrIntegerResult; + var status: i32 = whale_ir_integer_bits(left.low, left.high, + ir_integer_width(destination), ir_integer_signed(destination) as u64, &result); + if (status != 0 || result.status != 0) { + return ir_runtime_backend(p); + } + ir_runtime_make_scalar(p, inst.ty, result.low, result.high, &value); + } + } else if (inst.sub == 11) { + value.kind = 3; + value.pointer.address = left.low; + } else if (inst.sub == 10) { + var result: IrIntegerResult; + var status: i32 = whale_ir_integer_bits(left.pointer.address, 0, + ir_integer_width(destination), ir_integer_signed(destination) as u64, &result); + if (status != 0 || result.status != 0) { + return ir_runtime_backend(p); + } + ir_runtime_make_scalar(p, inst.ty, result.low, result.high, &value); + } else if (!ir_runtime_numeric(p, inst, &left, &right, &value)) { + return false; + } + } else if (op == 16) { + if (!ir_runtime_get(p, frame, inst.a, &left) || left.kind != 2 || inst.sub > 1) { + return ir_runtime_backend(p); + } + value = left; + value.kind = 1; + if (inst.sub == 1) { + ir_runtime_make_scalar(p, inst.ty, left.flag, 0, &value); + } + } else if (op == 17) { + if (!ir_runtime_get(p, frame, inst.a, &left) + || !ir_runtime_get(p, frame, inst.b, &right) + || !ir_runtime_numeric(p, inst, &left, &right, &value)) { + return false; + } + } else if (op == 18) { + return ir_runtime_event(p, 1, 1, inst); + } else if (op == 19 || op == 21) { + if (!ir_runtime_get(p, frame, inst.a, &left)) { + return false; + } + ir_runtime_event(p, 2, 1, inst); + p.result.event.left = left; + return false; + } else if (op == 20 || op == 22) { + if (!ir_runtime_get(p, frame, inst.a, &right) + || !ir_runtime_get(p, frame, inst.b, &left)) { + return false; + } + ir_runtime_event(p, 3, 2, inst); + p.result.event.left = left; + p.result.event.right = right; + return false; + } else if (op == 23) { + if (!ir_runtime_get(p, frame, inst.a, &left)) { + return false; + } + ir_runtime_event(p, 4, 2, inst); + p.result.event.left = left; + return false; + } else if (op == 24) { + if (!ir_runtime_get(p, frame, inst.a, &left)) { + return false; + } + var i: u64 = 0; + while (i < inst.plan_count) { + if (!ir_runtime_charge(p) + || !ir_runtime_get(p, frame, p.operands[inst.first + i], &right)) { + return false; + } + var plan: ptr = &p.plans[inst.plan_first + i]; + plan.low = right.low; + plan.high = right.high; + plan.signed = ir_verify_signed(p.types[right.ty].kind) as u64; + i += 1; + } + ir_runtime_event(p, 7, 1, inst); + p.result.event.left = left; + p.result.event.first = inst.plan_first; + p.result.event.count = inst.plan_count; + return false; + } else if (op == 25 || op == 26) { + if (!ir_runtime_get(p, frame, inst.a, &left) + || !ir_runtime_get(p, frame, inst.b, &right) + || !ir_runtime_get(p, frame, inst.c, &third)) { + return false; + } + var event: u64 = 5; + if (op == 26) { + event = 6; + } + ir_runtime_event(p, event, 2, inst); + p.result.event.left = left; + p.result.event.right = right; + p.result.event.flag = right.low & 255; + p.result.event.size = third.low; + return false; + } else if (op == 27 || op == 28) { + value.kind = 4; + value.signature = inst.signature; + if (op == 28) { + value.target_kind = 1; + value.target = p.functions[inst.a].id; + } + } else if (op == 29) { + var target: u64 = inst.a; + if (inst.flags != 0) { + if (!ir_runtime_get(p, frame, inst.a, &left) || left.kind != 4) { + return ir_runtime_backend(p); + } + if (left.target_kind == 0) { + return ir_runtime_error(p, 14, site, 0, 0); + } + if (left.target_kind != 1) { + return ir_runtime_error(p, 15, site, 0, 0); + } + target = ir_runtime_find(p, left.target); + if (p.result.status != 0) { + return false; + } + if (target == 18446744073709551615 + || !ir_runtime_equal(p, left.signature, p.functions[target].signature)) { + if (p.result.status != 0) { + return false; + } + return ir_runtime_error(p, 16, site, 0, 0); + } + } + p.pending_target = target; + p.phase = 4; + return true; + } else if (op == 30) { + if (!ir_runtime_get(p, frame, inst.a, &left)) { + return false; + } + if (left.low != 0) { + return ir_runtime_error(p, 13, site, inst.global, 0); + } + return true; + } else if (op >= 31 && op <= 33) { + var next: u64 = inst.a; + if (op == 32) { + if (!ir_runtime_get(p, frame, inst.a, &left)) { + return false; + } + next = inst.c; + if (left.low != 0) { + next = inst.b; + } + } else if (op == 33) { + if (!ir_runtime_get(p, frame, inst.a, &left)) { + return false; + } + next = inst.b; + var i: u64 = 0; + while (i < inst.count) { + if (!ir_runtime_charge(p)) { + return false; + } + var first: u64 = inst.first + i * 3; + if (left.low == p.operands[first] && left.high == p.operands[first + 1]) { + next = p.operands[first + 2]; + break; + } + i += 1; + } + } + frame.predecessor = frame.block; + frame.block = next; + frame.instruction = 0; + return true; + } else if (op == 34) { + if (inst.a != 18446744073709551615 + && !ir_runtime_get(p, frame, inst.a, &value)) { + return false; + } + p.pending_value = value; + p.pending_value.ty = inst.ty; + ir_runtime_event(p, 11, 4, inst); + p.result.event.owner = frame.allocation_start; + return false; + } else if (op == 35) { + return ir_runtime_error(p, 13, site, inst.global, 0); + } else { + return ir_runtime_backend(p); + } + return ir_runtime_put(p, frame, inst.dst, &value); +} diff --git a/ir/runtime_model.wave b/ir/runtime_model.wave new file mode 100644 index 0000000..580bf69 --- /dev/null +++ b/ir/runtime_model.wave @@ -0,0 +1,195 @@ +// SPDX-License-Identifier: MPL-2.0 +// Caller-owned IR records and execution storage; no native address is a value ID. +struct IrRuntimeValue { + kind: u64; + ty: u64; + literal: u64; + low: u64; + high: u64; + flag: u64; + pointer: IrMemPointer; + signature: u64; + target_kind: u64; + target: u64; + origin: u64; +} + +struct IrRuntimeSlot { + generation: u64; + value: IrRuntimeValue; +} + +struct IrRuntimeFrame { + function: u64; + block: u64; + predecessor: u64; + instruction: u64; + value_base: u64; + value_count: u64; + generation: u64; + allocation_start: u64; + return_slot: u64; + call_site: u64; +} + +struct IrRuntimeFunction { + id: u64; + signature: u64; + entry: u64; + first_block: u64; + block_count: u64; + first_parameter: u64; + parameter_count: u64; + value_count: u64; + first_value_type: u64; + has_body: u64; + linkage: u64; +} + +struct IrRuntimeBlock { + id: u64; + function: u64; + first: u64; + count: u64; +} + +struct IrRuntimeInstruction { + op: u64; + sub: u64; + ty: u64; + other: u64; + dst: u64; + a: u64; + b: u64; + c: u64; + align: u64; + size: u64; + natural: u64; + first: u64; + count: u64; + low: u64; + high: u64; + literal: u64; + signature: u64; + flags: u64; + global: u64; + plan_first: u64; + plan_count: u64; +} + +struct IrRuntimeGlobal { + id: u64; + ty: u64; + size: u64; + align: u64; + natural: u64; + readonly: u64; + initialized: u64; + value: IrRuntimeValue; +} + +struct IrRuntimeEvent { + kind: u64; + ty: u64; + size: u64; + natural: u64; + align: u64; + flag: u64; + owner: u64; + first: u64; + count: u64; + frame_capacity: u64; + value_capacity: u64; + phi_capacity: u64; + left: IrRuntimeValue; + right: IrRuntimeValue; +} + +struct IrRuntimeResult { + status: u64; + error: u64; + site: u64; + detail: u64; + extra: u64; + global: u64; + steps: u64; + value: IrRuntimeValue; + event: IrRuntimeEvent; +} + +struct IrRuntimeDriver { + types: ptr; + type_count: u64; + type_edges: ptr; + type_edge_count: u64; + functions: ptr; + function_count: u64; + blocks: ptr; + block_count: u64; + instructions: ptr; + instruction_count: u64; + operands: ptr; + operand_count: u64; + value_types: ptr; + value_type_count: u64; + globals: ptr; + global_count: u64; + global_values: ptr; + arguments: ptr; + argument_count: u64; + scalar_arguments: u64; + entry_id: u64; + storage: ptr; + layout_nodes: ptr; + layouts: ptr; + layout_offsets: ptr; + plans: ptr; + plan_capacity: u64; + plan_count: u64; + ordinals: ptr; + function_table: ptr; + function_table_capacity: u64; + prepared: ptr; + pending_previous: ptr; + pending_next: ptr; + pending_flags: ptr; + callable_flags: ptr; + callable_targets: ptr; + callable_count: u64; + indirect_signatures: ptr; + indirect_sites: ptr; + indirect_count: u64; + indirect_capacity: u64; + pending_head: u64; + frames: ptr; + frame_capacity: u64; + frame_count: u64; + slots: ptr; + slot_capacity: u64; + slot_count: u64; + phis: ptr; + phi_capacity: u64; + phase: u64; + cursor: u64; + global_phase: u64; + entry: u64; + pending: u64; + pending_destination: u64; + pending_type: u64; + pending_flag: u64; + pending_target: u64; + pending_site: u64; + pending_value: IrRuntimeValue; + resume: u64; + resume_value: IrRuntimeValue; + memory_allocations: u64; + frames_created: u64; + steps: u64; + work: u64; + max_steps: u64; + max_depth: u64; + max_frames: u64; + max_values: u64; + max_work: u64; + result: ptr; +} diff --git a/ir/runtime_prepare.wave b/ir/runtime_prepare.wave new file mode 100644 index 0000000..a09862d --- /dev/null +++ b/ir/runtime_prepare.wave @@ -0,0 +1,612 @@ +// SPDX-License-Identifier: MPL-2.0 +// Preparation and admission are native decisions over caller-owned, bounded records. +fun ir_runtime_error(p: ptr, error: u64, site: u64, + detail: u64, extra: u64) -> bool { + p.result.status = 3; + p.result.error = error; + p.result.site = site; + p.result.detail = detail; + p.result.extra = extra; + p.result.steps = p.steps; + return false; +} + +fun ir_runtime_backend(p: ptr) -> bool { + p.result.status = 4; + p.result.site = p.pending_site; + p.result.steps = p.steps; + return false; +} + +fun ir_runtime_charge(p: ptr) -> bool { + if (p.work >= p.max_work) { + return ir_runtime_error(p, 18, p.pending_site, p.max_work, 0); + } + p.work += 1; + return true; +} + +fun ir_runtime_equal(p: ptr, a: u64, b: u64) -> bool { + if (a >= p.type_count || b >= p.type_count) { + ir_runtime_backend(p); + return false; + } + var result: IrVerifyResult; + result.status = 0; + result.work = p.work; + var equal: bool = ir_verify_equal(a, b, p.types, p.type_edges, 1024, + &result, p.max_work); + p.work = result.work; + if (result.status != 0) { + ir_runtime_error(p, 18, p.pending_site, p.max_work, 0); + } + return equal; +} + +fun ir_runtime_scalar(kind: u64) -> bool { + return kind >= 1 && kind <= 16; +} + +fun ir_runtime_call_value(kind: u64) -> bool { + return kind >= 1 && kind <= 18; +} + +fun ir_runtime_value_type(p: ptr, ty: u64) -> bool { + var t: ptr = &p.types[ty]; + if (ir_runtime_call_value(t.kind)) { + return true; + } + return t.kind == 21 && t.count == 2 + && ir_verify_integer(p.types[p.type_edges[t.first]].kind) + && p.types[p.type_edges[t.first + 1]].kind == 1; +} + +fun ir_runtime_callable(p: ptr, signature: u64) -> bool { + var t: ptr = &p.types[signature]; + if (t.kind != 18 || t.extra != 0 || t.count == 0) { + return false; + } + var i: u64 = 0; + while (i < t.count) { + if (!ir_runtime_charge(p)) { + return false; + } + var kind: u64 = p.types[p.type_edges[t.first + i]].kind; + if (!(i == 0 && kind == 0) && !ir_runtime_call_value(kind)) { + return false; + } + i += 1; + } + return true; +} + +fun ir_runtime_find(p: ptr, id: u64) -> u64 { + var mask: u64 = p.function_table_capacity - 1; + var index: u64 = ir_source_mix(id) & mask; + var count: u64 = 0; + while (count < p.function_table_capacity) { + if (!ir_runtime_charge(p)) { + return 18446744073709551615; + } + var function: u64 = p.function_table[index]; + if (function == 18446744073709551615 || p.functions[function].id == id) { + return function; + } + index = (index + 1) & mask; + count += 1; + } + ir_runtime_backend(p); + return 18446744073709551615; +} + +fun ir_runtime_push_pending(p: ptr, function: u64) -> bool { + if (!ir_runtime_charge(p) || function >= p.function_count) { + return false; + } + if (p.prepared[function] != 0) { + return true; + } + if (p.pending_flags[function] != 0) { + var previous: u64 = p.pending_previous[function]; + var next: u64 = p.pending_next[function]; + if (previous == 18446744073709551615) { + p.pending_head = next; + } else { + p.pending_next[previous] = next; + } + if (next != 18446744073709551615) { + p.pending_previous[next] = previous; + } + } + p.pending_previous[function] = 18446744073709551615; + p.pending_next[function] = p.pending_head; + if (p.pending_head != 18446744073709551615) { + p.pending_previous[p.pending_head] = function; + } + p.pending_head = function; + p.pending_flags[function] = 1; + return true; +} + +fun ir_runtime_target(p: ptr, target: u64, site: u64) -> bool { + if (target >= p.function_count) { + return ir_runtime_backend(p); + } + if (p.functions[target].linkage != 0 || p.functions[target].has_body == 0) { + return ir_runtime_error(p, 5, site, 9, 0); + } + return ir_runtime_push_pending(p, target); +} + +fun ir_runtime_add_callable(p: ptr, target: u64) -> bool { + if (target >= p.function_count) { + return ir_runtime_backend(p); + } + if (p.callable_flags[target] != 0) { + return true; + } + p.callable_flags[target] = 1; + p.callable_targets[p.callable_count] = target; + p.callable_count += 1; + var i: u64 = 0; + while (i < p.indirect_count) { + if (ir_runtime_equal(p, p.functions[target].signature, p.indirect_signatures[i])) { + return ir_runtime_target(p, target, p.indirect_sites[i]); + } + if (p.result.status != 0) { + return false; + } + i += 1; + } + return true; +} + +fun ir_runtime_add_indirect(p: ptr, signature: u64, site: u64) -> bool { + var i: u64 = 0; + while (i < p.indirect_count) { + if (ir_runtime_equal(p, signature, p.indirect_signatures[i])) { + return true; + } + if (p.result.status != 0) { + return false; + } + i += 1; + } + if (p.indirect_count >= p.indirect_capacity) { + return ir_runtime_backend(p); + } + p.indirect_signatures[p.indirect_count] = signature; + p.indirect_sites[p.indirect_count] = site; + p.indirect_count += 1; + i = 0; + while (i < p.callable_count) { + var target: u64 = p.callable_targets[i]; + if (ir_runtime_equal(p, signature, p.functions[target].signature)) { + if (!ir_runtime_target(p, target, site)) { + return false; + } + } + if (p.result.status != 0) { + return false; + } + i += 1; + } + return true; +} + +fun ir_runtime_layout(p: ptr, ty: u64) -> bool { + var remaining: u64 = p.max_work - p.work; + var status: i32 = ir_layout_node(ty, p.layout_nodes, p.type_count, p.type_edges, + p.type_edge_count, p.storage, 1024, p.layouts, p.layout_offsets, &remaining); + p.work = p.max_work - remaining; + if (status == 6) { + return ir_runtime_error(p, 18, p.pending_site, p.max_work, 0); + } + if (status != 0) { + return ir_runtime_backend(p); + } + return true; +} + +fun ir_runtime_supported(p: ptr, inst: ptr, + site: u64) -> bool { + var op: u64 = inst.op; + var kind: u64 = p.types[inst.ty].kind; + var integer: bool = ir_verify_integer(kind); + var scalar: bool = ir_runtime_scalar(kind); + var floating: bool = ir_verify_float(kind); + var valid: bool = op == 0 || op == 1 || op == 2 || op == 3 || op >= 24; + var reason: u64 = 3; + if (op == 4) { + valid = scalar; + reason = 1; + } else if (op == 5) { + valid = false; + reason = 0; + } else if (op == 6 || op == 13 || op == 15) { + valid = ir_runtime_value_type(p, inst.ty); + reason = 2; + } else if (op == 7 || op == 8) { + valid = integer || floating; + } else if (op == 9 || op == 17) { + valid = integer; + } else if (op == 10 || op == 11) { + valid = kind == 1 || integer || kind == 17 || (op == 10 && floating); + } else if (op == 12) { + valid = floating; + } else if (op == 14) { + var source: u64 = p.types[inst.other].kind; + valid = ir_verify_cast(inst.sub, source, kind); + reason = 4; + } else if (op == 16) { + valid = scalar; + reason = 2; + } else if (op == 18 || op == 23) { + valid = p.layout_nodes[inst.ty].kind != 0; + reason = 5; + if (op == 23) { + reason = 8; + } + } else if (op >= 19 && op <= 22) { + valid = ir_runtime_value_type(p, inst.ty); + reason = 6; + if (op == 20 || op == 22) { + reason = 7; + } + } + if (!valid) { + return ir_runtime_error(p, 5, site, reason, 0); + } + return true; +} + +fun ir_runtime_prepare_function(p: ptr, function: u64) -> bool { + var f: ptr = &p.functions[function]; + if (!ir_runtime_callable(p, f.signature)) { + if (p.result.status != 0) { + return false; + } + return ir_runtime_error(p, 2, 18446744073709551615, function, 0); + } + var b: u64 = f.first_block; + while (b < f.first_block + f.block_count) { + var block: ptr = &p.blocks[b]; + var i: u64 = block.first; + while (i < block.first + block.count) { + if (!ir_runtime_charge(p)) { + return false; + } + var inst: ptr = &p.instructions[i]; + if ((inst.op == 3 || inst.op == 4) && inst.dst < f.value_count) { + if ((inst.literal == 1 || inst.literal == 2) && inst.high == 0) { + p.ordinals[f.first_value_type + inst.dst] = inst.low; + } + } + i += 1; + } + b += 1; + } + b = f.first_block; + while (b < f.first_block + f.block_count) { + var block: ptr = &p.blocks[b]; + var i: u64 = block.first; + while (i < block.first + block.count) { + p.pending_site = i; + if (!ir_runtime_charge(p)) { + return false; + } + var inst: ptr = &p.instructions[i]; + if (!ir_runtime_supported(p, inst, i)) { + return false; + } + if (inst.op == 29) { + if (inst.sub != 0) { + return ir_runtime_error(p, 5, i, 9, 0); + } + if (inst.flags == 0) { + if (!ir_runtime_target(p, inst.a, i)) { + return false; + } + } else { + var signature: u64 = p.value_types[f.first_value_type + inst.a]; + if (!ir_runtime_add_indirect(p, signature, i)) { + return false; + } + } + } else if (inst.op == 28) { + if (!ir_runtime_add_callable(p, inst.a)) { + return false; + } + } else if (inst.op == 18 || inst.op == 23) { + if (!ir_runtime_layout(p, inst.ty)) { + return false; + } + inst.size = p.layouts[inst.ty].size; + inst.natural = p.layouts[inst.ty].allocation_align; + } else if (inst.op == 24) { + var selected: u64 = p.types[p.value_types[f.first_value_type + inst.a]].child; + inst.plan_first = p.plan_count; + inst.plan_count = inst.count; + var index: u64 = 0; + while (index < inst.count) { + if (!ir_runtime_charge(p) || p.plan_count >= p.plan_capacity) { + if (p.result.status == 0) { + ir_runtime_backend(p); + } + return false; + } + var plan: ptr = &p.plans[p.plan_count]; + plan.kind = 0; + if (index == 0 || p.types[selected].kind == 19) { + if (index != 0) { + selected = p.types[selected].child; + } + if (!ir_runtime_layout(p, selected)) { + return false; + } + plan.amount = p.layouts[selected].size; + if (plan.amount == 0) { + return ir_runtime_error(p, 5, i, 10, 0); + } + } else { + var ordinal: u64 = p.ordinals[f.first_value_type + + p.operands[inst.first + index]]; + if (!ir_runtime_layout(p, selected) + || ordinal >= p.types[selected].count) { + return ir_runtime_backend(p); + } + plan.kind = 1; + plan.amount = p.layout_offsets[p.types[selected].first + ordinal]; + selected = p.type_edges[p.types[selected].first + ordinal]; + } + p.plan_count += 1; + index += 1; + } + } + i += 1; + } + b += 1; + } + return true; +} + +fun ir_runtime_clear_value(value: ptr) { + value.kind = 0; + value.ty = 18446744073709551615; + value.literal = 0; + value.low = 0; + value.high = 0; + value.flag = 0; + value.pointer.address = 0; + value.pointer.present = 0; + value.pointer.arena = 0; + value.pointer.allocation = 0; + value.pointer.generation = 0; + value.pointer.lower = 0; + value.pointer.upper = 0; + value.pointer.offset = 0; + value.pointer.read = 0; + value.pointer.write = 0; + value.signature = 18446744073709551615; + value.target_kind = 0; + value.target = 0; + value.origin = 1; +} + +fun ir_runtime_literal(kind: u64) -> u64 { + if (kind == 1) { + return 3; + } + if (ir_verify_signed(kind)) { + return 1; + } + if (ir_verify_unsigned(kind)) { + return 2; + } + return kind - 10; +} + +fun ir_runtime_make_scalar(p: ptr, ty: u64, low: u64, high: u64, + value: ptr) { + ir_runtime_clear_value(value); + value.kind = 1; + value.ty = ty; + value.literal = ir_runtime_literal(p.types[ty].kind); + value.low = low; + value.high = high; +} + +fun ir_runtime_initialize(p: ptr) -> bool { + p.pending_site = 18446744073709551615; + p.pending_head = 18446744073709551615; + p.result.global = 18446744073709551615; + p.result.site = 18446744073709551615; + if (!ir_power_two(p.function_table_capacity) + || p.function_count > p.function_table_capacity / 2 + || !ir_storage_valid(p.storage) + || p.scalar_arguments > 1) { + return ir_runtime_backend(p); + } + var i: u64 = 0; + while (i < p.function_table_capacity) { + if (!ir_runtime_charge(p)) { + return false; + } + p.function_table[i] = 18446744073709551615; + i += 1; + } + i = 0; + while (i < p.function_count) { + if (!ir_runtime_charge(p)) { + return false; + } + var f: ptr = &p.functions[i]; + if (f.signature >= p.type_count || p.types[f.signature].kind != 18 + || f.first_block > p.block_count || f.block_count > p.block_count - f.first_block + || f.first_value_type > p.value_type_count + || f.value_count > p.value_type_count - f.first_value_type + || f.first_parameter > p.operand_count + || f.parameter_count > p.operand_count - f.first_parameter) { + return ir_runtime_backend(p); + } + var mask: u64 = p.function_table_capacity - 1; + var slot: u64 = ir_source_mix(f.id) & mask; + while (p.function_table[slot] != 18446744073709551615) { + if (!ir_runtime_charge(p)) { + return false; + } + if (p.functions[p.function_table[slot]].id == f.id) { + return ir_runtime_backend(p); + } + slot = (slot + 1) & mask; + } + p.function_table[slot] = i; + p.prepared[i] = 0; + p.pending_flags[i] = 0; + p.callable_flags[i] = 0; + i += 1; + } + i = 0; + while (i < p.type_count) { + if (!ir_runtime_charge(p)) { + return false; + } + var t: ptr = &p.types[i]; + var node: ptr = &p.layout_nodes[i]; + node.child = t.child; + node.first = t.first; + node.count = t.count; + node.kind = 0; + var width: u64 = ir_verify_width(t.kind); + if (t.kind == 1 || width == 1 || width == 8) { + node.kind = 1; + } else if (width == 16) { + node.kind = 2; + } else if (width == 32) { + node.kind = 3; + } else if (width == 64) { + node.kind = 4; + } else if (width == 128) { + node.kind = 5; + } else if (t.kind == 17 || t.kind == 18) { + node.kind = t.kind - 11; + node.child = i; + } else if (t.kind >= 19 && t.kind <= 21) { + node.kind = t.kind - 11; + } + i += 1; + } + i = 0; + while (i < p.value_type_count) { + if (!ir_runtime_charge(p)) { + return false; + } + p.ordinals[i] = 18446744073709551615; + i += 1; + } + p.entry = ir_runtime_find(p, p.entry_id); + if (p.result.status != 0) { + return false; + } + if (p.entry == 18446744073709551615 || p.functions[p.entry].has_body == 0) { + return ir_runtime_error(p, 1, 18446744073709551615, p.entry_id, 0); + } + var entry: ptr = &p.functions[p.entry]; + var signature: ptr = &p.types[entry.signature]; + if (p.scalar_arguments == 1) { + i = 0; + while (i < signature.count) { + if (!ir_runtime_charge(p)) { + return false; + } + var kind: u64 = p.types[p.type_edges[signature.first + i]].kind; + if (!(i == 0 && kind == 0) && !ir_runtime_scalar(kind)) { + return ir_runtime_error(p, 2, 18446744073709551615, p.entry, 0); + } + i += 1; + } + } + if (p.argument_count != entry.parameter_count) { + return ir_runtime_error(p, 3, 18446744073709551615, + entry.parameter_count, p.argument_count); + } + i = 0; + while (i < p.argument_count) { + if (!ir_runtime_charge(p)) { + return false; + } + var argument: ptr = &p.arguments[i]; + var ty: u64 = p.type_edges[signature.first + 1 + i]; + var kind: u64 = p.types[ty].kind; + var valid: bool = false; + if (argument.kind == 1) { + valid = ir_runtime_scalar(kind) + && ir_const_value_valid(kind, argument.literal, argument.low, argument.high); + } else if (argument.kind == 3) { + valid = kind == 17; + } else if (argument.kind == 4) { + valid = kind == 18 && ir_runtime_equal(p, ty, argument.signature); + if (valid && argument.target_kind == 1) { + var target: u64 = ir_runtime_find(p, argument.target); + valid = target != 18446744073709551615 && argument.origin == 1; + if (valid) { + valid = ir_runtime_equal(p, ty, p.functions[target].signature); + } + if (valid && !ir_runtime_add_callable(p, target)) { + return false; + } + } else if (argument.target_kind > 2) { + valid = false; + } + } + if (p.result.status != 0) { + return false; + } + if (valid && p.scalar_arguments == 0) { + valid = ir_runtime_equal(p, argument.ty, ty); + } + if (!valid) { + return ir_runtime_error(p, 4, 18446744073709551615, i, ty); + } + argument.ty = ty; + i += 1; + } + if (!ir_runtime_push_pending(p, p.entry)) { + return false; + } + while (p.pending_head != 18446744073709551615) { + var function: u64 = p.pending_head; + p.pending_head = p.pending_next[function]; + if (p.pending_head != 18446744073709551615) { + p.pending_previous[p.pending_head] = 18446744073709551615; + } + p.pending_flags[function] = 0; + p.prepared[function] = 1; + if (!ir_runtime_prepare_function(p, function)) { + return false; + } + } + i = 0; + while (i < p.global_count) { + if (!ir_runtime_charge(p)) { + return false; + } + p.result.global = i; + var global: ptr = &p.globals[i]; + if (!ir_runtime_call_value(p.types[global.ty].kind)) { + return ir_runtime_error(p, 17, 18446744073709551615, i, 0); + } + if (!ir_runtime_layout(p, global.ty)) { + return false; + } + global.size = p.layouts[global.ty].size; + global.natural = p.layouts[global.ty].align; + i += 1; + } + p.result.global = 18446744073709551615; + p.pending_site = 18446744073709551615; + p.phase = 1; + p.cursor = 0; + p.global_phase = 0; + return true; +} diff --git a/ir/src/const_expr.rs b/ir/src/const_expr.rs index 8e5dc6f..2b0cbf3 100644 --- a/ir/src/const_expr.rs +++ b/ir/src/const_expr.rs @@ -65,6 +65,7 @@ pub enum ConstEvalError { DuplicateDefinition(ConstRef), CyclicReference, ResultMismatch, + Backend(&'static str), } impl ConstExpr { @@ -111,6 +112,22 @@ impl ConstExpr { &self, resolve: &impl Fn(ConstRef) -> Option<(Type, ConstValue)>, limits: crate::IrLimits, + ) -> Result { + #[cfg(whale_wave_ir)] + { + crate::constant_wave::evaluate(self, resolve, limits) + } + #[cfg(not(whale_wave_ir))] + { + self.evaluate_with_error_site_reference(resolve, limits) + } + } + + #[cfg(any(not(whale_wave_ir), test))] + pub(crate) fn evaluate_with_error_site_reference( + &self, + resolve: &impl Fn(ConstRef) -> Option<(Type, ConstValue)>, + limits: crate::IrLimits, ) -> Result { let mut budget = crate::limits::Budget::new(limits) .map_err(|error| (ConstEvalError::ResourceLimit(error), self))?; @@ -122,7 +139,7 @@ impl ConstExpr { while let Some(expr) = inspect.pop() { match &expr.kind { ConstExprKind::Literal(v) => { - if !crate::constant::valid_constant(&expr.ty, v) { + if !crate::constant::valid_constant_reference(&expr.ty, v) { return Err((ConstEvalError::InvalidLiteral, expr)); } }, @@ -136,7 +153,7 @@ impl ConstExpr { if ty != expr.ty { return Err((ConstEvalError::TypeMismatch, expr)); } - if !crate::constant::valid_constant(&ty, &value) { + if !crate::constant::valid_constant_reference(&ty, &value) { return Err((ConstEvalError::InvalidLiteral, expr)); } resolved.insert(expr as *const ConstExpr, value); @@ -145,7 +162,7 @@ impl ConstExpr { if expr.ty != value.ty { return Err((ConstEvalError::TypeMismatch, expr)); } - if crate::interpreter::integer::shape(&expr.ty).is_none() + if crate::interpreter::integer::reference::shape(&expr.ty).is_none() && !matches!(expr.ty, Type::F16 | Type::F32 | Type::F64) { return Err((ConstEvalError::UnsupportedOperation, expr)); @@ -218,12 +235,14 @@ impl ConstExpr { continue; }, ConstExprKind::Neg(_) => match values.pop().expect("neg operand") { - ConstValue::F(value) => ConstValue::F(crate::float::arithmetic::negate(value)), - value => crate::interpreter::integer::pack( + ConstValue::F(value) => { + ConstValue::F(crate::float::arithmetic::reference::negate(value)) + }, + value => crate::interpreter::integer::reference::pack( &expr.ty, - 0u128.wrapping_sub(crate::interpreter::integer::raw( + 0u128.wrapping_sub(crate::interpreter::integer::reference::raw( &value, - crate::interpreter::integer::shape(&expr.ty).unwrap().0, + crate::interpreter::integer::reference::shape(&expr.ty).unwrap().0, )), ), }, @@ -276,7 +295,7 @@ impl ConstExpr { ) }, }; - if !crate::constant::valid_constant(&expr.ty, &value) { + if !crate::constant::valid_constant_reference(&expr.ty, &value) { return Err((ConstEvalError::InvalidLiteral, expr)); } values.push(value); @@ -285,6 +304,7 @@ impl ConstExpr { } } +#[cfg(any(not(whale_wave_ir), test))] pub(crate) fn same_value(left: &ConstValue, right: &ConstValue) -> bool { match (left, right) { // Compare the stored payload, including signed zero and NaN bits. @@ -294,6 +314,7 @@ pub(crate) fn same_value(left: &ConstValue, right: &ConstValue) -> bool { } // Preserve the existing scalar constant evaluation rules. +#[cfg(any(not(whale_wave_ir), test))] fn ty_int_bits(ty: &Type) -> Option { Some(match ty { Type::I1 | Type::U1 => 1, @@ -306,10 +327,12 @@ fn ty_int_bits(ty: &Type) -> Option { }) } +#[cfg(any(not(whale_wave_ir), test))] fn is_signed_int(ty: &Type) -> bool { matches!(ty, Type::I1 | Type::I8 | Type::I16 | Type::I32 | Type::I64 | Type::I128) } +#[cfg(any(not(whale_wave_ir), test))] fn wrap_u(v: u128, ty: &Type) -> u128 { let bits = ty_int_bits(ty).unwrap_or(128); if bits >= 128 { @@ -319,6 +342,7 @@ fn wrap_u(v: u128, ty: &Type) -> u128 { v & mask } +#[cfg(any(not(whale_wave_ir), test))] fn wrap_i(v: i128, ty: &Type) -> i128 { let bits = ty_int_bits(ty).unwrap_or(128); if bits >= 128 { @@ -335,11 +359,13 @@ fn wrap_i(v: i128, ty: &Type) -> i128 { } } +#[cfg(any(not(whale_wave_ir), test))] fn shift_count(ty: &Type, raw: u128) -> u32 { let bits = ty_int_bits(ty).expect("integer expression validated"); (wrap_u(raw, ty) % u128::from(bits)) as u32 } +#[cfg(any(not(whale_wave_ir), test))] fn const_not(ty: &Type, value: &ConstValue) -> Result { match value { ConstValue::I(v) if is_signed_int(ty) => Ok(ConstValue::I(wrap_i(!v, ty))), @@ -348,6 +374,7 @@ fn const_not(ty: &Type, value: &ConstValue) -> Result crate::BinOp::FRem, _ => return Err(ConstEvalError::UnsupportedOperation), }; - let value = crate::float::arithmetic::arithmetic(&op, *a, *b).unwrap(); + let value = crate::float::arithmetic::reference::arithmetic(&op, *a, *b).unwrap(); return Ok(ConstValue::F(value)); } @@ -419,6 +446,7 @@ fn const_bin( Err(ConstEvalError::UnsupportedOperation) } +#[cfg(any(not(whale_wave_ir), test))] fn const_cmp( op: ConstCompareOp, ty: &Type, @@ -439,7 +467,7 @@ fn const_cmp( ConstCompareOp::Ge => crate::CmpOp::FGe, }; return a - .compare(*b, &generic.float_predicate().unwrap()) + .compare_reference(*b, &generic.float_predicate().unwrap()) .ok_or(ConstEvalError::TypeMismatch); } @@ -486,3 +514,175 @@ fn const_cmp( Err(ConstEvalError::UnsupportedOperation) } + +#[cfg(all(test, whale_wave_ir))] +mod wave_tests { + use super::*; + + use std::cell::RefCell; + + fn next(seed: &mut u64) -> u64 { + *seed ^= *seed << 13; + *seed ^= *seed >> 7; + *seed ^= *seed << 17; + *seed + } + + fn literal(ty: &Type, seed: &mut u64) -> ConstExpr { + let bits = u128::from(next(seed)) | (u128::from(next(seed)) << 64); + let value = match ty { + Type::Bool => ConstValue::Bool(bits & 1 != 0), + Type::F16 => ConstValue::F(crate::FloatBits::F16(bits as u16)), + Type::F32 => ConstValue::F(crate::FloatBits::F32(bits as u32)), + Type::F64 => ConstValue::F(crate::FloatBits::F64(bits as u64)), + _ => crate::interpreter::integer::reference::pack(ty, bits), + }; + ConstExpr::literal(ty.clone(), value) + } + + fn tree(ty: &Type, seed: &mut u64, depth: usize) -> ConstExpr { + if depth == 0 || next(seed) % 4 == 0 { + return literal(ty, seed); + } + if next(seed) % 10 == 0 { + return ConstExpr { + ty: ty.clone(), + kind: ConstExprKind::Reference(ConstRef::Global(GlobalId((next(seed) % 5) as u32))), + }; + } + let kind = if *ty == Type::Bool { + ConstExprKind::Binary { + op: if next(seed) & 1 == 0 { + ConstBinaryOp::LogicalAnd + } else { + ConstBinaryOp::LogicalOr + }, + left: Box::new(tree(ty, seed, depth - 1)), + right: Box::new(tree(ty, seed, depth - 1)), + } + } else if next(seed) % 5 == 0 { + if next(seed) & 1 == 0 { + ConstExprKind::Neg(Box::new(tree(ty, seed, depth - 1))) + } else { + ConstExprKind::Not(Box::new(tree(ty, seed, depth - 1))) + } + } else { + let op = match next(seed) % 10 { + 0 => ConstBinaryOp::Add, + 1 => ConstBinaryOp::Sub, + 2 => ConstBinaryOp::Mul, + 3 => ConstBinaryOp::BitAnd, + 4 => ConstBinaryOp::BitOr, + 5 => ConstBinaryOp::BitXor, + 6 => ConstBinaryOp::Div, + 7 => ConstBinaryOp::Rem, + 8 => ConstBinaryOp::ShiftLeft, + _ => ConstBinaryOp::ShiftRight, + }; + ConstExprKind::Binary { + op, + left: Box::new(tree(ty, seed, depth - 1)), + right: Box::new(tree(ty, seed, depth - 1)), + } + }; + ConstExpr { ty: ty.clone(), kind } + } + + fn compare(expression: &ConstExpr) { + let seen = RefCell::new(Vec::new()); + let resolve = |reference| { + seen.borrow_mut().push(reference); + match reference { + ConstRef::Global(GlobalId(0)) => Some((Type::I32, ConstValue::I(7))), + ConstRef::Global(GlobalId(1)) => Some((Type::I32, ConstValue::I(0))), + ConstRef::Global(GlobalId(2)) => Some((Type::U128, ConstValue::U(u128::MAX))), + ConstRef::Global(GlobalId(3)) => Some((Type::Bool, ConstValue::Bool(true))), + _ => None, + } + }; + let expected = + expression.evaluate_with_error_site_reference(&resolve, crate::IrLimits::default()); + let expected_calls = seen.replace(Vec::new()); + let actual = expression.evaluate_with_error_site(&resolve, crate::IrLimits::default()); + assert_eq!(*seen.borrow(), expected_calls, "reference order {expression:?}"); + match (actual, expected) { + (Ok(actual), Ok(expected)) => assert_eq!(actual, expected, "{expression:?}"), + (Err((actual, site)), Err((expected, expected_site))) => { + assert_eq!(actual, expected, "{expression:?}"); + assert!(std::ptr::eq(site, expected_site), "error site {expression:?}"); + }, + (actual, expected) => { + panic!("constant divergence {expression:?}: {actual:?} / {expected:?}") + }, + } + } + + #[test] + fn wave_constants_match_independent_reference_values_errors_sites_and_resolver_order() { + let types = [ + Type::Bool, + Type::I1, + Type::U1, + Type::I8, + Type::U8, + Type::I16, + Type::U16, + Type::I32, + Type::U32, + Type::I64, + Type::U64, + Type::I128, + Type::U128, + Type::F16, + Type::F32, + Type::F64, + ]; + let mut seed = 0x0003_5235_3558_u64; + for _ in 0..4000 { + let ty = &types[next(&mut seed) as usize % types.len()]; + let mut expression = tree(ty, &mut seed, 5); + if next(&mut seed) % 3 == 0 { + let op = match next(&mut seed) % 6 { + 0 => ConstCompareOp::Eq, + 1 => ConstCompareOp::Ne, + 2 => ConstCompareOp::Lt, + 3 => ConstCompareOp::Le, + 4 => ConstCompareOp::Gt, + _ => ConstCompareOp::Ge, + }; + expression = ConstExpr { + ty: Type::Bool, + kind: ConstExprKind::Compare { + op, + left: Box::new(expression), + right: Box::new(tree(ty, &mut seed, 3)), + }, + }; + } + compare(&expression); + } + for expression in [ + ConstExpr::literal(Type::I1, ConstValue::I(1)), + ConstExpr::literal(Type::U8, ConstValue::U(256)), + ConstExpr::literal(Type::Bool, ConstValue::U(1)), + ConstExpr::literal(Type::F32, ConstValue::F(crate::FloatBits::F64(0))), + ] { + compare(&expression); + } + } + + #[test] + fn constant_work_is_bounded_even_when_validation_would_skip_a_branch() { + let expression = ConstExpr::literal(Type::I32, ConstValue::I(7)); + assert!(matches!( + expression.evaluate_with_limits( + &|_| None, + crate::IrLimits { max_analysis_work: 0, ..Default::default() } + ), + Err(ConstEvalError::ResourceLimit(crate::LimitError { + resource: crate::Resource::AnalysisWork, + .. + })) + )); + } +} diff --git a/ir/src/constant.rs b/ir/src/constant.rs index 1676bff..442e4ee 100644 --- a/ir/src/constant.rs +++ b/ir/src/constant.rs @@ -5,6 +5,18 @@ use crate::{ConstValue, Type}; /// Check a literal's category and range without rounding or wrapping its value. /// Floating payload widths must match the declared type. pub(crate) fn valid_constant(ty: &Type, value: &ConstValue) -> bool { + #[cfg(whale_wave_ir)] + { + crate::constant_wave::valid_literal(ty, value) + } + #[cfg(not(whale_wave_ir))] + { + valid_constant_reference(ty, value) + } +} + +#[cfg(any(not(whale_wave_ir), test))] +pub(crate) fn valid_constant_reference(ty: &Type, value: &ConstValue) -> bool { use Type::*; match (ty, value) { (Bool, ConstValue::Bool(_)) => true, diff --git a/ir/src/constant_wave.rs b/ir/src/constant_wave.rs new file mode 100644 index 0000000..024830e --- /dev/null +++ b/ir/src/constant_wave.rs @@ -0,0 +1,377 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Borrowed typed expression packets and resumable reference-value transport. +use crate::verifier::wave_semantics::{Input as Types, Node as TypeNode}; + +use crate::{ + ConstEvalError, ConstExpr, ConstExprKind, ConstRef, ConstValue, FloatBits, IrLimits, + LimitError, Resource, Type, +}; + +#[repr(C)] +#[derive(Clone, Copy, Default)] +pub(crate) struct Node { + pub(crate) kind: u64, + pub(crate) op: u64, + pub(crate) ty: u64, + pub(crate) left: u64, + pub(crate) right: u64, + pub(crate) reference: u64, + pub(crate) literal: u64, + pub(crate) low: u64, + pub(crate) high: u64, +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct Resolved { + ty: u64, + literal: u64, + low: u64, + high: u64, + present: u64, +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct Value { + literal: u64, + low: u64, + high: u64, + present: u64, +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct Frame { + node: u64, + phase: u64, + depth: u64, +} + +#[repr(C)] +#[derive(Default)] +struct State { + initialized: u64, + phase: u64, + length: u64, + checked_types: u64, + work: u64, + root: u64, +} + +#[repr(C)] +struct Context { + nodes: *const Node, + node_count: u64, + types: *const TypeNode, + type_count: u64, + edges: *const u64, + edge_count: u64, + resolved: *mut Resolved, + resolved_count: u64, + values: *mut Value, + value_count: u64, + frames: *mut Frame, + capacity: u64, + state: *mut State, + root: u64, + max_depth: u64, + max_work: u64, +} + +#[repr(C)] +#[derive(Default)] +struct ResultRecord { + status: u64, + index: u64, + detail: u64, + literal: u64, + low: u64, + high: u64, + work: u64, +} + +unsafe extern "C" { + fn whale_ir_const_literal(kind: u64, literal: u64, low: u64, high: u64) -> i32; + + fn whale_ir_const_step(context: *mut Context, result: *mut ResultRecord) -> i32; +} + +pub(crate) struct Wire<'a> { + pub(crate) types: Types, + pub(crate) nodes: Vec, + pub(crate) sources: Vec<&'a ConstExpr>, + limits: IrLimits, +} + +impl<'a> Wire<'a> { + pub(crate) fn new(limits: IrLimits) -> Self { + Self { types: Types::default(), nodes: Vec::new(), sources: Vec::new(), limits } + } + + pub(crate) fn expression(&mut self, expr: &'a ConstExpr) -> Result { + let mut node = Node { ty: self.types.ty(&expr.ty), ..Node::default() }; + match &expr.kind { + ConstExprKind::Literal(value) => { + let (tag, low, high) = payload(value); + node.literal = tag; + node.low = low; + node.high = high; + }, + ConstExprKind::Reference(reference) => match reference { + ConstRef::Global(id) => { + node.kind = 1; + node.reference = id.0.into(); + }, + ConstRef::Local(id) => { + node.kind = 2; + node.reference = id.0.into(); + }, + }, + ConstExprKind::Not(child) => { + node.kind = 3; + node.left = self.expression(child)?; + }, + ConstExprKind::Neg(child) => { + node.kind = 4; + node.left = self.expression(child)?; + }, + ConstExprKind::Binary { op, left, right } => { + node.kind = 5; + node.op = match op { + crate::ConstBinaryOp::Add => 0, + crate::ConstBinaryOp::Sub => 1, + crate::ConstBinaryOp::Mul => 2, + crate::ConstBinaryOp::BitAnd => 3, + crate::ConstBinaryOp::BitOr => 4, + crate::ConstBinaryOp::BitXor => 5, + crate::ConstBinaryOp::Div => 6, + crate::ConstBinaryOp::Rem => 7, + crate::ConstBinaryOp::ShiftLeft => 8, + crate::ConstBinaryOp::ShiftRight => 9, + crate::ConstBinaryOp::LogicalAnd => 10, + crate::ConstBinaryOp::LogicalOr => 11, + }; + node.left = self.expression(left)?; + node.right = self.expression(right)?; + }, + ConstExprKind::Compare { op, left, right } => { + node.kind = 6; + node.op = match op { + crate::ConstCompareOp::Eq => 0, + crate::ConstCompareOp::Ne => 1, + crate::ConstCompareOp::Lt => 2, + crate::ConstCompareOp::Le => 3, + crate::ConstCompareOp::Gt => 4, + crate::ConstCompareOp::Ge => 5, + }; + node.left = self.expression(left)?; + node.right = self.expression(right)?; + }, + } + self.nodes + .try_reserve(1) + .map_err(|_| self.resource(Resource::Nodes, self.limits.max_nodes))?; + self.sources + .try_reserve(1) + .map_err(|_| self.resource(Resource::Nodes, self.limits.max_nodes))?; + let id = self.nodes.len() as u64; + self.nodes.push(node); + self.sources.push(expr); + Ok(id) + } + + fn resource(&self, resource: Resource, limit: usize) -> ConstEvalError { + ConstEvalError::ResourceLimit(LimitError { resource, limit }) + } +} + +pub(crate) fn payload(value: &ConstValue) -> (u64, u64, u64) { + let (tag, bits) = match value { + ConstValue::I(v) => (1, *v as u128), + ConstValue::U(v) => (2, *v), + ConstValue::Bool(v) => (3, u128::from(*v)), + ConstValue::F(FloatBits::F16(v)) => (4, u128::from(*v)), + ConstValue::F(FloatBits::F32(v)) => (5, u128::from(*v)), + ConstValue::F(FloatBits::F64(v)) => (6, u128::from(*v)), + }; + (tag, bits as u64, (bits >> 64) as u64) +} + +fn decode(tag: u64, low: u64, high: u64, ty: &Type) -> Option { + let bits = u128::from(low) | (u128::from(high) << 64); + let value = match tag { + 1 => ConstValue::I(bits as i128), + 2 => ConstValue::U(bits), + 3 if low <= 1 && high == 0 => ConstValue::Bool(low != 0), + 4 if low <= u16::MAX.into() && high == 0 => ConstValue::F(FloatBits::F16(low as u16)), + 5 if low <= u32::MAX.into() && high == 0 => ConstValue::F(FloatBits::F32(low as u32)), + 6 if high == 0 => ConstValue::F(FloatBits::F64(low)), + _ => return None, + }; + crate::constant::valid_constant(ty, &value).then_some(value) +} + +fn allocate(count: usize, limits: IrLimits) -> Result, ConstEvalError> { + let mut values = Vec::new(); + values.try_reserve_exact(count).map_err(|_| { + ConstEvalError::ResourceLimit(LimitError { + resource: Resource::Nodes, + limit: limits.max_nodes, + }) + })?; + values.resize(count, T::default()); + Ok(values) +} + +fn backend() -> ConstEvalError { + ConstEvalError::Backend("constant expression transport") +} + +pub(crate) fn evaluate<'e>( + expr: &'e ConstExpr, + resolve: &impl Fn(ConstRef) -> Option<(Type, ConstValue)>, + limits: IrLimits, +) -> Result { + let mut budget = + crate::limits::Budget::new(limits).map_err(|e| (ConstEvalError::ResourceLimit(e), expr))?; + budget.expression(expr).map_err(|e| (ConstEvalError::ResourceLimit(e), expr))?; + let mut wire = Wire::new(limits); + let root = wire.expression(expr).map_err(|e| (e, expr))?; + let count = wire.nodes.len(); + let mut resolved = allocate::(count, limits).map_err(|e| (e, expr))?; + let mut values = allocate::(count, limits).map_err(|e| (e, expr))?; + let capacity = limits.max_const_depth.saturating_mul(2).saturating_add(3); + let mut frames = allocate::(capacity, limits).map_err(|e| (e, expr))?; + let mut state = State::default(); + let mut previous_work = 0; + loop { + let mut context = Context { + nodes: wire.nodes.as_ptr(), + node_count: count as u64, + types: wire.types.nodes.as_ptr(), + type_count: wire.types.nodes.len() as u64, + edges: wire.types.edges.as_ptr(), + edge_count: wire.types.edges.len() as u64, + resolved: resolved.as_mut_ptr(), + resolved_count: count as u64, + values: values.as_mut_ptr(), + value_count: count as u64, + frames: frames.as_mut_ptr(), + capacity: capacity as u64, + state: &mut state, + root, + max_depth: limits.max_const_depth as u64, + max_work: limits.max_analysis_work as u64, + }; + let mut result = ResultRecord::default(); + let status = unsafe { whale_ir_const_step(&mut context, &mut result) }; + if i32::try_from(result.status).ok() != Some(status) + || result.work > limits.max_analysis_work as u64 + || result.work < previous_work + || state.work != result.work + || state.length > capacity as u64 + { + return Err((backend(), expr)); + } + previous_work = result.work; + let index = usize::try_from(result.index).map_err(|_| (backend(), expr))?; + let failed = *wire.sources.get(index).ok_or_else(|| (backend(), expr))?; + let resource = |resource, limit| { + (ConstEvalError::ResourceLimit(LimitError { resource, limit }), failed) + }; + match status { + 0 => { + if result.index != root || state.phase != 2 || state.length != 0 { + return Err((backend(), expr)); + } + return decode(result.literal, result.low, result.high, &expr.ty) + .ok_or_else(|| (backend(), expr)); + }, + 10 => { + let node = wire.nodes.get(index).ok_or_else(|| (backend(), expr))?; + if !matches!(node.kind, 1 | 2) + || node.reference != result.detail + || resolved[index].present != 0 + { + return Err((backend(), expr)); + } + let reference = match failed.kind { + ConstExprKind::Reference(reference) => reference, + _ => return Err((backend(), expr)), + }; + match resolve(reference) { + None => resolved[index].present = 2, + Some((ty, value)) => { + if let Err(e) = budget.ty(&ty) { + crate::limits::discard_type(ty); + return Err((ConstEvalError::ResourceLimit(e), failed)); + } + let type_id = wire.types.ty(&ty); + let (literal, low, high) = payload(&value); + resolved[index] = Resolved { ty: type_id, literal, low, high, present: 1 }; + }, + } + }, + 1 => return Err((ConstEvalError::InvalidLiteral, failed)), + 2 => return Err((ConstEvalError::TypeMismatch, failed)), + 3 => return Err((ConstEvalError::UnsupportedOperation, failed)), + 4 => return Err((ConstEvalError::DivisionByZero, failed)), + 5 => return Err((ConstEvalError::RemainderByZero, failed)), + 6 => { + return Err(( + match failed.kind { + ConstExprKind::Reference(reference) => { + ConstEvalError::UnknownReference(reference) + }, + _ => backend(), + }, + failed, + )) + }, + 7 => { + return Err(if result.detail == 0 { + resource(Resource::AnalysisWork, limits.max_analysis_work) + } else if result.detail == 1 { + resource(Resource::ConstantDepth, limits.max_const_depth) + } else { + (backend(), expr) + }) + }, + _ => return Err((backend(), expr)), + } + } +} + +pub(crate) fn valid_literal(ty: &Type, value: &ConstValue) -> bool { + let kind = match ty { + Type::Void => 0, + Type::Bool => 1, + Type::I1 => 2, + Type::U1 => 3, + Type::I8 => 4, + Type::I16 => 5, + Type::I32 => 6, + Type::I64 => 7, + Type::I128 => 8, + Type::U8 => 9, + Type::U16 => 10, + Type::U32 => 11, + Type::U64 => 12, + Type::U128 => 13, + Type::F16 => 14, + Type::F32 => 15, + Type::F64 => 16, + Type::Ptr(_) => 17, + Type::FnPtr(_) => 18, + Type::Array(..) => 19, + Type::Struct(_) => 20, + Type::Tuple(_) => 21, + }; + let (tag, low, high) = payload(value); + match unsafe { whale_ir_const_literal(kind, tag, low, high) } { + 0 => false, + 1 => true, + _ => panic!("Wave literal validation transport"), + } +} diff --git a/ir/src/diagnostic.rs b/ir/src/diagnostic.rs index 99cc4b9..8f12d24 100644 --- a/ir/src/diagnostic.rs +++ b/ir/src/diagnostic.rs @@ -104,6 +104,7 @@ impl ToDiagnostic for InterpreterError { let code = match self.root_cause() { Self::Diagnostic { .. } => "ir.run.diagnostic", Self::Verification(..) => "ir.run.verification", + Self::Backend { .. } => "ir.run.backend", Self::UnknownFunction(..) => "ir.run.unknown-function", Self::UnsupportedGlobal(..) => "ir.run.unsupported-global", Self::GlobalMemory { .. } => "ir.run.global-memory", @@ -119,6 +120,7 @@ impl ToDiagnostic for InterpreterError { }; let mut d = Diagnostic::new("ir", "run", code, self.to_string()); let site = match self.root_cause() { + Self::Backend { site, .. } => *site, Self::UnsupportedInstruction { site, .. } | Self::StepLimit { site, .. } | Self::MemoryLimit { site, .. } diff --git a/ir/src/effects.rs b/ir/src/effects.rs index 9a58a1e..d438a52 100644 --- a/ir/src/effects.rs +++ b/ir/src/effects.rs @@ -1,6 +1,9 @@ // SPDX-License-Identifier: MPL-2.0 //! Conservative observable-effect classification, independent of optimizer policy. -use crate::{BinOp, CastOp, Instruction, Terminator, Type}; +#[cfg(any(not(whale_wave_ir), test))] +use crate::{BinOp, CastOp, Type}; + +use crate::{Instruction, Terminator}; #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct Effects { @@ -16,12 +19,31 @@ impl Effects { /// Necessary, never sufficient, for deleting an unused instruction. A pass /// must also prove no SSA/source/CFG identity or required observation is lost. pub fn permits_unused_removal(self) -> bool { - self == Self::default() + #[cfg(whale_wave_ir)] + { + crate::effects_wave::removable(self).expect("Wave effect classification") + } + #[cfg(not(whale_wave_ir))] + { + self == Self::default() + } } } impl Instruction { pub fn effects(&self) -> Effects { + #[cfg(whale_wave_ir)] + { + crate::effects_wave::instruction(self).expect("Wave instruction effects") + } + #[cfg(not(whale_wave_ir))] + { + self.effects_reference() + } + } + + #[cfg(any(not(whale_wave_ir), test))] + pub(crate) fn effects_reference(&self) -> Effects { use Instruction::*; let mut e = Effects::default(); match self { @@ -90,6 +112,157 @@ impl Instruction { impl Terminator { pub fn effects(&self) -> Effects { + #[cfg(whale_wave_ir)] + { + crate::effects_wave::terminator(self).expect("Wave terminator effects") + } + #[cfg(not(whale_wave_ir))] + { + self.effects_reference() + } + } + + #[cfg(any(not(whale_wave_ir), test))] + pub(crate) fn effects_reference(&self) -> Effects { Effects { may_trap: matches!(self, Self::Trap { .. }), ..Effects::default() } } } + +#[cfg(test)] +mod tests { + use super::*; + + use crate::{ + BlockId, Callee, CallingConvention, ConstExpr, ConstValue, FunctionId, FunctionSignature, + GlobalId, ValueId, + }; + + #[test] + fn all_instruction_and_terminator_effects_match_the_independent_inventory() { + use Instruction::*; + let id = ValueId(0); + let ty = Type::I32; + let signature = FunctionSignature::whale(vec![], Type::Void); + let mut instructions = vec![ + GlobalAddr { dst: id, global: GlobalId(0), ty: ty.clone() }, + LifetimeEnd { ptr: id }, + PtrDiff { dst: id, lhs: id, rhs: id }, + ConstDecl { + dst: id, + name: "x".into(), + expression: ConstExpr::literal(ty.clone(), ConstValue::I(0)), + value: ConstValue::I(0), + }, + Const { dst: id, ty: ty.clone(), value: ConstValue::I(0) }, + Undef { dst: id, ty: ty.clone() }, + Mov { dst: id, ty: ty.clone(), src: id }, + Neg { dst: id, ty: ty.clone(), src: id }, + Not { dst: id, ty: ty.clone(), src: id }, + Cmp { dst: id, op: crate::CmpOp::Eq, ty: ty.clone(), lhs: id, rhs: id }, + ICmp { dst: id, pred: crate::ICmpPred::Eq, ty: ty.clone(), lhs: id, rhs: id }, + FCmp { dst: id, pred: crate::FCmpPred::Oeq, ty: Type::F32, lhs: id, rhs: id }, + Select { dst: id, ty: ty.clone(), cond: id, on_true: id, on_false: id }, + Phi { dst: id, ty: ty.clone(), incomings: vec![(id, BlockId(0))] }, + Extract { dst: id, dst_ty: ty.clone(), tuple: id, index: 0 }, + Checked { dst: id, op: crate::CheckedOp::UAdd, ty: ty.clone(), lhs: id, rhs: id }, + Alloca { dst: id, ty: ty.clone(), align: 4 }, + VolatileLoad { dst: id, ty: ty.clone(), ptr: id, align: 4 }, + VolatileStore { ty: ty.clone(), value: id, ptr: id, align: 4 }, + Load { dst: id, ty: ty.clone(), ptr: id, align: 4 }, + Store { ty: ty.clone(), value: id, ptr: id, align: 4 }, + Uninit { ty: ty.clone(), ptr: id, align: 4 }, + Gep { + dst: id, + dst_ty: Type::Ptr(Box::new(ty.clone())), + base_ptr: id, + indices: vec![id], + }, + Memcpy { dst: id, src: id, n: id, align: 4 }, + Memset { dst: id, val: id, n: id, align: 4 }, + NullFunction { dst: id, signature: signature.clone() }, + FunctionAddr { dst: id, function: FunctionId(0), signature }, + Call { + convention: CallingConvention::Whale, + dst: None, + ret_ty: Type::Void, + callee: Callee::Direct(FunctionId(0)), + args: vec![], + }, + TrapIf { cond: id, reason: "test".into() }, + ]; + for op in [ + BinOp::Add, + BinOp::Sub, + BinOp::Mul, + BinOp::UDiv, + BinOp::SDiv, + BinOp::URem, + BinOp::SRem, + BinOp::FAdd, + BinOp::FSub, + BinOp::FMul, + BinOp::FDiv, + BinOp::FRem, + BinOp::And, + BinOp::Or, + BinOp::Xor, + BinOp::Shl, + BinOp::LShr, + BinOp::AShr, + ] { + instructions.push(Bin { dst: id, op, ty: ty.clone(), lhs: id, rhs: id }); + } + for op in [ + CastOp::CheckedInt, + CastOp::ZExt, + CastOp::SExt, + CastOp::Trunc, + CastOp::FExt, + CastOp::FTrunc, + CastOp::IToF_S, + CastOp::IToF_U, + CastOp::FToI_S, + CastOp::FToI_U, + CastOp::Bitcast, + CastOp::PtrToInt, + CastOp::IntToPtr, + ] { + instructions.push(Cast { + dst: id, + op, + dst_ty: ty.clone(), + src_ty: ty.clone(), + src: id, + }); + } + let pointer = Type::Ptr(Box::new(Type::I32)); + instructions.push(Cmp { + dst: id, + op: crate::CmpOp::Eq, + ty: pointer.clone(), + lhs: id, + rhs: id, + }); + instructions.push(ICmp { + dst: id, + pred: crate::ICmpPred::Eq, + ty: pointer, + lhs: id, + rhs: id, + }); + for instruction in instructions { + let expected = instruction.effects_reference(); + assert_eq!(instruction.effects(), expected, "{instruction:?}"); + assert_eq!(expected.permits_unused_removal(), expected == Effects::default()); + } + for terminator in [ + Terminator::Br { target: BlockId(0) }, + Terminator::CBr { cond: id, then_bb: BlockId(0), else_bb: BlockId(1) }, + Terminator::Switch { ty, value: id, default_bb: BlockId(0), cases: vec![] }, + Terminator::Ret { ty: Type::Void, value: None }, + Terminator::Trap { reason: "test".into() }, + ] { + assert_eq!(terminator.effects(), terminator.effects_reference()); + } + } +} diff --git a/ir/src/effects_wave.rs b/ir/src/effects_wave.rs new file mode 100644 index 0000000..338b846 --- /dev/null +++ b/ir/src/effects_wave.rs @@ -0,0 +1,140 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Enum/data transport for the Wave effect classifier. +use super::effects::Effects; + +use crate::{BinOp, CastOp, Instruction, Terminator, Type}; + +unsafe extern "C" { + fn whale_ir_effects(op: u64, sub: u64, pointer: u64, terminator: u64, output: *mut u64) -> i32; + + fn whale_ir_effects_removable(mask: u64) -> i32; +} + +fn decode(mask: u64) -> Option { + (mask <= 63).then_some(Effects { + reads_memory: mask & 1 != 0, + writes_memory: mask & 2 != 0, + volatile: mask & 4 != 0, + calls: mask & 8 != 0, + may_trap: mask & 16 != 0, + changes_lifetime: mask & 32 != 0, + }) +} + +pub(crate) fn removable(e: Effects) -> Result { + let mask = u64::from(e.reads_memory) + | (u64::from(e.writes_memory) << 1) + | (u64::from(e.volatile) << 2) + | (u64::from(e.calls) << 3) + | (u64::from(e.may_trap) << 4) + | (u64::from(e.changes_lifetime) << 5); + match unsafe { whale_ir_effects_removable(mask) } { + 0 => Ok(false), + 1 => Ok(true), + _ => Err("effect classification transport"), + } +} + +pub(crate) fn instruction(i: &Instruction) -> Result { + use Instruction::*; + let op = match i { + GlobalAddr { .. } => 0, + LifetimeEnd { .. } => 1, + PtrDiff { .. } => 2, + ConstDecl { .. } => 3, + Const { .. } => 4, + Undef { .. } => 5, + Mov { .. } => 6, + Bin { .. } => 7, + Neg { .. } => 8, + Not { .. } => 9, + Cmp { .. } => 10, + ICmp { .. } => 11, + FCmp { .. } => 12, + Select { .. } => 13, + Cast { .. } => 14, + Phi { .. } => 15, + Extract { .. } => 16, + Checked { .. } => 17, + Alloca { .. } => 18, + VolatileLoad { .. } => 19, + VolatileStore { .. } => 20, + Load { .. } => 21, + Store { .. } => 22, + Uninit { .. } => 23, + Gep { .. } => 24, + Memcpy { .. } => 25, + Memset { .. } => 26, + NullFunction { .. } => 27, + FunctionAddr { .. } => 28, + Call { .. } => 29, + TrapIf { .. } => 30, + }; + let sub = match i { + Bin { op, .. } => match op { + BinOp::Add => 0, + BinOp::Sub => 1, + BinOp::Mul => 2, + BinOp::UDiv => 3, + BinOp::SDiv => 4, + BinOp::URem => 5, + BinOp::SRem => 6, + BinOp::FAdd => 7, + BinOp::FSub => 8, + BinOp::FMul => 9, + BinOp::FDiv => 10, + BinOp::FRem => 11, + BinOp::And => 12, + BinOp::Or => 13, + BinOp::Xor => 14, + BinOp::Shl => 15, + BinOp::LShr => 16, + BinOp::AShr => 17, + }, + Cast { op, .. } => match op { + CastOp::CheckedInt => 0, + CastOp::ZExt => 1, + CastOp::SExt => 2, + CastOp::Trunc => 3, + CastOp::FExt => 4, + CastOp::FTrunc => 5, + CastOp::IToF_S => 6, + CastOp::IToF_U => 7, + CastOp::FToI_S => 8, + CastOp::FToI_U => 9, + CastOp::Bitcast => 10, + CastOp::PtrToInt => 11, + CastOp::IntToPtr => 12, + }, + _ => 0, + }; + let pointer = match i { + Cmp { ty: Type::Ptr(_), .. } | ICmp { ty: Type::Ptr(_), .. } => 1, + _ => 0, + }; + run(op, sub, pointer, 0) +} + +pub(crate) fn terminator(t: &Terminator) -> Result { + run( + match t { + Terminator::Br { .. } => 0, + Terminator::CBr { .. } => 1, + Terminator::Switch { .. } => 2, + Terminator::Ret { .. } => 3, + Terminator::Trap { .. } => 4, + }, + 0, + 0, + 1, + ) +} + +fn run(op: u64, sub: u64, pointer: u64, terminator: u64) -> Result { + let mut mask = u64::MAX; + let status = unsafe { whale_ir_effects(op, sub, pointer, terminator, &mut mask) }; + if status != 0 { + return Err("effect classification transport"); + } + decode(mask).ok_or("effect classification transport") +} diff --git a/ir/src/float.rs b/ir/src/float.rs index bd37255..be03035 100644 --- a/ir/src/float.rs +++ b/ir/src/float.rs @@ -2,6 +2,22 @@ pub mod arithmetic; +#[cfg(whale_wave_ir)] +#[path = "float/wave.rs"] +mod wave; + +/// A malformed native response is distinct from a defined invalid conversion. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct FloatBackendError(pub &'static str); + +impl std::fmt::Display for FloatBackendError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "Wave float backend error: {}", self.0) + } +} + +impl std::error::Error for FloatBackendError {} + /// Exact IEEE storage bits. Equality compares storage, including NaN payloads. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum FloatBits { @@ -27,11 +43,84 @@ impl FloatBits { } } + /// Compare equal-width IEEE values; unsupported width pairs return `None`. + pub fn try_compare( + self, + rhs: Self, + predicate: &crate::FCmpPred, + ) -> Result, FloatBackendError> { + #[cfg(whale_wave_ir)] + { + wave::compare(self, rhs, predicate) + } + #[cfg(not(whale_wave_ir))] + { + Ok(self.compare_reference(rhs, predicate)) + } + } + + /// Compare storage through the explicit ordered/unordered predicate. + pub fn compare(self, rhs: Self, predicate: &crate::FCmpPred) -> Option { + self.try_compare(rhs, predicate).expect("Wave float comparison backend invariant") + } + + /// Read exact-width hexadecimal storage bits. + pub fn parse(width: u16, text: &str) -> Result { + #[cfg(whale_wave_ir)] + { + wave::parse(width, text) + } + #[cfg(not(whale_wave_ir))] + { + Self::parse_reference(width, text) + } + } + + /// Numeric conversion with explicit backend errors; unsupported widths return `None`. + pub fn try_from_f64(width: u16, value: f64) -> Result, FloatBackendError> { + if !matches!(width, 16 | 32 | 64) { + return Ok(None); + } + #[cfg(whale_wave_ir)] + { + wave::from_f64(width, value.to_bits()).map(Some) + } + #[cfg(not(whale_wave_ir))] + { + Ok(Self::from_f64_reference(width, value).ok()) + } + } + + /// Numeric convenience conversion. Use variants to preserve source storage bits. + pub fn from_f64(width: u16, value: f64) -> Result { + Self::try_from_f64(width, value) + .map_err(|e| e.to_string())? + .ok_or_else(|| "float width must be 16, 32 or 64".into()) + } + + /// Expand storage to binary64 using the defined per-width NaN payload rules. + pub fn try_to_f64(self) -> Result { + #[cfg(whale_wave_ir)] + { + wave::to_binary64(self).map(f64::from_bits) + } + #[cfg(not(whale_wave_ir))] + { + Ok(self.to_f64_reference()) + } + } + + /// Numeric convenience view of the Wave-produced binary64 storage. + pub fn to_f64(self) -> f64 { + self.try_to_f64().expect("Wave storage conversion backend invariant") + } + /// Compare equal-width IEEE values using an explicit ordered/unordered /// predicate. Returns `None` for mismatched widths. Integer bit ordering /// avoids host floating exceptions/conversions and treats both zeros equal; /// any quiet or signaling NaN makes the operands unordered. - pub fn compare(self, rhs: Self, predicate: &crate::FCmpPred) -> Option { + #[cfg(any(not(whale_wave_ir), test))] + pub(crate) fn compare_reference(self, rhs: Self, predicate: &crate::FCmpPred) -> Option { use crate::FCmpPred::*; use std::cmp::Ordering; @@ -83,7 +172,8 @@ impl FloatBits { } /// Exact-width hexadecimal storage, not a decimal floating-point number. - pub fn parse(width: u16, text: &str) -> Result { + #[cfg(any(not(whale_wave_ir), test))] + fn parse_reference(width: u16, text: &str) -> Result { let digits = match width { 16 => 4, 32 => 8, @@ -103,7 +193,8 @@ impl FloatBits { } /// Numeric convenience conversion. Use the variants to preserve source bits. - pub fn from_f64(width: u16, value: f64) -> Result { + #[cfg(any(not(whale_wave_ir), test))] + fn from_f64_reference(width: u16, value: f64) -> Result { Ok(match width { 16 => Self::F16(f64_to_f16(value)), 32 => Self::F32((value as f32).to_bits()), @@ -112,7 +203,8 @@ impl FloatBits { }) } - pub fn to_f64(self) -> f64 { + #[cfg(any(not(whale_wave_ir), test))] + fn to_f64_reference(self) -> f64 { match self { Self::F64(bits) => f64::from_bits(bits), Self::F32(bits) => f32::from_bits(bits) as f64, @@ -145,6 +237,7 @@ impl std::fmt::Display for FloatBits { } // Direct binary64 -> binary16 rounding avoids the intermediate f32 double round. +#[cfg(any(not(whale_wave_ir), test))] fn f64_to_f16(value: f64) -> u16 { let bits = value.to_bits(); let sign = ((bits >> 48) & 0x8000) as u16; @@ -175,3 +268,76 @@ fn f64_to_f16(value: f64) -> u16 { sign | ((((unbiased + 14) as u16) << 10) + rounded as u16) } } + +#[cfg(all(test, whale_wave_ir))] +mod wave_tests { + use super::*; + + #[test] + fn wave_storage_conveniences_preserve_reference_payload_and_spelling_rules() { + for (width, raw) in [ + (16, 0u64), + (16, 1), + (16, 0x7c01), + (16, 0xfcff), + (32, 0x7f800001), + (32, 0xffc12345), + (32, 1), + (64, 0x7ff0000000000001), + (64, 0xfff800000000cafe), + (64, 1), + ] { + let text = format!("0x{raw:0digits$x}", digits = usize::from(width) / 4); + let value = FloatBits::parse(width, &text).unwrap(); + assert_eq!(value, FloatBits::parse_reference(width, &text).unwrap()); + assert_eq!(value.to_f64().to_bits(), value.to_f64_reference().to_bits(), "{value:?}"); + for pred in [ + crate::FCmpPred::Oeq, + crate::FCmpPred::One, + crate::FCmpPred::Olt, + crate::FCmpPred::Ole, + crate::FCmpPred::Ogt, + crate::FCmpPred::Oge, + crate::FCmpPred::Ord, + crate::FCmpPred::Uno, + crate::FCmpPred::Ueq, + crate::FCmpPred::Une, + crate::FCmpPred::Ult, + crate::FCmpPred::Ule, + crate::FCmpPred::Ugt, + crate::FCmpPred::Uge, + ] { + assert_eq!( + value.try_compare(value, &pred).unwrap(), + value.compare_reference(value, &pred) + ); + } + } + for bits in [ + 0, + 1, + 0x8000000000000000, + 0x3ff0020000000001, + 0x7ff0000000000000, + 0x7ff0000000000001, + 0xfff800000000cafe, + u64::MAX, + ] { + for width in [16, 32, 64] { + let input = f64::from_bits(bits); + assert_eq!( + FloatBits::from_f64(width, input).unwrap(), + FloatBits::from_f64_reference(width, input).unwrap(), + "{bits:x} {width}" + ); + } + } + for width in [16, 32, 64, 80] { + for text in + ["", "0", "0X0", "0x0000", "0xGGGG", "0x01🦀", "0x12345678", "0x0123456789abcdef"] + { + assert_eq!(FloatBits::parse(width, text), FloatBits::parse_reference(width, text)); + } + } + } +} diff --git a/ir/src/float/arithmetic.rs b/ir/src/float/arithmetic.rs index acf1202..4a0ac06 100644 --- a/ir/src/float/arithmetic.rs +++ b/ir/src/float/arithmetic.rs @@ -1,251 +1,120 @@ // SPDX-License-Identifier: MPL-2.0 -//! Integer IEEE arithmetic. Finite values are sign * significand * 2^exponent. -//! A u128 holds exact products (at most 106 bits). Addition/division retain -//! guard, round and sticky bits; only pack performs nearest-even rounding. -use crate::{BinOp, FloatBits}; - -#[path = "conversions.rs"] -mod conversions; - -pub use conversions::convert; - -#[derive(Clone, Copy)] -struct Format { - width: u32, - fraction: u32, - bias: i32, -} - -impl Format { - fn of(value: FloatBits) -> Self { - match value { - FloatBits::F16(_) => Self { width: 16, fraction: 10, bias: 15 }, - FloatBits::F32(_) => Self { width: 32, fraction: 23, bias: 127 }, - FloatBits::F64(_) => Self { width: 64, fraction: 52, bias: 1023 }, - } - } - - fn sign(self) -> u64 { - 1u64 << (self.width - 1) - } - - fn infinity(self) -> u64 { - ((self.bias as u64) * 2 + 1) << self.fraction - } - - fn nan(self) -> FloatBits { - self.bits(self.infinity() | (1u64 << (self.fraction - 1))) - } - - fn bits(self, raw: u64) -> FloatBits { - match self.width { - 16 => FloatBits::F16(raw as u16), - 32 => FloatBits::F32(raw as u32), - _ => FloatBits::F64(raw), - } - } - - fn special(self, negative: bool, infinity: bool) -> FloatBits { - self.bits( - if negative { self.sign() } else { 0 } | if infinity { self.infinity() } else { 0 }, - ) - } - - fn unpack(self, value: FloatBits) -> Parts { - let bits = value.bits(); - let exp = ((bits & !self.sign()) >> self.fraction) as i32; - let fraction = bits & ((1u64 << self.fraction) - 1); - let special = exp == 2 * self.bias + 1; - Parts { - negative: bits & self.sign() != 0, - sig: if exp == 0 || special { - u128::from(fraction) - } else { - u128::from(fraction) | (1u128 << self.fraction) - }, - exp: exp.max(1) - self.bias - self.fraction as i32, - nan: special && fraction != 0, - infinity: special && fraction == 0, - } - } - - fn pack(self, negative: bool, sig: u128, exp: i32) -> FloatBits { - if sig == 0 { - return self.special(negative, false); - } - let highest = (127 - sig.leading_zeros()) as i32; - let target = - (exp + highest - self.fraction as i32).max(1 - self.bias - self.fraction as i32); - let shift = target - exp; - let mut rounded = if shift > 0 { round(sig, shift as u32) } else { sig << (-shift as u32) }; - let mut target = target; - if rounded >= (1u128 << (self.fraction + 1)) { - rounded >>= 1; - target += 1; - } - if rounded == 0 { - return self.special(negative, false); - } - let exponent = if rounded < (1u128 << self.fraction) { - 0 - } else { - target + self.fraction as i32 + self.bias - }; - if exponent > 2 * self.bias { - return self.special(negative, true); - } - self.bits( - (if negative { self.sign() } else { 0 }) - | ((exponent as u64) << self.fraction) - | ((rounded as u64) & ((1u64 << self.fraction) - 1)), - ) +//! Defined IEEE arithmetic. Wave owns the product path; the explicit Rust +//! reference remains available for conformance during migration. +use crate::{BinOp, CastOp, ConstValue, FloatBackendError, FloatBits, Type}; + +#[cfg(any(not(whale_wave_ir), test))] +#[path = "arithmetic_reference.rs"] +pub(crate) mod reference; + +pub fn try_arithmetic( + op: &BinOp, + lhs: FloatBits, + rhs: FloatBits, +) -> Result, FloatBackendError> { + #[cfg(whale_wave_ir)] + { + super::wave::arithmetic(op, lhs, rhs) + } + #[cfg(not(whale_wave_ir))] + { + Ok(reference::arithmetic(op, lhs, rhs)) } } -#[derive(Clone, Copy)] -struct Parts { - negative: bool, - sig: u128, - exp: i32, - nan: bool, - infinity: bool, +pub fn arithmetic(op: &BinOp, lhs: FloatBits, rhs: FloatBits) -> Option { + try_arithmetic(op, lhs, rhs).expect("Wave floating arithmetic backend invariant") } -impl Parts { - fn normalize(&mut self, f: Format) { - if self.sig != 0 { - let shift = self.sig.leading_zeros() - (127 - f.fraction); - self.sig <<= shift; - self.exp -= shift as i32; - } +pub fn try_negate(value: FloatBits) -> Result { + #[cfg(whale_wave_ir)] + { + super::wave::negate(value) + } + #[cfg(not(whale_wave_ir))] + { + Ok(reference::negate(value)) } } -fn round(value: u128, shift: u32) -> u128 { - if shift > 128 { - return 0; - } - if shift == 128 { - return u128::from(value > 1u128 << 127); - } - let q = value >> shift; - let remainder = value & ((1u128 << shift) - 1); - let halfway = 1u128 << (shift - 1); - q + u128::from(remainder > halfway || (remainder == halfway && q & 1 != 0)) +pub fn negate(value: FloatBits) -> FloatBits { + try_negate(value).expect("Wave floating negation backend invariant") } -fn jam(value: u128, shift: u32) -> u128 { - if shift == 0 { - value - } else if shift >= 128 { - u128::from(value != 0) - } else { - (value >> shift) | u128::from(value & ((1u128 << shift) - 1) != 0) +pub fn try_convert( + op: &CastOp, + src: &Type, + dst: &Type, + value: &ConstValue, +) -> Result, FloatBackendError> { + #[cfg(whale_wave_ir)] + { + super::wave::convert(op, src, dst, value) + } + #[cfg(not(whale_wave_ir))] + { + Ok(reference::convert(op, src, dst, value)) } } -/// IEEE sign-bit negation preserves zeros and NaN payloads without rounding. -pub fn negate(value: FloatBits) -> FloatBits { - let f = Format::of(value); - f.bits(value.bits() ^ f.sign()) +pub fn convert(op: &CastOp, src: &Type, dst: &Type, value: &ConstValue) -> Option { + try_convert(op, src, dst, value).expect("Wave floating conversion backend invariant") } -pub fn arithmetic(op: &BinOp, lhs: FloatBits, rhs: FloatBits) -> Option { - if !matches!(op, BinOp::FAdd | BinOp::FSub | BinOp::FMul | BinOp::FDiv | BinOp::FRem) { - return None; - } - if lhs.width() != rhs.width() { - return None; - } - let f = Format::of(lhs); - let mut a = f.unpack(lhs); - let mut b = f.unpack(rhs); - if a.nan || b.nan { - return Some(f.nan()); - } - if *op == BinOp::FSub { - b.negative = !b.negative; - } - let negative = a.negative ^ b.negative; - a.normalize(f); - b.normalize(f); - Some(match op { - BinOp::FAdd | BinOp::FSub => { - if a.infinity || b.infinity { - if a.infinity && b.infinity && negative { - f.nan() - } else { - f.special(if a.infinity { a.negative } else { b.negative }, true) - } - } else if a.sig == 0 && b.sig == 0 { - f.special(a.negative && b.negative, false) - } else if a.sig == 0 { - f.pack(b.negative, b.sig, b.exp) - } else if b.sig == 0 { - f.pack(a.negative, a.sig, a.exp) - } else { - if (a.exp, a.sig) < (b.exp, b.sig) { - std::mem::swap(&mut a, &mut b); - } - // Three low bits retain ties and inexact aligned tails. Unlike - // a host float intermediary, cancellation happens before rounding. - let av = a.sig << 3; - let bv = jam(b.sig << 3, (a.exp - b.exp) as u32); - if a.negative == b.negative { - f.pack(a.negative, av + bv, a.exp - 3) - } else { - f.pack(a.negative && av != bv, av - bv, a.exp - 3) +#[cfg(all(test, whale_wave_ir))] +mod tests { + use super::*; + + #[test] + fn wave_matches_retained_ieee_reference_for_random_storage_and_operations() { + let mut state = 0x0003_5301_2864_u64; + for _ in 0..1000 { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + let a = state; + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + let b = state; + for (left, right) in [ + (FloatBits::F16(a as u16), FloatBits::F16(b as u16)), + (FloatBits::F32(a as u32), FloatBits::F32(b as u32)), + (FloatBits::F64(a), FloatBits::F64(b)), + ] { + for op in [BinOp::FAdd, BinOp::FSub, BinOp::FMul, BinOp::FDiv, BinOp::FRem] { + assert_eq!( + try_arithmetic(&op, left, right).unwrap(), + reference::arithmetic(&op, left, right), + "{op:?} {left:?} {right:?}" + ); } - } - }, - BinOp::FMul => { - if (a.infinity && b.sig == 0 && !b.infinity) - || (b.infinity && a.sig == 0 && !a.infinity) - { - f.nan() - } else if a.infinity || b.infinity { - f.special(negative, true) - } else { - f.pack(negative, a.sig * b.sig, a.exp + b.exp) - } - }, - BinOp::FDiv => { - if (a.infinity && b.infinity) - || (!a.infinity && !b.infinity && a.sig == 0 && b.sig == 0) - { - f.nan() - } else if a.infinity || b.sig == 0 && !b.infinity { - f.special(negative, true) - } else if b.infinity || a.sig == 0 { - f.special(negative, false) - } else { - let shift = f.fraction + 4; - let numerator = a.sig << shift; - let q = (numerator / b.sig) | u128::from(numerator % b.sig != 0); - f.pack(negative, q, a.exp - b.exp - shift as i32) - } - }, - BinOp::FRem => { - if a.infinity || b.sig == 0 && !b.infinity { - f.nan() - } else if b.infinity || a.sig == 0 || a.exp < b.exp { - lhs - } else { - // Exact fmod remainder with logarithmic work even for the full - // binary64 exponent span. Products are bounded by 106 bits. - let mut r = a.sig % b.sig; - let mut power = 2u128 % b.sig; - let mut shift = (a.exp - b.exp) as u32; - while shift != 0 { - if shift & 1 != 0 { - r = (r * power) % b.sig; + assert_eq!(try_negate(left).unwrap(), reference::negate(left)); + for destination in [ + Type::F16, + Type::F32, + Type::F64, + Type::I1, + Type::U1, + Type::I32, + Type::U32, + Type::I128, + Type::U128, + ] { + let source = match left { + FloatBits::F16(_) => Type::F16, + FloatBits::F32(_) => Type::F32, + FloatBits::F64(_) => Type::F64, + }; + for op in [CastOp::FExt, CastOp::FTrunc, CastOp::FToI_S, CastOp::FToI_U] { + let value = ConstValue::F(left); + assert_eq!( + try_convert(&op, &source, &destination, &value).unwrap(), + reference::convert(&op, &source, &destination, &value) + ); } - power = (power * power) % b.sig; - shift >>= 1; } - f.pack(a.negative, r, b.exp) } - }, - _ => return None, - }) + } + } } diff --git a/ir/src/float/arithmetic_reference.rs b/ir/src/float/arithmetic_reference.rs new file mode 100644 index 0000000..6b24ccc --- /dev/null +++ b/ir/src/float/arithmetic_reference.rs @@ -0,0 +1,251 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Integer IEEE arithmetic. Finite values are sign * significand * 2^exponent. +//! A u128 holds exact products (at most 106 bits). Addition/division retain +//! guard, round and sticky bits; only pack performs nearest-even rounding. +use crate::{BinOp, FloatBits}; + +#[path = "conversions_reference.rs"] +mod conversions; + +pub use conversions::convert; + +#[derive(Clone, Copy)] +struct Format { + width: u32, + fraction: u32, + bias: i32, +} + +impl Format { + fn of(value: FloatBits) -> Self { + match value { + FloatBits::F16(_) => Self { width: 16, fraction: 10, bias: 15 }, + FloatBits::F32(_) => Self { width: 32, fraction: 23, bias: 127 }, + FloatBits::F64(_) => Self { width: 64, fraction: 52, bias: 1023 }, + } + } + + fn sign(self) -> u64 { + 1u64 << (self.width - 1) + } + + fn infinity(self) -> u64 { + ((self.bias as u64) * 2 + 1) << self.fraction + } + + fn nan(self) -> FloatBits { + self.bits(self.infinity() | (1u64 << (self.fraction - 1))) + } + + fn bits(self, raw: u64) -> FloatBits { + match self.width { + 16 => FloatBits::F16(raw as u16), + 32 => FloatBits::F32(raw as u32), + _ => FloatBits::F64(raw), + } + } + + fn special(self, negative: bool, infinity: bool) -> FloatBits { + self.bits( + if negative { self.sign() } else { 0 } | if infinity { self.infinity() } else { 0 }, + ) + } + + fn unpack(self, value: FloatBits) -> Parts { + let bits = value.bits(); + let exp = ((bits & !self.sign()) >> self.fraction) as i32; + let fraction = bits & ((1u64 << self.fraction) - 1); + let special = exp == 2 * self.bias + 1; + Parts { + negative: bits & self.sign() != 0, + sig: if exp == 0 || special { + u128::from(fraction) + } else { + u128::from(fraction) | (1u128 << self.fraction) + }, + exp: exp.max(1) - self.bias - self.fraction as i32, + nan: special && fraction != 0, + infinity: special && fraction == 0, + } + } + + fn pack(self, negative: bool, sig: u128, exp: i32) -> FloatBits { + if sig == 0 { + return self.special(negative, false); + } + let highest = (127 - sig.leading_zeros()) as i32; + let target = + (exp + highest - self.fraction as i32).max(1 - self.bias - self.fraction as i32); + let shift = target - exp; + let mut rounded = if shift > 0 { round(sig, shift as u32) } else { sig << (-shift as u32) }; + let mut target = target; + if rounded >= (1u128 << (self.fraction + 1)) { + rounded >>= 1; + target += 1; + } + if rounded == 0 { + return self.special(negative, false); + } + let exponent = if rounded < (1u128 << self.fraction) { + 0 + } else { + target + self.fraction as i32 + self.bias + }; + if exponent > 2 * self.bias { + return self.special(negative, true); + } + self.bits( + (if negative { self.sign() } else { 0 }) + | ((exponent as u64) << self.fraction) + | ((rounded as u64) & ((1u64 << self.fraction) - 1)), + ) + } +} + +#[derive(Clone, Copy)] +struct Parts { + negative: bool, + sig: u128, + exp: i32, + nan: bool, + infinity: bool, +} + +impl Parts { + fn normalize(&mut self, f: Format) { + if self.sig != 0 { + let shift = self.sig.leading_zeros() - (127 - f.fraction); + self.sig <<= shift; + self.exp -= shift as i32; + } + } +} + +fn round(value: u128, shift: u32) -> u128 { + if shift > 128 { + return 0; + } + if shift == 128 { + return u128::from(value > 1u128 << 127); + } + let q = value >> shift; + let remainder = value & ((1u128 << shift) - 1); + let halfway = 1u128 << (shift - 1); + q + u128::from(remainder > halfway || (remainder == halfway && q & 1 != 0)) +} + +fn jam(value: u128, shift: u32) -> u128 { + if shift == 0 { + value + } else if shift >= 128 { + u128::from(value != 0) + } else { + (value >> shift) | u128::from(value & ((1u128 << shift) - 1) != 0) + } +} + +/// IEEE sign-bit negation preserves zeros and NaN payloads without rounding. +pub fn negate(value: FloatBits) -> FloatBits { + let f = Format::of(value); + f.bits(value.bits() ^ f.sign()) +} + +pub fn arithmetic(op: &BinOp, lhs: FloatBits, rhs: FloatBits) -> Option { + if !matches!(op, BinOp::FAdd | BinOp::FSub | BinOp::FMul | BinOp::FDiv | BinOp::FRem) { + return None; + } + if lhs.width() != rhs.width() { + return None; + } + let f = Format::of(lhs); + let mut a = f.unpack(lhs); + let mut b = f.unpack(rhs); + if a.nan || b.nan { + return Some(f.nan()); + } + if *op == BinOp::FSub { + b.negative = !b.negative; + } + let negative = a.negative ^ b.negative; + a.normalize(f); + b.normalize(f); + Some(match op { + BinOp::FAdd | BinOp::FSub => { + if a.infinity || b.infinity { + if a.infinity && b.infinity && negative { + f.nan() + } else { + f.special(if a.infinity { a.negative } else { b.negative }, true) + } + } else if a.sig == 0 && b.sig == 0 { + f.special(a.negative && b.negative, false) + } else if a.sig == 0 { + f.pack(b.negative, b.sig, b.exp) + } else if b.sig == 0 { + f.pack(a.negative, a.sig, a.exp) + } else { + if (a.exp, a.sig) < (b.exp, b.sig) { + std::mem::swap(&mut a, &mut b); + } + // Three low bits retain ties and inexact aligned tails. Unlike + // a host float intermediary, cancellation happens before rounding. + let av = a.sig << 3; + let bv = jam(b.sig << 3, (a.exp - b.exp) as u32); + if a.negative == b.negative { + f.pack(a.negative, av + bv, a.exp - 3) + } else { + f.pack(a.negative && av != bv, av - bv, a.exp - 3) + } + } + }, + BinOp::FMul => { + if (a.infinity && b.sig == 0 && !b.infinity) + || (b.infinity && a.sig == 0 && !a.infinity) + { + f.nan() + } else if a.infinity || b.infinity { + f.special(negative, true) + } else { + f.pack(negative, a.sig * b.sig, a.exp + b.exp) + } + }, + BinOp::FDiv => { + if (a.infinity && b.infinity) + || (!a.infinity && !b.infinity && a.sig == 0 && b.sig == 0) + { + f.nan() + } else if a.infinity || b.sig == 0 && !b.infinity { + f.special(negative, true) + } else if b.infinity || a.sig == 0 { + f.special(negative, false) + } else { + let shift = f.fraction + 4; + let numerator = a.sig << shift; + let q = (numerator / b.sig) | u128::from(numerator % b.sig != 0); + f.pack(negative, q, a.exp - b.exp - shift as i32) + } + }, + BinOp::FRem => { + if a.infinity || b.sig == 0 && !b.infinity { + f.nan() + } else if b.infinity || a.sig == 0 || a.exp < b.exp { + lhs + } else { + // Exact fmod remainder with logarithmic work even for the full + // binary64 exponent span. Products are bounded by 106 bits. + let mut r = a.sig % b.sig; + let mut power = 2u128 % b.sig; + let mut shift = (a.exp - b.exp) as u32; + while shift != 0 { + if shift & 1 != 0 { + r = (r * power) % b.sig; + } + power = (power * power) % b.sig; + shift >>= 1; + } + f.pack(a.negative, r, b.exp) + } + }, + _ => return None, + }) +} diff --git a/ir/src/float/conversions.rs b/ir/src/float/conversions_reference.rs similarity index 98% rename from ir/src/float/conversions.rs rename to ir/src/float/conversions_reference.rs index 089d83d..6e04bd7 100644 --- a/ir/src/float/conversions.rs +++ b/ir/src/float/conversions_reference.rs @@ -15,7 +15,7 @@ fn format(ty: &Type) -> Option { /// None is a defined invalid numerical conversion, never a poison value. pub fn convert(op: &CastOp, src: &Type, dst: &Type, value: &ConstValue) -> Option { - use crate::interpreter::integer; + use crate::interpreter::integer::reference as integer; if !crate::constant::valid_constant(src, value) { return None; } diff --git a/ir/src/float/wave.rs b/ir/src/float/wave.rs new file mode 100644 index 0000000..bb6b6de --- /dev/null +++ b/ir/src/float/wave.rs @@ -0,0 +1,280 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Scalar bit transport. All numerical decisions execute in Wave. +use crate::{BinOp, CastOp, ConstValue, FCmpPred, FloatBackendError, FloatBits, Type}; + +#[repr(C)] +#[derive(Default)] +struct Request { + mode: u64, + operation: u64, + source: u64, + destination: u64, + left_kind: u64, + left_low: u64, + left_high: u64, + right_kind: u64, + right_low: u64, + right_high: u64, +} + +#[repr(C)] +#[derive(Default)] +struct ResultRecord { + status: u64, + low: u64, + high: u64, + flag: u64, +} + +#[repr(C)] +#[derive(Default)] +struct LiteralResult { + status: u64, + low: u64, + high: u64, + work: u64, +} + +unsafe extern "C" { + fn whale_ir_float(request: *const Request, result: *mut ResultRecord) -> i32; + + fn whale_ir_parse_literal( + source: *const u8, + length: u64, + category: u64, + width: u64, + max_work: u64, + result: *mut LiteralResult, + ) -> i32; +} + +fn backend() -> FloatBackendError { + FloatBackendError("scalar transport") +} + +fn kind(ty: &Type) -> u64 { + match ty { + Type::Void => 0, + Type::Bool => 1, + Type::I1 => 2, + Type::U1 => 3, + Type::I8 => 4, + Type::I16 => 5, + Type::I32 => 6, + Type::I64 => 7, + Type::I128 => 8, + Type::U8 => 9, + Type::U16 => 10, + Type::U32 => 11, + Type::U64 => 12, + Type::U128 => 13, + Type::F16 => 14, + Type::F32 => 15, + Type::F64 => 16, + _ => u64::MAX, + } +} + +fn float_kind(value: FloatBits) -> u64 { + match value { + FloatBits::F16(_) => 14, + FloatBits::F32(_) => 15, + FloatBits::F64(_) => 16, + } +} + +fn payload(value: &ConstValue) -> (u64, u64, u64) { + let (tag, bits) = match value { + ConstValue::I(value) => (1, *value as u128), + ConstValue::U(value) => (2, *value), + ConstValue::Bool(value) => (3, u128::from(*value)), + ConstValue::F(FloatBits::F16(value)) => (4, u128::from(*value)), + ConstValue::F(FloatBits::F32(value)) => (5, u128::from(*value)), + ConstValue::F(FloatBits::F64(value)) => (6, u128::from(*value)), + }; + (tag, bits as u64, (bits >> 64) as u64) +} + +fn request(mode: u64, left: FloatBits) -> Request { + let (left_kind, left_low, left_high) = payload(&ConstValue::F(left)); + Request { mode, source: float_kind(left), left_kind, left_low, left_high, ..Request::default() } +} + +fn run(request: &Request) -> Result, FloatBackendError> { + let mut result = ResultRecord::default(); + let status = unsafe { whale_ir_float(request, &mut result) }; + if i32::try_from(result.status).ok() != Some(status) || result.flag > 1 { + return Err(backend()); + } + match status { + 0 => { + if (request.mode != 2 && result.flag != 0) + || (request.mode == 2 && (result.low != 0 || result.high != 0)) + { + return Err(backend()); + } + Ok(Some(result)) + }, + 1 if result.low == 0 && result.high == 0 && result.flag == 0 => Ok(None), + _ => Err(backend()), + } +} + +fn float(kind: u64, record: &ResultRecord) -> Result { + if record.high != 0 { + return Err(backend()); + } + match kind { + 14 => Ok(FloatBits::F16(record.low.try_into().map_err(|_| backend())?)), + 15 => Ok(FloatBits::F32(record.low.try_into().map_err(|_| backend())?)), + 16 => Ok(FloatBits::F64(record.low)), + _ => Err(backend()), + } +} + +pub(super) fn arithmetic( + op: &BinOp, + lhs: FloatBits, + rhs: FloatBits, +) -> Result, FloatBackendError> { + let mut q = request(0, lhs); + q.destination = float_kind(rhs); + q.operation = match op { + BinOp::FAdd => 0, + BinOp::FSub => 1, + BinOp::FMul => 2, + BinOp::FDiv => 3, + BinOp::FRem => 4, + _ => u64::MAX, + }; + (q.right_kind, q.right_low, q.right_high) = payload(&ConstValue::F(rhs)); + run(&q)?.map(|record| float(q.source, &record)).transpose() +} + +pub(super) fn negate(value: FloatBits) -> Result { + let q = request(1, value); + float(q.source, &run(&q)?.ok_or_else(backend)?) +} + +pub(super) fn compare( + lhs: FloatBits, + rhs: FloatBits, + pred: &FCmpPred, +) -> Result, FloatBackendError> { + let mut q = request(2, lhs); + q.destination = float_kind(rhs); + q.operation = match pred { + FCmpPred::Oeq => 0, + FCmpPred::One => 1, + FCmpPred::Olt => 2, + FCmpPred::Ole => 3, + FCmpPred::Ogt => 4, + FCmpPred::Oge => 5, + FCmpPred::Ord => 6, + FCmpPred::Uno => 7, + FCmpPred::Ueq => 8, + FCmpPred::Une => 9, + FCmpPred::Ult => 10, + FCmpPred::Ule => 11, + FCmpPred::Ugt => 12, + FCmpPred::Uge => 13, + }; + (q.right_kind, q.right_low, q.right_high) = payload(&ConstValue::F(rhs)); + Ok(run(&q)?.map(|r| r.flag != 0)) +} + +pub(super) fn convert( + op: &CastOp, + src: &Type, + dst: &Type, + value: &ConstValue, +) -> Result, FloatBackendError> { + let mut q = + Request { mode: 3, source: kind(src), destination: kind(dst), ..Request::default() }; + q.operation = match op { + CastOp::FExt => 0, + CastOp::FTrunc => 1, + CastOp::IToF_S => 2, + CastOp::IToF_U => 3, + CastOp::FToI_S => 4, + CastOp::FToI_U => 5, + _ => u64::MAX, + }; + (q.left_kind, q.left_low, q.left_high) = payload(value); + let Some(r) = run(&q)? else { return Ok(None) }; + let bits = u128::from(r.low) | (u128::from(r.high) << 64); + let signed = bits as i128; + let value = match dst { + Type::F16 | Type::F32 | Type::F64 => ConstValue::F(float(q.destination, &r)?), + Type::I1 if matches!(signed, -1 | 0) => ConstValue::I(signed), + Type::I8 if i8::try_from(signed).is_ok() => ConstValue::I(signed), + Type::I16 if i16::try_from(signed).is_ok() => ConstValue::I(signed), + Type::I32 if i32::try_from(signed).is_ok() => ConstValue::I(signed), + Type::I64 if i64::try_from(signed).is_ok() => ConstValue::I(signed), + Type::I128 => ConstValue::I(signed), + Type::U1 if bits <= 1 => ConstValue::U(bits), + Type::U8 if u8::try_from(bits).is_ok() => ConstValue::U(bits), + Type::U16 if u16::try_from(bits).is_ok() => ConstValue::U(bits), + Type::U32 if u32::try_from(bits).is_ok() => ConstValue::U(bits), + Type::U64 if u64::try_from(bits).is_ok() => ConstValue::U(bits), + Type::U128 => ConstValue::U(bits), + _ => return Err(backend()), + }; + Ok(Some(value)) +} + +pub(super) fn to_binary64(value: FloatBits) -> Result { + let r = run(&request(4, value))?.ok_or_else(backend)?; + if r.high != 0 { + return Err(backend()); + } + Ok(r.low) +} + +pub(super) fn from_f64(width: u16, bits: u64) -> Result { + let mut q = request(5, FloatBits::F64(bits)); + q.destination = match width { + 16 => 14, + 32 => 15, + 64 => 16, + _ => return Err(FloatBackendError("float width must be 16, 32 or 64")), + }; + float(q.destination, &run(&q)?.ok_or_else(backend)?) +} + +pub(super) fn parse(width: u16, text: &str) -> Result { + if !matches!(width, 16 | 32 | 64) { + return Err("float width must be 16, 32 or 64".into()); + } + let mut result = LiteralResult::default(); + let status = unsafe { + whale_ir_parse_literal( + text.as_ptr(), + text.len() as u64, + 4, + width.into(), + text.len() as u64, + &mut result, + ) + }; + if i32::try_from(result.status).ok() != Some(status) + || result.work != text.len() as u64 + || (status != 0 && (result.low != 0 || result.high != 0)) + { + return Err(backend().to_string()); + } + match status { + 0 if result.high == 0 => float( + match width { + 16 => 14, + 32 => 15, + _ => 16, + }, + &ResultRecord { low: result.low, ..ResultRecord::default() }, + ) + .map_err(|e| e.to_string()), + 6 => Err("float value must start with 0x".into()), + 7 => Err(format!("f{width} requires exactly {} hexadecimal digits", width / 4)), + _ => Err(backend().to_string()), + } +} diff --git a/ir/src/fold_integer.rs b/ir/src/fold_integer.rs new file mode 100644 index 0000000..e9ca847 --- /dev/null +++ b/ir/src/fold_integer.rs @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Explicit integer constant propagation; the O0 pipeline never enables it. +use super::{Pass, PassChange}; + +use crate::{IrLimits, Module}; + +#[cfg(whale_wave_ir)] +#[path = "fold_integer_wave.rs"] +mod wave; + +#[derive(Clone, Copy, Debug, Default)] +pub struct IntegerConstantFold { + pub limits: IrLimits, +} + +impl Pass for IntegerConstantFold { + fn name(&self) -> &str { + "integer-constant-fold" + } + + fn run(&mut self, module: &mut Module) -> Result { + #[cfg(whale_wave_ir)] + return wave::fold(module, self.limits); + #[cfg(not(whale_wave_ir))] + { + let _ = module; + Err("integer constant folding requires the Wave IR module".into()) + } + } +} diff --git a/ir/src/fold_integer_wave.rs b/ir/src/fold_integer_wave.rs new file mode 100644 index 0000000..5725e1d --- /dev/null +++ b/ir/src/fold_integer_wave.rs @@ -0,0 +1,465 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Lossless enum/ID transport and allocation for the Wave integer folder. +use super::*; + +use crate::{BinOp, CmpOp, ConstValue, ICmpPred, Instruction, Type, ValueId}; + +#[repr(C)] +#[derive(Default)] +struct Node { + op: u64, + sub: u64, + scope: u64, + id: u64, + kind: u64, + literal: u64, + low: u64, + high: u64, + first: u64, + count: u64, +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct Value { + known: u64, + kind: u64, + low: u64, + high: u64, + replace: u64, +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct Slot { + key: u64, + index: u64, + present: u64, +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct User { + index: u64, + next: u64, +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct Pending { + head: u64, + queued: u64, +} + +#[repr(C)] +struct Input { + nodes: *const Node, + count: u64, + references: *const u64, + reference_count: u64, + values: *mut Value, + slots: *mut Slot, + capacity: u64, + users: *mut User, + pending: *mut Pending, + queue: *mut u64, + max_work: u64, +} + +#[repr(C)] +#[derive(Default)] +struct Output { + status: u64, + changed: u64, + folded: u64, + work: u64, +} + +unsafe extern "C" { + fn whale_ir_fold_integer(input: *const Input, output: *mut Output) -> i32; +} + +fn kind(ty: &Type) -> u64 { + match ty { + Type::Bool => 1, + Type::I1 => 2, + Type::U1 => 3, + Type::I8 => 4, + Type::I16 => 5, + Type::I32 => 6, + Type::I64 => 7, + Type::I128 => 8, + Type::U8 => 9, + Type::U16 => 10, + Type::U32 => 11, + Type::U64 => 12, + Type::U128 => 13, + _ => 0, + } +} + +fn binary(op: &BinOp) -> Option { + Some(match op { + BinOp::Add => 0, + BinOp::Sub => 1, + BinOp::Mul => 2, + BinOp::UDiv => 3, + BinOp::SDiv => 4, + BinOp::URem => 5, + BinOp::SRem => 6, + BinOp::And => 12, + BinOp::Or => 13, + BinOp::Xor => 14, + BinOp::Shl => 15, + BinOp::LShr => 16, + BinOp::AShr => 17, + _ => return None, + }) +} + +fn predicate(op: &ICmpPred) -> u64 { + match op { + ICmpPred::Eq => 0, + ICmpPred::Ne => 1, + ICmpPred::Ult => 2, + ICmpPred::Ule => 3, + ICmpPred::Ugt => 4, + ICmpPred::Uge => 5, + ICmpPred::Slt => 6, + ICmpPred::Sle => 7, + ICmpPred::Sgt => 8, + ICmpPred::Sge => 9, + } +} + +fn comparison(op: &CmpOp) -> Option { + Some(match op { + CmpOp::Eq => 0, + CmpOp::Ne => 1, + CmpOp::ULt => 2, + CmpOp::ULe => 3, + CmpOp::UGt => 4, + CmpOp::UGe => 5, + CmpOp::SLt => 6, + CmpOp::SLe => 7, + CmpOp::SGt => 8, + CmpOp::SGe => 9, + _ => return None, + }) +} + +fn literal(node: &mut Node, value: &ConstValue) { + let bits = match value { + ConstValue::I(value) => { + node.literal = 1; + *value as u128 + }, + ConstValue::U(value) => { + node.literal = 2; + *value + }, + ConstValue::Bool(value) => { + node.literal = 3; + u128::from(*value) + }, + _ => return, + }; + node.low = bits as u64; + node.high = (bits >> 64) as u64; +} + +fn allocate(count: usize) -> Result, String> { + let mut values = Vec::new(); + values.try_reserve_exact(count).map_err(|_| "constant folder allocation failed")?; + values.resize(count, T::default()); + Ok(values) +} + +fn result_id(i: &Instruction) -> Option { + use Instruction::*; + Some(match i { + GlobalAddr { dst, .. } + | PtrDiff { dst, .. } + | ConstDecl { dst, .. } + | Const { dst, .. } + | Undef { dst, .. } + | Mov { dst, .. } + | Bin { dst, .. } + | Neg { dst, .. } + | Not { dst, .. } + | Cmp { dst, .. } + | ICmp { dst, .. } + | FCmp { dst, .. } + | Select { dst, .. } + | Cast { dst, .. } + | Phi { dst, .. } + | Extract { dst, .. } + | Checked { dst, .. } + | Alloca { dst, .. } + | VolatileLoad { dst, .. } + | Load { dst, .. } + | Gep { dst, .. } + | NullFunction { dst, .. } + | FunctionAddr { dst, .. } => *dst, + Call { dst, .. } => return *dst, + LifetimeEnd { .. } + | VolatileStore { .. } + | Uninit { .. } + | Store { .. } + | Memcpy { .. } + | Memset { .. } + | TrapIf { .. } => return None, + }) +} + +fn marshal(i: &Instruction, node: &mut Node, references: &mut Vec) { + use Instruction::*; + let mut operands = |ids: &[ValueId]| references.extend(ids.iter().map(|id| u64::from(id.0))); + match i { + Const { ty, value, .. } => { + node.op = 4; + node.kind = kind(ty); + literal(node, value); + }, + ConstDecl { expression, value, .. } => { + node.op = 3; + node.kind = kind(&expression.ty); + literal(node, value); + }, + Mov { ty, src, .. } | Neg { ty, src, .. } | Not { ty, src, .. } => { + node.op = match i { + Mov { .. } => 6, + Neg { .. } => 8, + _ => 9, + }; + node.kind = kind(ty); + operands(&[*src]); + }, + Bin { op, ty, lhs, rhs, .. } if binary(op).is_some() && kind(ty) > 1 => { + node.op = 7; + node.sub = binary(op).unwrap(); + node.kind = kind(ty); + operands(&[*lhs, *rhs]); + }, + Cmp { op, ty, lhs, rhs, .. } if comparison(op).is_some() && kind(ty) != 0 => { + node.op = 10; + node.sub = comparison(op).unwrap(); + node.kind = kind(ty); + operands(&[*lhs, *rhs]); + }, + ICmp { pred, ty, lhs, rhs, .. } if kind(ty) != 0 => { + node.op = 11; + node.sub = predicate(pred); + node.kind = kind(ty); + operands(&[*lhs, *rhs]); + }, + Select { ty, cond, on_true, on_false, .. } if kind(ty) != 0 => { + node.op = 13; + node.kind = kind(ty); + operands(&[*cond, *on_true, *on_false]); + }, + Phi { ty, incomings, .. } if kind(ty) != 0 => { + node.op = 15; + node.kind = kind(ty); + references.extend(incomings.iter().map(|(id, _)| u64::from(id.0))); + }, + _ => {}, + } + // Unsupported literal categories stay indexed, with no arithmetic fallback. + if node.kind == 0 { + node.op = 63; + references.truncate(node.first as usize); + } +} + +fn decode(value: Value) -> Result<(Type, ConstValue), String> { + let bits = u128::from(value.low) | (u128::from(value.high) << 64); + let ty = match value.kind { + 1 => Type::Bool, + 2 => Type::I1, + 3 => Type::U1, + 4 => Type::I8, + 5 => Type::I16, + 6 => Type::I32, + 7 => Type::I64, + 8 => Type::I128, + 9 => Type::U8, + 10 => Type::U16, + 11 => Type::U32, + 12 => Type::U64, + 13 => Type::U128, + _ => return Err("constant folder result type transport".into()), + }; + let constant = match value.kind { + 1 if bits <= 1 => ConstValue::Bool(bits != 0), + 2 | 4..=8 => ConstValue::I(bits as i128), + 3 | 9..=13 => ConstValue::U(bits), + _ => return Err("constant folder result literal transport".into()), + }; + if !crate::constant::valid_constant(&ty, &constant) { + return Err("constant folder result literal transport".into()); + } + Ok((ty, constant)) +} + +fn reference_count(instruction: &Instruction) -> usize { + use Instruction::*; + match instruction { + Mov { ty, .. } | Neg { ty, .. } | Not { ty, .. } if kind(ty) != 0 => 1, + Bin { op, ty, .. } if binary(op).is_some() && kind(ty) > 1 => 2, + Cmp { op, ty, .. } if comparison(op).is_some() && kind(ty) != 0 => 2, + ICmp { ty, .. } if kind(ty) != 0 => 2, + Select { ty, .. } if kind(ty) != 0 => 3, + Phi { ty, incomings, .. } if kind(ty) != 0 => incomings.len(), + _ => 0, + } +} + +pub(super) fn fold(module: &mut Module, limits: IrLimits) -> Result { + crate::verify_module_with_limits(module, limits).map_err(|e| format!("{e:?}"))?; + let count = module + .functions + .iter() + .try_fold(0usize, |n, f| { + f.blocks.iter().try_fold(n.checked_add(f.params.len())?, |n, b| { + n.checked_add(b.instructions.iter().filter(|i| result_id(i).is_some()).count()) + }) + }) + .ok_or("constant folder model limit exceeded")?; + let capacity = count + .checked_mul(2) + .and_then(|n| n.max(2).checked_next_power_of_two()) + .ok_or("constant folder model limit exceeded")?; + let reference_count = module + .functions + .iter() + .flat_map(|f| &f.blocks) + .flat_map(|b| &b.instructions) + .try_fold(0usize, |count, instruction| count.checked_add(reference_count(instruction))) + .ok_or("constant folder reference limit exceeded")?; + if count > limits.max_nodes + || capacity > limits.max_analysis_work + || reference_count > limits.max_nodes + { + return Err("constant folder model limit exceeded".into()); + } + // Admit every owned transport and worst-case staged replacement before + // reserving any model buffer, even when callers raise the IR node limit. + let workspace = count + .checked_mul(80 + 40 + 16 + 8 + 32 + std::mem::size_of::() + 24) + .and_then(|n| n.checked_add(capacity.checked_mul(24)?)) + .and_then(|n| n.checked_add(reference_count.checked_mul(24)?)) + .ok_or("constant folder workspace limit exceeded")?; + if workspace > 128 * 1024 * 1024 { + return Err("constant folder workspace limit exceeded".into()); + } + let mut nodes = Vec::new(); + let mut paths = Vec::new(); + let mut references = Vec::new(); + nodes.try_reserve_exact(count).map_err(|_| "constant folder allocation failed")?; + paths.try_reserve_exact(count).map_err(|_| "constant folder allocation failed")?; + references + .try_reserve_exact(reference_count) + .map_err(|_| "constant folder allocation failed")?; + for (fi, function) in module.functions.iter().enumerate() { + for parameter in &function.params { + nodes.push(Node { + op: 31, + scope: function.id.0.into(), + id: parameter.id.0.into(), + kind: kind(¶meter.ty), + first: references.len() as u64, + ..Node::default() + }); + paths.push(None); + } + for (bi, block) in function.blocks.iter().enumerate() { + for (ii, instruction) in block.instructions.iter().enumerate() { + let Some(id) = result_id(instruction) else { continue }; + let mut node = Node { + op: 63, + scope: function.id.0.into(), + id: id.0.into(), + first: references.len() as u64, + ..Node::default() + }; + marshal(instruction, &mut node, &mut references); + node.count = references.len() as u64 - node.first; + nodes.push(node); + paths.push(Some((fi, bi, ii))); + } + } + } + if references.len() != reference_count { + return Err("constant folder reference transport".into()); + } + let mut values = allocate::(count)?; + let mut slots = allocate::(capacity)?; + let mut users = allocate::(references.len())?; + let mut pending = allocate::(count)?; + let mut queue = allocate::(count)?; + let input = Input { + nodes: nodes.as_ptr(), + count: count as u64, + references: references.as_ptr(), + reference_count: references.len() as u64, + values: values.as_mut_ptr(), + slots: slots.as_mut_ptr(), + capacity: capacity as u64, + users: users.as_mut_ptr(), + pending: pending.as_mut_ptr(), + queue: queue.as_mut_ptr(), + max_work: limits.max_analysis_work as u64, + }; + let mut output = Output::default(); + let status = unsafe { whale_ir_fold_integer(&input, &mut output) }; + if status == 1 && output.status == 1 { + return Err("constant folder analysis work limit exceeded".into()); + } + if status != 0 + || output.status != 0 + || output.changed > 1 + || output.folded > count as u64 + || output.work > limits.max_analysis_work as u64 + { + return Err("constant folder transport".into()); + } + let mut replacements = Vec::new(); + replacements + .try_reserve_exact(output.folded as usize) + .map_err(|_| "constant folder allocation failed")?; + for ((value, node), path) in values.into_iter().zip(nodes).zip(paths) { + if value.known > 1 || value.replace > value.known { + return Err("constant folder result transport".into()); + } + if value.replace == 0 { + continue; + } + let path = path.ok_or("constant folder replacement transport")?; + if !matches!(node.op, 6..=11 | 13 | 15) { + return Err("constant folder replacement transport".into()); + } + let expected = if matches!(node.op, 10 | 11) { 1 } else { node.kind }; + if value.kind != expected { + return Err("constant folder result type transport".into()); + } + let (ty, value) = decode(value)?; + replacements.push((path, Instruction::Const { dst: ValueId(node.id as u32), ty, value })); + } + if replacements.len() as u64 != output.folded + || output.changed != u64::from(!replacements.is_empty()) + { + return Err("constant folder report transport".into()); + } + for ((fi, bi, ii), instruction) in replacements { + module.functions[fi].blocks[bi].instructions[ii] = instruction; + } + Ok(PassChange { + changed: output.changed != 0, + invalidates: if output.changed != 0 { + super::super::Invalidates::ALL + } else { + Default::default() + }, + }) +} diff --git a/ir/src/interpreter/integer.rs b/ir/src/interpreter/integer.rs index 2efe9d0..391a476 100644 --- a/ir/src/interpreter/integer.rs +++ b/ir/src/interpreter/integer.rs @@ -1,9 +1,32 @@ // SPDX-License-Identifier: MPL-2.0 - +//! Fixed-width scalar transport. Production numeric decisions run in Wave. +#[cfg(any(test, not(whale_wave_ir)))] use super::TrapReason; -use crate::{BinOp, CastOp, CheckedOp, ConstValue, Type}; +use crate::Type; + +#[cfg(any(test, not(whale_wave_ir)))] +use crate::{BinOp, CastOp, CheckedOp, ConstValue, ICmpPred}; + +#[cfg(any(test, not(whale_wave_ir)))] +#[path = "integer_reference.rs"] +pub(crate) mod reference; + +#[cfg(any(test, not(whale_wave_ir)))] +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum IntegerError { + Trap(TrapReason), + Backend(&'static str), +} + +#[cfg(any(test, not(whale_wave_ir)))] +impl From for IntegerError { + fn from(value: TrapReason) -> Self { + Self::Trap(value) + } +} +/// Mapping enum tags into the scalar wire inventory is a typed transport step. pub(crate) fn shape(ty: &Type) -> Option<(u32, bool)> { use Type::*; Some(match ty { @@ -23,151 +46,536 @@ pub(crate) fn shape(ty: &Type) -> Option<(u32, bool)> { }) } -fn mask(bits: u32) -> u128 { - if bits == 128 { - u128::MAX - } else { - (1u128 << bits) - 1 +#[cfg(all(test, whale_wave_ir))] +mod wave { + use super::*; + + #[repr(C)] + #[derive(Default)] + struct ResultRecord { + status: u64, + low: u64, + high: u64, + flag: u64, + } + + unsafe extern "C" { + fn whale_ir_integer( + mode: u64, + op: u64, + source_kind: u64, + destination_kind: u64, + a_low: u64, + a_high: u64, + b_low: u64, + b_high: u64, + result: *mut ResultRecord, + ) -> i32; + + fn whale_ir_integer_bits( + low: u64, + high: u64, + width: u64, + signed: u64, + result: *mut ResultRecord, + ) -> i32; + } + + fn backend() -> IntegerError { + IntegerError::Backend("integer semantics transport") + } + + fn kind(ty: &Type) -> Result { + Ok(match ty { + Type::Bool => 1, + Type::I1 => 2, + Type::U1 => 3, + Type::I8 => 4, + Type::I16 => 5, + Type::I32 => 6, + Type::I64 => 7, + Type::I128 => 8, + Type::U8 => 9, + Type::U16 => 10, + Type::U32 => 11, + Type::U64 => 12, + Type::U128 => 13, + _ => return Err(backend()), + }) + } + + fn payload(value: &ConstValue) -> Result { + Ok(match value { + ConstValue::Bool(value) => u128::from(*value), + ConstValue::I(value) => *value as u128, + ConstValue::U(value) => *value, + _ => return Err(backend()), + }) + } + + fn check( + status: i32, + record: &ResultRecord, + flags: bool, + traps: u8, + ) -> Result<(u128, bool), IntegerError> { + if i32::try_from(record.status).ok() != Some(status) + || record.flag > u64::from(flags) + || (status != 0 && (record.low != 0 || record.high != 0 || record.flag != 0)) + { + return Err(backend()); + } + if (1..=3).contains(&status) && traps & (1u8 << status) == 0 { + return Err(backend()); + } + match status { + 0 => Ok((u128::from(record.low) | (u128::from(record.high) << 64), record.flag != 0)), + 1 => Err(IntegerError::Trap(TrapReason::DivisionByZero)), + 2 => Err(IntegerError::Trap(TrapReason::RemainderByZero)), + 3 => Err(IntegerError::Trap(TrapReason::InvalidConversion)), + _ => Err(backend()), + } + } + + fn decode(ty: &Type, raw: u128) -> Result { + let value = match ty { + Type::Bool if raw <= 1 => ConstValue::Bool(raw != 0), + _ if shape(ty).is_some_and(|(_, signed)| signed) => ConstValue::I(raw as i128), + _ if shape(ty).is_some() => ConstValue::U(raw), + _ => return Err(backend()), + }; + if !crate::constant::valid_constant(ty, &value) { + return Err(backend()); + } + Ok(value) + } + + pub(super) fn bits(value: u128, width: u32, signed: bool) -> Result { + let mut result = ResultRecord::default(); + let status = unsafe { + whale_ir_integer_bits( + value as u64, + (value >> 64) as u64, + width.into(), + u64::from(signed), + &mut result, + ) + }; + check(status, &result, false, 0).map(|(value, _)| value) + } + + pub(super) fn call( + mode: u64, + op: u64, + source: &Type, + destination: &Type, + a: &ConstValue, + b: &ConstValue, + ) -> Result<(ConstValue, bool), IntegerError> { + let (source_kind, destination_kind) = (kind(source)?, kind(destination)?); + let (a, b) = (payload(a)?, payload(b)?); + let mut result = ResultRecord::default(); + let status = unsafe { + whale_ir_integer( + mode, + op, + source_kind, + destination_kind, + a as u64, + (a >> 64) as u64, + b as u64, + (b >> 64) as u64, + &mut result, + ) + }; + let traps = if mode == 4 { + 1 << 3 + } else if mode == 0 && matches!(op, 3 | 4) { + 1 << 1 + } else if mode == 0 && matches!(op, 5 | 6) { + 1 << 2 + } else { + 0 + }; + let (raw, flag) = check(status, &result, mode == 1, traps)?; + Ok((decode(destination, raw)?, flag)) + } + + #[cfg(test)] + mod transport_tests { + use super::*; + + #[test] + fn malformed_numeric_responses_cannot_be_fabricated_data_traps() { + for status in 1..=3 { + let record = ResultRecord { status: status as u64, ..Default::default() }; + assert!(matches!(check(status, &record, false, 0), Err(IntegerError::Backend(_)))); + assert!(matches!( + check(status, &record, false, 1 << status), + Err(IntegerError::Trap(_)) + )); + } + let record = ResultRecord { status: 1, low: 9, ..Default::default() }; + assert!(matches!(check(1, &record, false, 2), Err(IntegerError::Backend(_)))); + let record = ResultRecord { flag: 2, ..Default::default() }; + assert!(matches!(check(0, &record, true, 0), Err(IntegerError::Backend(_)))); + assert!(matches!(check(0, &ResultRecord::default(), false, 0), Ok((0, false)))); + assert!(matches!( + check(1, &ResultRecord::default(), false, 2), + Err(IntegerError::Backend(_)) + )); + } + } +} + +#[cfg(any(test, not(whale_wave_ir)))] +pub(crate) fn try_raw(value: &ConstValue, bits: u32) -> Result { + if bits == 0 || bits > 128 || matches!(value, ConstValue::F(_)) { + return Err(IntegerError::Backend("integer storage category")); + } + #[cfg(whale_wave_ir)] + { + let value = match value { + ConstValue::I(value) => *value as u128, + ConstValue::U(value) => *value, + ConstValue::Bool(value) => u128::from(*value), + _ => return Err(IntegerError::Backend("integer storage category")), + }; + wave::bits(value, bits, false) + } + #[cfg(not(whale_wave_ir))] + { + Ok(reference::raw(value, bits)) } } +#[cfg(any(test, not(whale_wave_ir)))] pub(crate) fn raw(value: &ConstValue, bits: u32) -> u128 { - (match value { - ConstValue::I(v) => *v as u128, - ConstValue::U(v) => *v, - ConstValue::Bool(v) => u128::from(*v), - ConstValue::F(_) => unreachable!("scalar subset checked before execution"), - }) & mask(bits) + try_raw(value, bits).expect("Wave integer storage transport") } -fn signed(value: u128, bits: u32) -> i128 { - if bits < 128 && value & (1u128 << (bits - 1)) != 0 { - (value | !mask(bits)) as i128 - } else { - value as i128 +#[cfg(any(test, not(whale_wave_ir)))] +pub(crate) fn try_pack(ty: &Type, value: u128) -> Result { + #[cfg(whale_wave_ir)] + { + wave::call(5, 0, ty, ty, &ConstValue::U(value), &ConstValue::U(0)).map(|(value, _)| value) + } + #[cfg(not(whale_wave_ir))] + { + Ok(reference::pack(ty, value)) } } +#[cfg(any(test, not(whale_wave_ir)))] pub(crate) fn pack(ty: &Type, value: u128) -> ConstValue { - let (bits, is_signed) = shape(ty).expect("integer subset checked"); - let value = value & mask(bits); - if is_signed { - ConstValue::I(signed(value, bits)) - } else { - ConstValue::U(value) - } + try_pack(ty, value).expect("Wave integer storage transport") } -pub(super) fn bin( +#[cfg(any(test, not(whale_wave_ir)))] +pub(crate) fn try_bin( op: &BinOp, ty: &Type, lhs: &ConstValue, rhs: &ConstValue, -) -> Result { - let (bits, _) = shape(ty).expect("integer subset checked"); - let a = raw(lhs, bits); - let b = raw(rhs, bits); - // Reduce the complete unsigned N-bit pattern before narrowing to a shift count. - let count = (b % u128::from(bits)) as u32; - let value = match op { - BinOp::Add => a.wrapping_add(b), - BinOp::Sub => a.wrapping_sub(b), - BinOp::Mul => a.wrapping_mul(b), - BinOp::UDiv | BinOp::SDiv if b == 0 => return Err(TrapReason::DivisionByZero), - BinOp::URem | BinOp::SRem if b == 0 => return Err(TrapReason::RemainderByZero), - BinOp::UDiv => a / b, - BinOp::URem => a % b, - BinOp::SDiv => signed(a, bits).wrapping_div(signed(b, bits)) as u128, - BinOp::SRem => signed(a, bits).wrapping_rem(signed(b, bits)) as u128, - BinOp::And => a & b, - BinOp::Or => a | b, - BinOp::Xor => a ^ b, - BinOp::Shl => a << count, - BinOp::LShr => a >> count, - BinOp::AShr => (signed(a, bits) >> count) as u128, - _ => unreachable!("integer subset checked"), - }; - Ok(pack(ty, value)) +) -> Result { + #[cfg(whale_wave_ir)] + { + let op = match op { + BinOp::Add => 0, + BinOp::Sub => 1, + BinOp::Mul => 2, + BinOp::UDiv => 3, + BinOp::SDiv => 4, + BinOp::URem => 5, + BinOp::SRem => 6, + BinOp::And => 12, + BinOp::Or => 13, + BinOp::Xor => 14, + BinOp::Shl => 15, + BinOp::LShr => 16, + BinOp::AShr => 17, + _ => return Err(IntegerError::Backend("noninteger binary opcode")), + }; + wave::call(0, op, ty, ty, lhs, rhs).map(|(value, _)| value) + } + #[cfg(not(whale_wave_ir))] + { + reference::bin(op, ty, lhs, rhs).map_err(Into::into) + } } -pub(super) fn checked( +#[cfg(any(test, not(whale_wave_ir)))] +pub(crate) fn try_checked( op: &CheckedOp, ty: &Type, lhs: &ConstValue, rhs: &ConstValue, -) -> (ConstValue, bool) { - let (bits, _) = shape(ty).expect("integer subset checked"); - let a = raw(lhs, bits); - let b = raw(rhs, bits); - let (wrapped, overflow) = match op { - CheckedOp::UAdd => { - let (sum, carry) = a.overflowing_add(b); - (sum, carry || sum > mask(bits)) - }, - CheckedOp::USub => (a.wrapping_sub(b), a < b), - CheckedOp::UMul => (a.wrapping_mul(b), a.checked_mul(b).is_none_or(|v| v > mask(bits))), - CheckedOp::SAdd | CheckedOp::SSub | CheckedOp::SMul => { - let sa = signed(a, bits); - let sb = signed(b, bits); - let (wrapped, exact) = match op { - CheckedOp::SAdd => (a.wrapping_add(b), sa.checked_add(sb)), - CheckedOp::SSub => (a.wrapping_sub(b), sa.checked_sub(sb)), - _ => (a.wrapping_mul(b), sa.checked_mul(sb)), - }; - let overflow = exact.is_none_or(|v| { - bits < 128 && (v < -(1i128 << (bits - 1)) || v >= (1i128 << (bits - 1))) - }); - (wrapped, overflow) - }, - }; - (pack(ty, wrapped), overflow) +) -> Result<(ConstValue, bool), IntegerError> { + #[cfg(whale_wave_ir)] + { + wave::call( + 1, + match op { + CheckedOp::UAdd => 0, + CheckedOp::USub => 1, + CheckedOp::UMul => 2, + CheckedOp::SAdd => 3, + CheckedOp::SSub => 4, + CheckedOp::SMul => 5, + }, + ty, + ty, + lhs, + rhs, + ) + } + #[cfg(not(whale_wave_ir))] + { + Ok(reference::checked(op, ty, lhs, rhs)) + } } -pub(super) fn cast(op: &CastOp, src_ty: &Type, dst_ty: &Type, value: &ConstValue) -> ConstValue { - let bits = shape(src_ty).map_or(1, |s| s.0); - let value = raw(value, bits); - let value = if *op == CastOp::SExt { signed(value, bits) as u128 } else { value }; - pack(dst_ty, value) +#[cfg(any(test, not(whale_wave_ir)))] +pub(crate) fn try_cast( + op: &CastOp, + source: &Type, + destination: &Type, + value: &ConstValue, +) -> Result { + #[cfg(whale_wave_ir)] + { + let op = match op { + CastOp::ZExt => 0, + CastOp::SExt => 1, + CastOp::Trunc => 2, + CastOp::Bitcast => 3, + _ => return Err(IntegerError::Backend("noninteger cast opcode")), + }; + wave::call(2, op, source, destination, value, &ConstValue::U(0)).map(|(value, _)| value) + } + #[cfg(not(whale_wave_ir))] + { + Ok(reference::cast(op, source, destination, value)) + } } -pub(super) fn compare( - pred: &crate::ICmpPred, +#[cfg(any(test, not(whale_wave_ir)))] +pub(crate) fn try_compare( + pred: &ICmpPred, ty: &Type, lhs: &ConstValue, rhs: &ConstValue, -) -> bool { - use crate::ICmpPred::*; - let bits = shape(ty).map_or(1, |s| s.0); - let a = raw(lhs, bits); - let b = raw(rhs, bits); - match pred { - Eq => a == b, - Ne => a != b, - Ult => a < b, - Ule => a <= b, - Ugt => a > b, - Uge => a >= b, - Slt => signed(a, bits) < signed(b, bits), - Sle => signed(a, bits) <= signed(b, bits), - Sgt => signed(a, bits) > signed(b, bits), - Sge => signed(a, bits) >= signed(b, bits), +) -> Result { + #[cfg(whale_wave_ir)] + { + let op = match pred { + ICmpPred::Eq => 0, + ICmpPred::Ne => 1, + ICmpPred::Ult => 2, + ICmpPred::Ule => 3, + ICmpPred::Ugt => 4, + ICmpPred::Uge => 5, + ICmpPred::Slt => 6, + ICmpPred::Sle => 7, + ICmpPred::Sgt => 8, + ICmpPred::Sge => 9, + }; + let (ConstValue::Bool(value), _) = wave::call(3, op, ty, &Type::Bool, lhs, rhs)? else { + return Err(IntegerError::Backend("integer comparison transport")); + }; + Ok(value) + } + #[cfg(not(whale_wave_ir))] + { + Ok(reference::compare(pred, ty, lhs, rhs)) + } +} + +#[cfg(any(test, not(whale_wave_ir)))] +pub(crate) fn try_checked_cast( + source: &Type, + destination: &Type, + value: &ConstValue, +) -> Result { + #[cfg(whale_wave_ir)] + { + wave::call(4, 0, source, destination, value, &ConstValue::U(0)).map(|(value, _)| value) + } + #[cfg(not(whale_wave_ir))] + { + reference::checked_cast(source, destination, value).map_err(Into::into) } } -/// Range checks use mathematical sign/magnitude, never an overflowing i128 cast. -pub(super) fn checked_cast( - src: &Type, - dst: &Type, +#[cfg(any(test, not(whale_wave_ir)))] +pub(crate) fn try_unary( + negate: bool, + ty: &Type, value: &ConstValue, -) -> Result { - let (sb, ss) = shape(src).expect("verified integer source"); - let (db, ds) = shape(dst).expect("verified integer destination"); - let raw = raw(value, sb); - let negative = ss && signed(raw, sb) < 0; - let magnitude = if negative { signed(raw, sb).unsigned_abs() } else { raw }; - let maximum = if ds { (1u128 << (db - 1)) - u128::from(!negative) } else { mask(db) }; - if (negative && !ds) || magnitude > maximum { - return Err(TrapReason::InvalidConversion); - } - Ok(pack(dst, if negative { 0u128.wrapping_sub(magnitude) } else { magnitude })) +) -> Result { + #[cfg(whale_wave_ir)] + { + wave::call(6, u64::from(!negate), ty, ty, value, &ConstValue::U(0)).map(|(value, _)| value) + } + #[cfg(not(whale_wave_ir))] + { + let raw = reference::raw(value, shape(ty).expect("integer unary type").0); + Ok(reference::pack(ty, if negate { 0u128.wrapping_sub(raw) } else { !raw })) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn types() -> [Type; 12] { + [ + Type::I1, + Type::U1, + Type::I8, + Type::U8, + Type::I16, + Type::U16, + Type::I32, + Type::U32, + Type::I64, + Type::U64, + Type::I128, + Type::U128, + ] + } + + #[test] + fn numeric_bridge_matches_reference_at_all_widths_and_signed_boundaries() { + let mut random = 0x0035_2035_2128_u128; + for ty in types() { + let width = shape(&ty).unwrap().0; + let bit = 1u128 << (width - 1); + let patterns = [0, 1, bit, bit.wrapping_sub(1), u128::MAX, u64::MAX as u128]; + for raw in patterns { + let a = reference::pack(&ty, raw); + assert_eq!(pack(&ty, raw), a); + assert_eq!( + super::raw(&a, shape(&ty).unwrap().0), + reference::raw(&a, shape(&ty).unwrap().0) + ); + assert_eq!( + try_unary(true, &ty, &a).unwrap(), + reference::pack(&ty, 0u128.wrapping_sub(raw)) + ); + assert_eq!(try_unary(false, &ty, &a).unwrap(), reference::pack(&ty, !raw)); + for _ in 0..20 { + random ^= random << 13; + random ^= random >> 17; + random ^= random << 5; + let b = reference::pack(&ty, random); + for op in [ + BinOp::Add, + BinOp::Sub, + BinOp::Mul, + BinOp::UDiv, + BinOp::SDiv, + BinOp::URem, + BinOp::SRem, + BinOp::And, + BinOp::Or, + BinOp::Xor, + BinOp::Shl, + BinOp::LShr, + BinOp::AShr, + ] { + assert_eq!( + try_bin(&op, &ty, &a, &b), + reference::bin(&op, &ty, &a, &b).map_err(IntegerError::Trap), + "{ty:?} {op:?} {a:?} {b:?}" + ); + } + for op in [ + CheckedOp::UAdd, + CheckedOp::USub, + CheckedOp::UMul, + CheckedOp::SAdd, + CheckedOp::SSub, + CheckedOp::SMul, + ] { + assert_eq!( + try_checked(&op, &ty, &a, &b).unwrap(), + reference::checked(&op, &ty, &a, &b) + ); + } + for pred in [ + ICmpPred::Eq, + ICmpPred::Ne, + ICmpPred::Ult, + ICmpPred::Ule, + ICmpPred::Ugt, + ICmpPred::Uge, + ICmpPred::Slt, + ICmpPred::Sle, + ICmpPred::Sgt, + ICmpPred::Sge, + ] { + assert_eq!( + try_compare(&pred, &ty, &a, &b).unwrap(), + reference::compare(&pred, &ty, &a, &b) + ); + } + for destination in types() { + assert_eq!( + try_checked_cast(&ty, &destination, &a), + reference::checked_cast(&ty, &destination, &a) + .map_err(IntegerError::Trap) + ); + let dest_width = shape(&destination).unwrap().0; + for op in if width < dest_width { + vec![CastOp::ZExt, CastOp::SExt] + } else if width > dest_width { + vec![CastOp::Trunc] + } else { + vec![CastOp::Bitcast] + } { + assert_eq!( + try_cast(&op, &ty, &destination, &a).unwrap(), + reference::cast(&op, &ty, &destination, &a) + ); + } + } + } + } + } + for pred in [ICmpPred::Eq, ICmpPred::Ne] { + for a in [false, true] { + for b in [false, true] { + assert_eq!( + try_compare(&pred, &Type::Bool, &ConstValue::Bool(a), &ConstValue::Bool(b)) + .unwrap(), + reference::compare( + &pred, + &Type::Bool, + &ConstValue::Bool(a), + &ConstValue::Bool(b) + ) + ); + } + } + } + } + + #[cfg(whale_wave_ir)] + #[test] + fn invalid_backend_requests_remain_distinct_from_defined_data_traps() { + assert_eq!( + try_bin(&BinOp::FAdd, &Type::I32, &ConstValue::I(1), &ConstValue::I(2)), + Err(IntegerError::Backend("noninteger binary opcode")) + ); + assert!(matches!(try_pack(&Type::F64, 1), Err(IntegerError::Backend(_)))); + assert_eq!( + try_bin(&BinOp::UDiv, &Type::U128, &ConstValue::U(1), &ConstValue::U(0)), + Err(IntegerError::Trap(TrapReason::DivisionByZero)) + ); + assert_eq!( + try_bin(&BinOp::SRem, &Type::I128, &ConstValue::I(1), &ConstValue::I(0)), + Err(IntegerError::Trap(TrapReason::RemainderByZero)) + ); + } } diff --git a/ir/src/interpreter/integer_reference.rs b/ir/src/interpreter/integer_reference.rs new file mode 100644 index 0000000..2efe9d0 --- /dev/null +++ b/ir/src/interpreter/integer_reference.rs @@ -0,0 +1,173 @@ +// SPDX-License-Identifier: MPL-2.0 + +use super::TrapReason; + +use crate::{BinOp, CastOp, CheckedOp, ConstValue, Type}; + +pub(crate) fn shape(ty: &Type) -> Option<(u32, bool)> { + use Type::*; + Some(match ty { + I1 => (1, true), + U1 => (1, false), + I8 => (8, true), + U8 => (8, false), + I16 => (16, true), + U16 => (16, false), + I32 => (32, true), + U32 => (32, false), + I64 => (64, true), + U64 => (64, false), + I128 => (128, true), + U128 => (128, false), + _ => return None, + }) +} + +fn mask(bits: u32) -> u128 { + if bits == 128 { + u128::MAX + } else { + (1u128 << bits) - 1 + } +} + +pub(crate) fn raw(value: &ConstValue, bits: u32) -> u128 { + (match value { + ConstValue::I(v) => *v as u128, + ConstValue::U(v) => *v, + ConstValue::Bool(v) => u128::from(*v), + ConstValue::F(_) => unreachable!("scalar subset checked before execution"), + }) & mask(bits) +} + +fn signed(value: u128, bits: u32) -> i128 { + if bits < 128 && value & (1u128 << (bits - 1)) != 0 { + (value | !mask(bits)) as i128 + } else { + value as i128 + } +} + +pub(crate) fn pack(ty: &Type, value: u128) -> ConstValue { + let (bits, is_signed) = shape(ty).expect("integer subset checked"); + let value = value & mask(bits); + if is_signed { + ConstValue::I(signed(value, bits)) + } else { + ConstValue::U(value) + } +} + +pub(super) fn bin( + op: &BinOp, + ty: &Type, + lhs: &ConstValue, + rhs: &ConstValue, +) -> Result { + let (bits, _) = shape(ty).expect("integer subset checked"); + let a = raw(lhs, bits); + let b = raw(rhs, bits); + // Reduce the complete unsigned N-bit pattern before narrowing to a shift count. + let count = (b % u128::from(bits)) as u32; + let value = match op { + BinOp::Add => a.wrapping_add(b), + BinOp::Sub => a.wrapping_sub(b), + BinOp::Mul => a.wrapping_mul(b), + BinOp::UDiv | BinOp::SDiv if b == 0 => return Err(TrapReason::DivisionByZero), + BinOp::URem | BinOp::SRem if b == 0 => return Err(TrapReason::RemainderByZero), + BinOp::UDiv => a / b, + BinOp::URem => a % b, + BinOp::SDiv => signed(a, bits).wrapping_div(signed(b, bits)) as u128, + BinOp::SRem => signed(a, bits).wrapping_rem(signed(b, bits)) as u128, + BinOp::And => a & b, + BinOp::Or => a | b, + BinOp::Xor => a ^ b, + BinOp::Shl => a << count, + BinOp::LShr => a >> count, + BinOp::AShr => (signed(a, bits) >> count) as u128, + _ => unreachable!("integer subset checked"), + }; + Ok(pack(ty, value)) +} + +pub(super) fn checked( + op: &CheckedOp, + ty: &Type, + lhs: &ConstValue, + rhs: &ConstValue, +) -> (ConstValue, bool) { + let (bits, _) = shape(ty).expect("integer subset checked"); + let a = raw(lhs, bits); + let b = raw(rhs, bits); + let (wrapped, overflow) = match op { + CheckedOp::UAdd => { + let (sum, carry) = a.overflowing_add(b); + (sum, carry || sum > mask(bits)) + }, + CheckedOp::USub => (a.wrapping_sub(b), a < b), + CheckedOp::UMul => (a.wrapping_mul(b), a.checked_mul(b).is_none_or(|v| v > mask(bits))), + CheckedOp::SAdd | CheckedOp::SSub | CheckedOp::SMul => { + let sa = signed(a, bits); + let sb = signed(b, bits); + let (wrapped, exact) = match op { + CheckedOp::SAdd => (a.wrapping_add(b), sa.checked_add(sb)), + CheckedOp::SSub => (a.wrapping_sub(b), sa.checked_sub(sb)), + _ => (a.wrapping_mul(b), sa.checked_mul(sb)), + }; + let overflow = exact.is_none_or(|v| { + bits < 128 && (v < -(1i128 << (bits - 1)) || v >= (1i128 << (bits - 1))) + }); + (wrapped, overflow) + }, + }; + (pack(ty, wrapped), overflow) +} + +pub(super) fn cast(op: &CastOp, src_ty: &Type, dst_ty: &Type, value: &ConstValue) -> ConstValue { + let bits = shape(src_ty).map_or(1, |s| s.0); + let value = raw(value, bits); + let value = if *op == CastOp::SExt { signed(value, bits) as u128 } else { value }; + pack(dst_ty, value) +} + +pub(super) fn compare( + pred: &crate::ICmpPred, + ty: &Type, + lhs: &ConstValue, + rhs: &ConstValue, +) -> bool { + use crate::ICmpPred::*; + let bits = shape(ty).map_or(1, |s| s.0); + let a = raw(lhs, bits); + let b = raw(rhs, bits); + match pred { + Eq => a == b, + Ne => a != b, + Ult => a < b, + Ule => a <= b, + Ugt => a > b, + Uge => a >= b, + Slt => signed(a, bits) < signed(b, bits), + Sle => signed(a, bits) <= signed(b, bits), + Sgt => signed(a, bits) > signed(b, bits), + Sge => signed(a, bits) >= signed(b, bits), + } +} + +/// Range checks use mathematical sign/magnitude, never an overflowing i128 cast. +pub(super) fn checked_cast( + src: &Type, + dst: &Type, + value: &ConstValue, +) -> Result { + let (sb, ss) = shape(src).expect("verified integer source"); + let (db, ds) = shape(dst).expect("verified integer destination"); + let raw = raw(value, sb); + let negative = ss && signed(raw, sb) < 0; + let magnitude = if negative { signed(raw, sb).unsigned_abs() } else { raw }; + let maximum = if ds { (1u128 << (db - 1)) - u128::from(!negative) } else { mask(db) }; + if (negative && !ds) || magnitude > maximum { + return Err(TrapReason::InvalidConversion); + } + Ok(pack(dst, if negative { 0u128.wrapping_sub(magnitude) } else { magnitude })) +} diff --git a/ir/src/interpreter/memory.rs b/ir/src/interpreter/memory.rs index c72bcf0..8771ca8 100644 --- a/ir/src/interpreter/memory.rs +++ b/ir/src/interpreter/memory.rs @@ -1,15 +1,18 @@ // SPDX-License-Identifier: MPL-2.0 //! Synthetic 64-bit addresses, byte initialization and separately copied capabilities. -use super::{scalar, FunctionPointer, FunctionTarget, Value}; +#[cfg(not(whale_wave_ir))] +use super::scalar; + +use super::{FunctionPointer, FunctionTarget, Value}; use crate::{ConstValue, Target, Type, TypeLayout}; -use std::{ - collections::HashMap, - sync::{ - atomic::{AtomicU64, Ordering}, - Arc, - }, +#[cfg(not(whale_wave_ir))] +use std::collections::HashMap; + +use std::sync::{ + atomic::{AtomicU64, Ordering}, + Arc, }; static NEXT_ARENA: AtomicU64 = AtomicU64::new(1); @@ -89,7 +92,12 @@ impl std::fmt::Display for MemoryTrap { #[derive(Debug)] pub(super) enum Fault { Trap(MemoryTrap), - Limit { resource: MemoryResource, limit: u64 }, + Limit { + resource: MemoryResource, + limit: u64, + }, + #[cfg_attr(not(whale_wave_ir), allow(dead_code))] + Backend(&'static str), } impl From for Fault { @@ -101,21 +109,21 @@ impl From for Fault { type Result = std::result::Result; #[derive(Clone, Copy, Debug, PartialEq, Eq)] -struct Capability { - arena: u64, - allocation: usize, - generation: u64, - lower: u64, - upper: u64, - offset: u64, - read: bool, - write: bool, +pub(super) struct Capability { + pub(super) arena: u64, + pub(super) allocation: usize, + pub(super) generation: u64, + pub(super) lower: u64, + pub(super) upper: u64, + pub(super) offset: u64, + pub(super) read: bool, + pub(super) write: bool, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) struct Pointer { pub address: u64, - capability: Option, + pub(super) capability: Option, } impl Pointer { @@ -124,589 +132,30 @@ impl Pointer { } } -#[derive(Clone, Debug, PartialEq, Eq)] -enum StoredPointer { - Data(Pointer), - Function(FunctionPointer), -} - -impl StoredPointer { - fn bits(&self) -> u64 { - match self { - Self::Data(p) => p.address, - Self::Function(p) => p.bits(), - } - } -} - -#[derive(Clone, Debug, PartialEq, Eq)] -struct Fragment { - pointer: StoredPointer, - byte: u8, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum AllocationKind { - Stack, - Global, -} - -struct Allocation { - kind: AllocationKind, - address: u64, - generation: u64, - alive: bool, - read: bool, - write: bool, - bytes: Vec, - initialized: Vec, - fragments: HashMap, -} - #[derive(Clone, Debug)] pub(super) enum GepStep { Stride(u64), Field(u64), } -pub(super) struct Memory { - arena: u64, - allocations: Vec, - limits: MemoryLimits, - bytes: u64, - fragments: usize, - work: u64, - next_address: u64, -} - fn layout(ty: &Type) -> TypeLayout { crate::layout_of_with_limit(ty, Target::X86_64WhaleLinux, crate::MAX_IR_NESTING) .expect("bounded layout checked before execution") } -impl Memory { - pub fn new(limits: MemoryLimits) -> Self { - Self { - arena: NEXT_ARENA.fetch_add(1, Ordering::Relaxed), - allocations: Vec::new(), - limits, - bytes: 0, - fragments: 0, - work: 0, - next_address: 0x1000, - } - } - - fn limit(resource: MemoryResource, limit: u64) -> Fault { - Fault::Limit { resource, limit } - } - - fn charge(&mut self, work: u64) -> Result<()> { - self.work = self - .work - .checked_add(work) - .filter(|n| *n <= self.limits.max_work) - .ok_or_else(|| Self::limit(MemoryResource::Work, self.limits.max_work))?; - Ok(()) - } - - pub fn allocate(&mut self, size: u64, natural: u32, align: u32) -> Result { - if self.allocations.len() >= self.limits.max_allocations { - return Err(Self::limit( - MemoryResource::Allocations, - self.limits.max_allocations as u64, - )); - } - let bytes = self - .bytes - .checked_add(size) - .filter(|n| *n <= self.limits.max_bytes) - .ok_or_else(|| Self::limit(MemoryResource::Bytes, self.limits.max_bytes))?; - let length = - usize::try_from(size).map_err(|_| Self::limit(MemoryResource::HostAllocation, size))?; - let alignment = u64::from(align.max(natural)); - let address = self - .next_address - .checked_add(alignment - 1) - .map(|a| a & !(alignment - 1)) - .ok_or(MemoryTrap::AddressOverflow)?; - let next = address - .checked_add(size.max(1)) - .and_then(|a| a.checked_add(1)) - .ok_or(MemoryTrap::AddressOverflow)?; - self.charge( - size.checked_mul(2) - .and_then(|n| n.checked_add(1)) - .ok_or(MemoryTrap::AddressOverflow)?, - )?; - let mut data = Vec::new(); - let mut initialized = Vec::new(); - data.try_reserve_exact(length) - .map_err(|_| Self::limit(MemoryResource::HostAllocation, size))?; - initialized - .try_reserve_exact(length) - .map_err(|_| Self::limit(MemoryResource::HostAllocation, size))?; - self.allocations - .try_reserve(1) - .map_err(|_| Self::limit(MemoryResource::HostAllocation, size))?; - // Physical zero bytes are not semantic initialization. - data.resize(length, 0); - initialized.resize(length, 0); - let capability = Capability { - arena: self.arena, - allocation: self.allocations.len(), - generation: 0, - lower: 0, - upper: size, - offset: 0, - read: true, - write: true, - }; - self.allocations.push(Allocation { - kind: AllocationKind::Stack, - address, - generation: 0, - alive: true, - read: true, - write: true, - bytes: data, - initialized, - fragments: HashMap::new(), - }); - self.bytes = bytes; - self.next_address = next; - Ok(Pointer { address, capability: Some(capability) }) - } - - pub fn allocate_global(&mut self, size: u64, natural: u32, align: u32) -> Result { - let pointer = self.allocate(size, natural, align)?; - self.allocations[pointer.capability.unwrap().allocation].kind = AllocationKind::Global; - Ok(pointer) - } - - pub fn seal_global(&mut self, mut pointer: Pointer, readonly: bool) -> Result { - let (id, _) = self.identity(pointer)?; - if self.allocations[id].kind != AllocationKind::Global { - return Err(MemoryTrap::InvalidLifetimeEnd.into()); - } - self.allocations[id].write = !readonly; - pointer.capability.as_mut().unwrap().write = !readonly; - Ok(pointer) - } - - pub fn retire_stack(&mut self, pointer: Pointer, owner_start: usize) -> Result<()> { - let (id, capability) = self.identity(pointer)?; - if id < owner_start - || self.allocations[id].kind != AllocationKind::Stack - || capability.offset != 0 - || capability.lower != 0 - || capability.upper != self.allocations[id].bytes.len() as u64 - { - return Err(MemoryTrap::InvalidLifetimeEnd.into()); - } - self.charge(1 + self.allocations[id].fragments.len() as u64)?; - self.retire_allocation(id); - Ok(()) - } - - fn retire_allocation(&mut self, id: usize) { - let allocation = &mut self.allocations[id]; - if allocation.alive { - allocation.alive = false; - self.fragments -= allocation.fragments.len(); - allocation.fragments.clear(); - allocation.bytes.clear(); - allocation.initialized.clear(); - } - } - - pub fn difference(&self, lhs: Pointer, rhs: Pointer) -> Result { - let (a, left) = self.identity(lhs)?; - let (b, right) = self.identity(rhs)?; - if a != b || left.generation != right.generation { - return Err(MemoryTrap::DifferentAllocation.into()); - } - Ok(i128::from(left.offset) - i128::from(right.offset)) - } - - pub fn compare_order(&self, lhs: Pointer, rhs: Pointer) -> Result { - Ok(self.difference(lhs, rhs)?.cmp(&0)) - } - - fn identity(&self, pointer: Pointer) -> Result<(usize, Capability)> { - if pointer.address == 0 { - return Err(MemoryTrap::NullPointer.into()); - } - let cap = pointer.capability.ok_or(MemoryTrap::MissingProvenance)?; - if cap.arena != self.arena { - return Err(MemoryTrap::ExpiredAllocation.into()); - } - let allocation = - self.allocations.get(cap.allocation).ok_or(MemoryTrap::ExpiredAllocation)?; - if !allocation.alive || allocation.generation != cap.generation { - return Err(MemoryTrap::ExpiredAllocation.into()); - } - if cap.lower > cap.offset - || cap.offset > cap.upper - || cap.upper > allocation.bytes.len() as u64 - || allocation.address.checked_add(cap.offset) != Some(pointer.address) - { - return Err(MemoryTrap::OutOfBounds.into()); - } - Ok((cap.allocation, cap)) - } - - fn access( - &self, - pointer: Pointer, - n: u64, - align: u32, - write: bool, - ) -> Result<(usize, usize, usize)> { - let (id, cap) = self.identity(pointer)?; - let end = cap.offset.checked_add(n).ok_or(MemoryTrap::AddressOverflow)?; - if end > cap.upper { - return Err(MemoryTrap::OutOfBounds.into()); - } - let allocation = &self.allocations[id]; - let permitted = - if write { cap.write && allocation.write } else { cap.read && allocation.read }; - if !permitted { - return Err(MemoryTrap::PermissionDenied.into()); - } - if pointer.address % u64::from(align) != 0 { - return Err( - MemoryTrap::Misaligned { address: pointer.address, alignment: align }.into() - ); - } - Ok((id, cap.offset as usize, end as usize)) - } - - pub fn gep( - &self, - pointer: Pointer, - plan: &[GepStep], - indices: &[ConstValue], - ) -> Result { - if indices.is_empty() { - return Ok(pointer); - } - let (_, mut cap) = self.identity(pointer)?; - let base = i128::from(pointer.address) - i128::from(cap.offset); - let mut offset = i128::from(cap.offset); - for (step, index) in plan.iter().zip(indices) { - let delta = match step { - GepStep::Field(offset) => i128::from(*offset), - GepStep::Stride(stride) => { - let index = match index { - ConstValue::I(v) => *v, - ConstValue::U(v) => { - i128::try_from(*v).map_err(|_| MemoryTrap::AddressOverflow)? - }, - _ => unreachable!("verified integer GEP index"), - }; - index.checked_mul(i128::from(*stride)).ok_or(MemoryTrap::AddressOverflow)? - }, - }; - offset = offset.checked_add(delta).ok_or(MemoryTrap::AddressOverflow)?; - let address = base.checked_add(offset).ok_or(MemoryTrap::AddressOverflow)?; - if !(0..=i128::from(u64::MAX)).contains(&address) { - return Err(MemoryTrap::AddressOverflow.into()); - } - } - let offset = u64::try_from(offset).map_err(|_| MemoryTrap::OutOfBounds)?; - if offset < cap.lower || offset > cap.upper { - return Err(MemoryTrap::OutOfBounds.into()); - } - let address = u64::try_from(base + i128::from(offset)).unwrap(); - cap.offset = offset; - Ok(Pointer { address, capability: Some(cap) }) - } - - pub fn equal(&self, lhs: Pointer, rhs: Pointer) -> Result { - if lhs.address == 0 && rhs.address == 0 { - return Ok(true); - } - if lhs.address == 0 { - self.identity(rhs)?; - return Ok(false); - } - if rhs.address == 0 { - self.identity(lhs)?; - return Ok(false); - } - let (_, a) = self.identity(lhs)?; - let (_, b) = self.identity(rhs)?; - Ok((a.allocation, a.generation, a.offset) == (b.allocation, b.generation, b.offset)) - } - - fn replace_fragments( - &mut self, - id: usize, - start: usize, - end: usize, - new: &[(usize, Fragment)], - ) -> Result<()> { - let allocation = &self.allocations[id]; - self.charge(3 * allocation.fragments.capacity() as u64 + new.len() as u64)?; - let removed = - self.allocations[id].fragments.keys().filter(|i| **i >= start && **i < end).count(); - let count = self.fragments - removed + new.len(); - if count > self.limits.max_pointer_fragments { - return Err(Self::limit( - MemoryResource::PointerFragments, - self.limits.max_pointer_fragments as u64, - )); - } - self.allocations[id] - .fragments - .try_reserve(new.len()) - .map_err(|_| Self::limit(MemoryResource::HostAllocation, new.len() as u64))?; - self.allocations[id].fragments.retain(|i, _| *i < start || *i >= end); - self.allocations[id].fragments.extend(new.iter().cloned()); - self.fragments = count; - Ok(()) - } - - pub fn uninit(&mut self, pointer: Pointer, size: u64, align: u32) -> Result<()> { - let (id, start, end) = self.access(pointer, size, align, true)?; - self.charge((end - start) as u64)?; - self.replace_fragments(id, start, end, &[])?; - self.allocations[id].initialized[start..end].fill(0); - Ok(()) - } - - pub fn copy(&mut self, dst: Pointer, src: Pointer, size: u64, align: u32) -> Result<()> { - // No access occurs for an empty operation, even for null/raw pointers. - if size == 0 { - return Ok(()); - } - let (source, ss, se) = self.access(src, size, align, false)?; - let (destination, ds, de) = self.access(dst, size, align, true)?; - if source == destination && ss < de && ds < se { - return Err(MemoryTrap::OverlappingCopy.into()); - } - self.charge( - size.checked_mul(4) - .ok_or(MemoryTrap::AddressOverflow)? - .checked_add(self.allocations[source].fragments.capacity() as u64) - .ok_or(MemoryTrap::AddressOverflow)?, - )?; - let source = &self.allocations[source]; - let mut data = Vec::new(); - let mut initialized = Vec::new(); - let mut fragments = Vec::new(); - let count = source.fragments.len().min(se - ss); - data.try_reserve_exact(se - ss) - .map_err(|_| Self::limit(MemoryResource::HostAllocation, size))?; - initialized - .try_reserve_exact(se - ss) - .map_err(|_| Self::limit(MemoryResource::HostAllocation, size))?; - fragments - .try_reserve_exact(count) - .map_err(|_| Self::limit(MemoryResource::HostAllocation, count as u64))?; - data.extend_from_slice(&source.bytes[ss..se]); - initialized.extend_from_slice(&source.initialized[ss..se]); - fragments.extend( - source - .fragments - .iter() - .filter(|(at, _)| **at >= ss && **at < se) - .map(|(at, tag)| (ds + (*at - ss), tag.clone())), - ); - // Reserve/check metadata before any destination bytes are changed. - self.replace_fragments(destination, ds, de, &fragments)?; - self.allocations[destination].bytes[ds..de].copy_from_slice(&data); - self.allocations[destination].initialized[ds..de].copy_from_slice(&initialized); - Ok(()) - } - - pub fn set(&mut self, dst: Pointer, byte: u8, size: u64, align: u32) -> Result<()> { - if size == 0 { - return Ok(()); - } - let (id, start, end) = self.access(dst, size, align, true)?; - self.charge(size.checked_mul(2).ok_or(MemoryTrap::AddressOverflow)?)?; - self.replace_fragments(id, start, end, &[])?; - self.allocations[id].bytes[start..end].fill(byte); - self.allocations[id].initialized[start..end].fill(1); - Ok(()) - } +#[cfg(not(whale_wave_ir))] +#[path = "memory_reference.rs"] +mod reference; - #[cfg(test)] - pub fn load(&mut self, pointer: Pointer, ty: &Type, align: u32) -> Result { - self.load_with_signature(pointer, ty, align, None) - } +#[cfg(not(whale_wave_ir))] +pub(super) use reference::Memory; - pub fn load_with_signature( - &mut self, - pointer: Pointer, - ty: &Type, - align: u32, - signature: Option<&Arc>, - ) -> Result { - let (id, start, end) = self.access(pointer, layout(ty).size, align, false)?; - self.charge((end - start) as u64)?; - if let Type::Tuple(fields) = ty { - let offsets = layout(ty).field_offsets; - let a = self.load_scalar(id, start + offsets[0] as usize, &fields[0], None)?; - let b = self.load_scalar(id, start + offsets[1] as usize, &fields[1], None)?; - return Ok(Value::Checked(a.scalar().clone(), b.boolean())); - } - self.load_scalar(id, start, ty, signature) - } - - fn load_scalar( - &self, - id: usize, - start: usize, - ty: &Type, - callable_signature: Option<&Arc>, - ) -> Result { - let allocation = &self.allocations[id]; - let n = layout(ty).size as usize; - for offset in start..start + n { - if allocation.initialized[offset] == 0 { - return Err(MemoryTrap::Uninitialized { offset: offset as u64 }.into()); - } - } - let bytes = &allocation.bytes[start..start + n]; - if *ty == Type::Bool { - return match bytes[0] { - 0 => Ok(Value::Scalar(ConstValue::Bool(false))), - 1 => Ok(Value::Scalar(ConstValue::Bool(true))), - byte => Err(MemoryTrap::InvalidBool { byte }.into()), - }; - } - if matches!(ty, Type::Ptr(_) | Type::FnPtr(_)) { - let address = u64::from_le_bytes(bytes.try_into().unwrap()); - let complete = allocation.fragments.get(&start).filter(|fragment| { - fragment.byte == 0 - && fragment.pointer.bits() == address - && (0..8).all(|i| { - allocation.fragments.get(&(start + i)) - == Some(&Fragment { pointer: fragment.pointer.clone(), byte: i as u8 }) - }) - }); - return Ok(match ty { - Type::Ptr(_) => Value::Pointer(if address == 0 { - Pointer::raw(0) - } else { - match complete.map(|f| &f.pointer) { - Some(StoredPointer::Data(pointer)) => *pointer, - _ => Pointer::raw(address), - } - }), - Type::FnPtr(signature) => { - let signature = callable_signature - .cloned() - .unwrap_or_else(|| Arc::new((**signature).clone())); - let target = if address == 0 { - FunctionTarget::Null - } else { - match complete.map(|f| &f.pointer) { - Some(StoredPointer::Function(pointer)) - if pointer.signature == signature => - { - return Ok(Value::FunctionPointer(pointer.clone())) - }, - _ => FunctionTarget::InvalidBits(address), - } - }; - Value::FunctionPointer(FunctionPointer { signature, target }) - }, - _ => unreachable!(), - }); - } - let mut bits = [0u8; 16]; - bits[..n].copy_from_slice(bytes); - Ok(Value::Scalar(scalar::pack(ty, u128::from_le_bytes(bits)))) - } +#[cfg(whale_wave_ir)] +#[path = "memory_wave.rs"] +mod wave; - pub fn store(&mut self, pointer: Pointer, ty: &Type, value: &Value, align: u32) -> Result<()> { - let (id, start, end) = self.access(pointer, layout(ty).size, align, true)?; - let mut bytes = Vec::new(); - let mut fragments = Vec::new(); - if let (Type::Tuple(fields), Value::Checked(v, flag)) = (ty, value) { - let offsets = layout(ty).field_offsets; - Self::encode( - &fields[0], - &Value::Scalar(v.clone()), - start + offsets[0] as usize, - &mut bytes, - &mut fragments, - ); - Self::encode( - &fields[1], - &Value::Scalar(ConstValue::Bool(*flag)), - start + offsets[1] as usize, - &mut bytes, - &mut fragments, - ); - } else { - Self::encode(ty, value, start, &mut bytes, &mut fragments); - } - self.charge((end - start) as u64)?; - self.replace_fragments(id, start, end, &fragments)?; - for (at, byte) in bytes { - self.allocations[id].bytes[at] = byte; - self.allocations[id].initialized[at] = 1; - } - Ok(()) - } - - fn encode( - ty: &Type, - value: &Value, - start: usize, - bytes: &mut Vec<(usize, u8)>, - fragments: &mut Vec<(usize, Fragment)>, - ) { - let n = layout(ty).size as usize; - let data = match value { - Value::Pointer(p) => { - for i in 0..8 { - fragments.push(( - start + i, - Fragment { pointer: StoredPointer::Data(*p), byte: i as u8 }, - )); - } - u128::from(p.address).to_le_bytes() - }, - Value::FunctionPointer(p) => { - for i in 0..8 { - fragments.push(( - start + i, - Fragment { pointer: StoredPointer::Function(p.clone()), byte: i as u8 }, - )); - } - u128::from(p.bits()).to_le_bytes() - }, - Value::Scalar(v) => scalar::raw(ty, v).to_le_bytes(), - _ => unreachable!("verified scalar or checked storage"), - }; - bytes.extend(data[..n].iter().enumerate().map(|(i, b)| (start + i, *b))); - } - - pub fn allocation_count(&self) -> usize { - self.allocations.len() - } - - pub fn retire_from(&mut self, start: usize) -> Result<()> { - self.charge((self.allocations.len() - start) as u64)?; - for id in start..self.allocations.len() { - if self.allocations[id].kind == AllocationKind::Stack { - self.retire_allocation(id); - } - } - Ok(()) - } - - #[cfg(test)] - pub fn retire_all(&mut self) { - self.retire_from(0).unwrap(); - } -} +#[cfg(whale_wave_ir)] +pub(super) use wave::Memory; #[cfg(test)] mod tests { @@ -749,15 +198,15 @@ mod tests { m.store(readonly, &Type::U64, &Value::Scalar(ConstValue::U(0)), 8), MemoryTrap::PermissionDenied, ); - m.allocations[0].read = false; + m.test_read(0, false); trapped(m.load(p, &Type::U8, 1), MemoryTrap::PermissionDenied); - m.allocations[0].read = true; + m.test_read(0, true); let mut narrow = p; narrow.capability.as_mut().unwrap().upper = 4; trapped(m.load(narrow, &Type::U64, 1), MemoryTrap::OutOfBounds); - m.allocations[0].generation += 1; + m.test_generation(0, 1); trapped(m.load(p, &Type::U8, 1), MemoryTrap::ExpiredAllocation); - m.allocations[0].generation -= 1; + m.test_generation(0, -1); m.retire_all(); trapped(m.load(p, &Type::U8, 1), MemoryTrap::ExpiredAllocation); // Empty copy/set do not access even an expired capability. diff --git a/ir/src/interpreter/memory/generated.rs b/ir/src/interpreter/memory/generated.rs index a1bbb96..6b0c6cf 100644 --- a/ir/src/interpreter/memory/generated.rs +++ b/ir/src/interpreter/memory/generated.rs @@ -395,6 +395,9 @@ fn run(ops: &[Op]) { for (i, &op) in ops.iter().enumerate() { let expected = model.apply(op, &bits); let result = actual(&mut memory, bases, &tokens, &types, global, op); + if let (Err(Fault::Trap(actual)), Err(expected)) = (&result, &expected) { + assert_eq!(actual, expected, "operation {i}: {op:?}"); + } outcome(result, expected); check_state(&mut memory, bases, &tokens, global, &model, &signature); assert!(memory.work <= 4_000_000, "step {i}"); @@ -544,37 +547,19 @@ fn memory_resource_rejections_never_publish_partial_destination_changes() { assert_eq!(m.load(dst, &Type::ptr_to(Type::U8), 1).unwrap().pointer(), target); } } - let before = ( - m.allocations[2].bytes.clone(), - m.allocations[2].initialized.clone(), - m.allocations[2].fragments.clone(), - ); + let before = m.test_snapshot(2); m.limits.max_work = m.work; assert!(matches!( m.retire_stack(dst, 0), Err(Fault::Limit { resource: MemoryResource::Work, .. }) )); - assert!(m.allocations[2].alive); - assert_eq!( - ( - m.allocations[2].bytes.clone(), - m.allocations[2].initialized.clone(), - m.allocations[2].fragments.clone() - ), - before - ); + assert!(m.test_alive(2)); + assert_eq!(m.test_snapshot(2), before); assert!(matches!( m.set(dst, 0, 8, 1), Err(Fault::Limit { resource: MemoryResource::Work, .. }) )); - assert_eq!( - ( - m.allocations[2].bytes.clone(), - m.allocations[2].initialized.clone(), - m.allocations[2].fragments.clone() - ), - before - ); + assert_eq!(m.test_snapshot(2), before); } let mut m = Memory::new(MemoryLimits { max_bytes: 3, ..Default::default() }); assert!(matches!( diff --git a/ir/src/interpreter/memory_reference.rs b/ir/src/interpreter/memory_reference.rs new file mode 100644 index 0000000..2a571eb --- /dev/null +++ b/ir/src/interpreter/memory_reference.rs @@ -0,0 +1,598 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Explicit Rust conformance implementation. +use super::*; + +#[derive(Clone, Debug, PartialEq, Eq)] +enum StoredPointer { + Data(Pointer), + Function(FunctionPointer), +} + +impl StoredPointer { + fn bits(&self) -> u64 { + match self { + Self::Data(p) => p.address, + Self::Function(p) => p.bits(), + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct Fragment { + pointer: StoredPointer, + byte: u8, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum AllocationKind { + Stack, + Global, +} + +pub(super) struct Allocation { + kind: AllocationKind, + address: u64, + pub(super) generation: u64, + alive: bool, + pub(super) read: bool, + write: bool, + pub(super) bytes: Vec, + initialized: Vec, + fragments: HashMap, +} + +pub(crate) struct Memory { + arena: u64, + pub(super) allocations: Vec, + pub(super) limits: MemoryLimits, + bytes: u64, + fragments: usize, + pub(super) work: u64, + next_address: u64, +} + +impl Memory { + #[cfg(test)] + pub(super) fn test_snapshot(&self, id: usize) -> (Vec, Vec, String) { + let a = &self.allocations[id]; + (a.bytes.clone(), a.initialized.clone(), format!("{:?}", a.fragments)) + } + + #[cfg(test)] + pub(super) fn test_alive(&self, id: usize) -> bool { + self.allocations[id].alive + } + + #[cfg(test)] + pub(super) fn test_read(&mut self, id: usize, read: bool) { + self.allocations[id].read = read; + } + + #[cfg(test)] + pub(super) fn test_generation(&mut self, id: usize, delta: i64) { + self.allocations[id].generation = + self.allocations[id].generation.wrapping_add_signed(delta); + } + + pub fn new(limits: MemoryLimits) -> Self { + Self { + arena: NEXT_ARENA.fetch_add(1, Ordering::Relaxed), + allocations: Vec::new(), + limits, + bytes: 0, + fragments: 0, + work: 0, + next_address: 0x1000, + } + } + + fn limit(resource: MemoryResource, limit: u64) -> Fault { + Fault::Limit { resource, limit } + } + + fn charge(&mut self, work: u64) -> Result<()> { + self.work = self + .work + .checked_add(work) + .filter(|n| *n <= self.limits.max_work) + .ok_or_else(|| Self::limit(MemoryResource::Work, self.limits.max_work))?; + Ok(()) + } + + pub fn allocate(&mut self, size: u64, natural: u32, align: u32) -> Result { + if self.allocations.len() >= self.limits.max_allocations { + return Err(Self::limit( + MemoryResource::Allocations, + self.limits.max_allocations as u64, + )); + } + let bytes = self + .bytes + .checked_add(size) + .filter(|n| *n <= self.limits.max_bytes) + .ok_or_else(|| Self::limit(MemoryResource::Bytes, self.limits.max_bytes))?; + let length = + usize::try_from(size).map_err(|_| Self::limit(MemoryResource::HostAllocation, size))?; + let alignment = u64::from(align.max(natural)); + let address = self + .next_address + .checked_add(alignment - 1) + .map(|a| a & !(alignment - 1)) + .ok_or(MemoryTrap::AddressOverflow)?; + let next = address + .checked_add(size.max(1)) + .and_then(|a| a.checked_add(1)) + .ok_or(MemoryTrap::AddressOverflow)?; + self.charge( + size.checked_mul(2) + .and_then(|n| n.checked_add(1)) + .ok_or(MemoryTrap::AddressOverflow)?, + )?; + let mut data = Vec::new(); + let mut initialized = Vec::new(); + data.try_reserve_exact(length) + .map_err(|_| Self::limit(MemoryResource::HostAllocation, size))?; + initialized + .try_reserve_exact(length) + .map_err(|_| Self::limit(MemoryResource::HostAllocation, size))?; + self.allocations + .try_reserve(1) + .map_err(|_| Self::limit(MemoryResource::HostAllocation, size))?; + // Physical zero bytes are not semantic initialization. + data.resize(length, 0); + initialized.resize(length, 0); + let capability = Capability { + arena: self.arena, + allocation: self.allocations.len(), + generation: 0, + lower: 0, + upper: size, + offset: 0, + read: true, + write: true, + }; + self.allocations.push(Allocation { + kind: AllocationKind::Stack, + address, + generation: 0, + alive: true, + read: true, + write: true, + bytes: data, + initialized, + fragments: HashMap::new(), + }); + self.bytes = bytes; + self.next_address = next; + Ok(Pointer { address, capability: Some(capability) }) + } + + pub fn allocate_global(&mut self, size: u64, natural: u32, align: u32) -> Result { + let pointer = self.allocate(size, natural, align)?; + self.allocations[pointer.capability.unwrap().allocation].kind = AllocationKind::Global; + Ok(pointer) + } + + pub fn seal_global(&mut self, mut pointer: Pointer, readonly: bool) -> Result { + let (id, _) = self.identity(pointer)?; + if self.allocations[id].kind != AllocationKind::Global { + return Err(MemoryTrap::InvalidLifetimeEnd.into()); + } + self.allocations[id].write = !readonly; + pointer.capability.as_mut().unwrap().write = !readonly; + Ok(pointer) + } + + pub fn retire_stack(&mut self, pointer: Pointer, owner_start: usize) -> Result<()> { + let (id, capability) = self.identity(pointer)?; + if id < owner_start + || self.allocations[id].kind != AllocationKind::Stack + || capability.offset != 0 + || capability.lower != 0 + || capability.upper != self.allocations[id].bytes.len() as u64 + { + return Err(MemoryTrap::InvalidLifetimeEnd.into()); + } + self.charge(1 + self.allocations[id].fragments.len() as u64)?; + self.retire_allocation(id); + Ok(()) + } + + fn retire_allocation(&mut self, id: usize) { + let allocation = &mut self.allocations[id]; + if allocation.alive { + allocation.alive = false; + self.fragments -= allocation.fragments.len(); + allocation.fragments.clear(); + allocation.bytes.clear(); + allocation.initialized.clear(); + } + } + + pub fn difference(&self, lhs: Pointer, rhs: Pointer) -> Result { + let (a, left) = self.identity(lhs)?; + let (b, right) = self.identity(rhs)?; + if a != b || left.generation != right.generation { + return Err(MemoryTrap::DifferentAllocation.into()); + } + Ok(i128::from(left.offset) - i128::from(right.offset)) + } + + pub fn compare_order(&self, lhs: Pointer, rhs: Pointer) -> Result { + Ok(self.difference(lhs, rhs)?.cmp(&0)) + } + + fn identity(&self, pointer: Pointer) -> Result<(usize, Capability)> { + if pointer.address == 0 { + return Err(MemoryTrap::NullPointer.into()); + } + let cap = pointer.capability.ok_or(MemoryTrap::MissingProvenance)?; + if cap.arena != self.arena { + return Err(MemoryTrap::ExpiredAllocation.into()); + } + let allocation = + self.allocations.get(cap.allocation).ok_or(MemoryTrap::ExpiredAllocation)?; + if !allocation.alive || allocation.generation != cap.generation { + return Err(MemoryTrap::ExpiredAllocation.into()); + } + if cap.lower > cap.offset + || cap.offset > cap.upper + || cap.upper > allocation.bytes.len() as u64 + || allocation.address.checked_add(cap.offset) != Some(pointer.address) + { + return Err(MemoryTrap::OutOfBounds.into()); + } + Ok((cap.allocation, cap)) + } + + fn access( + &self, + pointer: Pointer, + n: u64, + align: u32, + write: bool, + ) -> Result<(usize, usize, usize)> { + let (id, cap) = self.identity(pointer)?; + let end = cap.offset.checked_add(n).ok_or(MemoryTrap::AddressOverflow)?; + if end > cap.upper { + return Err(MemoryTrap::OutOfBounds.into()); + } + let allocation = &self.allocations[id]; + let permitted = + if write { cap.write && allocation.write } else { cap.read && allocation.read }; + if !permitted { + return Err(MemoryTrap::PermissionDenied.into()); + } + if pointer.address % u64::from(align) != 0 { + return Err( + MemoryTrap::Misaligned { address: pointer.address, alignment: align }.into() + ); + } + Ok((id, cap.offset as usize, end as usize)) + } + + pub fn gep( + &self, + pointer: Pointer, + plan: &[GepStep], + indices: &[ConstValue], + ) -> Result { + if indices.is_empty() { + return Ok(pointer); + } + let (_, mut cap) = self.identity(pointer)?; + let base = i128::from(pointer.address) - i128::from(cap.offset); + let mut offset = i128::from(cap.offset); + for (step, index) in plan.iter().zip(indices) { + let delta = match step { + GepStep::Field(offset) => i128::from(*offset), + GepStep::Stride(stride) => { + let index = match index { + ConstValue::I(v) => *v, + ConstValue::U(v) => { + i128::try_from(*v).map_err(|_| MemoryTrap::AddressOverflow)? + }, + _ => unreachable!("verified integer GEP index"), + }; + index.checked_mul(i128::from(*stride)).ok_or(MemoryTrap::AddressOverflow)? + }, + }; + offset = offset.checked_add(delta).ok_or(MemoryTrap::AddressOverflow)?; + let address = base.checked_add(offset).ok_or(MemoryTrap::AddressOverflow)?; + if !(0..=i128::from(u64::MAX)).contains(&address) { + return Err(MemoryTrap::AddressOverflow.into()); + } + } + let offset = u64::try_from(offset).map_err(|_| MemoryTrap::OutOfBounds)?; + if offset < cap.lower || offset > cap.upper { + return Err(MemoryTrap::OutOfBounds.into()); + } + let address = u64::try_from(base + i128::from(offset)).unwrap(); + cap.offset = offset; + Ok(Pointer { address, capability: Some(cap) }) + } + + pub fn equal(&self, lhs: Pointer, rhs: Pointer) -> Result { + if lhs.address == 0 && rhs.address == 0 { + return Ok(true); + } + if lhs.address == 0 { + self.identity(rhs)?; + return Ok(false); + } + if rhs.address == 0 { + self.identity(lhs)?; + return Ok(false); + } + let (_, a) = self.identity(lhs)?; + let (_, b) = self.identity(rhs)?; + Ok((a.allocation, a.generation, a.offset) == (b.allocation, b.generation, b.offset)) + } + + fn replace_fragments( + &mut self, + id: usize, + start: usize, + end: usize, + new: &[(usize, Fragment)], + ) -> Result<()> { + let allocation = &self.allocations[id]; + self.charge(3 * allocation.fragments.capacity() as u64 + new.len() as u64)?; + let removed = + self.allocations[id].fragments.keys().filter(|i| **i >= start && **i < end).count(); + let count = self.fragments - removed + new.len(); + if count > self.limits.max_pointer_fragments { + return Err(Self::limit( + MemoryResource::PointerFragments, + self.limits.max_pointer_fragments as u64, + )); + } + self.allocations[id] + .fragments + .try_reserve(new.len()) + .map_err(|_| Self::limit(MemoryResource::HostAllocation, new.len() as u64))?; + self.allocations[id].fragments.retain(|i, _| *i < start || *i >= end); + self.allocations[id].fragments.extend(new.iter().cloned()); + self.fragments = count; + Ok(()) + } + + pub fn uninit(&mut self, pointer: Pointer, size: u64, align: u32) -> Result<()> { + let (id, start, end) = self.access(pointer, size, align, true)?; + self.charge((end - start) as u64)?; + self.replace_fragments(id, start, end, &[])?; + self.allocations[id].initialized[start..end].fill(0); + Ok(()) + } + + pub fn copy(&mut self, dst: Pointer, src: Pointer, size: u64, align: u32) -> Result<()> { + // No access occurs for an empty operation, even for null/raw pointers. + if size == 0 { + return Ok(()); + } + let (source, ss, se) = self.access(src, size, align, false)?; + let (destination, ds, de) = self.access(dst, size, align, true)?; + if source == destination && ss < de && ds < se { + return Err(MemoryTrap::OverlappingCopy.into()); + } + self.charge( + size.checked_mul(4) + .ok_or(MemoryTrap::AddressOverflow)? + .checked_add(self.allocations[source].fragments.capacity() as u64) + .ok_or(MemoryTrap::AddressOverflow)?, + )?; + let source = &self.allocations[source]; + let mut data = Vec::new(); + let mut initialized = Vec::new(); + let mut fragments = Vec::new(); + let count = source.fragments.len().min(se - ss); + data.try_reserve_exact(se - ss) + .map_err(|_| Self::limit(MemoryResource::HostAllocation, size))?; + initialized + .try_reserve_exact(se - ss) + .map_err(|_| Self::limit(MemoryResource::HostAllocation, size))?; + fragments + .try_reserve_exact(count) + .map_err(|_| Self::limit(MemoryResource::HostAllocation, count as u64))?; + data.extend_from_slice(&source.bytes[ss..se]); + initialized.extend_from_slice(&source.initialized[ss..se]); + fragments.extend( + source + .fragments + .iter() + .filter(|(at, _)| **at >= ss && **at < se) + .map(|(at, tag)| (ds + (*at - ss), tag.clone())), + ); + // Reserve/check metadata before any destination bytes are changed. + self.replace_fragments(destination, ds, de, &fragments)?; + self.allocations[destination].bytes[ds..de].copy_from_slice(&data); + self.allocations[destination].initialized[ds..de].copy_from_slice(&initialized); + Ok(()) + } + + pub fn set(&mut self, dst: Pointer, byte: u8, size: u64, align: u32) -> Result<()> { + if size == 0 { + return Ok(()); + } + let (id, start, end) = self.access(dst, size, align, true)?; + self.charge(size.checked_mul(2).ok_or(MemoryTrap::AddressOverflow)?)?; + self.replace_fragments(id, start, end, &[])?; + self.allocations[id].bytes[start..end].fill(byte); + self.allocations[id].initialized[start..end].fill(1); + Ok(()) + } + + #[cfg(test)] + pub fn load(&mut self, pointer: Pointer, ty: &Type, align: u32) -> Result { + self.load_with_signature(pointer, ty, align, None) + } + + pub fn load_with_signature( + &mut self, + pointer: Pointer, + ty: &Type, + align: u32, + signature: Option<&Arc>, + ) -> Result { + let (id, start, end) = self.access(pointer, layout(ty).size, align, false)?; + self.charge((end - start) as u64)?; + if let Type::Tuple(fields) = ty { + let offsets = layout(ty).field_offsets; + let a = self.load_scalar(id, start + offsets[0] as usize, &fields[0], None)?; + let b = self.load_scalar(id, start + offsets[1] as usize, &fields[1], None)?; + return Ok(Value::Checked(a.scalar().clone(), b.boolean())); + } + self.load_scalar(id, start, ty, signature) + } + + fn load_scalar( + &self, + id: usize, + start: usize, + ty: &Type, + callable_signature: Option<&Arc>, + ) -> Result { + let allocation = &self.allocations[id]; + let n = layout(ty).size as usize; + for offset in start..start + n { + if allocation.initialized[offset] == 0 { + return Err(MemoryTrap::Uninitialized { offset: offset as u64 }.into()); + } + } + let bytes = &allocation.bytes[start..start + n]; + if *ty == Type::Bool { + return match bytes[0] { + 0 => Ok(Value::Scalar(ConstValue::Bool(false))), + 1 => Ok(Value::Scalar(ConstValue::Bool(true))), + byte => Err(MemoryTrap::InvalidBool { byte }.into()), + }; + } + if matches!(ty, Type::Ptr(_) | Type::FnPtr(_)) { + let address = u64::from_le_bytes(bytes.try_into().unwrap()); + let complete = allocation.fragments.get(&start).filter(|fragment| { + fragment.byte == 0 + && fragment.pointer.bits() == address + && (0..8).all(|i| { + allocation.fragments.get(&(start + i)) + == Some(&Fragment { pointer: fragment.pointer.clone(), byte: i as u8 }) + }) + }); + return Ok(match ty { + Type::Ptr(_) => Value::Pointer(if address == 0 { + Pointer::raw(0) + } else { + match complete.map(|f| &f.pointer) { + Some(StoredPointer::Data(pointer)) => *pointer, + _ => Pointer::raw(address), + } + }), + Type::FnPtr(signature) => { + let signature = callable_signature + .cloned() + .unwrap_or_else(|| Arc::new((**signature).clone())); + let target = if address == 0 { + FunctionTarget::Null + } else { + match complete.map(|f| &f.pointer) { + Some(StoredPointer::Function(pointer)) + if pointer.signature == signature => + { + return Ok(Value::FunctionPointer(pointer.clone())) + }, + _ => FunctionTarget::InvalidBits(address), + } + }; + Value::FunctionPointer(FunctionPointer { signature, target }) + }, + _ => unreachable!(), + }); + } + let mut bits = [0u8; 16]; + bits[..n].copy_from_slice(bytes); + Ok(Value::Scalar(scalar::pack(ty, u128::from_le_bytes(bits)))) + } + + pub fn store(&mut self, pointer: Pointer, ty: &Type, value: &Value, align: u32) -> Result<()> { + let (id, start, end) = self.access(pointer, layout(ty).size, align, true)?; + let mut bytes = Vec::new(); + let mut fragments = Vec::new(); + if let (Type::Tuple(fields), Value::Checked(v, flag)) = (ty, value) { + let offsets = layout(ty).field_offsets; + Self::encode( + &fields[0], + &Value::Scalar(v.clone()), + start + offsets[0] as usize, + &mut bytes, + &mut fragments, + ); + Self::encode( + &fields[1], + &Value::Scalar(ConstValue::Bool(*flag)), + start + offsets[1] as usize, + &mut bytes, + &mut fragments, + ); + } else { + Self::encode(ty, value, start, &mut bytes, &mut fragments); + } + self.charge((end - start) as u64)?; + self.replace_fragments(id, start, end, &fragments)?; + for (at, byte) in bytes { + self.allocations[id].bytes[at] = byte; + self.allocations[id].initialized[at] = 1; + } + Ok(()) + } + + fn encode( + ty: &Type, + value: &Value, + start: usize, + bytes: &mut Vec<(usize, u8)>, + fragments: &mut Vec<(usize, Fragment)>, + ) { + let n = layout(ty).size as usize; + let data = match value { + Value::Pointer(p) => { + for i in 0..8 { + fragments.push(( + start + i, + Fragment { pointer: StoredPointer::Data(*p), byte: i as u8 }, + )); + } + u128::from(p.address).to_le_bytes() + }, + Value::FunctionPointer(p) => { + for i in 0..8 { + fragments.push(( + start + i, + Fragment { pointer: StoredPointer::Function(p.clone()), byte: i as u8 }, + )); + } + u128::from(p.bits()).to_le_bytes() + }, + Value::Scalar(v) => scalar::raw(ty, v).to_le_bytes(), + _ => unreachable!("verified scalar or checked storage"), + }; + bytes.extend(data[..n].iter().enumerate().map(|(i, b)| (start + i, *b))); + } + + pub fn allocation_count(&self) -> usize { + self.allocations.len() + } + + pub fn retire_from(&mut self, start: usize) -> Result<()> { + self.charge((self.allocations.len() - start) as u64)?; + for id in start..self.allocations.len() { + if self.allocations[id].kind == AllocationKind::Stack { + self.retire_allocation(id); + } + } + Ok(()) + } + + #[cfg(test)] + pub fn retire_all(&mut self) { + self.retire_from(0).unwrap(); + } +} diff --git a/ir/src/interpreter/memory_wave.rs b/ir/src/interpreter/memory_wave.rs new file mode 100644 index 0000000..80fc190 --- /dev/null +++ b/ir/src/interpreter/memory_wave.rs @@ -0,0 +1,832 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Allocation and typed transport for Wave-owned tracked memory. +use super::*; + +#[repr(C)] +#[derive(Clone, Copy, Debug, Default)] +struct RawPointer { + address: u64, + present: u64, + arena: u64, + allocation: u64, + generation: u64, + lower: u64, + upper: u64, + offset: u64, + read: u64, + write: u64, +} + +impl From for RawPointer { + fn from(p: Pointer) -> Self { + match p.capability { + None => Self { address: p.address, ..Self::default() }, + Some(c) => Self { + address: p.address, + present: 1, + arena: c.arena, + allocation: c.allocation as u64, + generation: c.generation, + lower: c.lower, + upper: c.upper, + offset: c.offset, + read: u64::from(c.read), + write: u64::from(c.write), + }, + } + } +} + +impl RawPointer { + fn decode(self) -> Result { + if self.present > 1 || self.read > 1 || self.write > 1 { + return Err(backend()); + } + Ok(Pointer { + address: self.address, + capability: if self.present == 0 { + None + } else { + Some(Capability { + arena: self.arena, + allocation: usize::try_from(self.allocation).map_err(|_| backend())?, + generation: self.generation, + lower: self.lower, + upper: self.upper, + offset: self.offset, + read: self.read != 0, + write: self.write != 0, + }) + }, + }) + } +} + +#[repr(C)] +#[derive(Clone, Copy, Debug, Default)] +struct Authority { + kind: u64, + pointer: RawPointer, + signature: u64, + target_kind: u64, + target: u64, +} + +#[repr(C)] +#[derive(Clone, Copy, Debug, Default)] +struct Fragment { + occupied: u64, + offset: u64, + ordinal: u64, + authority: Authority, +} + +#[repr(C)] +#[derive(Clone, Copy)] +struct RawAllocation { + kind: u64, + address: u64, + generation: u64, + alive: u64, + read: u64, + write: u64, + length: u64, + data: *mut u8, + initialized: *mut u8, + fragments: *mut Fragment, + fragment_capacity: u64, + fragment_count: u64, +} + +impl Default for RawAllocation { + fn default() -> Self { + Self { + kind: 0, + address: 0, + generation: 0, + alive: 0, + read: 0, + write: 0, + length: 0, + data: std::ptr::null_mut(), + initialized: std::ptr::null_mut(), + fragments: std::ptr::null_mut(), + fragment_capacity: 0, + fragment_count: 0, + } + } +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct State { + arena: u64, + allocations: u64, + bytes: u64, + fragments: u64, + work: u64, + next_address: u64, +} + +#[repr(C)] +struct Limits { + bytes: u64, + allocations: u64, + fragments: u64, + work: u64, +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct Part { + offset: u64, + kind: u64, + low: u64, + high: u64, + authority: Authority, +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct Gep { + kind: u64, + amount: u64, + low: u64, + high: u64, + signed: u64, +} + +#[repr(C)] +struct Request { + op: u64, + mode: u64, + size: u64, + natural: u64, + align: u64, + flag: u64, + owner: u64, + pointer: RawPointer, + source: RawPointer, + parts: *const Part, + part_count: u64, + geps: *const Gep, + gep_count: u64, +} + +impl Default for Request { + fn default() -> Self { + Self { + op: 0, + mode: 0, + size: 0, + natural: 0, + align: 0, + flag: 0, + owner: 0, + pointer: RawPointer::default(), + source: RawPointer::default(), + parts: std::ptr::null(), + part_count: 0, + geps: std::ptr::null(), + gep_count: 0, + } + } +} + +#[repr(C)] +#[derive(Default)] +struct RawResult { + status: u64, + detail: u64, + extra: u64, + work: u64, + allocation: u64, + start: u64, + end: u64, + fragments: u64, + fragment_capacity: u64, + low: u64, + high: u64, + pointer: RawPointer, +} + +unsafe extern "C" { + fn whale_ir_memory( + state: *mut State, + limits: *const Limits, + allocations: *mut RawAllocation, + allocation_capacity: u64, + request: *const Request, + fragments: *mut Fragment, + fragment_capacity: u64, + output_parts: *mut Part, + output_part_capacity: u64, + result: *mut RawResult, + ) -> i32; +} + +pub(super) struct Allocation { + pub(super) bytes: Vec, + initialized: Vec, + fragments: Vec, +} + +pub(crate) struct Memory { + state: State, + raw: Vec, + pub(super) allocations: Vec, + pub(super) limits: MemoryLimits, + pub(super) work: u64, + signatures: Vec>, +} + +fn backend() -> Fault { + Fault::Backend("tracked memory transport") +} + +fn host(limit: u64) -> Fault { + Fault::Limit { resource: MemoryResource::HostAllocation, limit } +} + +fn zeroed(count: usize) -> Result> { + let mut v = Vec::new(); + v.try_reserve_exact(count).map_err(|_| host(count as u64))?; + v.resize(count, T::default()); + Ok(v) +} + +fn kind(ty: &Type) -> Result { + Ok(match ty { + Type::Bool => 1, + Type::I1 => 2, + Type::U1 => 3, + Type::I8 => 4, + Type::I16 => 5, + Type::I32 => 6, + Type::I64 => 7, + Type::I128 => 8, + Type::U8 => 9, + Type::U16 => 10, + Type::U32 => 11, + Type::U64 => 12, + Type::U128 => 13, + Type::F16 => 14, + Type::F32 => 15, + Type::F64 => 16, + Type::Ptr(_) => 17, + Type::FnPtr(_) => 18, + _ => return Err(backend()), + }) +} + +fn raw_scalar(value: &ConstValue) -> u128 { + match value { + ConstValue::Bool(v) => u128::from(*v), + ConstValue::I(v) => *v as u128, + ConstValue::U(v) => *v, + ConstValue::F(v) => u128::from(v.bits()), + } +} + +fn scalar_from(part: &Part) -> Result { + let bits = u128::from(part.low) | (u128::from(part.high) << 64); + Ok(match part.kind { + 1 if part.low <= 1 && part.high == 0 => ConstValue::Bool(part.low != 0), + 2 | 4..=8 => ConstValue::I(bits as i128), + 3 | 9..=13 => ConstValue::U(bits), + 14 if part.high == 0 && part.low <= u16::MAX.into() => { + ConstValue::F(crate::FloatBits::F16(part.low as u16)) + }, + 15 if part.high == 0 && part.low <= u32::MAX.into() => { + ConstValue::F(crate::FloatBits::F32(part.low as u32)) + }, + 16 if part.high == 0 => ConstValue::F(crate::FloatBits::F64(part.low)), + _ => return Err(backend()), + }) +} + +impl Memory { + #[cfg(test)] + pub(super) fn test_snapshot(&self, id: usize) -> (Vec, Vec, String) { + let a = &self.allocations[id]; + (a.bytes.clone(), a.initialized.clone(), format!("{:?}", a.fragments)) + } + + #[cfg(test)] + pub(super) fn test_alive(&self, id: usize) -> bool { + self.raw[id].alive == 1 + } + + pub fn new(limits: MemoryLimits) -> Self { + Self { + state: State { + arena: NEXT_ARENA.fetch_add(1, Ordering::Relaxed), + next_address: 0x1000, + ..State::default() + }, + raw: Vec::new(), + allocations: Vec::new(), + limits, + work: 0, + signatures: Vec::new(), + } + } + + fn fault(result: &RawResult) -> Fault { + let trap = match result.status { + 1 => MemoryTrap::NullPointer, + 2 => MemoryTrap::MissingProvenance, + 3 => MemoryTrap::ExpiredAllocation, + 4 => MemoryTrap::OutOfBounds, + 5 => MemoryTrap::AddressOverflow, + 6 => MemoryTrap::PermissionDenied, + 7 => MemoryTrap::Misaligned { address: result.detail, alignment: result.extra as u32 }, + 8 => MemoryTrap::Uninitialized { offset: result.detail }, + 9 => MemoryTrap::InvalidBool { byte: result.detail as u8 }, + 11 => MemoryTrap::OverlappingCopy, + 12 => MemoryTrap::DifferentAllocation, + 13 => MemoryTrap::InvalidLifetimeEnd, + 101..=105 => { + return Fault::Limit { + resource: match result.status { + 101 => MemoryResource::Bytes, + 102 => MemoryResource::Allocations, + 103 => MemoryResource::PointerFragments, + 104 => MemoryResource::Work, + _ => MemoryResource::HostAllocation, + }, + limit: result.detail, + } + }, + _ => return backend(), + }; + Fault::Trap(trap) + } + + fn run( + &mut self, + request: &Request, + fragments: &mut [Fragment], + parts: &mut [Part], + ) -> Result { + let limits = Limits { + bytes: self.limits.max_bytes, + allocations: self.limits.max_allocations as u64, + fragments: self.limits.max_pointer_fragments as u64, + work: self.limits.max_work, + }; + let before = self.state; + let mut result = RawResult::default(); + let status = unsafe { + whale_ir_memory( + &mut self.state, + &limits, + self.raw.as_mut_ptr(), + self.raw.len() as u64, + request, + fragments.as_mut_ptr(), + fragments.len() as u64, + parts.as_mut_ptr(), + parts.len() as u64, + &mut result, + ) + }; + if i32::try_from(result.status).ok() != Some(status) + || result.work > self.limits.max_work.saturating_sub(before.work) + || self.state.allocations > self.raw.len() as u64 + || self.state.allocations > self.limits.max_allocations as u64 + || self.state.bytes > self.limits.max_bytes + || self.state.fragments > self.limits.max_pointer_fragments as u64 + || self.state.work > self.limits.max_work + || self.state.arena != before.arena + || self.state.work < before.work + || self.state.bytes < before.bytes + || self.state.allocations < before.allocations + { + return Err(backend()); + } + self.work = self.state.work; + if status != 0 { + return Err(Self::fault(&result)); + } + Ok(result) + } + + fn simple(&mut self, mut q: Request) -> Result { + q.mode = 1; + self.run(&q, &mut [], &mut []) + } + + pub fn allocate(&mut self, size: u64, natural: u32, align: u32) -> Result { + self.allocate_kind(size, natural, align, false) + } + + pub fn allocate_global(&mut self, size: u64, natural: u32, align: u32) -> Result { + self.allocate_kind(size, natural, align, true) + } + + fn allocate_kind( + &mut self, + size: u64, + natural: u32, + align: u32, + global: bool, + ) -> Result { + let mut q = Request { + op: 0, + size, + natural: natural.into(), + align: align.into(), + flag: u64::from(global), + ..Request::default() + }; + let probe = self.run(&q, &mut [], &mut [])?; + if probe.allocation != self.state.allocations { + return Err(backend()); + } + let length = usize::try_from(size).map_err(|_| host(size))?; + let mut data = zeroed::(length)?; + let mut initialized = zeroed::(length)?; + self.raw.try_reserve(1).map_err(|_| host(size))?; + self.allocations.try_reserve(1).map_err(|_| host(size))?; + let old_count = self.raw.len(); + self.raw.push(RawAllocation { + data: data.as_mut_ptr(), + initialized: initialized.as_mut_ptr(), + ..RawAllocation::default() + }); + q.mode = 1; + let committed = match self.run(&q, &mut [], &mut []) { + Ok(r) => r, + Err(e) => { + self.raw.truncate(old_count); + return Err(e); + }, + }; + if self.state.allocations != old_count as u64 + 1 + || committed.allocation != old_count as u64 + || committed.pointer.address != probe.pointer.address + { + return Err(backend()); + } + self.allocations.push(Allocation { bytes: data, initialized, fragments: Vec::new() }); + committed.pointer.decode() + } + + pub fn seal_global(&mut self, pointer: Pointer, readonly: bool) -> Result { + self.simple(Request { + op: 1, + pointer: pointer.into(), + flag: u64::from(readonly), + ..Request::default() + })? + .pointer + .decode() + } + + pub fn retire_stack(&mut self, pointer: Pointer, owner_start: usize) -> Result<()> { + let r = self.simple(Request { + op: 2, + pointer: pointer.into(), + owner: owner_start as u64, + ..Request::default() + })?; + let _ = r; + self.sync_retired(owner_start); + Ok(()) + } + + fn sync_retired(&mut self, start: usize) { + for (raw, buffer) in self.raw.iter().zip(&mut self.allocations).skip(start) { + if raw.alive == 0 { + buffer.bytes.clear(); + buffer.initialized.clear(); + buffer.fragments.clear(); + } + } + } + + pub fn retire_from(&mut self, start: usize) -> Result<()> { + self.simple(Request { op: 11, owner: start as u64, ..Request::default() })?; + self.sync_retired(start); + Ok(()) + } + + #[cfg(test)] + pub fn retire_all(&mut self) { + self.retire_from(0).unwrap(); + } + + pub fn allocation_count(&self) -> usize { + self.raw.len() + } + + pub fn difference(&self, lhs: Pointer, rhs: Pointer) -> Result { + let r = self.readonly(Request { + op: 10, + pointer: lhs.into(), + source: rhs.into(), + ..Request::default() + })?; + Ok((u128::from(r.low) | u128::from(r.high) << 64) as i128) + } + + pub fn equal(&self, lhs: Pointer, rhs: Pointer) -> Result { + let r = self.readonly(Request { + op: 9, + pointer: lhs.into(), + source: rhs.into(), + ..Request::default() + })?; + if r.low > 1 { + return Err(backend()); + } + Ok(r.low != 0) + } + + fn readonly(&self, q: Request) -> Result { + let mut state = self.state; + let limits = Limits { + bytes: self.limits.max_bytes, + allocations: self.limits.max_allocations as u64, + fragments: self.limits.max_pointer_fragments as u64, + work: self.limits.max_work, + }; + let mut result = RawResult::default(); + let status = unsafe { + whale_ir_memory( + &mut state, + &limits, + self.raw.as_ptr().cast_mut(), + self.raw.len() as u64, + &q, + std::ptr::null_mut(), + 0, + std::ptr::null_mut(), + 0, + &mut result, + ) + }; + if i32::try_from(result.status).ok() != Some(status) || state.work != self.state.work { + return Err(backend()); + } + if status != 0 { + return Err(Self::fault(&result)); + } + Ok(result) + } + + pub fn gep( + &self, + pointer: Pointer, + plan: &[GepStep], + indices: &[ConstValue], + ) -> Result { + if plan.len() != indices.len() { + return Err(backend()); + } + let mut geps = Vec::new(); + geps.try_reserve_exact(plan.len()).map_err(|_| host(plan.len() as u64))?; + for (step, value) in plan.iter().zip(indices) { + let (raw, signed) = match value { + ConstValue::I(v) => (*v as u128, 1), + ConstValue::U(v) => (*v, 0), + _ => return Err(backend()), + }; + let (kind, amount) = match step { + GepStep::Stride(n) => (0, *n), + GepStep::Field(n) => (1, *n), + }; + geps.push(Gep { kind, amount, low: raw as u64, high: (raw >> 64) as u64, signed }); + } + self.readonly(Request { + op: 8, + pointer: pointer.into(), + geps: geps.as_ptr(), + gep_count: geps.len() as u64, + ..Request::default() + })? + .pointer + .decode() + } + + fn mutate(&mut self, mut q: Request) -> Result<()> { + let probe = self.run(&q, &mut [], &mut [])?; + let count = usize::try_from(probe.fragment_capacity).map_err(|_| backend())?; + if count > self.limits.max_pointer_fragments.saturating_mul(4) { + return Err(backend()); + } + let mut fragments = zeroed::(count)?; + q.mode = 1; + let result = self.run(&q, &mut fragments, &mut [])?; + if result.allocation == u64::MAX { + if probe.allocation != u64::MAX || result.fragment_capacity != 0 { + return Err(backend()); + } + return Ok(()); + } + let id = usize::try_from(result.allocation).map_err(|_| backend())?; + if id >= self.allocations.len() + || result.fragment_capacity != fragments.len() as u64 + || result.fragment_capacity != probe.fragment_capacity + || result.fragments != probe.fragments + { + return Err(backend()); + } + self.allocations[id].fragments = fragments; + Ok(()) + } + + pub fn uninit(&mut self, pointer: Pointer, size: u64, align: u32) -> Result<()> { + self.mutate(Request { + op: 5, + pointer: pointer.into(), + size, + align: align.into(), + ..Request::default() + }) + } + + pub fn copy(&mut self, dst: Pointer, src: Pointer, size: u64, align: u32) -> Result<()> { + self.mutate(Request { + op: 6, + pointer: dst.into(), + source: src.into(), + size, + align: align.into(), + ..Request::default() + }) + } + + pub fn set(&mut self, dst: Pointer, octet: u8, size: u64, align: u32) -> Result<()> { + self.mutate(Request { + op: 7, + pointer: dst.into(), + flag: octet.into(), + size, + align: align.into(), + ..Request::default() + }) + } + + fn signature(&mut self, signature: &Arc) -> Result { + // Canonical IDs describe structural types, never native addresses. + crate::limits::Budget::new(crate::IrLimits::default()) + .and_then(|mut b| b.signature(signature)) + .map_err(|_| backend())?; + for (id, candidate) in self.signatures.iter().enumerate() { + let a = Type::FnPtr(Box::new((**signature).clone())); + let b = Type::FnPtr(Box::new((**candidate).clone())); + if crate::verifier::wave_types_equal( + &a, + &b, + crate::IrLimits::default().max_analysis_work, + ) + .map_err(|_| backend())? + .0 + { + return Ok(id as u64 + 1); + } + } + self.signatures.try_reserve(1).map_err(|_| host(self.signatures.len() as u64))?; + self.signatures.push(signature.clone()); + Ok(self.signatures.len() as u64) + } + + fn part( + &mut self, + ty: &Type, + value: Option<&Value>, + offset: u64, + signature: Option<&Arc>, + ) -> Result { + let mut part = Part { offset, kind: kind(ty)?, ..Part::default() }; + if let Some(Value::Pointer(p)) = value { + part.low = p.address; + part.authority = Authority { kind: 1, pointer: (*p).into(), ..Authority::default() }; + } else if let Some(Value::FunctionPointer(p)) = value { + let sid = self.signature(&p.signature)?; + let (target_kind, target) = match p.target { + FunctionTarget::Null => (0, 0), + FunctionTarget::Defined(id) => (1, u64::from(id.0)), + FunctionTarget::InvalidBits(bits) => (2, bits), + }; + part.low = p.bits(); + part.authority = + Authority { kind: 2, signature: sid, target_kind, target, ..Authority::default() }; + } else if let Some(Value::Scalar(v)) = value { + let bits = raw_scalar(v); + part.low = bits as u64; + part.high = (bits >> 64) as u64; + } else if value.is_some() { + return Err(backend()); + } + if let Type::FnPtr(sig) = ty { + let sig = signature.cloned().unwrap_or_else(|| Arc::new((**sig).clone())); + part.authority.signature = self.signature(&sig)?; + } + Ok(part) + } + + pub fn store(&mut self, pointer: Pointer, ty: &Type, value: &Value, align: u32) -> Result<()> { + let mut parts = Vec::new(); + if let (Type::Tuple(fields), Value::Checked(v, flag)) = (ty, value) { + let offsets = layout(ty).field_offsets; + parts.push(self.part(&fields[0], Some(&Value::Scalar(v.clone())), offsets[0], None)?); + parts.push(self.part( + &fields[1], + Some(&Value::Scalar(ConstValue::Bool(*flag))), + offsets[1], + None, + )?); + } else { + parts.push(self.part(ty, Some(value), 0, None)?); + } + self.mutate(Request { + op: 4, + pointer: pointer.into(), + size: layout(ty).size, + align: align.into(), + parts: parts.as_ptr(), + part_count: parts.len() as u64, + ..Request::default() + }) + } + + #[cfg(test)] + pub fn load(&mut self, pointer: Pointer, ty: &Type, align: u32) -> Result { + self.load_with_signature(pointer, ty, align, None) + } + + pub fn load_with_signature( + &mut self, + pointer: Pointer, + ty: &Type, + align: u32, + signature: Option<&Arc>, + ) -> Result { + let mut inputs = Vec::new(); + if let Type::Tuple(fields) = ty { + let offsets = layout(ty).field_offsets; + inputs.push(self.part(&fields[0], None, offsets[0], None)?); + inputs.push(self.part(&fields[1], None, offsets[1], None)?); + } else { + inputs.push(self.part(ty, None, 0, signature)?); + } + let mut output = [Part::default(); 2]; + let q = Request { + op: 3, + mode: 1, + pointer: pointer.into(), + size: layout(ty).size, + align: align.into(), + parts: inputs.as_ptr(), + part_count: inputs.len() as u64, + ..Request::default() + }; + self.run(&q, &mut [], &mut output)?; + if inputs.len() == 2 { + return Ok(Value::Checked( + scalar_from(&output[0])?, + matches!(scalar_from(&output[1])?, ConstValue::Bool(true)), + )); + } + let part = &output[0]; + if matches!(ty, Type::Ptr(_)) { + return Ok(Value::Pointer(if part.authority.kind == 1 { + part.authority.pointer.decode()? + } else { + Pointer::raw(part.low) + })); + } + if let Type::FnPtr(sig) = ty { + let signature = signature.cloned().unwrap_or_else(|| Arc::new((**sig).clone())); + let target = if part.low == 0 { + FunctionTarget::Null + } else if part.authority.kind == 2 { + match part.authority.target_kind { + 0 => FunctionTarget::Null, + 1 => FunctionTarget::Defined(crate::FunctionId( + part.authority.target.try_into().map_err(|_| backend())?, + )), + 2 => FunctionTarget::InvalidBits(part.authority.target), + _ => return Err(backend()), + } + } else { + FunctionTarget::InvalidBits(part.low) + }; + return Ok(Value::FunctionPointer(FunctionPointer { signature, target })); + } + Ok(Value::Scalar(scalar_from(part)?)) + } + + #[cfg(test)] + pub(super) fn test_read(&mut self, id: usize, read: bool) { + self.raw[id].read = u64::from(read); + } + + #[cfg(test)] + pub(super) fn test_generation(&mut self, id: usize, delta: i64) { + self.raw[id].generation = self.raw[id].generation.wrapping_add_signed(delta); + } +} diff --git a/ir/src/interpreter/mod.rs b/ir/src/interpreter/mod.rs index ee8ec77..7694e58 100644 --- a/ir/src/interpreter/mod.rs +++ b/ir/src/interpreter/mod.rs @@ -8,15 +8,20 @@ mod scalar; mod memory; +#[cfg(whale_wave_ir)] +mod runtime_wave; + pub use memory::{MemoryLimits, MemoryResource, MemoryTrap}; use crate::*; -use std::{ - collections::{HashMap, HashSet}, - fmt, - sync::Arc, -}; +#[cfg(not(whale_wave_ir))] +use std::collections::HashMap; + +use std::{fmt, sync::Arc}; + +#[cfg(not(whale_wave_ir))] +use std::collections::HashSet; /// Limits verification as well as executed instructions and terminators. #[derive(Clone, Copy, Debug)] @@ -178,6 +183,10 @@ pub enum InterpreterError { diagnostic: Box, }, Verification(Box), + Backend { + site: Option, + reason: &'static str, + }, UnknownFunction(FunctionId), UnsupportedGlobal(crate::GlobalId), GlobalMemory { @@ -224,6 +233,7 @@ impl fmt::Display for InterpreterError { match self { Self::Diagnostic { cause, diagnostic } => { cause.root_cause().fmt(f)?; diagnostic.fmt(f) }, Self::Verification(e) => write!(f, "IR verification failed: {e:?}"), + Self::Backend { site, reason } => { write!(f, "IR Wave backend error: {reason}")?; if let Some(site) = site { write!(f, " at {site}")?; } Ok(()) }, Self::UnsupportedGlobal(id) => write!(f, "unsupported interpreter global storage @g{}", id.0), Self::GlobalMemory { global, reason } => write!(f, "global storage @g{}: {reason}", global.0), Self::GlobalMemoryLimit { global, resource, limit } => write!(f, "global storage @g{} memory {resource:?} limit {limit}", global.0), @@ -267,6 +277,7 @@ impl InterpreterError { fn runtime_site(&self) -> Option { match self.root_cause() { Self::Trap(trap) => Some(trap.site), + Self::Backend { site, .. } => *site, Self::StepLimit { site, .. } | Self::MemoryLimit { site, .. } | Self::CallLimit { site, .. } => Some(*site), @@ -438,6 +449,7 @@ impl Value { } } + #[cfg(any(test, not(whale_wave_ir)))] fn pointer(&self) -> memory::Pointer { match self { Self::Pointer(p) => *p, @@ -445,6 +457,7 @@ impl Value { } } + #[cfg(not(whale_wave_ir))] fn boolean(&self) -> bool { match self.scalar() { ConstValue::Bool(v) => *v, @@ -457,6 +470,7 @@ fn scalar_type(ty: &Type) -> bool { *ty == Type::Bool || integer::shape(ty).is_some() || scalar::float_type(ty) } +#[cfg(not(whale_wave_ir))] fn value_type(ty: &Type) -> bool { scalar_type(ty) || matches!(ty, Type::Ptr(_) | Type::FnPtr(_)) @@ -500,6 +514,7 @@ fn destination(inst: &Instruction) -> Option { } } +#[cfg(not(whale_wave_ir))] fn supported(inst: &Instruction) -> Result<(), &'static str> { use Instruction::*; let unsupported = match inst { @@ -576,6 +591,7 @@ fn supported(inst: &Instruction) -> Result<(), &'static str> { Err(unsupported) } +#[cfg(not(whale_wave_ir))] fn allocation_type(root: &Type) -> bool { let mut pending = vec![root]; while let Some(ty) = pending.pop() { @@ -591,8 +607,26 @@ fn allocation_type(root: &Type) -> bool { true } +#[cfg(not(whale_wave_ir))] +fn integer_failure( + error: integer::IntegerError, + site: ExecutionSite, + steps: u64, +) -> InterpreterError { + match error { + integer::IntegerError::Trap(reason) => { + InterpreterError::Trap(InterpreterTrap { site, reason, steps }) + }, + integer::IntegerError::Backend(reason) => { + InterpreterError::Backend { site: Some(site), reason } + }, + } +} + +#[cfg(not(whale_wave_ir))] fn memory_failure(fault: memory::Fault, site: ExecutionSite, steps: u64) -> InterpreterError { match fault { + memory::Fault::Backend(reason) => InterpreterError::Backend { site: Some(site), reason }, memory::Fault::Trap(reason) => InterpreterError::Trap(InterpreterTrap { site, reason: TrapReason::Memory(reason), @@ -604,6 +638,7 @@ fn memory_failure(fault: memory::Fault, site: ExecutionSite, steps: u64) -> Inte } } +#[cfg(not(whale_wave_ir))] fn gep_plan( value_types: &HashMap, ordinals: &HashMap, @@ -636,6 +671,7 @@ fn gep_plan( plan } +#[cfg(not(whale_wave_ir))] fn pointer_compare( memory: &memory::Memory, pred: &ICmpPred, @@ -657,6 +693,7 @@ fn pointer_compare( }) } +#[cfg(not(whale_wave_ir))] fn cmp_pred(op: CmpOp) -> ICmpPred { use CmpOp::*; match op { @@ -729,6 +766,7 @@ impl Arguments<'_, '_> { } } + #[cfg(not(whale_wave_ir))] fn value(&self, index: usize) -> Value { match self { Self::Scalars(values) => Value::Scalar(values[index].clone()), @@ -736,6 +774,7 @@ impl Arguments<'_, '_> { } } + #[cfg(not(whale_wave_ir))] fn valid_type(&self, index: usize, expected: &Type) -> bool { match self { Self::Scalars(_) => true, @@ -759,6 +798,7 @@ impl Arguments<'_, '_> { } } +#[cfg(not(whale_wave_ir))] struct Prepared<'a> { fun: &'a Function, value_capacity: usize, @@ -770,15 +810,22 @@ struct Prepared<'a> { struct Frame { function: FunctionId, + #[cfg(not(whale_wave_ir))] values: HashMap, + #[cfg(not(whale_wave_ir))] current: BlockId, + #[cfg(not(whale_wave_ir))] predecessor: Option, + #[cfg(not(whale_wave_ir))] instruction: usize, + #[cfg(not(whale_wave_ir))] allocation_start: usize, + #[cfg(not(whale_wave_ir))] return_destination: Option, call_site: Option, } +#[cfg(not(whale_wave_ir))] fn callable_signature(signature: &FunctionSignature) -> bool { signature.convention == CallingConvention::Whale && !signature.variadic @@ -786,10 +833,12 @@ fn callable_signature(signature: &FunctionSignature) -> bool { && (signature.ret == Type::Void || call_value_type(&signature.ret)) } +#[cfg(not(whale_wave_ir))] fn call_value_type(ty: &Type) -> bool { scalar_type(ty) || matches!(ty, Type::Ptr(_) | Type::FnPtr(_)) } +#[cfg(not(whale_wave_ir))] fn intern_signature<'a>( signatures: &mut HashMap<&'a FunctionSignature, Arc>, signature: &'a FunctionSignature, @@ -797,6 +846,7 @@ fn intern_signature<'a>( signatures.entry(signature).or_insert_with(|| Arc::new(signature.clone())).clone() } +#[cfg(not(whale_wave_ir))] fn frame_values( fun: &Function, arguments: impl IntoIterator, @@ -943,6 +993,17 @@ fn runtime_failure( } } +#[cfg(whale_wave_ir)] +fn run_inner<'module>( + module: &'module Module, + function: FunctionId, + arguments: Arguments<'_, '_>, + options: InterpreterOptions, +) -> Result, InterpreterError> { + runtime_wave::run(module, function, arguments, options) +} + +#[cfg(not(whale_wave_ir))] fn run_inner<'module>( module: &'module Module, function: FunctionId, @@ -1200,6 +1261,7 @@ fn run_inner<'module>( let mut global_pointers = HashMap::new(); for global in &module.global_storage { let failure = |fault| match fault { + memory::Fault::Backend(reason) => InterpreterError::Backend { site: None, reason }, memory::Fault::Trap(reason) => { InterpreterError::GlobalMemory { global: global.id, reason } }, @@ -1448,20 +1510,17 @@ fn run_inner<'module>( ConstValue::F(value) => { ConstValue::F(crate::float::arithmetic::negate(*value)) }, - value => integer::pack( - ty, - 0u128.wrapping_sub(integer::raw(value, integer::shape(ty).unwrap().0)), - ), + value => integer::try_unary(true, ty, value) + .map_err(|e| integer_failure(e, at, steps))?, }), Instruction::Bin { op, ty, lhs, rhs, .. } => Value::Scalar( - integer::bin(op, ty, scalar(lhs), scalar(rhs)).map_err(|reason| { - InterpreterError::Trap(InterpreterTrap { site: at, reason, steps }) - })?, + integer::try_bin(op, ty, scalar(lhs), scalar(rhs)) + .map_err(|e| integer_failure(e, at, steps))?, + ), + Instruction::Not { ty, src, .. } => Value::Scalar( + integer::try_unary(false, ty, scalar(src)) + .map_err(|e| integer_failure(e, at, steps))?, ), - Instruction::Not { ty, src, .. } => Value::Scalar(integer::pack( - ty, - !integer::raw(scalar(src), integer::shape(ty).unwrap().0), - )), Instruction::Cmp { op, ty, lhs, rhs, .. } => { let result = if scalar::float_type(ty) { scalar::compare( @@ -1478,7 +1537,8 @@ fn run_inner<'module>( ) .map_err(|e| memory_failure(e, at, steps))? } else { - integer::compare(&cmp_pred(*op), ty, scalar(lhs), scalar(rhs)) + integer::try_compare(&cmp_pred(*op), ty, scalar(lhs), scalar(rhs)) + .map_err(|e| integer_failure(e, at, steps))? }; Value::Scalar(ConstValue::Bool(result)) }, @@ -1487,7 +1547,8 @@ fn run_inner<'module>( pointer_compare(&memory, pred, get(lhs).pointer(), get(rhs).pointer()) .map_err(|e| memory_failure(e, at, steps))? } else { - integer::compare(pred, ty, scalar(lhs), scalar(rhs)) + integer::try_compare(pred, ty, scalar(lhs), scalar(rhs)) + .map_err(|e| integer_failure(e, at, steps))? }; Value::Scalar(ConstValue::Bool(result)) }, @@ -1514,15 +1575,8 @@ fn run_inner<'module>( })?, ), CastOp::CheckedInt => Value::Scalar( - integer::checked_cast(src_ty, dst_ty, scalar(src)).map_err( - |reason| { - InterpreterError::Trap(InterpreterTrap { - site: at, - reason, - steps, - }) - }, - )?, + integer::try_checked_cast(src_ty, dst_ty, scalar(src)) + .map_err(|e| integer_failure(e, at, steps))?, ), CastOp::IntToPtr => { Value::Pointer(memory::Pointer::raw( @@ -1537,7 +1591,10 @@ fn run_inner<'module>( CastOp::Bitcast => { Value::Scalar(scalar::pack(dst_ty, scalar::raw(src_ty, scalar(src)))) }, - _ => Value::Scalar(integer::cast(op, src_ty, dst_ty, scalar(src))), + _ => Value::Scalar( + integer::try_cast(op, src_ty, dst_ty, scalar(src)) + .map_err(|e| integer_failure(e, at, steps))?, + ), }, Instruction::Alloca { align, .. } => { let (size, natural) = sizes[&(current, index)]; @@ -1600,7 +1657,8 @@ fn run_inner<'module>( ) }, Instruction::Checked { op, ty, lhs, rhs, .. } => { - let (v, overflow) = integer::checked(op, ty, scalar(lhs), scalar(rhs)); + let (v, overflow) = integer::try_checked(op, ty, scalar(lhs), scalar(rhs)) + .map_err(|e| integer_failure(e, at, steps))?; Value::Checked(v, overflow) }, Instruction::Extract { tuple, index, .. } => match get(tuple) { diff --git a/ir/src/interpreter/runtime_wave.rs b/ir/src/interpreter/runtime_wave.rs new file mode 100644 index 0000000..b3de54b --- /dev/null +++ b/ir/src/interpreter/runtime_wave.rs @@ -0,0 +1,1837 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Typed transport for the resumable Wave interpreter. Rust owns buffers and +//! memory-operation requests; Wave owns reachability, execution and counters. +use super::*; + +use std::collections::HashMap; + +const MISSING: u64 = u64::MAX; + +static VOID_TYPE: Type = Type::Void; + +const BACKEND: &str = "invalid Wave interpreter transport"; + +const ALLOCATION: &str = "unable to allocate Wave interpreter transport"; + +type Result = std::result::Result; + +trait WireDefault { + fn wire_default() -> Self; +} + +impl WireDefault for u64 { + fn wire_default() -> Self { + 0 + } +} + +impl WireDefault for u8 { + fn wire_default() -> Self { + 0 + } +} + +impl WireDefault for *mut T { + fn wire_default() -> Self { + std::ptr::null_mut() + } +} + +macro_rules! record { + ($name:ident { $($field:ident: $ty:ty),* $(,)? }) => { + #[repr(C)] + #[derive(Clone, Copy)] + struct $name { $($field: $ty),* } + + impl Default for $name { + fn default() -> Self { Self { $($field: <$ty as WireDefault>::wire_default()),* } } + } + + impl WireDefault for $name { fn wire_default() -> Self { Self::default() } } + }; +} +record!(RawType { kind: u64, child: u64, first: u64, count: u64, extra: u64 }); +record!(RawPointer { + address: u64, + present: u64, + arena: u64, + allocation: u64, + generation: u64, + lower: u64, + upper: u64, + offset: u64, + read: u64, + write: u64 +}); +record!(RawGep { kind: u64, amount: u64, low: u64, high: u64, signed: u64 }); +record!(Storage { + ptr_bits: u64, + pointer_align: u64, + scalar_align1: u64, + scalar_align2: u64, + scalar_align4: u64, + scalar_align8: u64, + scalar_align16: u64, + large_array_threshold: u64, + large_array_align: u64, + has_large_array: u64 +}); +record!(LayoutNode { kind: u64, child: u64, first: u64, count: u64 }); +record!(Layout { size: u64, align: u64, stride: u64, allocation_align: u64, depth: u64 }); +record!(RawValue { + kind: u64, + ty: u64, + literal: u64, + low: u64, + high: u64, + flag: u64, + pointer: RawPointer, + signature: u64, + target_kind: u64, + target: u64, + origin: u64 +}); +record!(RawSlot { generation: u64, value: RawValue }); +record!(RawFrame { + function: u64, + block: u64, + predecessor: u64, + instruction: u64, + value_base: u64, + value_count: u64, + generation: u64, + allocation_start: u64, + return_slot: u64, + call_site: u64 +}); +record!(RawFunction { + id: u64, + signature: u64, + entry: u64, + first_block: u64, + block_count: u64, + first_parameter: u64, + parameter_count: u64, + value_count: u64, + first_value_type: u64, + has_body: u64, + linkage: u64 +}); +record!(RawBlock { id: u64, function: u64, first: u64, count: u64 }); +record!(RawInstruction { + op: u64, + sub: u64, + ty: u64, + other: u64, + dst: u64, + a: u64, + b: u64, + c: u64, + align: u64, + size: u64, + natural: u64, + first: u64, + count: u64, + low: u64, + high: u64, + literal: u64, + signature: u64, + flags: u64, + global: u64, + plan_first: u64, + plan_count: u64 +}); +record!(RawGlobal { + id: u64, + ty: u64, + size: u64, + align: u64, + natural: u64, + readonly: u64, + initialized: u64, + value: RawValue +}); +record!(RawEvent { + kind: u64, + ty: u64, + size: u64, + natural: u64, + align: u64, + flag: u64, + owner: u64, + first: u64, + count: u64, + frame_capacity: u64, + value_capacity: u64, + phi_capacity: u64, + left: RawValue, + right: RawValue +}); +record!(RawResult { + status: u64, + error: u64, + site: u64, + detail: u64, + extra: u64, + global: u64, + steps: u64, + value: RawValue, + event: RawEvent +}); +record!(RawDriver { + types: *mut RawType, + type_count: u64, + type_edges: *mut u64, + type_edge_count: u64, + functions: *mut RawFunction, + function_count: u64, + blocks: *mut RawBlock, + block_count: u64, + instructions: *mut RawInstruction, + instruction_count: u64, + operands: *mut u64, + operand_count: u64, + value_types: *mut u64, + value_type_count: u64, + globals: *mut RawGlobal, + global_count: u64, + global_values: *mut RawValue, + arguments: *mut RawValue, + argument_count: u64, + scalar_arguments: u64, + entry_id: u64, + storage: *mut Storage, + layout_nodes: *mut LayoutNode, + layouts: *mut Layout, + layout_offsets: *mut u64, + plans: *mut RawGep, + plan_capacity: u64, + plan_count: u64, + ordinals: *mut u64, + function_table: *mut u64, + function_table_capacity: u64, + prepared: *mut u8, + pending_previous: *mut u64, + pending_next: *mut u64, + pending_flags: *mut u8, + callable_flags: *mut u8, + callable_targets: *mut u64, + callable_count: u64, + indirect_signatures: *mut u64, + indirect_sites: *mut u64, + indirect_count: u64, + indirect_capacity: u64, + pending_head: u64, + frames: *mut RawFrame, + frame_capacity: u64, + frame_count: u64, + slots: *mut RawSlot, + slot_capacity: u64, + slot_count: u64, + phis: *mut RawValue, + phi_capacity: u64, + phase: u64, + cursor: u64, + global_phase: u64, + entry: u64, + pending: u64, + pending_destination: u64, + pending_type: u64, + pending_flag: u64, + pending_target: u64, + pending_site: u64, + pending_value: RawValue, + resume: u64, + resume_value: RawValue, + memory_allocations: u64, + frames_created: u64, + steps: u64, + work: u64, + max_steps: u64, + max_depth: u64, + max_frames: u64, + max_values: u64, + max_work: u64, + result: *mut RawResult +}); + +unsafe extern "C" { + fn whale_ir_runtime_step(driver: *mut RawDriver) -> i32; +} + +fn backend(site: Option) -> InterpreterError { + InterpreterError::Backend { site, reason: BACKEND } +} + +fn reserve(values: &mut Vec, count: usize) -> Result<()> { + values + .try_reserve(count) + .map_err(|_| InterpreterError::Backend { site: None, reason: ALLOCATION }) +} + +fn push(values: &mut Vec, value: T) -> Result { + reserve(values, 1)?; + let index = values.len() as u64; + values.push(value); + Ok(index) +} + +fn initialized(count: usize) -> Result> { + let mut values = Vec::new(); + reserve(&mut values, count)?; + values.resize_with(count, T::default); + Ok(values) +} + +fn map_reserve(map: &mut HashMap, count: usize) -> Result<()> { + map.try_reserve(count).map_err(|_| InterpreterError::Backend { site: None, reason: ALLOCATION }) +} + +impl From for RawPointer { + fn from(value: memory::Pointer) -> Self { + let mut raw = Self { address: value.address, ..Self::default() }; + if let Some(c) = value.capability { + raw.present = 1; + raw.arena = c.arena; + raw.allocation = c.allocation as u64; + raw.generation = c.generation; + raw.lower = c.lower; + raw.upper = c.upper; + raw.offset = c.offset; + raw.read = u64::from(c.read); + raw.write = u64::from(c.write); + } + raw + } +} + +impl RawPointer { + fn decode(self) -> Result { + if self.present > 1 || self.read > 1 || self.write > 1 { + return Err(backend(None)); + } + Ok(memory::Pointer { + address: self.address, + capability: if self.present == 0 { + None + } else { + Some(memory::Capability { + arena: self.arena, + allocation: usize::try_from(self.allocation).map_err(|_| backend(None))?, + generation: self.generation, + lower: self.lower, + upper: self.upper, + offset: self.offset, + read: self.read != 0, + write: self.write != 0, + }) + }, + }) + } +} + +#[derive(Clone, Copy)] +enum TypeView<'a> { + Type(&'a Type), + Signature(&'a FunctionSignature), +} + +struct Program<'a> { + module: &'a Module, + types: Vec, + type_views: Vec>, + type_ids: HashMap<&'a Type, u64>, + signature_ids: HashMap<&'a FunctionSignature, u64>, + signature_arcs: HashMap>, + cached_types: HashMap, + edges: Vec, + functions: Vec, + blocks: Vec, + instructions: Vec, + operands: Vec, + value_types: Vec, + globals: Vec, + sites: Vec, + reasons: Vec<&'a str>, + declaration_ids: HashMap, + global_ids: HashMap, +} + +impl<'a> Program<'a> { + fn new(module: &'a Module) -> Result { + Ok(Self { + module, + types: Vec::new(), + type_views: Vec::new(), + type_ids: HashMap::new(), + signature_ids: HashMap::new(), + signature_arcs: HashMap::new(), + cached_types: HashMap::new(), + edges: Vec::new(), + functions: Vec::new(), + blocks: Vec::new(), + instructions: Vec::new(), + operands: Vec::new(), + value_types: Vec::new(), + globals: Vec::new(), + sites: Vec::new(), + reasons: Vec::new(), + declaration_ids: HashMap::new(), + global_ids: HashMap::new(), + }) + } + + fn append_type(&mut self, node: RawType, view: TypeView<'a>) -> Result { + let id = push(&mut self.types, node)?; + push(&mut self.type_views, view)?; + Ok(id) + } + + fn signature(&mut self, signature: &'a FunctionSignature) -> Result { + if let Some(id) = self.signature_ids.get(signature) { + return Ok(*id); + } + let mut children = Vec::new(); + push(&mut children, self.ty(&signature.ret)?)?; + for param in &signature.params { + push(&mut children, self.ty(param)?)?; + } + let first = self.edges.len() as u64; + reserve(&mut self.edges, children.len())?; + self.edges.extend(children); + let id = self.append_type( + RawType { + kind: 18, + first, + count: signature.params.len() as u64 + 1, + extra: u64::from(signature.convention == CallingConvention::SysV64) + | (u64::from(signature.variadic) << 1), + ..RawType::default() + }, + TypeView::Signature(signature), + )?; + map_reserve(&mut self.signature_ids, 1)?; + self.signature_ids.insert(signature, id); + Ok(id) + } + + fn ty(&mut self, ty: &'a Type) -> Result { + if let Some(id) = self.type_ids.get(ty) { + return Ok(*id); + } + if let Type::FnPtr(signature) = ty { + let id = self.signature(signature)?; + map_reserve(&mut self.type_ids, 1)?; + self.type_ids.insert(ty, id); + return Ok(id); + } + let mut node = RawType::default(); + node.kind = match ty { + Type::Void => 0, + Type::Bool => 1, + Type::I1 => 2, + Type::U1 => 3, + Type::I8 => 4, + Type::I16 => 5, + Type::I32 => 6, + Type::I64 => 7, + Type::I128 => 8, + Type::U8 => 9, + Type::U16 => 10, + Type::U32 => 11, + Type::U64 => 12, + Type::U128 => 13, + Type::F16 => 14, + Type::F32 => 15, + Type::F64 => 16, + Type::Ptr(child) => { + node.child = self.ty(child)?; + 17 + }, + Type::Array(child, count) => { + node.child = self.ty(child)?; + node.count = *count; + 19 + }, + Type::Struct(fields) | Type::Tuple(fields) => { + let mut children = Vec::new(); + reserve(&mut children, fields.len())?; + for field in fields { + children.push(self.ty(field)?); + } + node.first = self.edges.len() as u64; + node.count = fields.len() as u64; + reserve(&mut self.edges, children.len())?; + self.edges.extend(children); + if matches!(ty, Type::Struct(_)) { + 20 + } else { + 21 + } + }, + Type::FnPtr(_) => unreachable!(), + }; + let id = self.append_type(node, TypeView::Type(ty))?; + map_reserve(&mut self.type_ids, 1)?; + self.type_ids.insert(ty, id); + Ok(id) + } + + fn type_model(&self, id: u64) -> Result { + match self.type_views.get(usize::try_from(id).map_err(|_| backend(None))?) { + Some(TypeView::Type(ty)) => Ok((*ty).clone()), + Some(TypeView::Signature(signature)) => Ok(Type::FnPtr(Box::new((*signature).clone()))), + None => Err(backend(None)), + } + } + + fn prepare_type(&mut self, id: u64) -> Result<()> { + if let Some(TypeView::Signature(signature)) = self.type_views.get(id as usize) { + if !self.cached_types.contains_key(&id) { + map_reserve(&mut self.cached_types, 1)?; + self.cached_types.insert(id, Type::FnPtr(Box::new((*signature).clone()))); + } + } + Ok(()) + } + + fn type_ref(&self, id: u64) -> Result<&Type> { + match self.type_views.get(id as usize) { + Some(TypeView::Type(ty)) => Ok(ty), + Some(TypeView::Signature(_)) => self.cached_types.get(&id).ok_or_else(|| backend(None)), + None => Err(backend(None)), + } + } + + fn signature_arc(&mut self, id: u64) -> Result> { + if let Some(signature) = self.signature_arcs.get(&id) { + return Ok(signature.clone()); + } + let Some(TypeView::Signature(signature)) = self.type_views.get(id as usize) else { + return Err(backend(None)); + }; + let signature = Arc::new((*signature).clone()); + map_reserve(&mut self.signature_arcs, 1)?; + self.signature_arcs.insert(id, signature.clone()); + Ok(signature) + } + + fn value(&mut self, value: &Value, ty: u64, origin: bool) -> Result { + let mut raw = RawValue { ty, origin: u64::from(origin), ..RawValue::default() }; + match value { + Value::Scalar(value) => { + raw.kind = 1; + (raw.literal, raw.low, raw.high) = literal(value); + }, + Value::Checked(value, overflow) => { + raw.kind = 2; + raw.flag = u64::from(*overflow); + (raw.literal, raw.low, raw.high) = literal(value); + }, + Value::Pointer(pointer) => { + raw.kind = 3; + raw.pointer = (*pointer).into(); + }, + Value::FunctionPointer(pointer) => { + raw.kind = 4; + raw.signature = self + .signature_ids + .get(&*pointer.signature) + .copied() + .ok_or_else(|| backend(None))?; + (raw.target_kind, raw.target) = match pointer.target { + FunctionTarget::Null => (0, 0), + FunctionTarget::Defined(id) => (1, u64::from(id.0)), + FunctionTarget::InvalidBits(bits) => (2, bits), + }; + }, + } + Ok(raw) + } + + fn decode_value(&mut self, raw: RawValue) -> Result { + self.prepare_type(raw.ty)?; + let function_signature = + if raw.kind == 4 { Some(self.signature_arc(raw.signature)?) } else { None }; + let ty = self.type_ref(raw.ty)?; + match (raw.kind, ty) { + (1, _) => Ok(Value::Scalar(decode_literal(raw.literal, raw.low, raw.high, ty)?)), + (2, Type::Tuple(fields)) + if fields.len() == 2 && fields[1] == Type::Bool && raw.flag <= 1 => + { + Ok(Value::Checked( + decode_literal(raw.literal, raw.low, raw.high, &fields[0])?, + raw.flag != 0, + )) + }, + (3, Type::Ptr(_)) => Ok(Value::Pointer(raw.pointer.decode()?)), + (4, Type::FnPtr(expected)) if raw.origin <= 1 => { + let signature = function_signature.ok_or_else(|| backend(None))?; + if **expected != *signature { + return Err(backend(None)); + } + let target = match raw.target_kind { + 0 if raw.target == 0 => FunctionTarget::Null, + 1 if raw.origin == 1 => { + let id = FunctionId(u32::try_from(raw.target).map_err(|_| backend(None))?); + let index = *self.declaration_ids.get(&id).ok_or_else(|| backend(None))?; + if self.module.declarations[index as usize].signature != *signature { + return Err(backend(None)); + } + FunctionTarget::Defined(id) + }, + 2 => FunctionTarget::InvalidBits(raw.target), + _ => return Err(backend(None)), + }; + Ok(Value::FunctionPointer(FunctionPointer { signature, target })) + }, + _ => Err(backend(None)), + } + } + + fn marshal(&mut self) -> Result<()> { + map_reserve(&mut self.declaration_ids, self.module.declarations.len())?; + for (index, declaration) in self.module.declarations.iter().enumerate() { + self.declaration_ids.insert(declaration.id, index as u64); + } + map_reserve(&mut self.global_ids, self.module.global_storage.len())?; + for (index, global) in self.module.global_storage.iter().enumerate() { + self.global_ids.insert(global.id, index as u64); + } + let mut bodies = HashMap::new(); + map_reserve(&mut bodies, self.module.functions.len())?; + for function in &self.module.functions { + bodies.insert(function.id, function); + } + for (index, declaration) in self.module.declarations.iter().enumerate() { + let signature = self.signature(&declaration.signature)?; + let mut raw = RawFunction { + id: u64::from(declaration.id.0), + signature, + entry: MISSING, + first_block: self.blocks.len() as u64, + first_parameter: self.operands.len() as u64, + first_value_type: self.value_types.len() as u64, + linkage: u64::from(declaration.linkage == Linkage::External), + ..RawFunction::default() + }; + if let Some(function) = bodies.get(&declaration.id) { + raw.has_body = 1; + raw.block_count = function.blocks.len() as u64; + raw.parameter_count = function.params.len() as u64; + let mut slots = HashMap::new(); + map_reserve(&mut slots, function.value_types.len())?; + let mut annotations = HashMap::new(); + map_reserve(&mut annotations, function.value_types.len())?; + for (id, ty) in &function.value_types { + annotations.insert(*id, ty); + } + for param in &function.params { + let slot = slots.len() as u64; + slots.insert(param.id, slot); + let type_id = self.ty(¶m.ty)?; + push(&mut self.value_types, type_id)?; + push(&mut self.operands, slot)?; + } + for block in &function.blocks { + for instruction in &block.instructions { + if let Some(dst) = destination(instruction) { + let slot = slots.len() as u64; + slots.insert(dst, slot); + let ty = annotations.get(&dst).ok_or_else(|| backend(None))?; + let type_id = self.ty(ty)?; + push(&mut self.value_types, type_id)?; + } + } + } + raw.value_count = slots.len() as u64; + let mut blocks = HashMap::new(); + map_reserve(&mut blocks, function.blocks.len())?; + for (local, block) in function.blocks.iter().enumerate() { + blocks.insert(block.id, raw.first_block + local as u64); + } + raw.entry = *blocks.get(&function.entry).ok_or_else(|| backend(None))?; + for block in &function.blocks { + let first = self.instructions.len() as u64; + for (ordinal, instruction) in block.instructions.iter().enumerate() { + let native = self.instruction(instruction, &slots, &blocks)?; + push(&mut self.instructions, native)?; + push( + &mut self.sites, + ExecutionSite { + function: function.id, + block: block.id, + instruction: ordinal, + value: destination(instruction), + }, + )?; + } + let native = self.terminator( + block.terminator.as_ref().ok_or_else(|| backend(None))?, + &slots, + &blocks, + )?; + push(&mut self.instructions, native)?; + push( + &mut self.sites, + ExecutionSite { + function: function.id, + block: block.id, + instruction: block.instructions.len(), + value: None, + }, + )?; + push( + &mut self.blocks, + RawBlock { + id: u64::from(block.id.0), + function: index as u64, + first, + count: self.instructions.len() as u64 - first, + }, + )?; + } + } + push(&mut self.functions, raw)?; + } + for global in &self.module.global_storage { + let ty = self.ty(&global.ty)?; + let mut native = RawGlobal { + id: u64::from(global.id.0), + ty, + align: u64::from(global.align), + readonly: u64::from(global.readonly), + ..RawGlobal::default() + }; + if let GlobalStorageInit::Value(value) = &global.init { + native.initialized = 1; + native.value = self.value(&Value::Scalar(value.clone()), ty, true)?; + } + push(&mut self.globals, native)?; + } + Ok(()) + } + + fn instruction( + &mut self, + instruction: &'a Instruction, + slots: &HashMap, + blocks: &HashMap, + ) -> Result { + let slot = |id: &ValueId| slots.get(id).copied().ok_or_else(|| backend(None)); + let block = |id: &BlockId| blocks.get(id).copied().ok_or_else(|| backend(None)); + let mut raw = RawInstruction { + ty: self.ty(&VOID_TYPE)?, + dst: MISSING, + global: MISSING, + ..RawInstruction::default() + }; + if let Some(dst) = destination(instruction) { + raw.dst = slot(&dst)?; + } + match instruction { + Instruction::GlobalAddr { global, ty, .. } => { + raw.op = 0; + raw.ty = self.ty(ty)?; + raw.global = *self.global_ids.get(global).ok_or_else(|| backend(None))?; + }, + Instruction::LifetimeEnd { ptr } => { + raw.op = 1; + raw.sub = 1; + raw.a = slot(ptr)?; + }, + Instruction::PtrDiff { lhs, rhs, .. } => { + raw.op = 2; + raw.a = slot(lhs)?; + raw.b = slot(rhs)?; + }, + Instruction::ConstDecl { expression, value, .. } => { + raw.op = 3; + raw.ty = self.ty(&expression.ty)?; + (raw.literal, raw.low, raw.high) = literal(value); + }, + Instruction::Const { ty, value, .. } => { + raw.op = 4; + raw.ty = self.ty(ty)?; + (raw.literal, raw.low, raw.high) = literal(value); + }, + Instruction::Undef { ty, .. } => { + raw.op = 5; + raw.ty = self.ty(ty)?; + }, + Instruction::Mov { ty, src, .. } => { + raw.op = 6; + raw.ty = self.ty(ty)?; + raw.a = slot(src)?; + }, + Instruction::Bin { op, ty, lhs, rhs, .. } => { + raw.op = 7; + raw.sub = bin_code(op); + raw.ty = self.ty(ty)?; + raw.a = slot(lhs)?; + raw.b = slot(rhs)?; + }, + Instruction::Neg { ty, src, .. } | Instruction::Not { ty, src, .. } => { + raw.op = if matches!(instruction, Instruction::Neg { .. }) { 8 } else { 9 }; + raw.ty = self.ty(ty)?; + raw.a = slot(src)?; + }, + Instruction::Cmp { op, ty, lhs, rhs, .. } => { + raw.op = 10; + raw.sub = cmp_code(*op); + raw.ty = self.ty(ty)?; + raw.a = slot(lhs)?; + raw.b = slot(rhs)?; + }, + Instruction::ICmp { pred, ty, lhs, rhs, .. } => { + raw.op = 11; + raw.sub = icmp_code(pred); + raw.ty = self.ty(ty)?; + raw.a = slot(lhs)?; + raw.b = slot(rhs)?; + }, + Instruction::FCmp { pred, ty, lhs, rhs, .. } => { + raw.op = 12; + raw.sub = fcmp_code(pred); + raw.ty = self.ty(ty)?; + raw.a = slot(lhs)?; + raw.b = slot(rhs)?; + }, + Instruction::Select { ty, cond, on_true, on_false, .. } => { + raw.op = 13; + raw.ty = self.ty(ty)?; + raw.a = slot(cond)?; + raw.b = slot(on_true)?; + raw.c = slot(on_false)?; + }, + Instruction::Cast { op, dst_ty, src_ty, src, .. } => { + raw.op = 14; + raw.sub = cast_code(op); + raw.ty = self.ty(dst_ty)?; + raw.other = self.ty(src_ty)?; + raw.a = slot(src)?; + }, + Instruction::Phi { ty, incomings, .. } => { + raw.op = 15; + raw.ty = self.ty(ty)?; + raw.first = self.operands.len() as u64; + raw.count = incomings.len() as u64; + for (value, predecessor) in incomings { + push(&mut self.operands, slot(value)?)?; + push(&mut self.operands, block(predecessor)?)?; + } + }, + Instruction::Extract { dst_ty, tuple, index, .. } => { + raw.op = 16; + raw.ty = self.ty(dst_ty)?; + raw.a = slot(tuple)?; + raw.sub = u64::from(*index); + }, + Instruction::Checked { op, ty, lhs, rhs, .. } => { + raw.op = 17; + raw.sub = checked_code(op); + raw.ty = self.ty(ty)?; + raw.a = slot(lhs)?; + raw.b = slot(rhs)?; + }, + Instruction::Alloca { ty, align, .. } => { + raw.op = 18; + raw.ty = self.ty(ty)?; + raw.align = u64::from(*align); + }, + Instruction::VolatileLoad { ty, ptr, align, .. } + | Instruction::Load { ty, ptr, align, .. } => { + raw.op = + if matches!(instruction, Instruction::VolatileLoad { .. }) { 19 } else { 21 }; + raw.ty = self.ty(ty)?; + raw.a = slot(ptr)?; + raw.align = u64::from(*align); + }, + Instruction::VolatileStore { ty, value, ptr, align } + | Instruction::Store { ty, value, ptr, align } => { + raw.op = + if matches!(instruction, Instruction::VolatileStore { .. }) { 20 } else { 22 }; + raw.ty = self.ty(ty)?; + raw.a = slot(value)?; + raw.b = slot(ptr)?; + raw.align = u64::from(*align); + }, + Instruction::Uninit { ty, ptr, align } => { + raw.op = 23; + raw.ty = self.ty(ty)?; + raw.a = slot(ptr)?; + raw.align = u64::from(*align); + }, + Instruction::Gep { dst_ty, base_ptr, indices, .. } => { + raw.op = 24; + raw.ty = self.ty(dst_ty)?; + raw.a = slot(base_ptr)?; + raw.first = self.operands.len() as u64; + raw.count = indices.len() as u64; + for value in indices { + push(&mut self.operands, slot(value)?)?; + } + }, + Instruction::Memcpy { dst, src, n, align } => { + raw.op = 25; + raw.a = slot(dst)?; + raw.b = slot(src)?; + raw.c = slot(n)?; + raw.align = u64::from(*align); + }, + Instruction::Memset { dst, val, n, align } => { + raw.op = 26; + raw.a = slot(dst)?; + raw.b = slot(val)?; + raw.c = slot(n)?; + raw.align = u64::from(*align); + }, + Instruction::NullFunction { signature, .. } => { + raw.op = 27; + raw.signature = self.signature(signature)?; + raw.ty = raw.signature; + }, + Instruction::FunctionAddr { function, signature, .. } => { + raw.op = 28; + raw.signature = self.signature(signature)?; + raw.ty = raw.signature; + raw.a = *self.declaration_ids.get(function).ok_or_else(|| backend(None))?; + }, + Instruction::Call { convention, ret_ty, callee, args, .. } => { + raw.op = 29; + raw.ty = self.ty(ret_ty)?; + raw.sub = u64::from(*convention == CallingConvention::SysV64); + match callee { + Callee::Direct(function) => { + raw.a = *self.declaration_ids.get(function).ok_or_else(|| backend(None))?; + }, + Callee::Indirect(value) => { + raw.flags = 1; + raw.a = slot(value)?; + }, + } + raw.first = self.operands.len() as u64; + raw.count = args.len() as u64; + for arg in args { + push(&mut self.operands, slot(arg)?)?; + } + }, + Instruction::TrapIf { cond, reason } => { + raw.op = 30; + raw.a = slot(cond)?; + raw.global = push(&mut self.reasons, reason)?; + }, + } + Ok(raw) + } + + fn terminator( + &mut self, + terminator: &'a Terminator, + slots: &HashMap, + blocks: &HashMap, + ) -> Result { + let slot = |id: &ValueId| slots.get(id).copied().ok_or_else(|| backend(None)); + let block = |id: &BlockId| blocks.get(id).copied().ok_or_else(|| backend(None)); + let mut raw = RawInstruction { + ty: self.ty(&VOID_TYPE)?, + dst: MISSING, + global: MISSING, + ..RawInstruction::default() + }; + match terminator { + Terminator::Br { target } => { + raw.op = 31; + raw.a = block(target)?; + }, + Terminator::CBr { cond, then_bb, else_bb } => { + raw.op = 32; + raw.a = slot(cond)?; + raw.b = block(then_bb)?; + raw.c = block(else_bb)?; + }, + Terminator::Switch { ty, value, default_bb, cases } => { + raw.op = 33; + raw.ty = self.ty(ty)?; + raw.a = slot(value)?; + raw.b = block(default_bb)?; + raw.first = self.operands.len() as u64; + raw.count = cases.len() as u64; + for (value, target) in cases { + let (_, low, high) = literal(value); + push(&mut self.operands, low)?; + push(&mut self.operands, high)?; + push(&mut self.operands, block(target)?)?; + } + }, + Terminator::Ret { ty, value } => { + raw.op = 34; + raw.ty = self.ty(ty)?; + raw.a = value.as_ref().map(slot).transpose()?.unwrap_or(MISSING); + }, + Terminator::Trap { reason } => { + raw.op = 35; + raw.global = push(&mut self.reasons, reason)?; + }, + } + Ok(raw) + } +} + +fn literal(value: &ConstValue) -> (u64, u64, u64) { + let (kind, bits) = match value { + ConstValue::I(value) => (1, *value as u128), + ConstValue::U(value) => (2, *value), + ConstValue::Bool(value) => (3, u128::from(*value)), + ConstValue::F(FloatBits::F16(value)) => (4, u128::from(*value)), + ConstValue::F(FloatBits::F32(value)) => (5, u128::from(*value)), + ConstValue::F(FloatBits::F64(value)) => (6, u128::from(*value)), + }; + (kind, bits as u64, (bits >> 64) as u64) +} + +fn decode_literal(kind: u64, low: u64, high: u64, ty: &Type) -> Result { + let raw = u128::from(low) | (u128::from(high) << 64); + let signed_width = match ty { + Type::I1 => Some(1), + Type::I8 => Some(8), + Type::I16 => Some(16), + Type::I32 => Some(32), + Type::I64 => Some(64), + Type::I128 => Some(128), + _ => None, + }; + let unsigned_width = match ty { + Type::U1 => Some(1), + Type::U8 => Some(8), + Type::U16 => Some(16), + Type::U32 => Some(32), + Type::U64 => Some(64), + Type::U128 => Some(128), + _ => None, + }; + match kind { + 1 if signed_width.is_some_and(|width| { + width == 128 || ((raw as i128) << (128 - width) >> (128 - width)) == raw as i128 + }) => + { + Ok(ConstValue::I(raw as i128)) + }, + 2 if unsigned_width.is_some_and(|width| width == 128 || raw >> width == 0) => { + Ok(ConstValue::U(raw)) + }, + 3 if *ty == Type::Bool && raw <= 1 => Ok(ConstValue::Bool(raw != 0)), + 4 if *ty == Type::F16 && high == 0 && low <= u64::from(u16::MAX) => { + Ok(ConstValue::F(FloatBits::F16(low as u16))) + }, + 5 if *ty == Type::F32 && high == 0 && low <= u64::from(u32::MAX) => { + Ok(ConstValue::F(FloatBits::F32(low as u32))) + }, + 6 if *ty == Type::F64 && high == 0 => Ok(ConstValue::F(FloatBits::F64(low))), + _ => Err(backend(None)), + } +} + +fn bin_code(op: &BinOp) -> u64 { + match op { + BinOp::Add => 0, + BinOp::Sub => 1, + BinOp::Mul => 2, + BinOp::UDiv => 3, + BinOp::SDiv => 4, + BinOp::URem => 5, + BinOp::SRem => 6, + BinOp::FAdd => 7, + BinOp::FSub => 8, + BinOp::FMul => 9, + BinOp::FDiv => 10, + BinOp::FRem => 11, + BinOp::And => 12, + BinOp::Or => 13, + BinOp::Xor => 14, + BinOp::Shl => 15, + BinOp::LShr => 16, + BinOp::AShr => 17, + } +} + +fn cast_code(op: &CastOp) -> u64 { + match op { + CastOp::ZExt => 0, + CastOp::SExt => 1, + CastOp::Trunc => 2, + CastOp::FExt => 3, + CastOp::FTrunc => 4, + CastOp::IToF_S => 5, + CastOp::IToF_U => 6, + CastOp::FToI_S => 7, + CastOp::FToI_U => 8, + CastOp::Bitcast => 9, + CastOp::PtrToInt => 10, + CastOp::IntToPtr => 11, + CastOp::CheckedInt => 12, + } +} + +fn cmp_code(op: CmpOp) -> u64 { + match op { + CmpOp::Eq => 0, + CmpOp::Ne => 1, + CmpOp::SLt => 2, + CmpOp::SLe => 3, + CmpOp::SGt => 4, + CmpOp::SGe => 5, + CmpOp::ULt => 6, + CmpOp::ULe => 7, + CmpOp::UGt => 8, + CmpOp::UGe => 9, + CmpOp::FEq => 10, + CmpOp::FNe => 11, + CmpOp::FLt => 12, + CmpOp::FLe => 13, + CmpOp::FGt => 14, + CmpOp::FGe => 15, + } +} + +fn icmp_code(pred: &ICmpPred) -> u64 { + match pred { + ICmpPred::Eq => 0, + ICmpPred::Ne => 1, + ICmpPred::Ult => 2, + ICmpPred::Ule => 3, + ICmpPred::Ugt => 4, + ICmpPred::Uge => 5, + ICmpPred::Slt => 6, + ICmpPred::Sle => 7, + ICmpPred::Sgt => 8, + ICmpPred::Sge => 9, + } +} + +fn fcmp_code(pred: &FCmpPred) -> u64 { + match pred { + FCmpPred::Oeq => 0, + FCmpPred::One => 1, + FCmpPred::Olt => 2, + FCmpPred::Ole => 3, + FCmpPred::Ogt => 4, + FCmpPred::Oge => 5, + FCmpPred::Ord => 6, + FCmpPred::Uno => 7, + FCmpPred::Ueq => 8, + FCmpPred::Une => 9, + FCmpPred::Ult => 10, + FCmpPred::Ule => 11, + FCmpPred::Ugt => 12, + FCmpPred::Uge => 13, + } +} + +fn checked_code(op: &CheckedOp) -> u64 { + match op { + CheckedOp::UAdd => 0, + CheckedOp::USub => 1, + CheckedOp::UMul => 2, + CheckedOp::SAdd => 3, + CheckedOp::SSub => 4, + CheckedOp::SMul => 5, + } +} + +impl Program<'_> { + fn site(&self, index: u64, entry: FunctionId) -> Result { + if index != MISSING { + return self + .sites + .get(usize::try_from(index).map_err(|_| backend(None))?) + .copied() + .ok_or_else(|| backend(None)); + } + let body = self + .module + .functions + .iter() + .find(|function| function.id == entry) + .ok_or_else(|| backend(None))?; + Ok(ExecutionSite { function: entry, block: body.entry, instruction: 0, value: None }) + } + + fn error( + &self, + raw: &RawResult, + entry: FunctionId, + options: InterpreterOptions, + ) -> Result { + let count = |value| usize::try_from(value).map_err(|_| backend(None)); + let function = |index: u64| { + self.module + .declarations + .get(count(index)?) + .map(|decl| decl.id) + .ok_or_else(|| backend(None)) + }; + let at = || self.site(raw.site, entry); + let trap = |reason| { + Ok(InterpreterError::Trap(InterpreterTrap { site: at()?, reason, steps: raw.steps })) + }; + Ok(match raw.error { + 1 => InterpreterError::UnknownFunction(FunctionId( + u32::try_from(raw.detail).map_err(|_| backend(None))?, + )), + 2 => InterpreterError::UnsupportedSignature(function(raw.detail)?), + 3 => InterpreterError::ArgumentCount { + expected: count(raw.detail)?, + got: count(raw.extra)?, + }, + 4 => InterpreterError::ArgumentType { + index: count(raw.detail)?, + expected: self.type_model(raw.extra)?, + }, + 5 => InterpreterError::UnsupportedInstruction { + site: at()?, + operation: match raw.detail { + 0 => "undef", + 1 => "non-scalar constant", + 2 => "non-scalar value", + 3 => "non-integer arithmetic/comparison", + 4 => "unsupported cast", + 5 => "alloca", + 6 => "load", + 7 => "store", + 8 => "uninit", + 9 => "call", + 10 => "zero-sized pointer arithmetic", + _ => return Err(backend(None)), + }, + }, + 6 if raw.detail == options.max_steps => { + InterpreterError::StepLimit { site: at()?, limit: raw.detail } + }, + 7..=9 => { + let (resource, expected) = match raw.error { + 7 => (CallResource::Depth, options.max_call_depth as u64), + 8 => (CallResource::Frames, options.max_frames), + _ => (CallResource::Values, options.max_live_values as u64), + }; + if raw.detail != expected { + return Err(backend(None)); + } + InterpreterError::CallLimit { site: at()?, resource, limit: raw.detail } + }, + 10 => return trap(TrapReason::DivisionByZero), + 11 => return trap(TrapReason::RemainderByZero), + 12 => return trap(TrapReason::InvalidConversion), + 13 => { + let reason = self.reasons.get(count(raw.detail)?).ok_or_else(|| backend(None))?; + return trap(TrapReason::Explicit((*reason).to_owned())); + }, + 14 => return trap(TrapReason::NullFunction), + 15 => return trap(TrapReason::InvalidFunctionPointer), + 16 => return trap(TrapReason::FunctionSignatureMismatch), + 17 => InterpreterError::UnsupportedGlobal( + self.module.global_storage.get(count(raw.detail)?).ok_or_else(|| backend(None))?.id, + ), + 18 => { + InterpreterError::Verification(Box::new(VerifyError::ResourceLimit(LimitError { + resource: Resource::AnalysisWork, + limit: options.ir_limits.max_analysis_work, + }))) + }, + _ => return Err(backend(None)), + }) + } + + fn failure( + &self, + cause: InterpreterError, + entry: FunctionId, + frames: &[RawFrame], + trace_limit: usize, + ) -> InterpreterError { + let Some(site) = cause.runtime_site() else { + return cause; + }; + let mut budget = SourceDetailBudget::new(); + let original = execution_source(self.module, site, &mut budget); + let caller_count = frames.len().saturating_sub(1); + if original.is_none() && caller_count == 0 { + return cause; + } + let mut retained = caller_count.min(trace_limit.min(MAX_RUNTIME_TRACE_FRAMES)); + let mut calls = Vec::new(); + if calls.try_reserve_exact(retained).is_err() { + retained = 0; + } + for child in frames.iter().skip(1).rev().take(retained) { + let Some(callee) = + self.module.declarations.get(child.function as usize).map(|decl| decl.id) + else { + return backend(Some(site)); + }; + let Ok(call_site) = self.site(child.call_site, entry) else { + return backend(Some(site)); + }; + if child.call_site == MISSING { + return backend(Some(site)); + } + calls.push(RuntimeCallFrame { + caller: call_site.function, + callee, + site: call_site, + original: execution_source(self.module, call_site, &mut budget), + }); + } + calls.reverse(); + InterpreterError::Diagnostic { + cause: Box::new(cause), + diagnostic: Box::new(RuntimeDiagnostic { + site: Some(site), + global: None, + original, + calls, + omitted_call_frames: caller_count - retained, + omitted_source_details: budget.omitted, + }), + } + } + + fn memory_event( + &mut self, + event: &RawEvent, + plans: &[RawGep], + memory: &mut memory::Memory, + ) -> std::result::Result { + fn transport(_: T) -> memory::Fault { + memory::Fault::Backend(BACKEND) + } + let pointer = |value: RawValue| { + if value.kind != 3 { + return Err(memory::Fault::Backend(BACKEND)); + } + value.pointer.decode().map_err(transport) + }; + let align = u32::try_from(event.align).map_err(transport)?; + let mut value = RawValue { ty: event.ty, ..RawValue::default() }; + match event.kind { + 1 => { + let natural = u32::try_from(event.natural).map_err(transport)?; + let result = match event.flag { + 0 => memory.allocate(event.size, natural, align)?, + 1 => memory.allocate_global(event.size, natural, align)?, + _ => return Err(memory::Fault::Backend(BACKEND)), + }; + value.kind = 3; + value.pointer = result.into(); + }, + 2 => { + self.prepare_type(event.ty).map_err(transport)?; + let signature = + if matches!(self.type_ref(event.ty).map_err(transport)?, Type::FnPtr(_)) { + Some(self.signature_arc(event.ty).map_err(transport)?) + } else { + None + }; + let loaded = memory.load_with_signature( + pointer(event.left)?, + self.type_ref(event.ty).map_err(transport)?, + align, + signature.as_ref(), + )?; + value = self.value(&loaded, event.ty, true).map_err(transport)?; + }, + 3 => { + self.prepare_type(event.ty).map_err(transport)?; + let stored = self.decode_value(event.right).map_err(transport)?; + memory.store( + pointer(event.left)?, + self.type_ref(event.ty).map_err(transport)?, + &stored, + align, + )?; + }, + 4 => memory.uninit(pointer(event.left)?, event.size, align)?, + 5 => memory.copy(pointer(event.left)?, pointer(event.right)?, event.size, align)?, + 6 => memory.set( + pointer(event.left)?, + u8::try_from(event.flag).map_err(transport)?, + event.size, + align, + )?, + 7 => { + let first = usize::try_from(event.first).map_err(transport)?; + let end = first + .checked_add(usize::try_from(event.count).map_err(transport)?) + .ok_or(memory::Fault::Backend(BACKEND))?; + let plans = plans.get(first..end).ok_or(memory::Fault::Backend(BACKEND))?; + let mut steps = Vec::new(); + let mut indices = Vec::new(); + steps.try_reserve_exact(plans.len()).map_err(|_| memory::Fault::Limit { + resource: MemoryResource::HostAllocation, + limit: plans.len() as u64, + })?; + indices.try_reserve_exact(plans.len()).map_err(|_| memory::Fault::Limit { + resource: MemoryResource::HostAllocation, + limit: plans.len() as u64, + })?; + for plan in plans { + steps.push(match plan.kind { + 0 => memory::GepStep::Stride(plan.amount), + 1 => memory::GepStep::Field(plan.amount), + _ => return Err(memory::Fault::Backend(BACKEND)), + }); + let bits = u128::from(plan.low) | (u128::from(plan.high) << 64); + indices.push(match plan.signed { + 0 => ConstValue::U(bits), + 1 => ConstValue::I(bits as i128), + _ => return Err(memory::Fault::Backend(BACKEND)), + }); + } + value.kind = 3; + value.pointer = memory.gep(pointer(event.left)?, &steps, &indices)?.into(); + }, + 8 => memory.retire_stack( + pointer(event.left)?, + usize::try_from(event.owner).map_err(transport)?, + )?, + 9 => { + value.kind = 1; + (value.literal, value.low, value.high) = literal(&ConstValue::I( + memory.difference(pointer(event.left)?, pointer(event.right)?)?, + )); + }, + 10 => { + value.kind = 1; + (value.literal, value.low, value.high) = literal(&ConstValue::Bool( + memory.equal(pointer(event.left)?, pointer(event.right)?)?, + )); + }, + 11 => memory.retire_from(usize::try_from(event.owner).map_err(transport)?)?, + 12 if event.flag <= 1 => { + value.kind = 3; + value.pointer = memory.seal_global(pointer(event.left)?, event.flag != 0)?.into(); + }, + _ => return Err(memory::Fault::Backend(BACKEND)), + } + Ok(value) + } +} + +fn storage() -> Storage { + let target = Target::X86_64WhaleLinux.specification(); + let storage = &target.storage; + let (large_array_threshold, large_array_align, has_large_array) = storage + .large_array + .map(|(threshold, align)| (threshold, u64::from(align), 1)) + .unwrap_or((0, 0, 0)); + Storage { + ptr_bits: u64::from(storage.data.ptr_bits), + pointer_align: u64::from(storage.pointer_align), + scalar_align1: u64::from(storage.scalar_align[0]), + scalar_align2: u64::from(storage.scalar_align[1]), + scalar_align4: u64::from(storage.scalar_align[2]), + scalar_align8: u64::from(storage.scalar_align[3]), + scalar_align16: u64::from(storage.scalar_align[4]), + large_array_threshold, + large_array_align, + has_large_array, + } +} + +fn grow(buffer: &mut Vec, requested: u64, maximum: usize) -> Result { + let requested = usize::try_from(requested).map_err(|_| backend(None))?; + if requested > maximum { + return Err(backend(None)); + } + if requested <= buffer.len() { + return Ok(false); + } + reserve(buffer, requested - buffer.len())?; + buffer.resize_with(requested, T::default); + Ok(true) +} + +pub(super) fn run<'module>( + module: &'module Module, + function: FunctionId, + arguments: Arguments<'_, '_>, + options: InterpreterOptions, +) -> Result> { + verify_module_with_limits(module, options.ir_limits) + .map_err(|error| InterpreterError::Verification(Box::new(error)))?; + let mut program = Program::new(module)?; + program.marshal()?; + let mut input = Vec::new(); + reserve(&mut input, arguments.len())?; + match &arguments { + Arguments::Scalars(values) => { + for value in *values { + input.push(program.value(&Value::Scalar(value.clone()), MISSING, true)?); + } + }, + Arguments::Runtime(values) => { + for value in *values { + let ty = program.ty(&value.ty)?; + input.push(program.value( + &value.value, + ty, + arguments.valid_origin(input.len(), module), + )?); + } + }, + } + let type_count = program.types.len(); + let function_count = program.functions.len(); + let instruction_count = program.instructions.len(); + let global_count = program.globals.len(); + let table_capacity = function_count + .max(1) + .checked_mul(2) + .and_then(usize::checked_next_power_of_two) + .ok_or_else(|| backend(None))?; + let mut layout_nodes = initialized::(type_count)?; + let mut layouts = initialized::(type_count)?; + let mut offsets = initialized::(program.edges.len())?; + let mut plans = initialized::(program.operands.len())?; + let mut ordinals = initialized::(program.value_types.len())?; + let mut table = initialized::(table_capacity)?; + let mut prepared = initialized::(function_count)?; + let mut pending_previous = initialized::(function_count)?; + let mut pending_next = initialized::(function_count)?; + let mut pending_flags = initialized::(function_count)?; + let mut callable_flags = initialized::(function_count)?; + let mut callable_targets = initialized::(function_count)?; + let mut indirect_signatures = initialized::(instruction_count)?; + let mut indirect_sites = initialized::(instruction_count)?; + let mut global_values = initialized::(global_count)?; + let mut frames = Vec::::new(); + let mut slots = Vec::::new(); + let mut phis = Vec::::new(); + let mut storage = storage(); + let mut result = RawResult::default(); + let mut driver = RawDriver { + types: program.types.as_mut_ptr(), + type_count: type_count as u64, + type_edges: program.edges.as_mut_ptr(), + type_edge_count: program.edges.len() as u64, + functions: program.functions.as_mut_ptr(), + function_count: function_count as u64, + blocks: program.blocks.as_mut_ptr(), + block_count: program.blocks.len() as u64, + instructions: program.instructions.as_mut_ptr(), + instruction_count: instruction_count as u64, + operands: program.operands.as_mut_ptr(), + operand_count: program.operands.len() as u64, + value_types: program.value_types.as_mut_ptr(), + value_type_count: program.value_types.len() as u64, + globals: program.globals.as_mut_ptr(), + global_count: global_count as u64, + global_values: global_values.as_mut_ptr(), + arguments: input.as_mut_ptr(), + argument_count: input.len() as u64, + scalar_arguments: u64::from(matches!(arguments, Arguments::Scalars(_))), + entry_id: u64::from(function.0), + storage: &mut storage, + layout_nodes: layout_nodes.as_mut_ptr(), + layouts: layouts.as_mut_ptr(), + layout_offsets: offsets.as_mut_ptr(), + plans: plans.as_mut_ptr(), + plan_capacity: plans.len() as u64, + ordinals: ordinals.as_mut_ptr(), + function_table: table.as_mut_ptr(), + function_table_capacity: table.len() as u64, + prepared: prepared.as_mut_ptr(), + pending_previous: pending_previous.as_mut_ptr(), + pending_next: pending_next.as_mut_ptr(), + pending_flags: pending_flags.as_mut_ptr(), + callable_flags: callable_flags.as_mut_ptr(), + callable_targets: callable_targets.as_mut_ptr(), + indirect_signatures: indirect_signatures.as_mut_ptr(), + indirect_sites: indirect_sites.as_mut_ptr(), + indirect_capacity: indirect_signatures.len() as u64, + max_steps: options.max_steps, + max_depth: options.max_call_depth as u64, + max_frames: options.max_frames, + max_values: options.max_live_values as u64, + max_work: options.ir_limits.max_analysis_work as u64, + result: &mut result, + ..RawDriver::default() + }; + let mut memory = memory::Memory::new(options.memory_limits); + let mut previous_steps = 0; + let mut previous_work = 0; + loop { + driver.memory_allocations = memory.allocation_count() as u64; + // All spans are initialized, stable for this step, and exclusively borrowed. + let status = unsafe { whale_ir_runtime_step(&mut driver) }; + if status != result.status as i32 + || result.status > 4 + || driver.steps < previous_steps + || driver.steps > options.max_steps + || driver.work < previous_work + || driver.work > options.ir_limits.max_analysis_work as u64 + || result.steps != driver.steps + || driver.frame_count > frames.len() as u64 + || driver.slot_count > slots.len() as u64 + || driver.plan_count > plans.len() as u64 + { + return Err(backend(program.site(result.site, function).ok())); + } + previous_steps = driver.steps; + previous_work = driver.work; + let active_frames = &frames[..driver.frame_count as usize]; + let fail = + |cause| program.failure(cause, function, active_frames, options.max_trace_frames); + match result.status { + 0 => { + let value = if result.value.kind == 0 { + None + } else { + let ty = program.type_model(result.value.ty)?; + let value = program.decode_value(result.value)?; + let callable_module = matches!( + value, + Value::FunctionPointer(FunctionPointer { + target: FunctionTarget::Defined(_), + .. + }) + ) + .then_some(module); + Some(RuntimeValue { ty, value, callable_module }) + }; + return Ok(RuntimeInterpreterResult { value, steps: result.steps }); + }, + 1 => match program.memory_event(&result.event, &plans, &mut memory) { + Ok(value) => { + driver.resume_value = value; + driver.resume = 1; + }, + Err(fault) => { + let global = if result.global == MISSING { + None + } else { + Some( + module + .global_storage + .get(result.global as usize) + .ok_or_else(|| backend(None))? + .id, + ) + }; + let site = program.site(result.site, function).ok(); + let cause = match (global, fault) { + (_, memory::Fault::Backend(reason)) => { + InterpreterError::Backend { site, reason } + }, + (Some(global), memory::Fault::Trap(reason)) => { + InterpreterError::GlobalMemory { global, reason } + }, + (Some(global), memory::Fault::Limit { resource, limit }) => { + InterpreterError::GlobalMemoryLimit { global, resource, limit } + }, + (None, memory::Fault::Trap(reason)) => { + InterpreterError::Trap(InterpreterTrap { + site: site.ok_or_else(|| backend(None))?, + reason: TrapReason::Memory(reason), + steps: result.steps, + }) + }, + (None, memory::Fault::Limit { resource, limit }) => { + InterpreterError::MemoryLimit { + site: site.ok_or_else(|| backend(None))?, + resource, + limit, + } + }, + }; + return Err(program.failure( + cause, + function, + active_frames, + options.max_trace_frames, + )); + }, + }, + 2 => { + let event = &result.event; + let resized = (|| -> Result { + Ok(grow(&mut frames, event.frame_capacity, options.max_call_depth)? + | grow(&mut slots, event.value_capacity, options.max_live_values)? + | grow(&mut phis, event.phi_capacity, options.max_live_values)?) + })(); + let changed = resized.map_err(|cause| { + let cause = + if matches!(cause, InterpreterError::Backend { reason: ALLOCATION, .. }) { + match program.site(result.site, function) { + Ok(site) => InterpreterError::CallLimit { + site, + resource: CallResource::HostAllocation, + limit: event + .frame_capacity + .max(event.value_capacity) + .max(event.phi_capacity), + }, + Err(_) => cause, + } + } else { + cause + }; + program.failure( + cause, + function, + &frames[..driver.frame_count as usize], + options.max_trace_frames, + ) + })?; + if !changed { + return Err(program.failure( + backend(program.site(result.site, function).ok()), + function, + &frames[..driver.frame_count as usize], + options.max_trace_frames, + )); + } + driver.frames = frames.as_mut_ptr(); + driver.frame_capacity = frames.len() as u64; + driver.slots = slots.as_mut_ptr(); + driver.slot_capacity = slots.len() as u64; + driver.phis = phis.as_mut_ptr(); + driver.phi_capacity = phis.len() as u64; + driver.resume = 2; + }, + 3 => return Err(fail(program.error(&result, function, options)?)), + 4 => return Err(fail(backend(program.site(result.site, function).ok()))), + _ => return Err(backend(None)), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn wire_records_match_native_field_widths() { + use std::mem::{align_of, offset_of, size_of}; + assert_eq!(size_of::(), 40); + assert_eq!(size_of::(), 80); + assert_eq!(size_of::(), 160); + assert_eq!(size_of::(), 168); + assert_eq!(size_of::(), 80); + assert_eq!(size_of::(), 88); + assert_eq!(size_of::(), 32); + assert_eq!(size_of::(), 168); + assert_eq!(size_of::(), 216); + assert_eq!(align_of::(), 8); + assert_eq!(offset_of!(RawValue, pointer), 48); + assert_eq!(offset_of!(RawValue, origin), 152); + assert_eq!(offset_of!(RawSlot, value), 8); + assert_eq!(offset_of!(RawGlobal, value), 56); + } + + #[test] + fn pointer_transport_preserves_every_authority_field_and_rejects_flags() { + let pointer = memory::Pointer { + address: 0x1008, + capability: Some(memory::Capability { + arena: 7, + allocation: 13, + generation: 19, + lower: 3, + upper: 29, + offset: 8, + read: true, + write: false, + }), + }; + let raw = RawPointer::from(pointer); + assert_eq!(raw.decode().unwrap(), pointer); + for field in 0..3 { + let mut invalid = raw; + match field { + 0 => invalid.present = 2, + 1 => invalid.read = 2, + _ => invalid.write = 2, + } + assert!(matches!(invalid.decode(), Err(InterpreterError::Backend { .. }))); + } + assert_eq!( + RawPointer::from(memory::Pointer::raw(u64::MAX)).decode().unwrap(), + memory::Pointer::raw(u64::MAX) + ); + } + + #[test] + fn literal_transport_retains_payloads_and_rejects_truncated_results() { + for (ty, value) in [ + (Type::I1, ConstValue::I(-1)), + (Type::I128, ConstValue::I(i128::MIN)), + (Type::U128, ConstValue::U(u128::MAX)), + (Type::F16, ConstValue::F(FloatBits::F16(0xfd55))), + (Type::F32, ConstValue::F(FloatBits::F32(0x7f80_0123))), + (Type::F64, ConstValue::F(FloatBits::F64(0xfff0_0123_4567_89ab))), + ] { + let (kind, low, high) = literal(&value); + assert_eq!(decode_literal(kind, low, high, &ty).unwrap(), value); + } + for (kind, low, high, ty) in [ + (1, 128, 0, Type::I8), + (1, 1, 0, Type::I1), + (2, 256, 0, Type::U8), + (2, 0, 1, Type::U64), + (3, 2, 0, Type::Bool), + (4, 65536, 0, Type::F16), + (5, 1, 1, Type::F32), + (6, 0, 1, Type::F64), + ] { + assert!(matches!( + decode_literal(kind, low, high, &ty), + Err(InterpreterError::Backend { .. }) + )); + } + } + + #[test] + fn native_driver_rejects_invalid_transport_without_fabricating_a_value() { + assert_eq!(unsafe { whale_ir_runtime_step(std::ptr::null_mut()) }, 4); + let mut result = RawResult::default(); + let mut driver = RawDriver { result: &mut result, ..RawDriver::default() }; + driver.type_count = u64::MAX; + assert_eq!(unsafe { whale_ir_runtime_step(&mut driver) }, 4); + assert_eq!(result.status, 4); + assert_eq!(result.value.kind, 0); + driver.type_count = 1; + assert_eq!(unsafe { whale_ir_runtime_step(&mut driver) }, 4); + assert_eq!(result.status, 4); + assert_eq!(result.value.kind, 0); + } + + #[test] + fn marshaler_retains_sparse_ids_and_uses_dense_local_slots() { + let module = parse_module( + r#"module { + format_version 7 semantics_version 1 target "x86_64-whale-linux" + datalayout { ptr=64, endian=little } + declare @f4294967295 "sparse": whale (i64) -> i64, linkage internal + fn @f4294967295 "sparse"(%v2147483647 "argument": i64) -> i64, entry %b4294967295 { + %b4294967295 "entry": + %v4294967295: i64 = mov i64 %v2147483647 + ret i64 %v4294967295 + } + }"#, + ) + .unwrap(); + verify_module(&module).unwrap(); + let mut program = Program::new(&module).unwrap(); + program.marshal().unwrap(); + assert_eq!(program.functions[0].id, u64::from(u32::MAX)); + assert_eq!(program.functions[0].value_count, 2); + assert_eq!(program.functions[0].entry, 0); + assert_eq!(program.blocks[0].id, u64::from(u32::MAX)); + assert_eq!(program.instructions[0].a, 0); + assert_eq!(program.instructions[0].dst, 1); + assert_eq!(program.instructions[1].a, 1); + assert_eq!(program.sites[0].value, Some(ValueId(u32::MAX))); + assert_eq!(program.sites[1].instruction, 1); + } +} diff --git a/ir/src/interpreter/scalar.rs b/ir/src/interpreter/scalar.rs index 6f84f52..a96a46b 100644 --- a/ir/src/interpreter/scalar.rs +++ b/ir/src/interpreter/scalar.rs @@ -1,13 +1,18 @@ // SPDX-License-Identifier: MPL-2.0 //! Storage reinterpretation only: no floating-point arithmetic or conversion. +#[cfg(not(whale_wave_ir))] use super::integer; -use crate::{ConstValue, FloatBits, Type}; +use crate::Type; + +#[cfg(not(whale_wave_ir))] +use crate::{ConstValue, FloatBits}; pub(super) fn float_type(ty: &Type) -> bool { matches!(ty, Type::F16 | Type::F32 | Type::F64) } +#[cfg(not(whale_wave_ir))] pub(super) fn raw(ty: &Type, value: &ConstValue) -> u128 { match value { ConstValue::F(bits) => u128::from(bits.bits()), @@ -15,6 +20,7 @@ pub(super) fn raw(ty: &Type, value: &ConstValue) -> u128 { } } +#[cfg(not(whale_wave_ir))] pub(super) fn pack(ty: &Type, bits: u128) -> ConstValue { let float = match ty { Type::F16 => FloatBits::F16(bits as u16), @@ -25,6 +31,7 @@ pub(super) fn pack(ty: &Type, bits: u128) -> ConstValue { ConstValue::F(float) } +#[cfg(not(whale_wave_ir))] pub(super) fn compare(predicate: &crate::FCmpPred, lhs: &ConstValue, rhs: &ConstValue) -> bool { let (ConstValue::F(lhs), ConstValue::F(rhs)) = (lhs, rhs) else { unreachable!("verified floating operands") diff --git a/ir/src/lib.rs b/ir/src/lib.rs index d382d26..2b998e9 100644 --- a/ir/src/lib.rs +++ b/ir/src/lib.rs @@ -8,10 +8,16 @@ pub mod const_expr; mod constant; +#[cfg(whale_wave_ir)] +mod constant_wave; + pub mod float; pub mod effects; +#[cfg(whale_wave_ir)] +mod effects_wave; + pub mod pass; pub mod function; diff --git a/ir/src/pass.rs b/ir/src/pass.rs index ac770a5..4052f79 100644 --- a/ir/src/pass.rs +++ b/ir/src/pass.rs @@ -2,6 +2,20 @@ //! Verified, transactional pass boundaries. No optimization pipeline is enabled. use crate::{IrLimits, Module, VerifyError}; +#[cfg(whale_wave_ir)] +#[path = "pass_wave.rs"] +mod wave; + +#[path = "pass_dispose.rs"] +mod dispose; + +use dispose::discard; + +#[path = "fold_integer.rs"] +mod integer_fold; + +pub use integer_fold::IntegerConstantFold; + #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum AnalysisKind { Cfg, @@ -31,6 +45,7 @@ impl AnalysisState { self.epochs[kind as usize] } + #[cfg(not(whale_wave_ir))] fn invalidate(&mut self, which: Invalidates) -> Result<(), String> { let mut next = self.epochs; for (i, invalid) in [which.cfg, which.values, which.effects].into_iter().enumerate() { @@ -58,9 +73,12 @@ impl AnalysisCache { } pub fn get(&self, state: &AnalysisState) -> Option<&T> { - (std::sync::Arc::ptr_eq(&self.identity, &state.identity) - && self.epoch == state.epoch(self.kind)) - .then_some(&self.value) + #[cfg(whale_wave_ir)] + let current = wave::current(self, state); + #[cfg(not(whale_wave_ir))] + let current = std::sync::Arc::ptr_eq(&self.identity, &state.identity) + && self.epoch == state.epoch(self.kind); + current.then_some(&self.value) } } @@ -126,6 +144,19 @@ pub fn run_pass_with_limits( pass: &mut impl Pass, analyses: &mut AnalysisState, limits: IrLimits, +) -> Result { + #[cfg(whale_wave_ir)] + return wave::run(module, pass, analyses, limits); + #[cfg(not(whale_wave_ir))] + run_reference(module, pass, analyses, limits) +} + +#[cfg(not(whale_wave_ir))] +fn run_reference( + module: &mut Module, + pass: &mut impl Pass, + analyses: &mut AnalysisState, + limits: IrLimits, ) -> Result { let name = pass.name().to_owned(); let target = module.target.clone(); @@ -152,7 +183,81 @@ pub fn run_pass_with_limits( Ok(report) })(); if result.is_err() { - *module = before; + discard(std::mem::replace(module, before)); } result } + +#[cfg(all(test, whale_wave_ir))] +mod tests { + use super::*; + + use crate::{DataLayout, ModuleBuilder, Type}; + + fn module() -> Module { + let mut builder = ModuleBuilder::new("x86_64-whale-linux", DataLayout::default_64bit_le()); + let mut function = builder.begin_function("entry", vec![], Type::I32); + let value = function.const_i32(42); + function.ret(Some(value)); + function.finish(); + builder.finish() + } + + struct Edit; + + impl Pass for Edit { + fn name(&self) -> &str { + "edit" + } + + fn run(&mut self, module: &mut Module) -> Result { + module.functions[0].blocks[0].name.push_str("-changed"); + Ok(PassChange { changed: true, invalidates: Invalidates::ALL }) + } + } + + #[test] + fn wave_epoch_overflow_rolls_back_every_epoch_and_the_module() { + let mut module = module(); + let original = module.clone(); + let mut state = AnalysisState { epochs: [7, u64::MAX, 9], ..AnalysisState::default() }; + let cache = AnalysisCache::new(AnalysisKind::Values, &state, 42); + let error = run_pass(&mut module, &mut Edit, &mut state).unwrap_err(); + assert_eq!(error.stage, PassStage::Contract); + assert!(error.to_string().contains("epoch exhausted")); + assert_eq!(module, original); + assert_eq!(state.epochs, [7, u64::MAX, 9]); + assert_eq!(cache.get(&state), Some(&42)); + } + + struct Malformed(bool); + + impl Pass for Malformed { + fn name(&self) -> &str { + "malformed" + } + + fn run(&mut self, module: &mut Module) -> Result { + let mut ty = Type::I32; + for _ in 0..50_000 { + ty = Type::Ptr(Box::new(ty)); + } + module.functions[0].ret_ty = ty; + assert!(!self.0, "test transform panic"); + Ok(PassChange { changed: true, invalidates: Invalidates::ALL }) + } + } + + #[test] + fn failed_or_panicking_transforms_dispose_malformed_trees_iteratively() { + for panic in [false, true] { + let mut module = module(); + let original = module.clone(); + let mut state = AnalysisState::default(); + let error = run_pass(&mut module, &mut Malformed(panic), &mut state).unwrap_err(); + assert_eq!(error.stage, if panic { PassStage::Transform } else { PassStage::After }); + assert_eq!(module, original); + assert_eq!(state.epochs, [0; 3]); + } + } +} diff --git a/ir/src/pass_dispose.rs b/ir/src/pass_dispose.rs new file mode 100644 index 0000000..e1c6896 --- /dev/null +++ b/ir/src/pass_dispose.rs @@ -0,0 +1,89 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Iterative disposal of a rejected transform, including malformed deep trees. +use crate::limits::{discard_signature, discard_type}; + +use crate::{ConstExpr, ConstExprKind, Instruction, Module, Terminator}; + +fn expression(root: ConstExpr) { + let mut pending = vec![root]; + while let Some(expression) = pending.pop() { + discard_type(expression.ty); + match expression.kind { + ConstExprKind::Not(value) | ConstExprKind::Neg(value) => pending.push(*value), + ConstExprKind::Binary { left, right, .. } + | ConstExprKind::Compare { left, right, .. } => { + pending.push(*left); + pending.push(*right); + }, + ConstExprKind::Literal(_) | ConstExprKind::Reference(_) => {}, + } + } +} + +fn instruction(instruction: Instruction) { + use Instruction::*; + match instruction { + ConstDecl { expression: root, .. } => expression(root), + GlobalAddr { ty, .. } + | Const { ty, .. } + | Undef { ty, .. } + | Mov { ty, .. } + | Bin { ty, .. } + | Neg { ty, .. } + | Not { ty, .. } + | Cmp { ty, .. } + | ICmp { ty, .. } + | FCmp { ty, .. } + | Select { ty, .. } + | Phi { ty, .. } + | Checked { ty, .. } + | Alloca { ty, .. } + | VolatileLoad { ty, .. } + | VolatileStore { ty, .. } + | Load { ty, .. } + | Uninit { ty, .. } + | Store { ty, .. } => discard_type(ty), + Cast { src_ty, dst_ty, .. } => { + discard_type(src_ty); + discard_type(dst_ty); + }, + Extract { dst_ty, .. } | Gep { dst_ty, .. } => discard_type(dst_ty), + NullFunction { signature, .. } | FunctionAddr { signature, .. } => { + discard_signature(signature); + }, + Call { ret_ty, .. } => discard_type(ret_ty), + LifetimeEnd { .. } | PtrDiff { .. } | Memcpy { .. } | Memset { .. } | TrapIf { .. } => {}, + } +} + +pub(super) fn discard(module: Module) { + for global in module.globals { + discard_type(global.ty); + expression(global.init_expr); + } + for global in module.global_storage { + discard_type(global.ty); + } + for declaration in module.declarations { + discard_signature(declaration.signature); + } + for function in module.functions { + discard_type(function.ret_ty); + for parameter in function.params { + discard_type(parameter.ty); + } + for (_, ty) in function.value_types { + discard_type(ty); + } + for block in function.blocks { + for value in block.instructions { + instruction(value); + } + if let Some(Terminator::Switch { ty, .. } | Terminator::Ret { ty, .. }) = + block.terminator + { + discard_type(ty); + } + } + } +} diff --git a/ir/src/pass_wave.rs b/ir/src/pass_wave.rs new file mode 100644 index 0000000..122336d --- /dev/null +++ b/ir/src/pass_wave.rs @@ -0,0 +1,272 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Typed host actions for the Wave transactional pass controller. +use super::*; + +use std::io::{self, Write}; + +#[repr(C)] +#[derive(Default)] +struct State { + phase: u64, + epoch0: u64, + epoch1: u64, + epoch2: u64, + work: u64, + changed: u64, + mask: u64, + failure_stage: u64, + failure_detail: u64, +} + +#[repr(C)] +#[derive(Default)] +struct Reply { + action: u64, + failed: u64, + changed: u64, + mask: u64, +} + +#[repr(C)] +#[derive(Default)] +struct Output { + status: u64, + action: u64, + stage: u64, + detail: u64, + changed: u64, + mask: u64, + epoch0: u64, + epoch1: u64, + epoch2: u64, + work: u64, +} + +unsafe extern "C" { + fn whale_ir_pass_step( + state: *mut State, + reply: *const Reply, + before: *const u8, + before_count: u64, + after: *const u8, + after_count: u64, + max_work: u64, + result: *mut Output, + ) -> i32; + + fn whale_ir_analysis_current( + cache_identity: u64, + cache_epoch: u64, + state_identity: u64, + epoch0: u64, + epoch1: u64, + epoch2: u64, + kind: u64, + ) -> i32; +} + +pub(super) fn current(cache: &AnalysisCache, state: &AnalysisState) -> bool { + let result = unsafe { + whale_ir_analysis_current( + std::sync::Arc::as_ptr(&cache.identity) as usize as u64, + cache.epoch, + std::sync::Arc::as_ptr(&state.identity) as usize as u64, + state.epochs[0], + state.epochs[1], + state.epochs[2], + cache.kind as u64, + ) + }; + match result { + 0 => false, + 1 => true, + _ => panic!("Wave analysis cache transport"), + } +} + +struct Packet { + bytes: Vec, + limit: usize, +} + +impl Write for Packet { + fn write(&mut self, bytes: &[u8]) -> io::Result { + if bytes.len() > self.limit.saturating_sub(self.bytes.len()) { + return Err(io::Error::other("pass equality packet limit exceeded")); + } + self.bytes.try_reserve(bytes.len()).map_err(io::Error::other)?; + self.bytes.extend_from_slice(bytes); + Ok(bytes.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +fn packet(module: &Module, limits: IrLimits) -> Result, String> { + let ceiling = limits.max_analysis_work.saturating_mul(8).min(128 * 1024 * 1024); + let mut packet = Packet { bytes: Vec::new(), limit: ceiling }; + packet.write_all(&[0; 8]).map_err(|e| e.to_string())?; + crate::write_module( + module, + &mut packet, + crate::PrintLimits { + max_output_bytes: ceiling.saturating_sub(8), + max_nodes: limits.max_nodes, + max_work: limits.max_analysis_work, + max_depth: limits.max_type_depth.max(limits.max_const_depth), + ..crate::PrintLimits::default() + }, + ) + .map_err(|e| e.to_string())?; + let canonical_length = packet.bytes.len() as u64 - 8; + packet.bytes[..8].copy_from_slice(&canonical_length.to_le_bytes()); + // Canonical text contains every verified field except this ordered table. + // Its types match the printed definitions exactly by pre/post verification. + packet.write_all(&(module.functions.len() as u64).to_le_bytes()).map_err(|e| e.to_string())?; + for function in &module.functions { + packet.write_all(&function.id.0.to_le_bytes()).map_err(|e| e.to_string())?; + packet + .write_all(&(function.value_types.len() as u64).to_le_bytes()) + .map_err(|e| e.to_string())?; + for (id, _) in &function.value_types { + packet.write_all(&id.0.to_le_bytes()).map_err(|e| e.to_string())?; + } + } + Ok(packet.bytes) +} + +pub(super) fn run( + module: &mut Module, + pass: &mut impl Pass, + analyses: &mut AnalysisState, + limits: IrLimits, +) -> Result { + let name = pass.name().to_owned(); + let target = module.target.clone(); + let original_epochs = analyses.epochs; + let error = + |stage, cause| PassError { pass: name.clone(), target: target.clone(), stage, cause }; + let mut state = State { + epoch0: original_epochs[0], + epoch1: original_epochs[1], + epoch2: original_epochs[2], + ..State::default() + }; + let mut reply = Reply::default(); + let mut before_packet = Vec::new(); + let mut after_packet = Vec::new(); + let mut backup = None; + let mut cause = None; + // A complete run has at most nine typed actions; no unbounded host loop. + for _ in 0..12 { + let mut output = Output::default(); + let status = unsafe { + whale_ir_pass_step( + &mut state, + &reply, + before_packet.as_ptr(), + before_packet.len() as u64, + after_packet.as_ptr(), + after_packet.len() as u64, + limits.max_analysis_work as u64, + &mut output, + ) + }; + if status != 0 || output.status != 0 || output.changed > 1 || output.mask > 7 { + break; + } + reply = Reply { action: output.action, ..Reply::default() }; + match output.action { + 1 | 4 => { + if let Err(e) = crate::verify_module_with_limits(module, limits) { + cause = Some(PassFailure::Verification(Box::new(e))); + reply.failed = 1; + } + }, + 2 => match packet(module, limits) { + Ok(bytes) => { + before_packet = bytes; + backup = Some(module.clone()); + }, + Err(e) => { + cause = Some(PassFailure::Message(e)); + reply.failed = 1; + }, + }, + 3 => { + match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| pass.run(module))) { + Ok(Ok(change)) => { + reply.changed = u64::from(change.changed); + reply.mask = u64::from(change.invalidates.cfg) + | (u64::from(change.invalidates.values) << 1) + | (u64::from(change.invalidates.effects) << 2); + }, + Ok(Err(e)) => { + cause = Some(PassFailure::Message(e)); + reply.failed = 1; + }, + Err(_) => { + cause = Some(PassFailure::Message("transform panicked".into())); + reply.failed = 1; + }, + } + }, + 5 => match packet(module, limits) { + Ok(bytes) => after_packet = bytes, + Err(e) => { + cause = Some(PassFailure::Message(e)); + reply.failed = 1; + }, + }, + 7 => analyses.epochs = [output.epoch0, output.epoch1, output.epoch2], + 8 => { + if let Some(before) = backup.take() { + discard(std::mem::replace(module, before)); + } + analyses.epochs = original_epochs; + }, + 9 => { + return Ok(PassChange { + changed: output.changed != 0, + invalidates: Invalidates { + cfg: output.mask & 1 != 0, + values: output.mask & 2 != 0, + effects: output.mask & 4 != 0, + }, + }); + }, + 10 => { + let stage = match output.stage { + 0 => PassStage::Before, + 1 => PassStage::Transform, + 2 => PassStage::After, + 3 => PassStage::Contract, + _ => break, + }; + let message = match output.detail { + 0 => None, + 1 => { + Some("report must match the mutation and invalidate all analyses on change") + }, + 2 => Some("analysis epoch exhausted"), + 3 => Some("pass equality work limit exceeded"), + _ => break, + }; + return Err(error( + stage, + message.map(|s| PassFailure::Message(s.into())).or(cause).unwrap_or_else( + || PassFailure::Message("Wave pass controller missing diagnostic".into()), + ), + )); + }, + _ => break, + } + } + if let Some(before) = backup { + discard(std::mem::replace(module, before)); + } + analyses.epochs = original_epochs; + Err(error(PassStage::Contract, PassFailure::Message("Wave pass controller transport".into()))) +} diff --git a/ir/src/verifier.rs b/ir/src/verifier.rs index d613d2d..45969e2 100644 --- a/ir/src/verifier.rs +++ b/ir/src/verifier.rs @@ -16,7 +16,7 @@ mod wave_cfg; mod wave_shape; #[cfg(whale_wave_ir)] -mod wave_semantics; +pub(crate) mod wave_semantics; #[cfg(whale_wave_ir)] mod wave_ssa; diff --git a/ir/src/verifier/constants.rs b/ir/src/verifier/constants.rs index 068bbd6..ed6f3ab 100644 --- a/ir/src/verifier/constants.rs +++ b/ir/src/verifier/constants.rs @@ -1,10 +1,60 @@ -use std::collections::{HashMap, HashSet, VecDeque}; +use std::collections::HashMap; + +#[cfg(any(not(whale_wave_ir), test))] +use std::collections::{HashSet, VecDeque}; use super::VerifyError; -use crate::{ConstEvalError, ConstExpr, ConstRef, ConstValue, Function, Instruction, Module, Type}; +#[cfg(any(not(whale_wave_ir), test))] +use crate::ConstEvalError; + +use crate::{ConstExpr, ConstRef, ConstValue, Function, Instruction, Module, Type}; + +#[cfg(whale_wave_ir)] +#[path = "wave_constants.rs"] +mod wave; + +#[derive(Default)] +pub(super) struct Values { + entries: HashMap, + #[cfg(whale_wave_ir)] + index: Option, +} + +impl Values { + fn new() -> Self { + Self::default() + } +} + +impl std::ops::Deref for Values { + type Target = HashMap; + + fn deref(&self) -> &Self::Target { + &self.entries + } +} + +impl std::ops::DerefMut for Values { + fn deref_mut(&mut self) -> &mut Self::Target { + #[cfg(whale_wave_ir)] + { + self.index = None; + } + &mut self.entries + } +} -type Values = HashMap; +#[cfg(test)] +impl From<[(ConstRef, (Type, ConstValue)); N]> for Values { + fn from(entries: [(ConstRef, (Type, ConstValue)); N]) -> Self { + Self { + entries: HashMap::from(entries), + #[cfg(whale_wave_ir)] + index: None, + } + } +} fn lookup<'a>( locals: &'a Values, @@ -14,6 +64,7 @@ fn lookup<'a>( locals.get(&reference).or_else(|| globals.get(&reference)) } +#[derive(Clone, Copy)] struct Definition<'a> { id: ConstRef, ty: &'a Type, @@ -22,6 +73,24 @@ struct Definition<'a> { } fn evaluate( + scope: &str, + definitions: Vec>, + values: Values, + globals: &Values, + limits: crate::IrLimits, +) -> Result { + #[cfg(whale_wave_ir)] + { + wave::evaluate(scope, definitions, values, globals, limits) + } + #[cfg(not(whale_wave_ir))] + { + evaluate_reference(scope, definitions, values, globals, limits) + } +} + +#[cfg(any(not(whale_wave_ir), test))] +fn evaluate_reference( scope: &str, definitions: Vec>, mut values: Values, @@ -68,8 +137,11 @@ fn evaluate( let definition = &definitions[i]; let result = definition .expression - .evaluate_with_limits(&|reference| lookup(&values, globals, reference).cloned(), limits) - .map_err(|reason| error(definition.id, reason))?; + .evaluate_with_error_site_reference( + &|reference| lookup(&values, globals, reference).cloned(), + limits, + ) + .map_err(|(reason, _)| error(definition.id, reason))?; if !crate::const_expr::same_value(&result, definition.result) { return Err(error(definition.id, ConstEvalError::ResultMismatch)); } @@ -147,3 +219,147 @@ mod sharing_tests { ); } } + +#[cfg(all(test, whale_wave_ir))] +mod wave_tests { + use super::*; + + use crate::{ConstBinaryOp, ConstExprKind, DataLayout, Global, GlobalId}; + + fn reference(id: u32) -> ConstExpr { + ConstExpr { ty: Type::I32, kind: ConstExprKind::Reference(ConstRef::Global(GlobalId(id))) } + } + + fn literal() -> ConstExpr { + ConstExpr::literal(Type::I32, ConstValue::I(0)) + } + + fn global(id: u32, init: ConstExpr) -> Global { + Global { + id: GlobalId(id), + name: format!("g{id}"), + ty: Type::I32, + init: ConstValue::I(0), + init_expr: init, + align: 4, + } + } + + fn compare(globals: &[Global]) { + let definitions: Vec<_> = globals + .iter() + .map(|g| Definition { + id: ConstRef::Global(g.id), + ty: &g.ty, + expression: &g.init_expr, + result: &g.init, + }) + .collect(); + let expected = evaluate_reference( + "test", + definitions.clone(), + Values::new(), + &Values::new(), + crate::IrLimits::default(), + ); + let actual = evaluate( + "test", + definitions, + Values::new(), + &Values::new(), + crate::IrLimits::default(), + ); + match (actual, expected) { + (Ok(actual), Ok(expected)) => assert_eq!(actual.entries, expected.entries), + (Err(actual), Err(expected)) => { + assert_eq!(format!("{actual:?}"), format!("{expected:?}")) + }, + (actual, expected) => { + panic!("constant schedule divergence: {:?} / {:?}", actual.err(), expected.err()) + }, + } + } + + #[test] + fn wave_dependency_order_matches_reference_unknowns_duplicates_cycles_and_ready_prefixes() { + let mut seed = 0x3523_5042u64; + for _ in 0..500 { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1); + let count = 1 + (seed as usize % 40); + let mut globals = Vec::new(); + for id in 0..count { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1); + let expression = match seed % 5 { + 0 => literal(), + 1 => reference((seed as usize % (count + 1)) as u32), + _ => ConstExpr { + ty: Type::I32, + kind: ConstExprKind::Binary { + op: ConstBinaryOp::Add, + left: Box::new(reference((seed as usize % (count + 1)) as u32)), + right: Box::new(reference(((seed >> 32) as usize % count) as u32)), + }, + }, + }; + globals.push(global(id as u32, expression)); + } + if seed % 7 == 0 && globals.len() > 1 { + globals[1].id = globals[0].id; + } + if seed % 11 == 0 { + globals[0].ty = Type::U32; + } + compare(&globals); + } + let divide = ConstExpr { + ty: Type::I32, + kind: ConstExprKind::Binary { + op: ConstBinaryOp::Div, + left: Box::new(literal()), + right: Box::new(literal()), + }, + }; + compare(&[global(0, reference(1)), global(1, reference(0)), global(2, divide.clone())]); + compare(&[global(0, divide), global(1, reference(90))]); + compare(&[ + global(1, literal()), + global( + 2, + ConstExpr { + ty: Type::I32, + kind: ConstExprKind::Binary { + op: ConstBinaryOp::Add, + left: Box::new(reference(1)), + right: Box::new(reference(1)), + }, + }, + ), + ]); + } + + #[test] + fn local_scope_borrows_large_global_index_with_a_small_local_work_budget() { + let mut module = Module::new("x86_64-whale-linux", DataLayout::default_64bit_le()); + module.globals = (0..2000).map(|id| global(id, literal())).collect(); + let globals = verify_globals(&module, crate::IrLimits::default()).unwrap(); + let expression = reference(1999); + let expected = ConstValue::I(0); + for id in 0..100 { + let definitions = vec![Definition { + id: ConstRef::Local(crate::ValueId(id)), + ty: &Type::I32, + expression: &expression, + result: &expected, + }]; + let result = evaluate( + "local", + definitions, + Values::new(), + &globals, + crate::IrLimits { max_analysis_work: 64, ..Default::default() }, + ) + .unwrap(); + assert_eq!(result.get(&ConstRef::Local(crate::ValueId(id))).unwrap().1, expected); + } + } +} diff --git a/ir/src/verifier/wave_constants.rs b/ir/src/verifier/wave_constants.rs new file mode 100644 index 0000000..d40bd79 --- /dev/null +++ b/ir/src/verifier/wave_constants.rs @@ -0,0 +1,278 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Dependency packet transport; scheduling and stored-result equality run in Wave. +use super::{lookup, Definition, Values, VerifyError}; + +use crate::constant_wave::{Node, Wire}; + +use crate::verifier::wave_semantics::Node as TypeNode; + +use crate::{ConstEvalError, ConstRef, IrLimits, LimitError, Resource}; + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct RawDefinition { + kind: u64, + id: u64, + ty: u64, + root: u64, +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct Key { + kind: u64, + id: u64, +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct Slot { + kind: u64, + id: u64, + definition: u64, + present: u64, +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct Dependency { + user: u64, + next: u64, +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct Pending { + remaining: u64, + head: u64, + tail: u64, + mark: u64, + completed: u64, +} + +#[repr(C)] +struct Context { + definitions: *const RawDefinition, + definition_count: u64, + nodes: *const Node, + node_count: u64, + types: *const TypeNode, + type_count: u64, + type_edges: *const u64, + type_edge_count: u64, + base: *const Key, + base_count: u64, + imported: *const Slot, + imported_capacity: u64, + slots: *mut Slot, + capacity: u64, + pending: *mut Pending, + pending_count: u64, + dependencies: *mut Dependency, + dependency_capacity: u64, + stack: *mut u64, + stack_capacity: u64, + order: *mut u64, + order_capacity: u64, + max_work: u64, +} + +#[repr(C)] +#[derive(Default)] +struct ResultRecord { + status: u64, + definition: u64, + reference_kind: u64, + reference: u64, + count: u64, + work: u64, +} + +unsafe extern "C" { + fn whale_ir_const_schedule(context: *mut Context, result: *mut ResultRecord) -> i32; + + fn whale_ir_const_value_equal( + left_kind: u64, + left_low: u64, + left_high: u64, + right_kind: u64, + right_low: u64, + right_high: u64, + ) -> i32; +} + +#[derive(Default)] +pub(super) struct Index { + slots: Vec, +} + +fn resource(limits: IrLimits) -> ConstEvalError { + ConstEvalError::ResourceLimit(LimitError { + resource: Resource::AnalysisWork, + limit: limits.max_analysis_work, + }) +} + +fn backend() -> ConstEvalError { + ConstEvalError::Backend("constant dependency transport") +} + +fn allocate(count: usize, limits: IrLimits) -> Result, ConstEvalError> { + let mut values = Vec::new(); + values.try_reserve_exact(count).map_err(|_| resource(limits))?; + values.resize(count, T::default()); + Ok(values) +} + +fn key(reference: ConstRef) -> Key { + match reference { + ConstRef::Global(id) => Key { kind: 1, id: id.0.into() }, + ConstRef::Local(id) => Key { kind: 2, id: id.0.into() }, + } +} + +pub(super) fn evaluate( + scope: &str, + definitions: Vec>, + mut values: Values, + globals: &Values, + limits: IrLimits, +) -> Result { + if definitions.is_empty() { + return Ok(values); + } + let error = |at: usize, reason| VerifyError::InvalidConstExpression { + scope: scope.into(), + declaration: definitions[at].id, + reason, + }; + let mut wire = Wire::new(limits); + let mut budget = crate::limits::Budget::new(limits) + .map_err(|e| error(0, ConstEvalError::ResourceLimit(e)))?; + let mut raw = Vec::new(); + raw.try_reserve_exact(definitions.len()).map_err(|_| error(0, resource(limits)))?; + for definition in &definitions { + budget + .ty(definition.ty) + .and_then(|_| budget.expression(definition.expression)) + .map_err(|e| error(0, ConstEvalError::ResourceLimit(e)))?; + let root = wire.expression(definition.expression).map_err(|e| error(0, e))?; + let k = key(definition.id); + raw.push(RawDefinition { kind: k.kind, id: k.id, ty: wire.types.ty(definition.ty), root }); + } + let mut base = Vec::new(); + base.try_reserve_exact(values.len()).map_err(|_| error(0, resource(limits)))?; + base.extend(values.keys().copied().map(key)); + base.sort_unstable_by_key(|key| (key.kind, key.id)); + let capacity = raw + .len() + .checked_add(base.len()) + .and_then(|n| n.max(1).checked_mul(2)) + .and_then(usize::checked_next_power_of_two) + .ok_or_else(|| error(0, resource(limits)))?; + if capacity > limits.max_analysis_work { + return Err(error(0, resource(limits))); + } + let mut slots = allocate::(capacity, limits).map_err(|e| error(0, e))?; + let mut pending = allocate::(raw.len(), limits).map_err(|e| error(0, e))?; + let mut dependencies = + allocate::(wire.nodes.len(), limits).map_err(|e| error(0, e))?; + let mut stack = allocate::(limits.max_const_depth.saturating_add(2), limits) + .map_err(|e| error(0, e))?; + let mut order = allocate::(raw.len(), limits).map_err(|e| error(0, e))?; + let imported = match &globals.index { + Some(index) => index.slots.as_slice(), + None if globals.is_empty() => &[], + None => return Err(error(0, backend())), + }; + let mut context = Context { + definitions: raw.as_ptr(), + definition_count: raw.len() as u64, + nodes: wire.nodes.as_ptr(), + node_count: wire.nodes.len() as u64, + types: wire.types.nodes.as_ptr(), + type_count: wire.types.nodes.len() as u64, + type_edges: wire.types.edges.as_ptr(), + type_edge_count: wire.types.edges.len() as u64, + base: base.as_ptr(), + base_count: base.len() as u64, + imported: imported.as_ptr(), + imported_capacity: imported.len() as u64, + slots: slots.as_mut_ptr(), + capacity: slots.len() as u64, + pending: pending.as_mut_ptr(), + pending_count: pending.len() as u64, + dependencies: dependencies.as_mut_ptr(), + dependency_capacity: dependencies.len() as u64, + stack: stack.as_mut_ptr(), + stack_capacity: stack.len() as u64, + order: order.as_mut_ptr(), + order_capacity: order.len() as u64, + max_work: limits.max_analysis_work as u64, + }; + let mut result = ResultRecord::default(); + let status = unsafe { whale_ir_const_schedule(&mut context, &mut result) }; + if i32::try_from(result.status).ok() != Some(status) + || result.work > limits.max_analysis_work as u64 + || result.count > raw.len() as u64 + { + return Err(error(0, backend())); + } + let at = usize::try_from(result.definition) + .ok() + .filter(|at| *at < definitions.len()) + .ok_or_else(|| error(0, backend()))?; + match status { + 0 | 4 => {}, + 1 => return Err(error(at, ConstEvalError::DuplicateDefinition(definitions[at].id))), + 2 => return Err(error(at, ConstEvalError::TypeMismatch)), + 3 => { + let id = u32::try_from(result.reference).map_err(|_| error(at, backend()))?; + let reference = match result.reference_kind { + 1 => ConstRef::Global(crate::GlobalId(id)), + 2 => ConstRef::Local(crate::ValueId(id)), + _ => return Err(error(at, backend())), + }; + return Err(error(at, ConstEvalError::UnknownReference(reference))); + }, + 7 => return Err(error(at, resource(limits))), + _ => return Err(error(at, backend())), + } + if status == 0 && result.count != raw.len() as u64 { + return Err(error(0, backend())); + } + order.truncate(result.count as usize); + let mut seen = allocate::(raw.len(), limits).map_err(|e| error(0, e))?; + for id in order { + let i = usize::try_from(id) + .ok() + .filter(|i| *i < raw.len()) + .ok_or_else(|| error(0, backend()))?; + if seen[i] { + return Err(error(i, backend())); + } + seen[i] = true; + let definition = &definitions[i]; + let computed = definition + .expression + .evaluate_with_limits(&|reference| lookup(&values, globals, reference).cloned(), limits) + .map_err(|reason| error(i, reason))?; + let (left_kind, left_low, left_high) = crate::constant_wave::payload(&computed); + let (right_kind, right_low, right_high) = crate::constant_wave::payload(definition.result); + match unsafe { + whale_ir_const_value_equal( + left_kind, left_low, left_high, right_kind, right_low, right_high, + ) + } { + 1 => {}, + 0 => return Err(error(i, ConstEvalError::ResultMismatch)), + _ => return Err(error(i, backend())), + } + values.insert(definition.id, (definition.ty.clone(), computed)); + } + if status == 4 { + return Err(error(at, ConstEvalError::CyclicReference)); + } + values.index = Some(Index { slots }); + Ok(values) +} diff --git a/ir/src/verifier/wave_semantics.rs b/ir/src/verifier/wave_semantics.rs index 9c769e5..c63812c 100644 --- a/ir/src/verifier/wave_semantics.rs +++ b/ir/src/verifier/wave_semantics.rs @@ -10,7 +10,7 @@ use crate::{ const MISSING: u64 = u64::MAX; #[repr(C)] -pub(super) struct Node { +pub(crate) struct Node { kind: u64, child: u64, first: u64, @@ -98,15 +98,15 @@ unsafe extern "C" { } #[derive(Default)] -pub(super) struct Input { - pub(super) nodes: Vec, - pub(super) edges: Vec, +pub(crate) struct Input { + pub(crate) nodes: Vec, + pub(crate) edges: Vec, operands: Vec, } impl Input { // This only serializes syntax. Wave decides all type equality/category rules. - pub(super) fn ty(&mut self, ty: &Type) -> u64 { + pub(crate) fn ty(&mut self, ty: &Type) -> u64 { let mut node = Node { kind: 0, child: 0, first: 0, count: 0, extra: 0 }; node.kind = match ty { Type::Void => 0, diff --git a/ir/tests/ast_resource_limits.rs b/ir/tests/ast_resource_limits.rs index 46b5df0..bd1f185 100644 --- a/ir/tests/ast_resource_limits.rs +++ b/ir/tests/ast_resource_limits.rs @@ -167,6 +167,8 @@ fn child(name: &str) { .arg(std::env::current_exe().unwrap()) .arg("--exact") .arg(name) + // Locale archives can map over 200 MiB before this 50 MiB AST probe starts. + .env("LC_ALL", "C") .env("MALLOC_ARENA_MAX", "1") .env("WHALE_DEEP_AST_CHILD", "1") .output() diff --git a/ir/tests/integer_folding.rs b/ir/tests/integer_folding.rs new file mode 100644 index 0000000..496f826 --- /dev/null +++ b/ir/tests/integer_folding.rs @@ -0,0 +1,224 @@ +// SPDX-License-Identifier: MPL-2.0 +use ir::pass::*; + +use ir::*; + +#[cfg(whale_wave_ir)] +fn integer_module(ty: Type, a: ConstValue, b: ConstValue, op: BinOp) -> Module { + let mut module = ModuleBuilder::new("x86_64-whale-linux", DataLayout::default_64bit_le()); + let mut function = module.begin_function("fold", vec![], ty.clone()); + let literal = |f: &mut FunctionBuilder<'_>, value: ConstValue| match value { + ConstValue::I(value) => f.const_int(ty.clone(), value), + ConstValue::U(value) => f.const_uint(ty.clone(), value), + _ => unreachable!(), + }; + let a = literal(&mut function, a); + let b = literal(&mut function, b); + let result = function.bin(op, ty, a, b); + function.ret(Some(result)); + function.finish(); + module.finish() +} + +#[cfg(whale_wave_ir)] +#[test] +fn all_integer_widths_fold_modular_arithmetic_without_changing_ids_or_sources() { + let cases = [ + (Type::I1, ConstValue::I(-1), ConstValue::I(-1), ConstValue::I(0)), + (Type::U1, ConstValue::U(1), ConstValue::U(1), ConstValue::U(0)), + (Type::I8, ConstValue::I(127), ConstValue::I(1), ConstValue::I(-128)), + (Type::I16, ConstValue::I(32767), ConstValue::I(1), ConstValue::I(-32768)), + ( + Type::I32, + ConstValue::I(i32::MAX.into()), + ConstValue::I(1), + ConstValue::I(i32::MIN.into()), + ), + ( + Type::I64, + ConstValue::I(i64::MAX.into()), + ConstValue::I(1), + ConstValue::I(i64::MIN.into()), + ), + (Type::I128, ConstValue::I(i128::MAX), ConstValue::I(1), ConstValue::I(i128::MIN)), + (Type::U8, ConstValue::U(255), ConstValue::U(1), ConstValue::U(0)), + (Type::U16, ConstValue::U(65535), ConstValue::U(1), ConstValue::U(0)), + (Type::U32, ConstValue::U(u32::MAX.into()), ConstValue::U(1), ConstValue::U(0)), + (Type::U64, ConstValue::U(u64::MAX.into()), ConstValue::U(1), ConstValue::U(0)), + (Type::U128, ConstValue::U(u128::MAX), ConstValue::U(1), ConstValue::U(0)), + ]; + for (ty, a, b, expected) in cases { + let mut module = integer_module(ty, a, b, BinOp::Add); + module.sources.originals.push(OriginalNode { id: 118, span: None }); + module.sources.mappings.push(SourceMapping { + target: SourceTarget::Instruction { + function: FunctionId(0), + block: BlockId(0), + index: 2, + }, + original: 118, + }); + let original = module.clone(); + let mut state = AnalysisState::default(); + assert!( + run_pass(&mut module, &mut IntegerConstantFold::default(), &mut state).unwrap().changed + ); + assert_eq!(module.functions[0].value_types, original.functions[0].value_types); + assert_eq!(module.sources, original.sources); + assert_eq!(module.functions[0].blocks[0].instructions.len(), 3); + assert!( + matches!(&module.functions[0].blocks[0].instructions[2], Instruction::Const { dst: ValueId(2), value, .. } if value == &expected) + ); + assert_eq!(interpret(&original, FunctionId(0), &[]).unwrap().value, Some(expected.clone())); + assert_eq!(interpret(&module, FunctionId(0), &[]).unwrap().value, Some(expected)); + let before_second = module.clone(); + assert!( + !run_pass(&mut module, &mut IntegerConstantFold::default(), &mut state) + .unwrap() + .changed + ); + assert_eq!(module, before_second); + assert_eq!(state.epoch(AnalysisKind::Values), 1); + } +} + +#[cfg(whale_wave_ir)] +#[test] +fn trapping_arithmetic_and_memory_calls_remain_at_their_original_ordinals() { + for op in [BinOp::UDiv, BinOp::SDiv, BinOp::URem, BinOp::SRem] { + let mut module = if matches!(op, BinOp::UDiv | BinOp::URem) { + integer_module(Type::U128, ConstValue::U(u128::MAX), ConstValue::U(0), op) + } else { + integer_module(Type::I128, ConstValue::I(i128::MIN), ConstValue::I(0), op) + }; + let before = module.clone(); + assert!( + !run_pass( + &mut module, + &mut IntegerConstantFold::default(), + &mut AnalysisState::default() + ) + .unwrap() + .changed + ); + assert_eq!(module, before); + let before_error = interpret(&before, FunctionId(0), &[]).unwrap_err(); + let after_error = interpret(&module, FunctionId(0), &[]).unwrap_err(); + assert_eq!(format!("{before_error:?}"), format!("{after_error:?}")); + } + let mut module = parse_module(include_str!("fixtures/runtime-diagnostics-v7.wir")).unwrap(); + let before = module.clone(); + assert!( + !run_pass(&mut module, &mut IntegerConstantFold::default(), &mut AnalysisState::default()) + .unwrap() + .changed + ); + assert_eq!(module, before); +} + +#[cfg(whale_wave_ir)] +#[test] +fn propagation_handles_comparison_select_and_physically_reordered_sparse_scoped_ids() { + let text = r#"module { format_version 8 semantics_version 1 target "x86_64-whale-linux" + datalayout {ptr=64,endian=little} + declare @f4294967295 "test": whale () -> i128, linkage internal + declare @f7 "other": whale () -> u8, linkage internal + fn @f4294967295 "test"() -> i128, entry %b1 { + %b2 "exit": + %v4294967295: i128 = add i128 %v4000000000, %v3000000000 + %v12: bool = icmp eq i128 %v4294967295, %v4000000000 + %v13: i128 = select bool %v12, i128 %v3000000000, i128 %v4294967295 + ret i128 %v13 + %b1 "entry": + %v4000000000: i128 = const i128 42 + %v3000000000: i128 = const i128 0 + br label %b2 + } + fn @f7 "other"() -> u8, entry %b0 { + %b0 "entry": + %v4000000000: u8 = const u8 7 + ret u8 %v4000000000 + }}"#; + let mut module = parse_module(text).unwrap(); + let original = module.clone(); + let mut pass = IntegerConstantFold::default(); + assert!(run_pass(&mut module, &mut pass, &mut AnalysisState::default()).unwrap().changed); + for instruction in &module.functions[0].blocks[0].instructions { + assert!(matches!(instruction, Instruction::Const { .. })); + } + assert_eq!(module.functions[1], original.functions[1]); + assert_eq!( + interpret(&original, FunctionId(u32::MAX), &[]).unwrap().value, + Some(ConstValue::I(0)) + ); + assert_eq!( + interpret(&module, FunctionId(u32::MAX), &[]).unwrap().value, + Some(ConstValue::I(0)) + ); +} + +#[cfg(whale_wave_ir)] +#[test] +fn named_constant_declarations_and_global_expressions_are_preserved() { + let mut builder = ModuleBuilder::new("x86_64-whale-linux", DataLayout::default_64bit_le()); + builder.add_global_const( + "global", + ConstExpr::literal(Type::I32, ConstValue::I(40)), + ConstValue::I(40), + 4, + ); + let mut function = builder.begin_function("entry", vec![], Type::I32); + let a = function.const_decl( + "answer", + ConstExpr::literal(Type::I32, ConstValue::I(40)), + ConstValue::I(40), + ); + let b = function.const_i32(2); + let result = function.add(Type::I32, a, b); + function.ret(Some(result)); + function.finish(); + let mut module = builder.finish(); + let before = module.clone(); + assert!( + run_pass(&mut module, &mut IntegerConstantFold::default(), &mut AnalysisState::default()) + .unwrap() + .changed + ); + assert_eq!(module.globals, before.globals); + assert_eq!( + module.functions[0].blocks[0].instructions[0], + before.functions[0].blocks[0].instructions[0] + ); + assert_eq!(interpret(&module, FunctionId(0), &[]).unwrap().value, Some(ConstValue::I(42))); +} + +#[cfg(whale_wave_ir)] +#[test] +fn failed_fold_work_budget_preserves_module_and_cache() { + let mut module = integer_module(Type::U32, ConstValue::U(40), ConstValue::U(2), BinOp::Add); + let before = module.clone(); + let mut state = AnalysisState::default(); + let cache = AnalysisCache::new(AnalysisKind::Values, &state, 42); + let mut pass = + IntegerConstantFold { limits: IrLimits { max_analysis_work: 1, ..IrLimits::default() } }; + assert!(run_pass(&mut module, &mut pass, &mut state).is_err()); + assert_eq!(module, before); + assert_eq!(cache.get(&state), Some(&42)); +} + +#[cfg(not(whale_wave_ir))] +#[test] +fn integer_folding_is_explicitly_unavailable_without_a_wave_module() { + let mut builder = ModuleBuilder::new("x86_64-whale-linux", DataLayout::default_64bit_le()); + let mut function = builder.begin_function("entry", vec![], Type::Void); + function.ret(None); + function.finish(); + let mut module = builder.finish(); + let original = module.clone(); + let error = + run_pass(&mut module, &mut IntegerConstantFold::default(), &mut AnalysisState::default()) + .unwrap_err(); + assert_eq!(error.stage, PassStage::Transform); + assert!(error.to_string().contains("requires the Wave")); + assert_eq!(module, original); +} diff --git a/ir/tests/pass_effects.rs b/ir/tests/pass_effects.rs index 9cc57f0..934d659 100644 --- a/ir/tests/pass_effects.rs +++ b/ir/tests/pass_effects.rs @@ -242,3 +242,36 @@ fn volatile_function_pointer_loads_retain_the_callable_signature() { let m = parse_module(source).unwrap(); assert_eq!(interpret(&m, FunctionId(0), &[]).unwrap().value, Some(ConstValue::U(42))); } + +struct ReverseValueTable(bool); + +impl Pass for ReverseValueTable { + fn name(&self) -> &str { + "reverse-value-table" + } + + fn run(&mut self, module: &mut Module) -> Result { + module.functions[0].value_types.reverse(); + Ok(PassChange { + changed: self.0, + invalidates: if self.0 { Invalidates::ALL } else { Invalidates::default() }, + }) + } +} + +#[test] +fn exact_pass_identity_includes_unprinted_value_table_order() { + let mut module = module(false); + let original = module.clone(); + let text = print_module(&module); + let mut state = AnalysisState::default(); + assert_eq!( + run_pass(&mut module, &mut ReverseValueTable(false), &mut state).unwrap_err().stage, + PassStage::Contract + ); + assert_eq!(module, original); + assert!(run_pass(&mut module, &mut ReverseValueTable(true), &mut state).unwrap().changed); + assert_eq!(print_module(&module), text); + assert_ne!(module, original); + assert_eq!(state.epoch(AnalysisKind::Values), 1); +} diff --git a/ir/wide.wave b/ir/wide.wave new file mode 100644 index 0000000..8f1f6a8 --- /dev/null +++ b/ir/wide.wave @@ -0,0 +1,287 @@ +// SPDX-License-Identifier: MPL-2.0 +// Two-word arithmetic. No host pointer width, native u128 or runtime helpers. +struct IrWide { + low: u64; + high: u64; +} + +fun ir_wide_from(low: u64, high: u64, output: ptr) { + output.low = low; + output.high = high; +} + +fun ir_wide_zero(output: ptr) { + output.low = 0; + output.high = 0; +} + +fun ir_wide_cmp(a: ptr, b: ptr) -> i32 { + if (a.high < b.high || (a.high == b.high && a.low < b.low)) { + return -1; + } + if (a.high == b.high && a.low == b.low) { + return 0; + } + return 1; +} + +fun ir_wide_add(a: ptr, b: ptr, output: ptr) -> u64 { + var al: u64 = a.low; + var ah: u64 = a.high; + var bl: u64 = b.low; + var bh: u64 = b.high; + var low: u64 = al + bl; + var carry: u64 = (low < al) as u64; + var high: u64 = ah + bh; + var overflow: bool = high < ah; + var result: u64 = high + carry; + output.low = low; + output.high = result; + return (overflow || result < high) as u64; +} + +fun ir_wide_sub(a: ptr, b: ptr, output: ptr) -> u64 { + var al: u64 = a.low; + var ah: u64 = a.high; + var bl: u64 = b.low; + var bh: u64 = b.high; + var borrow: u64 = (al < bl) as u64; + var high: u64 = ah - bh; + output.low = al - bl; + output.high = high - borrow; + return (ah < bh || high < borrow) as u64; +} + +fun ir_wide_neg(a: ptr, output: ptr) { + var low: u64 = 0 - a.low; + var high: u64 = ~a.high; + if (low == 0) { + high += 1; + } + output.low = low; + output.high = high; +} + +fun ir_wide_shl(a: ptr, count: u64, output: ptr) { + var low: u64 = a.low; + var high: u64 = a.high; + if (count == 0) { + output.low = low; + output.high = high; + } else if (count >= 128) { + ir_wide_zero(output); + } else if (count >= 64) { + output.low = 0; + output.high = low << (count - 64); + } else { + output.low = low << count; + output.high = (high << count) | (low >> (64 - count)); + } +} + +fun ir_wide_shr(a: ptr, count: u64, output: ptr) { + var low: u64 = a.low; + var high: u64 = a.high; + if (count == 0) { + output.low = low; + output.high = high; + } else if (count >= 128) { + ir_wide_zero(output); + } else if (count >= 64) { + output.low = high >> (count - 64); + output.high = 0; + } else { + output.low = (low >> count) | (high << (64 - count)); + output.high = high >> count; + } +} + +fun ir_wide_mask(width: u64, output: ptr) { + if (width == 0) { + ir_wide_zero(output); + } else if (width < 64) { + output.low = (1 as u64 << width) - 1; + output.high = 0; + } else if (width == 64) { + output.low = 18446744073709551615; + output.high = 0; + } else if (width < 128) { + output.low = 18446744073709551615; + output.high = (1 as u64 << (width - 64)) - 1; + } else { + output.low = 18446744073709551615; + output.high = 18446744073709551615; + } +} + +fun ir_wide_ashr(a: ptr, count: u64, output: ptr) { + var value: IrWide = a[0]; + var negative: bool = (value.high & 9223372036854775808) != 0; + ir_wide_shr(&value, count, output); + if (negative && count != 0) { + var mask: IrWide; + if (count >= 128) { + ir_wide_zero(&mask); + } else { + ir_wide_mask(128 - count, &mask); + } + output.low = output.low | ~mask.low; + output.high = output.high | ~mask.high; + } +} + +fun ir_wide_trim(a: ptr, width: u64, output: ptr) { + var mask: IrWide; + ir_wide_mask(width, &mask); + output.low = a.low & mask.low; + output.high = a.high & mask.high; +} + +fun ir_wide_bit(a: ptr, index: u64) -> u64 { + if (index < 64) { + return (a.low >> index) & 1; + } + if (index < 128) { + return (a.high >> (index - 64)) & 1; + } + return 0; +} + +fun ir_wide_clz(a: ptr) -> u64 { + if (a.high == 0 && a.low == 0) { + return 128; + } + var value: u64 = a.high; + var count: u64 = 0; + if (value == 0) { + value = a.low; + count = 64; + } + var mask: u64 = 9223372036854775808; + while ((value & mask) == 0) { + count += 1; + mask = mask >> 1; + } + return count; +} + +fun ir_wide_mul64(a: u64, b: u64, output: ptr) { + var a0: u64 = a & 4294967295; + var a1: u64 = a >> 32; + var b0: u64 = b & 4294967295; + var b1: u64 = b >> 32; + var p00: u64 = a0 * b0; + var p01: u64 = a0 * b1; + var p10: u64 = a1 * b0; + var p11: u64 = a1 * b1; + var middle: u64 = (p00 >> 32) + (p01 & 4294967295) + (p10 & 4294967295); + output.low = (p00 & 4294967295) | (middle << 32); + output.high = p11 + (p01 >> 32) + (p10 >> 32) + (middle >> 32); +} + +fun ir_wide_mul(a: ptr, b: ptr, output: ptr) -> bool { + var al: u64 = a.low; + var ah: u64 = a.high; + var bl: u64 = b.low; + var bh: u64 = b.high; + var p00: IrWide; + var p01: IrWide; + var p10: IrWide; + ir_wide_mul64(al, bl, &p00); + ir_wide_mul64(al, bh, &p01); + ir_wide_mul64(ah, bl, &p10); + var high: u64 = p00.high + p01.low; + var overflow: bool = high < p00.high; + var final_high: u64 = high + p10.low; + overflow = overflow || final_high < high || p01.high != 0 || p10.high != 0 || (ah != 0 + && bh != 0); + output.low = p00.low; + output.high = final_high; + return overflow; +} + +fun ir_wide_divmod(a: ptr, b: ptr, quotient: ptr, + remainder: ptr) -> bool { + var numerator: IrWide = a[0]; + var divisor: IrWide = b[0]; + var q: IrWide; + var r: IrWide; + ir_wide_zero(&q); + ir_wide_zero(&r); + if (divisor.low == 0 && divisor.high == 0) { + ir_wide_zero(quotient); + ir_wide_zero(remainder); + return false; + } + var index: u64 = 128; + while (index != 0) { + index -= 1; + var carry: u64 = r.high >> 63; + ir_wide_shl(&r, 1, &r); + r.low = r.low | ir_wide_bit(&numerator, index); + if (carry != 0 || ir_wide_cmp(&r, &divisor) >= 0) { + ir_wide_sub(&r, &divisor, &r); + if (index < 64) { + q.low = q.low | (1 as u64 << index); + } else { + q.high = q.high | (1 as u64 << (index - 64)); + } + } + } + quotient[0] = q; + remainder[0] = r; + return true; +} + +fun ir_wide_jam(a: ptr, count: u64, output: ptr) { + var value: IrWide = a[0]; + if (count == 0) { + output[0] = value; + return; + } + if (count >= 128) { + output.low = (value.low != 0 || value.high != 0) as u64; + output.high = 0; + return; + } + var shifted: IrWide; + var back: IrWide; + ir_wide_shr(&value, count, &shifted); + ir_wide_shl(&shifted, count, &back); + if (ir_wide_cmp(&value, &back) != 0) { + shifted.low = shifted.low | 1; + } + output[0] = shifted; +} + +fun ir_wide_round(a: ptr, count: u64, output: ptr) { + var value: IrWide = a[0]; + if (count == 0) { + output[0] = value; + return; + } + if (count > 128) { + ir_wide_zero(output); + return; + } + var one: IrWide; + ir_wide_from(1, 0, &one); + var half: IrWide; + ir_wide_shl(&one, count - 1, &half); + if (count == 128) { + output.low = (ir_wide_cmp(&value, &half) > 0) as u64; + output.high = 0; + return; + } + var shifted: IrWide; + var back: IrWide; + var tail: IrWide; + ir_wide_shr(&value, count, &shifted); + ir_wide_shl(&shifted, count, &back); + ir_wide_sub(&value, &back, &tail); + var comparison: i32 = ir_wide_cmp(&tail, &half); + if (comparison > 0 || (comparison == 0 && (shifted.low & 1) != 0)) { + ir_wide_add(&shifted, &one, &shifted); + } + output[0] = shifted; +} diff --git a/tools/build_wave_ir.py b/tools/build_wave_ir.py index 6369515..d55bf7f 100644 --- a/tools/build_wave_ir.py +++ b/tools/build_wave_ir.py @@ -13,29 +13,93 @@ digest, ensure_bootstrap, run) -SOURCES = ("model.wave", "layout.wave", "lexer.wave", "header.wave", "type_parser.wave", - "literal.wave", "expression_parser.wave", "instruction_parser.wave", "module_parser.wave", "lower_hir.wave", - "lower_model.wave", "lower_output.wave", "lower_expression.wave", "lower_storage.wave", "lower_statement.wave", "lower_driver.wave", "builder.wave", "builder_namespace.wave", "builder_body.wave", - "verify.wave", "verifier_index.wave", "verifier_ssa.wave", "printer.wave", - "cfg.wave", "shape.wave", "source.wave", "lower_limits.wave", "entry.wave") -ABI_SOURCES = ("ir/src/wave_layout.rs", "ir/src/source_wave.rs", "ir/src/lower_ast/wave_limits.rs", "ir/src/parser/wave_lexer.rs", "ir/src/parser/wave_header.rs", - "ir/src/parser/wave_text.rs", "ir/src/parser/wave_type.rs", - "ir/src/parser/wave_literal.rs", "ir/src/parser/wave_expression.rs", - "ir/src/parser/wave_instruction.rs", - "ir/src/parser/wave_module.rs", - "ir/src/lower_ast/wave_hir.rs", - "ir/src/lower_ast/wave_lower.rs", - "ir/src/builder/wave.rs", - "ir/src/builder/namespace.rs", - "ir/src/builder/body.rs", - "ir/src/verifier/wave_semantics.rs", - "ir/src/verifier/wave_index.rs", - "ir/src/verifier/wave_ssa.rs", - "ir/src/printer_wave.rs", - "ir/src/verifier/wave_cfg.rs", "ir/src/verifier/wave_shape.rs") -TARGETS = ("x86_64-unknown-linux-gnu", "aarch64-unknown-linux-gnu", - "riscv64gc-unknown-linux-gnu", "x86_64-pc-windows-msvc", - "aarch64-pc-windows-msvc", "x86_64-apple-darwin", "aarch64-apple-darwin") +SOURCES = ( + 'model.wave', + 'layout.wave', + 'lexer.wave', + 'header.wave', + 'type_parser.wave', + 'literal.wave', + 'expression_parser.wave', + 'instruction_parser.wave', + 'module_parser.wave', + 'lower_hir.wave', + 'lower_model.wave', + 'lower_output.wave', + 'lower_expression.wave', + 'lower_storage.wave', + 'lower_statement.wave', + 'lower_driver.wave', + 'builder.wave', + 'builder_namespace.wave', + 'builder_body.wave', + 'verify.wave', + 'verifier_index.wave', + 'verifier_ssa.wave', + 'printer.wave', + 'cfg.wave', + 'shape.wave', + 'source.wave', + 'memory.wave', + 'lower_limits.wave', + 'wide.wave', + 'integer.wave', + 'float_model.wave', + 'float_arithmetic.wave', + 'float_convert.wave', + 'effects.wave', + 'passes.wave', + 'fold_integer.wave', + 'constant.wave', + 'constant_dependencies.wave', + 'runtime_model.wave', + 'runtime_prepare.wave', + 'runtime_execute.wave', + 'runtime_driver.wave', + 'entry.wave', +) +ABI_SOURCES = ( + 'ir/src/wave_layout.rs', + 'ir/src/interpreter/integer.rs', + 'ir/src/float/wave.rs', + 'ir/src/effects_wave.rs', + 'ir/src/pass_wave.rs', + 'ir/src/fold_integer_wave.rs', + 'ir/src/constant_wave.rs', + 'ir/src/interpreter/runtime_wave.rs', + 'ir/src/verifier/wave_constants.rs', + 'ir/src/source_wave.rs', + 'ir/src/interpreter/memory_wave.rs', + 'ir/src/lower_ast/wave_limits.rs', + 'ir/src/parser/wave_lexer.rs', + 'ir/src/parser/wave_header.rs', + 'ir/src/parser/wave_text.rs', + 'ir/src/parser/wave_type.rs', + 'ir/src/parser/wave_literal.rs', + 'ir/src/parser/wave_expression.rs', + 'ir/src/parser/wave_instruction.rs', + 'ir/src/parser/wave_module.rs', + 'ir/src/lower_ast/wave_hir.rs', + 'ir/src/lower_ast/wave_lower.rs', + 'ir/src/builder/wave.rs', + 'ir/src/builder/namespace.rs', + 'ir/src/builder/body.rs', + 'ir/src/verifier/wave_semantics.rs', + 'ir/src/verifier/wave_index.rs', + 'ir/src/verifier/wave_ssa.rs', + 'ir/src/printer_wave.rs', + 'ir/src/verifier/wave_cfg.rs', + 'ir/src/verifier/wave_shape.rs', +) +TARGETS = ( + 'x86_64-unknown-linux-gnu', + 'aarch64-unknown-linux-gnu', + 'riscv64gc-unknown-linux-gnu', + 'x86_64-pc-windows-msvc', + 'aarch64-pc-windows-msvc', + 'x86_64-apple-darwin', + 'aarch64-apple-darwin', +) def fnv64(data): diff --git a/tools/check_wave_ir_float.py b/tools/check_wave_ir_float.py new file mode 100644 index 0000000..b2306be --- /dev/null +++ b/tools/check_wave_ir_float.py @@ -0,0 +1,256 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Native Wave IEEE checks against exact Fraction and retained mathematical vectors.""" +import argparse +import ctypes as C +from fractions import Fraction +from pathlib import Path +import random + +from generate_float_vectors import arithmetic, decode, encode, shape + +MASK64 = (1 << 64) - 1 +MASK128 = (1 << 128) - 1 +KINDS = {'i1': 2, 'u1': 3, 'i8': 4, 'i16': 5, 'i32': 6, 'i64': 7, 'i128': 8, + 'u8': 9, 'u16': 10, 'u32': 11, 'u64': 12, 'u128': 13, + 'f16': 14, 'f32': 15, 'f64': 16} +FLOAT_KIND = {16: 14, 32: 15, 64: 16} +TAG = {16: 4, 32: 5, 64: 6} +OPS = ('fadd', 'fsub', 'fmul', 'fdiv', 'frem') +CASTS = ('fext', 'ftrunc', 'itof_s', 'itof_u', 'ftoi_s', 'ftoi_u') + + +class Request(C.Structure): + _fields_ = [(n, C.c_uint64) for n in + 'mode operation source destination left_kind left_low left_high right_kind right_low right_high'.split()] + + +class Result(C.Structure): + _fields_ = [(n, C.c_uint64) for n in 'status low high flag'.split()] + + +def scalar(ty, value): + if ty.startswith('f'): + return TAG[int(ty[1:])], value, 0 + return (1 if ty.startswith('i') else 2), value & MASK64, (value & MASK128) >> 64 + + +class Kernel: + def __init__(self, library): + self.run = C.CDLL(library).whale_ir_float + self.run.argtypes = [C.POINTER(Request), C.POINTER(Result)] + self.run.restype = C.c_int32 + + def call(self, mode, op, src, dst=0, left=(0, 0, 0), right=(0, 0, 0)): + request = Request(mode, op, src, dst, *left, *right) + result = Result(*([MASK64] * 4)) + status = self.run(C.byref(request), C.byref(result)) + assert status == result.status + if status: + assert (result.low, result.high, result.flag) == (0, 0, 0) + return None + assert result.flag <= 1 + return result.low | (result.high << 64), result.flag + + def arithmetic(self, width, op, a, b): + value = self.call(0, OPS.index(op), FLOAT_KIND[width], FLOAT_KIND[width], + (TAG[width], a, 0), (TAG[width], b, 0)) + assert value is not None and value[1] == 0 + return value[0] + + def convert(self, src, dst, op, value): + answer = self.call(3, CASTS.index(op), KINDS[src], KINDS[dst], scalar(src, value)) + return None if answer is None else answer[0] + + +def integer_range(ty): + width = int(ty[1:]) + if ty.startswith('i'): + return -(1 << (width - 1)), (1 << (width - 1)) - 1 + return 0, (1 << width) - 1 + + +def conversion_oracle(src, dst, value): + if src.startswith('f'): + decoded = decode(int(src[1:]), value) + else: + decoded = Fraction(value) + if dst.startswith('f'): + negative_zero = src.startswith('f') and bool(value >> (int(src[1:]) - 1)) and decoded == 0 + return encode(int(dst[1:]), decoded, negative_zero) + if isinstance(decoded, str): + return None + magnitude = abs(decoded.numerator) // decoded.denominator + truncated = -magnitude if decoded < 0 else magnitude + low, high = integer_range(dst) + return truncated & MASK128 if low <= truncated <= high else None + + +def retained(kernel, root): + rows = 0 + for line in (root / 'ir/tests/fixtures/float-arithmetic.txt').read_text().splitlines(): + if not line or line.startswith('#'): + continue + w, op, a, b, result = line.split() + assert kernel.arithmetic(int(w), op, int(a, 16), int(b, 16)) == int(result, 16), line + rows += 1 + for line in (root / 'ir/tests/fixtures/float-conversions.txt').read_text().splitlines(): + if not line or line.startswith('#'): + continue + src, dst, op, source, expected = line.split() + value = int(source, 16 if src.startswith('f') else 10) + want = None if expected == 'trap' else int(expected, 16 if dst.startswith('f') else 10) & MASK128 + actual = kernel.convert(src, dst, op, value) + assert actual == want, (line, actual, want) + rows += 1 + return rows + + +def half_extension(bits, width, numeric=True): + fraction, bias = shape(width) + sign = (bits >> 15) << (width - 1) + exponent = (bits >> 10) & 31 + mantissa = bits & 1023 + if exponent == 31: + if mantissa: + return (((2 * bias + 1) << fraction) | (1 << (fraction - 1))) if numeric else sign | ((2 * bias + 1) << fraction) | (mantissa << (fraction - 10)) + return sign | ((2 * bias + 1) << fraction) + if exponent: + return sign | ((exponent - 15 + bias) << fraction) | (mantissa << (fraction - 10)) + if not mantissa: + return sign + highest = mantissa.bit_length() - 1 + return sign | ((highest - 24 + bias) << fraction) | ((mantissa - (1 << highest)) << (fraction - highest)) + + +def exhaustive_half(kernel): + for bits in range(1 << 16): + nan = (bits & 0x7c00) == 0x7c00 and bits & 1023 + for width in (32, 64): + want = half_extension(bits, width) + actual = kernel.convert('f16', f'f{width}', 'fext', bits) + assert actual == want, (bits, width, actual, want) + back = kernel.convert(f'f{width}', 'f16', 'ftrunc', actual) + expected = 0x7e00 if nan else bits + assert back == expected, (bits, width, back, expected) + value = kernel.call(4, 0, 14, left=(4, bits, 0))[0] + expected = half_extension(bits, 64, numeric=False) + assert value == expected, (bits, value, expected) + + +def compare_oracle(width, a, b, predicate): + x, y = decode(width, a), decode(width, b) + ordered = x != 'nan' and y != 'nan' + order = 0 + if ordered: + if x == y: + order = 0 + elif x == '-inf' or y == 'inf': + order = -1 + elif x == 'inf' or y == '-inf': + order = 1 + else: + order = -1 if x < y else 1 + eq, lt, gt = order == 0, order < 0, order > 0 + return (ordered and eq, ordered and not eq, ordered and lt, ordered and not gt, + ordered and gt, ordered and not lt, ordered, not ordered, + not ordered or eq, not ordered or not eq, not ordered or lt, + not ordered or not gt, not ordered or gt, not ordered or not lt)[predicate] + + +def generated(kernel, count): + rng = random.Random(0x353f10a7) + integer_types = [ty for ty in KINDS if not ty.startswith('f')] + for i in range(count): + width = (16, 32, 64)[i % 3] + a, b = rng.getrandbits(width), rng.getrandbits(width) + op = OPS[i % 5] + want = arithmetic(width, op, a, b) + actual = kernel.arithmetic(width, op, a, b) + assert actual == want, (width, op, hex(a), hex(b), hex(actual), hex(want)) + neg = kernel.call(1, 0, FLOAT_KIND[width], left=(TAG[width], a, 0)) + assert neg == (a ^ (1 << (width - 1)), 0) + pred = i % 14 + compared = kernel.call(2, pred, FLOAT_KIND[width], FLOAT_KIND[width], + (TAG[width], a, 0), (TAG[width], b, 0)) + assert compared == (0, int(compare_oracle(width, a, b, pred))) + int_ty = rng.choice(integer_types) + low, high = integer_range(int_ty) + integer = rng.randrange(low, high + 1) + src = int_ty + dst = f'f{width}' + op = 'itof_s' if int_ty.startswith('i') else 'itof_u' + assert kernel.convert(src, dst, op, integer) == conversion_oracle(src, dst, integer) + op = 'ftoi_s' if int_ty.startswith('i') else 'ftoi_u' + assert kernel.convert(dst, src, op, a) == conversion_oracle(dst, src, a) + other_width = rng.choice([w for w in (16, 32, 64) if w != width]) + op = 'fext' if other_width > width else 'ftrunc' + assert kernel.convert(f'f{width}', f'f{other_width}', op, a) == conversion_oracle(f'f{width}', f'f{other_width}', a) + decoded = decode(width, a) + if width == 64: + want64 = a + elif width == 16: + want64 = half_extension(a, 64, numeric=False) + elif decoded == 'nan': + want64 = ((a >> 31) << 63) | (0x7ff << 52) | ((a & 0x7fffff) << 29) | (1 << 51) + else: + want64 = encode(64, decoded, decoded == 0 and bool(a >> 31)) + assert kernel.call(4, 0, FLOAT_KIND[width], left=(TAG[width], a, 0)) == (want64, 0) + host_bits = rng.getrandbits(64) + decoded = decode(64, host_bits) + if width == 64: + wanted = host_bits + elif decoded == 'nan': + fraction, bias = shape(width) + sign = (host_bits >> 63) << (width - 1) + wanted = sign | ((2 * bias + 1) << fraction) | (1 << (fraction - 1)) + if width == 32: + wanted |= (host_bits & ((1 << 52) - 1)) >> 29 + else: + wanted = encode(width, decoded, decoded == 0 and bool(host_bits >> 63)) + assert kernel.call(5, 0, 16, FLOAT_KIND[width], left=(6, host_bits, 0)) == (wanted, 0) + + +def invalid(kernel): + for mode, op, src, dst, left, right in [ + (0, 99, 15, 15, (5, 0x7fc00000, 0), (5, 0, 0)), + (0, 0, 14, 15, (4, 0, 0), (5, 0, 0)), + (0, 0, 14, 14, (4, 1 << 16, 0), (4, 0, 0)), + (1, 0, 15, 0, (5, 0, 1), (0, 0, 0)), + (3, 0, 16, 15, (6, 0, 0), (0, 0, 0)), + (3, 2, 9, 15, (2, 1, 0), (0, 0, 0)), + (3, 3, 4, 15, (1, 1, 0), (0, 0, 0)), + (3, 2, 4, 15, (1, 128, 0), (0, 0, 0)), + (2, 14, 15, 15, (5, 0, 0), (5, 0, 0)), + ]: + assert kernel.call(mode, op, src, dst, left, right) is None + output = Result(7, 7, 7, 7) + assert kernel.run(None, C.byref(output)) == 9 + assert (output.status, output.low, output.high, output.flag) == (9, 0, 0, 0) + request = Request() + assert kernel.run(C.byref(request), None) == 9 + for address in (MASK64, MASK64 - 79): + output = Result(7, 7, 7, 7) + assert kernel.run(C.cast(C.c_void_p(address), C.POINTER(Request)), C.byref(output)) == 9 + assert (output.status, output.low, output.high, output.flag) == (9, 0, 0, 0) + for mode in (6, MASK64): + request.mode = mode + output = Result() + assert kernel.run(C.byref(request), C.byref(output)) == 9 + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--library', required=True) + parser.add_argument('--cases', type=int, default=10000) + args = parser.parse_args() + kernel = Kernel(args.library) + rows = retained(kernel, Path(__file__).resolve().parents[1]) + exhaustive_half(kernel) + generated(kernel, args.cases) + invalid(kernel) + print(f'Wave IEEE: {rows} retained Fraction/conversion vectors, all 65536 binary16 patterns, {args.cases} independent arithmetic/cast/compare cases and transport failures passed') + + +if __name__ == '__main__': + main() diff --git a/tools/check_wave_ir_integer.py b/tools/check_wave_ir_integer.py new file mode 100644 index 0000000..a3a8a1c --- /dev/null +++ b/tools/check_wave_ir_integer.py @@ -0,0 +1,311 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Independent mathematical conformance for Wave fixed-width and two-word math.""" + +import argparse +import ctypes as C +import random + +MASK = (1 << 128) - 1 +SHAPES = { + 1: (1, False), + 2: (1, True), + 3: (1, False), + **{kind: (width, True) for kind, width in zip(range(4, 9), (8, 16, 32, 64, 128))}, + **{kind: (width, False) for kind, width in zip(range(9, 14), (8, 16, 32, 64, 128))}, +} +BINARY = (0, 1, 2, 3, 4, 5, 6, 12, 13, 14, 15, 16, 17) + + +class Result(C.Structure): + _fields_ = [(name, C.c_uint64) for name in ("status", "low", "high", "flag")] + + +def signed(value, width): + value &= (1 << width) - 1 + return value - (1 << width) if value >= (1 << (width - 1)) else value + + +def packed(value, kind): + width, negative = SHAPES[kind] + return (signed(value, width) if negative else value & ((1 << width) - 1)) & MASK + + +def trunc_div(a, b): + return (abs(a) // abs(b)) * (-1 if (a < 0) != (b < 0) else 1) + + +def oracle(mode, op, source, destination, a, b): + if source not in SHAPES or destination not in SHAPES or mode > 6: + return 4, 0, 0 + width, is_signed = SHAPES[source] + dest_width, dest_signed = SHAPES[destination] + mask = (1 << width) - 1 + a, b = a & mask, b & mask + value, flag = 0, 0 + if mode == 0: + if source == 1 or destination != source or op not in BINARY: + return 4, 0, 0 + if 3 <= op <= 6 and b == 0: + return (1 if op <= 4 else 2), 0, 0 + count = b % width + if op == 0: + value = a + b + elif op == 1: + value = a - b + elif op == 2: + value = a * b + elif op == 3: + value = a // b + elif op == 4: + value = trunc_div(signed(a, width), signed(b, width)) + elif op == 5: + value = a % b + elif op == 6: + sa, sb = signed(a, width), signed(b, width) + value = sa - trunc_div(sa, sb) * sb + elif op == 12: + value = a & b + elif op == 13: + value = a | b + elif op == 14: + value = a ^ b + elif op == 15: + value = a << count + elif op == 16: + value = a >> count + else: + value = signed(a, width) >> count + elif mode == 1: + if source == 1 or destination != source or op > 5: + return 4, 0, 0 + aa, bb = (a, b) if op < 3 else (signed(a, width), signed(b, width)) + value = aa + bb if op % 3 == 0 else aa - bb if op % 3 == 1 else aa * bb + minimum, maximum = (0, mask) if op < 3 else (-(1 << (width - 1)), (1 << (width - 1)) - 1) + flag = int(not minimum <= value <= maximum) + elif mode == 2: + valid = ( + destination != 1 + and op <= 3 + and ( + ( + op == 0 + and ((source == 1 and destination != 2) or (source != 1 and width < dest_width)) + ) + or (op == 1 and source != 1 and width < dest_width) + or (op == 2 and source != 1 and width > dest_width) + or (op == 3 and source != 1 and width == dest_width) + ) + ) + if not valid: + return 4, 0, 0 + value = signed(a, width) if op == 1 else a + elif mode == 3: + if op > 9 or destination != 1 or (source == 1 and op > 1): + return 4, 0, 0 + aa, bb = (signed(a, width), signed(b, width)) if op >= 6 else (a, b) + value = int( + ( + aa == bb, + aa != bb, + aa < bb, + aa <= bb, + aa > bb, + aa >= bb, + aa < bb, + aa <= bb, + aa > bb, + aa >= bb, + )[op] + ) + elif mode == 4: + if op != 0 or source == 1 or destination == 1: + return 4, 0, 0 + value = signed(a, width) if is_signed else a + minimum = -(1 << (dest_width - 1)) if dest_signed else 0 + maximum = (1 << (dest_width - int(dest_signed))) - 1 + if not minimum <= value <= maximum: + return 3, 0, 0 + elif mode == 5: + if op != 0 or source != destination: + return 4, 0, 0 + value = a + else: + if op > 1 or source == 1 or destination != source: + return 4, 0, 0 + value = -a if op == 0 else ~a + return 0, packed(value, destination), flag + + +class Kernel: + def __init__(self, path): + lib = C.CDLL(path) + self.scalar = lib.whale_ir_integer + self.scalar.argtypes = [C.c_uint64] * 8 + [C.POINTER(Result)] + self.scalar.restype = C.c_int32 + self.wide = lib.whale_ir_wide + self.wide.argtypes = [C.c_uint64] * 6 + [C.POINTER(Result)] + self.wide.restype = C.c_int32 + self.bits = lib.whale_ir_integer_bits + self.bits.argtypes = [C.c_uint64] * 4 + [C.POINTER(Result)] + self.bits.restype = C.c_int32 + + def call(self, mode, op, source, destination, a, b): + result = Result(99, 99, 99, 99) + code = self.scalar( + mode, + op, + source, + destination, + a & ((1 << 64) - 1), + (a >> 64) & ((1 << 64) - 1), + b & ((1 << 64) - 1), + (b >> 64) & ((1 << 64) - 1), + C.byref(result), + ) + assert code == result.status + return code, result.low | (result.high << 64), result.flag + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", required=True) + parser.add_argument("--cases", type=int, default=100000) + args = parser.parse_args() + kernel = Kernel(args.library) + rng = random.Random(0x352_128) + fixed = [0, 1, 2, 3, (1 << 64) - 1, 1 << 64, MASK] + fixed += [ + (1 << bit) + delta + for bit in (1, 7, 8, 15, 16, 31, 32, 63, 64, 126, 127) + for delta in (-1, 0, 1) + ] + count = 0 + for source in SHAPES: + for mode, operations in ((0, BINARY), (1, range(6)), (3, range(10)), (6, range(2))): + destination = 1 if mode == 3 else source + for op in operations: + for a in fixed: + for b in (0, 1, MASK, a, 1 << 127): + actual = kernel.call(mode, op, source, destination, a, b) + expected = oracle(mode, op, source, destination, a, b) + assert actual == expected, ( + mode, + op, + source, + destination, + a, + b, + actual, + expected, + ) + count += 1 + for destination in SHAPES: + for mode, operations in ((2, range(4)), (4, (0,))): + for op in operations: + for a in fixed: + actual = kernel.call(mode, op, source, destination, a, 0) + expected = oracle(mode, op, source, destination, a, 0) + assert actual == expected, ( + mode, + op, + source, + destination, + a, + actual, + expected, + ) + count += 1 + for _ in range(args.cases): + source, destination = rng.randrange(1, 14), rng.randrange(1, 14) + mode = rng.randrange(7) + if mode in (0, 1, 5, 6): + destination = source + if mode == 3: + destination = 1 + op = ( + rng.choice(BINARY) + if mode == 0 + else rng.randrange(6) + if mode == 1 + else rng.randrange(4) + if mode == 2 + else rng.randrange(10) + if mode == 3 + else rng.randrange(2) + if mode == 6 + else 0 + ) + a, b = rng.getrandbits(128), rng.getrandbits(128) + assert kernel.call(mode, op, source, destination, a, b) == oracle( + mode, op, source, destination, a, b + ), (mode, op, source, destination, a, b) + for _ in range(args.cases): + a, b, shift, op = ( + rng.getrandbits(rng.randrange(129)), + rng.getrandbits(rng.randrange(129)), + rng.randrange(260), + rng.randrange(12), + ) + result = Result() + status = kernel.wide( + op, a & ((1 << 64) - 1), a >> 64, b & ((1 << 64) - 1), b >> 64, shift, C.byref(result) + ) + expected, flag = 0, 0 + if op == 0: + expected, flag = (a + b) & MASK, int(a + b > MASK) + elif op == 1: + expected, flag = (a - b) & MASK, int(a < b) + elif op == 2: + expected, flag = (a * b) & MASK, int(a * b > MASK) + elif op == 3: + expected = a // b if b else 0 + elif op == 4: + expected = a % b if b else 0 + elif op == 5: + expected = (a << shift) & MASK + elif op == 6: + expected = a >> shift + elif op == 7: + expected = int(a > b) - int(a < b) + 1 + elif op == 8: + expected = 128 - a.bit_length() + elif op == 9: + expected = (a >> shift) | int(bool(a & ((1 << shift) - 1))) + elif op == 10: + q, tail = divmod(a, 1 << shift) + expected = q + int( + shift > 0 and (tail > (1 << (shift - 1)) or (tail == (1 << (shift - 1)) and q & 1)) + ) + else: + expected = (-a) & MASK + assert status == result.status == (1 if op in (3, 4) and not b else 0) + assert (result.low | (result.high << 64), result.flag) == (expected, flag), ( + op, + a, + b, + shift, + expected, + result.low | result.high << 64, + flag, + result.flag, + ) + for width in range(1, 129): + for is_signed in (0, 1): + for a in fixed: + result = Result() + status = kernel.bits( + a & ((1 << 64) - 1), a >> 64, width, is_signed, C.byref(result) + ) + expected = (signed(a, width) if is_signed else a & ((1 << width) - 1)) & MASK + assert status == result.status == 0 and result.low | (result.high << 64) == expected + for parameters in [(7, 0, 4, 4), (0, 7, 4, 4), (0, 0, 0, 4), (0, 0, 4, 14)]: + assert kernel.call(*parameters, 1, 1) == (4, 0, 0) + assert kernel.scalar(0, 0, 4, 4, 0, 0, 0, 0, None) == 4 + print( + f"Wave integers: {count} fixed boundaries, {args.cases} mathematical scalar vectors, {args.cases} two-word vectors and exact raw normalization passed" + ) + + +if __name__ == "__main__": + main() diff --git a/tools/check_wave_ir_memory.py b/tools/check_wave_ir_memory.py new file mode 100644 index 0000000..280ba8b --- /dev/null +++ b/tools/check_wave_ir_memory.py @@ -0,0 +1,272 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Independent byte-cell/capability conformance for the Wave memory kernel.""" +import argparse +import ctypes as C +import random + +U = C.c_uint64 +MASK = (1 << 64) - 1 + + +def record(name, fields): + return type(name, (C.Structure,), {'_fields_': [(key, U) for key in fields.split()]}) + + +Pointer = record('Pointer', 'address present arena allocation generation lower upper offset read write') +class Authority(C.Structure): + _fields_ = [('kind', U), ('pointer', Pointer), ('signature', U), ('target_kind', U), ('target', U)] +class Fragment(C.Structure): + _fields_ = [('occupied', U), ('offset', U), ('ordinal', U), ('authority', Authority)] +class Allocation(C.Structure): + _fields_ = [(n, U) for n in 'kind address generation alive read write length'.split()] + [('data', C.POINTER(C.c_uint8)), ('initialized', C.POINTER(C.c_uint8)), ('fragments', C.POINTER(Fragment)), ('fragment_capacity', U), ('fragment_count', U)] +State = record('State', 'arena allocations bytes fragments work next_address') +Limits = record('Limits', 'bytes allocations fragments work') +class Part(C.Structure): + _fields_ = [(n, U) for n in 'offset kind low high'.split()] + [('authority', Authority)] +Gep = record('Gep', 'kind amount low high signed') +class Request(C.Structure): + _fields_ = [(n, U) for n in 'op mode size natural align flag owner'.split()] + [('pointer', Pointer), ('source', Pointer), ('parts', C.POINTER(Part)), ('part_count', U), ('geps', C.POINTER(Gep)), ('gep_count', U)] +class Result(C.Structure): + _fields_ = [(n, U) for n in 'status detail extra work allocation start end fragments fragment_capacity low high'.split()] + [('pointer', Pointer)] + + +def clone(value): + return type(value).from_buffer_copy(bytes(value)) + + +class Memory: + def __init__(self, kernel, byte_limit=1000000, allocation_limit=1000, fragments=10000, work=10000000): + self.kernel = kernel + self.state = State(arena=17, next_address=4096) + self.limits = Limits(byte_limit, allocation_limit, fragments, work) + self.allocations = (Allocation * allocation_limit)() + self.buffers = [] + self.fragment_tables = {} + + def call(self, request, table=None): + output = (Part * 2)() + result = Result() + status = self.kernel(C.byref(self.state), C.byref(self.limits), self.allocations, len(self.allocations), C.byref(request), table, len(table) if table is not None else 0, output, 2, C.byref(result)) + assert status == result.status, (status, result.status) + assert self.state.work <= self.limits.work and result.work <= self.limits.work + return status, result, output + + def allocate(self, size, global_=False, align=1): + q = Request(op=0, size=size, natural=align, align=align, flag=int(global_)) + status, probe, _ = self.call(q) + if status: + return status, None + data = (C.c_uint8 * size)() + initialized = (C.c_uint8 * size)() + index = self.state.allocations + self.allocations[index].data = data + self.allocations[index].initialized = initialized + q.mode = 1 + status, result, _ = self.call(q) + assert status == 0 and result.pointer.address == probe.pointer.address + self.buffers.append((data, initialized)) + return status, clone(result.pointer) + + def mutate(self, q): + before = [(bytes(data), bytes(init)) for data, init in self.buffers] + status, probe, _ = self.call(q) + if status: + assert before == [(bytes(data), bytes(init)) for data, init in self.buffers] + return status + table = (Fragment * probe.fragment_capacity)() + q.mode = 1 + status, result, _ = self.call(q, table) + if status: + assert before == [(bytes(data), bytes(init)) for data, init in self.buffers] + elif result.allocation != MASK: + assert result.fragment_capacity == len(table) == probe.fragment_capacity + self.fragment_tables[result.allocation] = table + return status + + def store(self, pointer, kind, low, high=0, authority=None): + part = Part(kind=kind, low=low, high=high, authority=authority or Authority()) + parts = (Part * 1)(part) + size = {1: 1, 2: 1, 3: 1, 4: 1, 5: 2, 6: 4, 7: 8, 8: 16, 9: 1, 10: 2, 11: 4, 12: 8, 13: 16, 14: 2, 15: 4, 16: 8, 17: 8, 18: 8}[kind] + return self.mutate(Request(op=4, pointer=pointer, size=size, align=1, parts=parts, part_count=1)) + + def load(self, pointer, kind, signature=0): + parts = (Part * 1)(Part(kind=kind, authority=Authority(signature=signature))) + size = {1: 1, 2: 1, 3: 1, 4: 1, 5: 2, 6: 4, 7: 8, 8: 16, 9: 1, 10: 2, 11: 4, 12: 8, 13: 16, 14: 2, 15: 4, 16: 8, 17: 8, 18: 8}[kind] + status, result, out = self.call(Request(op=3, mode=1, pointer=pointer, size=size, align=1, parts=parts, part_count=1)) + return status, result, clone(out[0]) + + +def offset(pointer, amount, *, read=True, write=True, lower=0, upper=None): + p = clone(pointer) + p.address += amount + p.offset += amount + p.read, p.write = int(read), int(write) + p.lower = lower + if upper is not None: + p.upper = upper + return p + + +def fixed(kernel): + m = Memory(kernel) + _, object_ = m.allocate(8, align=8) + _, src = m.allocate(32, align=8) + _, dst = m.allocate(32, align=8) + assert m.load(src, 12)[0] == 8 + authority = Authority(kind=1, pointer=object_) + assert m.store(src, 17, object_.address, authority=authority) == 0 + assert m.mutate(Request(op=6, pointer=dst, source=src, size=4, align=1)) == 0 + assert m.load(dst, 17)[0] == 8 + assert m.mutate(Request(op=6, pointer=offset(dst, 4), source=offset(src, 4), size=4, align=1)) == 0 + status, _, part = m.load(dst, 17) + assert status == 0 and bytes(part.authority.pointer) == bytes(object_) + assert m.store(offset(dst, 7), 9, 0) == 0 + assert m.load(dst, 17)[2].authority.kind == 0 + for target in (0, 7, 2**32 - 1): + bits = target + 1 + authority = Authority(kind=2, signature=9, target_kind=1, target=target) + assert m.store(src, 18, bits, authority=authority) == 0 + assert m.load(src, 18, signature=9)[2].authority.target == target + assert m.load(src, 18, signature=10)[2].authority.kind == 0 + assert m.load(src, 17)[2].authority.kind == 0 + assert m.mutate(Request(op=6, pointer=offset(src, 1), source=src, size=8, align=1)) == 11 + assert m.mutate(Request(op=7, pointer=Pointer(), size=0, align=8)) == 0 + assert m.mutate(Request(op=6, pointer=Pointer(address=999), source=Pointer(), size=0, align=8)) == 0 + assert m.mutate(Request(op=7, pointer=offset(dst, 0, write=False), size=1, align=1)) == 6 + assert m.mutate(Request(op=7, pointer=offset(dst, 31), size=2, align=1)) == 4 + assert m.mutate(Request(op=7, pointer=offset(dst, 1), size=1, align=8)) == 7 + assert m.mutate(Request(op=7, pointer=dst, flag=2, size=1, align=1)) == 0 + assert m.load(dst, 1)[0] == 9 + q = Request(op=2, mode=1, pointer=object_, owner=0) + assert m.call(q)[0] == 0 + assert m.load(object_, 9)[0] == 3 + # Source bounds precede an expired destination in memcpy diagnostics. + assert m.mutate(Request(op=6, pointer=object_, source=offset(src, 33), size=1, align=1)) == 4 + assert m.call(Request(op=2, mode=1, pointer=object_, owner=0))[0] == 3 + _, glob = m.allocate(1, global_=True) + assert m.mutate(Request(op=7, pointer=glob, flag=77, size=1, align=1)) == 0 + status, seal, _ = m.call(Request(op=1, mode=1, pointer=glob, flag=1)) + assert status == 0 + glob = clone(seal.pointer) + assert m.mutate(Request(op=7, pointer=glob, flag=0, size=1, align=1)) == 6 + assert m.call(Request(op=2, mode=1, pointer=glob, owner=0))[0] == 13 + assert m.call(Request(op=11, mode=1, owner=0))[0] == 0 + assert m.load(glob, 9)[2].low == 77 + assert m.load(src, 9)[0] == 3 + + +def generated(kernel, cases): + rng = random.Random(0x354_128) + types = [(2, 1, True), (3, 1, False), (4, 8, True), (9, 8, False), (5, 16, True), (10, 16, False), (6, 32, True), (11, 32, False), (7, 64, True), (12, 64, False), (8, 128, True), (13, 128, False), (14, 16, False), (15, 32, False), (16, 64, False)] + m = Memory(kernel, work=100000000) + _, src = m.allocate(32) + _, dst = m.allocate(32) + for _ in range(cases): + kind, width, signed = rng.choice(types) + bits = rng.getrandbits(width) + expected = bits - (1 << width) if signed and bits >> (width - 1) else bits + raw = expected % (1 << 128) + assert m.store(src, kind, raw & MASK, raw >> 64) == 0 + size = max(1, width // 8) + assert m.mutate(Request(op=6, pointer=dst, source=src, size=size, align=1)) == 0 + status, _, output = m.load(dst, kind) + assert status == 0 and output.low | (output.high << 64) == raw + # Scalar stores erase authority even when bytes happen to match. + assert output.authority.kind == 0 + # A separate byte-cell model computes initialization/copy/overwrite independently. + m = Memory(kernel, work=100000000) + _, p = m.allocate(24) + _, q = m.allocate(24) + bases = [p, q] + data = [bytearray(24), bytearray(24)] + init = [bytearray(24), bytearray(24)] + for _ in range(cases): + code, a, b = rng.randrange(4), rng.randrange(2), rng.randrange(2) + at, source, n = rng.randrange(25), rng.randrange(25), rng.randrange(25) + valid = at + n <= 24 and (code != 2 or source + n <= 24) + overlap = code == 2 and a == b and at < source + n and source < at + n + if n == 0 and code in (0, 2): + valid, overlap = True, False + expected = 0 if valid and not overlap else 11 if valid else 4 + if code == 0: + octet = rng.randrange(256) + result = m.mutate(Request(op=7, pointer=offset(bases[a], at), size=n, flag=octet, align=1)) + if expected == 0: + data[a][at:at+n] = bytes([octet]) * n + init[a][at:at+n] = bytes([1]) * n + elif code == 1: + result = m.mutate(Request(op=5, pointer=offset(bases[a], at), size=n, align=1)) + if expected == 0: + init[a][at:at+n] = bytes(n) + elif code == 2: + result = m.mutate(Request(op=6, pointer=offset(bases[a], at), source=offset(bases[b], source), size=n, align=1)) + if expected == 0: + data[a][at:at+n] = data[b][source:source+n] + init[a][at:at+n] = init[b][source:source+n] + else: + status, _, value = m.load(offset(bases[a], at), 9) + expected = 4 if at == 24 else 8 if not init[a][at] else 0 + assert status == expected + if not status: + assert value.low == data[a][at] + continue + assert result == expected, (code, a, at, b, source, n, result, expected) + for index in range(2): + assert bytes(m.buffers[index][0]) == data[index] + assert bytes(m.buffers[index][1]) == init[index] + + +def limits(kernel): + for count in (0, 7, 8, 15, 16): + m = Memory(kernel, byte_limit=17, allocation_limit=3, fragments=count) + _, obj = m.allocate(1) + _, src = m.allocate(8) + _, dst = m.allocate(8) + assert m.allocate(1)[0] == 102 + assert m.mutate(Request(op=7, pointer=dst, size=8, flag=255, align=1)) == 0 + authority = Authority(kind=1, pointer=obj) + result = m.store(src, 17, obj.address, authority=authority) + if count < 8: + assert result == 103 + else: + assert result == 0 + result = m.mutate(Request(op=6, pointer=dst, source=src, size=8, align=1)) + assert result == (103 if count < 16 else 0) + if count < 16: + assert m.load(dst, 12)[2].low == MASK + before = bytes(m.buffers[2][0]) + m.limits.work = m.state.work + assert m.mutate(Request(op=7, pointer=dst, size=8, align=1)) == 104 + assert bytes(m.buffers[2][0]) == before + m = Memory(kernel) + _, p = m.allocate(8) + for n in (0, 8, -1, 9, -(1 << 127), (1 << 128)-1): + signed = int(n < 0) + raw = n % (1 << 128) + g = (Gep * 1)(Gep(kind=0, amount=1, low=raw & MASK, high=raw >> 64, signed=signed)) + status, result, _ = m.call(Request(op=8, pointer=p, geps=g, gep_count=1)) + expected = 0 if n in (0, 8) else 4 if n in (-1, 9) else 5 + assert status == expected, (n, status) + if status == 0: + assert result.pointer.address == p.address + n + assert m.call(Request(op=200))[0] == 200 + assert m.call(Request(op=4, pointer=p, size=8, align=1, part_count=1))[0] == 200 + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--library', required=True) + parser.add_argument('--cases', type=int, default=10000) + args = parser.parse_args() + kernel = C.CDLL(args.library).whale_ir_memory + kernel.argtypes = [C.POINTER(State), C.POINTER(Limits), C.POINTER(Allocation), U, C.POINTER(Request), C.POINTER(Fragment), U, C.POINTER(Part), U, C.POINTER(Result)] + assert C.sizeof(Pointer) == 80 and C.sizeof(Authority) == 112 and C.sizeof(Fragment) == 136 + fixed(kernel) + generated(kernel, args.cases) + limits(kernel) + print(f'Wave memory: {args.cases} integer/IEEE storage vectors + {args.cases} independent byte streams, authority/lifetime/global/resource regressions passed') + + +if __name__ == '__main__': + main() diff --git a/tools/check_wave_ir_passes.py b/tools/check_wave_ir_passes.py new file mode 100755 index 0000000..05b08dd --- /dev/null +++ b/tools/check_wave_ir_passes.py @@ -0,0 +1,357 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Independent native pass-controller/effect/constant-propagation conformance.""" + +import argparse +import ctypes as c +import random + + +def record(name, fields): + return type( + name, (c.Structure,), {"_fields_": [(field, c.c_uint64) for field in fields.split()]} + ) + + +Node = record("Node", "op sub scope id kind literal low high first count") +Value = record("Value", "known kind low high replace") +Slot = record("Slot", "key index present") +User = record("User", "index next") +Pending = record("Pending", "head queued") +Output = record("Output", "status changed folded work") +State = record("State", "phase epoch0 epoch1 epoch2 work changed mask failure_stage failure_detail") +Reply = record("Reply", "action failed changed mask") +PassOutput = record( + "PassOutput", "status action stage detail changed mask epoch0 epoch1 epoch2 work" +) + + +class Input(c.Structure): + _fields_ = [ + ("nodes", c.POINTER(Node)), + ("count", c.c_uint64), + ("references", c.POINTER(c.c_uint64)), + ("reference_count", c.c_uint64), + ("values", c.POINTER(Value)), + ("slots", c.POINTER(Slot)), + ("capacity", c.c_uint64), + ("users", c.POINTER(User)), + ("pending", c.POINTER(Pending)), + ("queue", c.POINTER(c.c_uint64)), + ("max_work", c.c_uint64), + ] + + +WIDTHS = { + 1: 1, + 2: 1, + 3: 1, + 4: 8, + 5: 16, + 6: 32, + 7: 64, + 8: 128, + 9: 8, + 10: 16, + 11: 32, + 12: 64, + 13: 128, +} +SIGNED = {2, 4, 5, 6, 7, 8} +MASK128 = (1 << 128) - 1 + + +def packed(value, kind): + width = WIDTHS[kind] + value &= (1 << width) - 1 + if kind in SIGNED and value >> (width - 1): + value -= 1 << width + return value & MASK128 + + +def arithmetic(op, a, b, kind): + width = WIDTHS[kind] + mask = (1 << width) - 1 + a, b = a & mask, b & mask + signed = lambda value: value - (1 << width) if value >> (width - 1) else value + if op in (3, 4, 5, 6) and b == 0: + return None + if op == 0: + result = a + b + elif op == 1: + result = a - b + elif op == 2: + result = a * b + elif op in (3, 5): + result = a // b if op == 3 else a % b + elif op in (4, 6): + sa, sb = signed(a), signed(b) + q = abs(sa) // abs(sb) * (-1 if (sa < 0) != (sb < 0) else 1) + result = q if op == 4 else sa - q * sb + elif op == 12: + result = a & b + elif op == 13: + result = a | b + elif op == 14: + result = a ^ b + elif op == 15: + result = a << (b % width) + elif op == 16: + result = a >> (b % width) + else: + result = signed(a) >> (b % width) + return packed(result, kind) + + +def fold(library, nodes, references, work=1_000_000): + count = len(nodes) + capacity = 1 << max(1, (2 * count - 1).bit_length()) + raw_nodes = (Node * count)(*nodes) + raw_refs = (c.c_uint64 * len(references))(*references) + values = (Value * count)() + slots = (Slot * capacity)() + users = (User * len(references))() + pending = (Pending * count)() + queue = (c.c_uint64 * count)() + input_ = Input( + raw_nodes, + count, + raw_refs, + len(references), + values, + slots, + capacity, + users, + pending, + queue, + work, + ) + output = Output() + status = library.whale_ir_fold_integer(c.byref(input_), c.byref(output)) + return status, output, values + + +def check_folds(library, cases): + rng = random.Random(0x3550118) + operations = [0, 1, 2, 3, 4, 5, 6, 12, 13, 14, 15, 16, 17] + for case in range(cases): + kind = rng.choice(list(range(2, 14))) + logical = [] + expected = [] + for index in range(64): + node = Node(scope=case & 0xFFFFFFFF, id=0xFFFFFFFF - index * 7919, kind=kind) + if index < 4 or rng.randrange(6) == 0: + node.op = 4 + node.literal = 1 if kind in SIGNED else 2 + value = packed(rng.getrandbits(WIDTHS[kind]), kind) + node.low, node.high = value & ((1 << 64) - 1), value >> 64 + refs = [] + expected.append(value) + else: + lhs, rhs = rng.sample(range(index), 2) + node.op = 7 + node.sub = rng.choice(operations) + refs = [logical[lhs][0].id, logical[rhs][0].id] + a, b = expected[lhs], expected[rhs] + expected.append( + None if a is None or b is None else arithmetic(node.sub, a, b, kind) + ) + logical.append((node, refs)) + order = list(range(len(logical))) + rng.shuffle(order) + nodes, references = [], [] + for index in order: + node, refs = logical[index] + node.first, node.count = len(references), len(refs) + nodes.append(node) + references.extend(refs) + status, output, values = fold(library, nodes, references) + assert status == 0 and output.status == 0, (case, status, output.work) + folded = 0 + for index, value in zip(order, values): + answer = expected[index] + assert value.known == int(answer is not None), (case, index) + if answer is not None: + assert value.low | (value.high << 64) == answer, (case, index) + assert value.kind == kind + replace = answer is not None and logical[index][0].op != 4 + assert value.replace == int(replace), (case, index) + folded += replace + assert output.folded == folded and output.changed == int(folded > 0) + # Replacing every folded node makes the same physical graph idempotent. + for node, value in zip(nodes, values): + if value.replace: + node.op, node.sub = 4, 0 + node.literal = 1 if kind in SIGNED else 2 + node.low, node.high = value.low, value.high + references = [] + for node, index in zip(nodes, order): + node.first = len(references) + refs = logical[index][1] if node.op == 7 else [] + node.count = len(refs) + references.extend(refs) + status, output, _ = fold(library, nodes, references) + assert status == 0 and output.folded == 0 and output.changed == 0 + # Bool comparisons feed select; equal phi inputs propagate while distinct + # constants and unknown parameters remain unknown, without losing traps. + nodes = [ + Node(op=4, id=0, kind=9, literal=2, low=42), + Node(op=4, id=1, kind=9, literal=2, low=7), + Node(op=11, id=2, kind=9, sub=0, count=2), + Node(op=13, id=3, kind=9, first=2, count=3), + Node(op=15, id=4, kind=9, first=5, count=2), + Node(op=15, id=5, kind=9, first=7, count=2), + Node(op=31, id=6, kind=9, first=9), + Node(op=4, id=7, kind=1, literal=3, low=0, first=9), + Node(op=13, id=8, kind=9, first=9, count=3), + Node(op=11, id=9, kind=1, sub=1, first=12, count=2), + ] + references = [0, 1, 2, 0, 1, 0, 0, 0, 1, 7, 6, 0, 2, 7] + status, output, values = fold(library, nodes, references) + assert status == 0 and output.folded == 5 + assert values[2].kind == 1 and values[2].low == 0 + assert values[3].low == 7 and values[4].low == 42 + assert values[5].known == values[6].known == 0 + assert values[8].low == 42 and values[9].low == 0 + assert fold(library, [], [])[0] == 0 + # Cross-function duplicate IDs remain separate; literal declarations never replaced. + nodes = [ + Node(op=3, scope=0, id=0xFFFFFFFF, kind=9, literal=2, low=42), + Node(op=4, scope=1, id=0xFFFFFFFF, kind=9, literal=2, low=7), + Node(op=6, scope=0, id=1, kind=9, count=1), + Node(op=6, scope=1, id=1, kind=9, first=1, count=1), + ] + status, _, values = fold(library, nodes, [0xFFFFFFFF, 0xFFFFFFFF]) + assert status == 0 and values[2].low == 42 and values[3].low == 7 + assert values[0].replace == 0 + status, output, _ = fold(library, nodes, [0xFFFFFFFF, 0xFFFFFFFF], work=1) + assert status == 1 and output.changed == 0 and output.folded == 0 + nodes[1].scope = 0 + assert fold(library, nodes, [0xFFFFFFFF, 0xFFFFFFFF])[0] == 2 + + +def pass_run(library, before, after, changed, mask, epochs=(0, 0, 0), failed=0, work=1000): + state = State(epoch0=epochs[0], epoch1=epochs[1], epoch2=epochs[2]) + reply = Reply() + first = (c.c_uint8 * len(before))(*before) + second = (c.c_uint8 * len(after))(*after) + actions = [] + for _ in range(12): + result = PassOutput() + status = library.whale_ir_pass_step( + c.byref(state), + c.byref(reply), + first, + len(before), + second, + len(after), + work, + c.byref(result), + ) + assert status == 0 and result.status == 0 + actions.append(result.action) + if result.action in (9, 10): + return result, actions + reply = Reply( + action=result.action, + failed=int(result.action == failed), + changed=changed if result.action == 3 else 0, + mask=mask if result.action == 3 else 0, + ) + raise AssertionError("controller did not terminate") + + +def check_passes(library): + for changed, before, after in [ + (0, b"same", b"same"), + (1, b"same", b"edit"), + (1, b"same", b"longer"), + ]: + result, actions = pass_run(library, before, after, changed, 7 * changed) + assert actions == [1, 2, 3, 4, 5, 7, 9] + assert result.epoch0 == result.epoch1 == result.epoch2 == changed + result, actions = pass_run(library, before, after, 1 - changed, 7 * (1 - changed)) + assert actions[-2:] == [8, 10] and result.stage == 3 and result.detail == 1 + for action, stage in [(1, 0), (2, 0), (3, 1), (4, 2), (5, 3)]: + result, actions = pass_run(library, b"same", b"edit", 1, 7, failed=action) + assert result.action == 10 and result.stage == stage + assert (8 in actions) == (action >= 3) + result, actions = pass_run(library, b"same", b"edit", 1, 7, epochs=(3, (1 << 64) - 1, 9)) + assert result.detail == 2 and actions[-2:] == [8, 10] + assert (result.epoch0, result.epoch1, result.epoch2) == (3, (1 << 64) - 1, 9) + result, _ = pass_run(library, b"0123456789", b"0123456789", 0, 0, work=1) + assert result.detail == 3 and result.stage == 3 + for kind in range(3): + for identity, epoch, expected in [(11, 2, 1), (12, 2, 0), (11, 1, 0)]: + assert library.whale_ir_analysis_current(identity, epoch, 11, 2, 2, 2, kind) == expected + assert library.whale_ir_analysis_current(11, 2, 11, 2, 2, 2, 3) == 2 + + +def check_effects(library): + fixed = { + 19: 21, + 20: 22, + 21: 17, + 22: 18, + 23: 18, + 26: 18, + 25: 19, + 18: 48, + 1: 48, + 29: 27, + 24: 16, + 2: 16, + 30: 16, + 5: 16, + } + for op in range(31): + for sub in range(18 if op == 7 else 13 if op == 14 else 1): + for pointer in (0, 1): + expected = fixed.get(op, 0) + if ( + op == 7 + and 3 <= sub <= 6 + or op == 14 + and sub in (0, 8, 9) + or op in (10, 11) + and pointer + ): + expected = 16 + output = c.c_uint64(0xFFFFFFFF) + assert library.whale_ir_effects(op, sub, pointer, 0, c.byref(output)) == 0 + assert output.value == expected + for mask in range(65): + assert library.whale_ir_effects_removable(mask) == ( + 1 if mask == 0 else 2 if mask > 63 else 0 + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", required=True) + parser.add_argument("--cases", type=int, default=2000) + args = parser.parse_args() + library = c.CDLL(args.library) + library.whale_ir_fold_integer.argtypes = [c.POINTER(Input), c.POINTER(Output)] + library.whale_ir_pass_step.argtypes = [ + c.POINTER(State), + c.POINTER(Reply), + c.POINTER(c.c_uint8), + c.c_uint64, + c.POINTER(c.c_uint8), + c.c_uint64, + c.c_uint64, + c.POINTER(PassOutput), + ] + library.whale_ir_analysis_current.argtypes = [c.c_uint64] * 7 + check_effects(library) + check_passes(library) + check_folds(library, args.cases) + print( + f"Wave passes: full effects inventory, transactional rollback/cache cases, " + f"{args.cases} sparse reordered 64-node mathematical fold DAGs and idempotence passed" + ) + + +if __name__ == "__main__": + main() diff --git a/tools/check_wave_ir_runtime.py b/tools/check_wave_ir_runtime.py new file mode 100644 index 0000000..f906604 --- /dev/null +++ b/tools/check_wave_ir_runtime.py @@ -0,0 +1,251 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Independent generated call/control streams for the actual Wave runtime.""" +import argparse +import ctypes as C +from pathlib import Path +import random +import re + +from check_wave_ir_memory import (Memory, Pointer, Request, Part, Allocation, + State, Limits, Fragment, Result, Gep, U, MASK) + + +def record(name, fields): + return type(name, (C.Structure,), {"_fields_": [(field, U) for field in fields.split()]}) + + +TYPES = { + "u64": U, "u8": C.c_uint8, + "IrVerifyType": record("Type", "kind child first count extra"), + "IrStorage": record("Storage", "ptr_bits pointer_align scalar_align1 scalar_align2 scalar_align4 scalar_align8 scalar_align16 large_array_threshold large_array_align has_large_array"), + "IrTypeNode": record("LayoutNode", "kind child first count"), + "IrTypeLayout": record("Layout", "size align stride allocation_align depth"), + "IrMemPointer": Pointer, + "IrMemGep": Gep, +} +# This reads only the record ABI. All generated operations and expected values below +# are independent of Wave instruction implementation and Rust reference execution. +for name, body in re.findall(r"struct (IrRuntime\w+)\s*\{([^}]+)\}", + (Path(__file__).resolve().parents[1] / "ir/runtime_model.wave").read_text()): + fields = [] + for field, kind in re.findall(r"(\w+):\s*([^;]+);", body): + pointer = re.fullmatch(r"ptr<(.+)>", kind) + fields.append((field, C.POINTER(TYPES[pointer[1]]) if pointer else TYPES[kind])) + TYPES[name] = type(name, (C.Structure,), {"_fields_": fields}) +V, I, F, B, D, R = [TYPES["IrRuntime" + name] for name in + ("Value", "Instruction", "Function", "Block", "Driver", "Result")] + + +def scalar(value, ty=1): + return V(kind=1, ty=ty, literal=2, low=value & MASK, origin=1) + + +class Program: + def __init__(self, functions, blocks, instructions, operands, value_types, arguments, entry, + max_steps=100000, max_depth=128, max_frames=100000, max_values=10000): + self.keep = [] + self.result = R() + self.driver = D(entry_id=entry, max_steps=max_steps, max_depth=max_depth, + max_frames=max_frames, max_values=max_values, max_work=10000000, + scalar_arguments=1, result=C.pointer(self.result)) + d = self.driver + types = [TYPES["IrVerifyType"](kind=0), TYPES["IrVerifyType"](kind=12), + TYPES["IrVerifyType"](kind=1), TYPES["IrVerifyType"](kind=17, child=1), + TYPES["IrVerifyType"](kind=18, first=0, count=2)] + self.array("types", types, TYPES["IrVerifyType"]) + self.array("type_edges", [1, 1], U) + self.array("functions", functions, F) + self.array("blocks", blocks, B) + self.array("instructions", instructions, I) + self.array("operands", operands, U) + self.array("value_types", value_types, U) + self.array("globals", [], TYPES["IrRuntimeGlobal"]) + self.array("global_values", [], V, count_field=None) + self.array("arguments", [scalar(a) for a in arguments], V) + for field, count, kind in [ + ("layout_nodes", len(types), TYPES["IrTypeNode"]), + ("layouts", len(types), TYPES["IrTypeLayout"]), ("layout_offsets", 2, U), + ("plans", len(operands), Gep), ("ordinals", len(value_types), U), + ("function_table", 1 << max(1, (len(functions) * 2 - 1).bit_length()), U), + ("prepared", len(functions), C.c_uint8), + ("pending_previous", len(functions), U), ("pending_next", len(functions), U), + ("pending_flags", len(functions), C.c_uint8), + ("callable_flags", len(functions), C.c_uint8), + ("callable_targets", len(functions), U), + ("indirect_signatures", len(instructions), U), + ("indirect_sites", len(instructions), U), + ("frames", 0, TYPES["IrRuntimeFrame"]), + ("slots", 0, TYPES["IrRuntimeSlot"]), ("phis", 0, V), + ]: + self.array(field, [kind() for _ in range(count)], kind, count_field=None) + d.plan_capacity = len(operands) + d.function_table_capacity = len(self.function_table) + d.indirect_capacity = len(instructions) + self.storage = TYPES["IrStorage"](64, 8, 1, 2, 4, 8, 16, 16, 16, 1) + d.storage = C.pointer(self.storage) + + def array(self, field, values, kind, count_field="auto"): + data = (kind * len(values))(*values) + setattr(self, field, data) + self.keep.append(data) + setattr(self.driver, field, data) + if count_field == "auto": + count_field = {"types": "type_count", "type_edges": "type_edge_count", + "functions": "function_count", "blocks": "block_count", + "instructions": "instruction_count", "operands": "operand_count", + "value_types": "value_type_count", "globals": "global_count", + "arguments": "argument_count"}[field] + if count_field: + setattr(self.driver, count_field, len(values)) + + def run(self, runtime, memory_kernel): + memory = Memory(memory_kernel) + d = self.driver + effects = [] + for _ in range(100000): + d.memory_allocations = memory.state.allocations + status = runtime(C.byref(d)) + r = self.result + assert status == r.status and d.work <= d.max_work and d.steps == r.steps + if status == 2: + for field, capacity, kind in [ + ("frames", r.event.frame_capacity, TYPES["IrRuntimeFrame"]), + ("slots", r.event.value_capacity, TYPES["IrRuntimeSlot"]), + ("phis", r.event.phi_capacity, V), + ]: + old = getattr(self, field) + if capacity > len(old): + self.array(field, list(old) + [kind() for _ in range(capacity - len(old))], + kind, count_field=None) + setattr(d, {"frames": "frame_capacity", "slots": "slot_capacity", + "phis": "phi_capacity"}[field], len(getattr(self, field))) + d.resume = 2 + elif status == 1: + e = r.event + effects.append((e.kind, r.site)) + value = V(ty=e.ty) + if e.kind == 1: + code, pointer = memory.allocate(e.size, global_=bool(e.flag), align=e.align) + assert code == 0 + value.kind, value.pointer = 3, pointer + elif e.kind == 2: + code, _, part = memory.load(e.left.pointer, 12) + assert code == 0 + value = scalar(part.low) + elif e.kind == 3: + assert memory.store(e.left.pointer, 12, e.right.low) == 0 + elif e.kind == 11: + assert memory.call(Request(op=11, mode=1, owner=e.owner))[0] == 0 + else: + raise AssertionError(("unexpected event", e.kind)) + d.resume_value, d.resume = value, 1 + else: + return status, r, effects + raise AssertionError("native runtime failed bounded termination") + + +def calls(rng, count): + depth = rng.randint(1, 12) + ids = rng.sample(range(1, 2**32), depth) + constants = [rng.getrandbits(64) for _ in range(depth)] + functions, blocks, instructions, operands, value_types = [], [], [], [], [] + for n in range(depth): + first = len(instructions) + parameter = len(operands) + operands.append(0) + first_type = len(value_types) + value_types.extend([1, 1, 1, 1, 3, 1]) + instructions += [I(op=4, ty=1, dst=1, literal=2, low=constants[n]), + I(op=7, sub=0, ty=1, dst=2, a=0, b=1)] + if n + 1 < depth: + args = len(operands) + operands.append(2) + instructions += [I(op=29, ty=1, dst=3, a=n + 1, first=args, count=1), + I(op=34, ty=1, dst=MASK, a=3)] + else: + # Distinct volatile sites are issued once, then resumed after the effect. + instructions += [I(op=18, ty=1, dst=4, align=8), + I(op=20, ty=1, dst=MASK, a=2, b=4, align=8), + I(op=19, ty=1, dst=5, a=4, align=8), + I(op=34, ty=1, dst=MASK, a=5)] + blocks.append(B(id=rng.getrandbits(32), function=n, first=first, + count=len(instructions) - first)) + functions.append(F(id=ids[n], signature=4, entry=n, first_block=n, block_count=1, + first_parameter=parameter, parameter_count=1, value_count=6, + first_value_type=first_type, has_body=1)) + argument = rng.getrandbits(64) + expected = (argument + sum(constants)) & MASK + program = Program(functions, blocks, instructions, operands, value_types, [argument], ids[0]) + return program, expected, depth + + +def loop(rng): + count = rng.randrange(0, 40) + argument = rng.getrandbits(64) + instructions = [ + I(op=4, ty=1, dst=1, literal=2, low=0), + I(op=4, ty=1, dst=2, literal=2, low=1), + I(op=4, ty=1, dst=3, literal=2, low=count), + I(op=7, ty=1, sub=0, dst=9, a=0, b=2), + I(op=31, ty=0, dst=MASK, a=1), + I(op=15, ty=1, dst=4, first=1, count=2), + I(op=15, ty=1, dst=5, first=5, count=2), + I(op=15, ty=1, dst=6, first=9, count=2), + I(op=11, ty=1, sub=2, dst=7, a=4, b=3), + I(op=32, ty=0, dst=MASK, a=7, b=2, c=3), + I(op=7, ty=1, sub=0, dst=8, a=4, b=2), + I(op=31, ty=0, dst=MASK, a=1), + I(op=34, ty=1, dst=MASK, a=5), + ] + operands = [0, 1, 0, 8, 2, 0, 0, 6, 2, 9, 0, 5, 2] + blocks = [B(id=100+n, function=0, first=first, count=size) + for n, (first, size) in enumerate([(0, 5), (5, 5), (10, 2), (12, 1)])] + function = F(id=77, signature=4, entry=0, first_block=0, block_count=4, + first_parameter=0, parameter_count=1, value_count=10, + first_value_type=0, has_body=1) + program = Program([function], blocks, instructions, operands, + [1, 1, 1, 1, 1, 1, 1, 2, 1, 1], [argument], 77) + return program, (argument + count % 2) & MASK, 11 + 7 * count + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--library", type=Path, required=True) + parser.add_argument("--cases", type=int, default=2000) + args = parser.parse_args() + library = C.CDLL(str(args.library.resolve())) + memory = library.whale_ir_memory + memory.argtypes = [C.POINTER(State), C.POINTER(Limits), C.POINTER(Allocation), U, + C.POINTER(Request), C.POINTER(Fragment), U, C.POINTER(Part), U, + C.POINTER(Result)] + runtime = library.whale_ir_runtime_step + runtime.argtypes = [C.POINTER(D)] + rng = random.Random(0x5748414C455254) + for case in range(args.cases): + program, expected, depth = calls(rng, case) + status, result, effects = program.run(runtime, memory) + assert status == 0, (case, status, result.error, result.site, result.detail) + assert result.value.kind == 1 and result.value.low == expected + assert len(effects) == depth + 3, (case, effects) + assert [kind for kind, _ in effects[:3]] == [1, 3, 2] + assert result.steps == 4 * depth + 2 + # Admission limits fail at the call before issuing any leaf memory effect. + if depth > 1 and case % 16 == 0: + limited, _, _ = calls(random.Random(case), case) + limited.driver.max_depth = 0 + status, result, effects = limited.run(runtime, memory) + assert status == 3 and result.error == 7 and not effects + for case in range(args.cases): + program, expected, steps = loop(rng) + status, result, effects = program.run(runtime, memory) + assert status == 0 and result.value.low == expected, (case, status, result.error) + assert result.steps == steps and len(effects) == 1 + program, _, _ = calls(rng, 0) + assert runtime(C.byref(program.driver)) == 2 + assert runtime(C.byref(program.driver)) == 4 + print(f"Wave runtime: {args.cases} generated call/volatile + {args.cases} independent phi/control streams passed") + + +if __name__ == "__main__": + main() From 62f7eb16ed516b6d80fea3e1109190c3a93152e4 Mon Sep 17 00:00:00 2001 From: LunaStev Date: Sat, 31 Oct 2026 13:22:24 +0900 Subject: [PATCH 5/8] assembler: move shared utilities and AMD64 to Wave Implement a bounded UTF-8 lexer, checked two-word expressions and neutral output accounting in shared Wave sources. Move the supported AMD64 grammar, namespace, relaxation, integer/SSE encoding and public encoding helpers into role-specific Wave files. Rust retains typed allocation/data bridges and explicit independent migration references. Link shared and ISA archives separately through explicit Meson options and validate pinned source/ABI/provenance before Cargo links either module. Bound materialized output, sparse storage, work, workspace and copied symbol names. Verify native O0/O2, exact parser diagnostics, mathematical layouts, NASM vectors, static Linux executions, workspace tests, Clippy and MSRV 1.86. Refs #356, #357. Signed-off-by: LunaStev --- .gitattributes | 3 +- .github/workflows/asmobj.yml | 46 +- BUILDING.md | 7 + CONTRIBUTING.md | 4 +- assembler/amd64/address.wave | 107 + assembler/amd64/branch.wave | 93 + assembler/amd64/build.rs | 46 + assembler/amd64/directives.wave | 158 ++ assembler/amd64/directives_encode.wave | 230 ++ assembler/amd64/emit.wave | 178 ++ assembler/amd64/encoder.wave | 386 +++ assembler/amd64/encoder_model.wave | 744 ++++++ assembler/amd64/expressions.wave | 206 ++ assembler/amd64/integer.wave | 306 +++ assembler/amd64/layout.wave | 411 +++ assembler/amd64/meson.build | 68 + assembler/amd64/namespace.wave | 393 +++ assembler/amd64/operands.wave | 226 ++ assembler/amd64/parser.wave | 174 ++ assembler/amd64/parser_model.wave | 56 + assembler/amd64/registers.wave | 589 +++++ assembler/amd64/src/ast_model.rs | 262 ++ assembler/amd64/src/encoder.rs | 2241 +---------------- .../amd64/src/encoder_namespace_errors.rs | 61 + assembler/amd64/src/encoder_reference.rs | 2210 ++++++++++++++++ assembler/amd64/src/encoder_wave.rs | 778 ++++++ assembler/amd64/src/encoding/address.rs | 154 +- .../amd64/src/encoding/address_reference.rs | 154 ++ assembler/amd64/src/encoding/modrm.rs | 13 +- assembler/amd64/src/encoding/rex.rs | 19 +- assembler/amd64/src/encoding/sib.rs | 13 +- assembler/amd64/src/lib.rs | 3 + assembler/amd64/src/parser.rs | 678 +---- assembler/amd64/src/parser_reference.rs | 664 +++++ assembler/amd64/src/parser_wave.rs | 745 ++++++ assembler/amd64/src/tables.rs | 122 +- assembler/amd64/sse.wave | 45 + assembler/ast_model.wave | 44 + assembler/build.rs | 21 + assembler/build_support.rs | 137 + assembler/declarations.wave | 17 + assembler/lexer.wave | 425 ++++ assembler/meson.build | 55 + assembler/model.wave | 51 + assembler/numeric.wave | 105 + assembler/output.wave | 37 + assembler/src/diagnostic.rs | 1 + assembler/src/error.rs | 3 + assembler/src/tokens.rs | 280 +- assembler/src/tokens_reference.rs | 237 ++ assembler/src/tokens_wave.rs | 229 ++ assembler/src/unicode_reference.rs | 864 +++++++ assembler/unicode.wave | 865 +++++++ meson.build | 19 +- meson.options | 4 + tools/build_wave_assembler.py | 193 ++ tools/check_wave_amd64_cli.py | 125 + tools/check_wave_amd64_layout.py | 187 ++ tools/check_wave_amd64_parser.py | 191 ++ tools/check_wave_assembler.py | 284 +++ tools/meson_cargo.py | 32 +- tools/test_build_wave_assembler.py | 162 ++ tools/test_meson_build.py | 15 + 63 files changed, 14005 insertions(+), 3171 deletions(-) create mode 100644 assembler/amd64/address.wave create mode 100644 assembler/amd64/branch.wave create mode 100644 assembler/amd64/build.rs create mode 100644 assembler/amd64/directives.wave create mode 100644 assembler/amd64/directives_encode.wave create mode 100644 assembler/amd64/emit.wave create mode 100644 assembler/amd64/encoder.wave create mode 100644 assembler/amd64/encoder_model.wave create mode 100644 assembler/amd64/expressions.wave create mode 100644 assembler/amd64/integer.wave create mode 100644 assembler/amd64/layout.wave create mode 100644 assembler/amd64/meson.build create mode 100644 assembler/amd64/namespace.wave create mode 100644 assembler/amd64/operands.wave create mode 100644 assembler/amd64/parser.wave create mode 100644 assembler/amd64/parser_model.wave create mode 100644 assembler/amd64/registers.wave create mode 100644 assembler/amd64/src/ast_model.rs create mode 100644 assembler/amd64/src/encoder_namespace_errors.rs create mode 100644 assembler/amd64/src/encoder_reference.rs create mode 100644 assembler/amd64/src/encoder_wave.rs create mode 100644 assembler/amd64/src/encoding/address_reference.rs create mode 100644 assembler/amd64/src/parser_reference.rs create mode 100644 assembler/amd64/src/parser_wave.rs create mode 100644 assembler/amd64/sse.wave create mode 100644 assembler/ast_model.wave create mode 100644 assembler/build.rs create mode 100644 assembler/build_support.rs create mode 100644 assembler/declarations.wave create mode 100644 assembler/lexer.wave create mode 100644 assembler/meson.build create mode 100644 assembler/model.wave create mode 100644 assembler/numeric.wave create mode 100644 assembler/output.wave create mode 100644 assembler/src/tokens_reference.rs create mode 100644 assembler/src/tokens_wave.rs create mode 100644 assembler/src/unicode_reference.rs create mode 100644 assembler/unicode.wave create mode 100644 tools/build_wave_assembler.py create mode 100644 tools/check_wave_amd64_cli.py create mode 100644 tools/check_wave_amd64_layout.py create mode 100644 tools/check_wave_amd64_parser.py create mode 100644 tools/check_wave_assembler.py create mode 100644 tools/test_build_wave_assembler.py diff --git a/.gitattributes b/.gitattributes index 8275a2b..3564612 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,6 +1,5 @@ *.wave text eol=lf linguist-language=Wave -toolchain/src/assembly_object.rs text eol=lf -ir/src/wave_layout.rs text eol=lf +*.rs text eol=lf *.ps1 linguist-vendored *.sh linguist-vendored Makefile linguist-vendored diff --git a/.github/workflows/asmobj.yml b/.github/workflows/asmobj.yml index 5964e76..2e2c2ae 100644 --- a/.github/workflows/asmobj.yml +++ b/.github/workflows/asmobj.yml @@ -44,7 +44,7 @@ jobs: - name: Install pinned compiler prerequisites run: | sudo apt-get update - sudo apt-get install --no-install-recommends -y wget software-properties-common ninja-build + sudo apt-get install --no-install-recommends -y wget software-properties-common ninja-build nasm wget --tries=3 --timeout=30 https://apt.llvm.org/llvm.sh -O "$RUNNER_TEMP/llvm.sh" sudo bash "$RUNNER_TEMP/llvm.sh" 21 sudo apt-get install --no-install-recommends -y llvm-21-dev lld-21 @@ -109,6 +109,41 @@ jobs: WHALE_WAVE_IR_DIR="$RUNNER_TEMP/wave-ir-o$optimization" \ cargo test -p ir --all-features --locked --offline done + - name: Run shared and AMD64 Wave assemblers at O0 and O2 + run: | + for optimization in 0 2; do + for module in common amd64; do + python3 tools/build_wave_assembler.py --module "$module" \ + --wave-source .asmobj-bootstrap-source \ + --bootstrap-dir "$RUNNER_TEMP/asmobj-bootstrap" --rust-toolchain 1.89.0 \ + --out-dir "$RUNNER_TEMP/assembler-$module-o$optimization" \ + --opt-level "$optimization" + done + export WHALE_WAVE_ASSEMBLER_DIR="$RUNNER_TEMP/assembler-common-o$optimization" + export WHALE_WAVE_AMD64_DIR="$RUNNER_TEMP/assembler-amd64-o$optimization" + export WHALE_ASMOBJ_DIR="$GITHUB_WORKSPACE/.ci-asmobj/x86_64-unknown-linux-gnu" + export WHALE_WAVE_IR_DIR="$RUNNER_TEMP/wave-ir-o2" + cc -shared -Wl,--whole-archive "$WHALE_WAVE_ASSEMBLER_DIR/libwhale_wave_assembler.a" \ + -Wl,--no-whole-archive -o "$RUNNER_TEMP/assembler-common-o$optimization.so" + assembler_python="$(command -v python3)" + timeout 180s python3 tools/fuzz_limits.py --memory-mib 512 -- "$assembler_python" \ + tools/check_wave_assembler.py \ + --library "$RUNNER_TEMP/assembler-common-o$optimization.so" --cases 10000 + cc -shared -Wl,--whole-archive "$WHALE_WAVE_AMD64_DIR/libwhale_wave_amd64.a" \ + "$WHALE_WAVE_ASSEMBLER_DIR/libwhale_wave_assembler.a" \ + -Wl,--no-whole-archive -o "$RUNNER_TEMP/assembler-amd64-o$optimization.so" + timeout 180s python3 tools/fuzz_limits.py --memory-mib 512 -- "$assembler_python" \ + tools/check_wave_amd64_parser.py \ + --library "$RUNNER_TEMP/assembler-amd64-o$optimization.so" --cases 20000 + timeout 180s python3 tools/fuzz_limits.py --memory-mib 512 -- "$assembler_python" \ + tools/check_wave_amd64_layout.py \ + --library "$RUNNER_TEMP/assembler-amd64-o$optimization.so" --cases 2000 + cargo test -p assembler -p amd64 --locked --offline + cargo build -p whale --all-features --locked --offline + timeout 180s python3 tools/fuzz_limits.py --memory-mib 512 -- "$assembler_python" \ + tools/check_wave_amd64_cli.py --binary target/debug/whale \ + --output-dir ".ci-artifacts/amd64-o$optimization" --cases 2000 + done - name: Reproduce the pinned typed HIR fixture run: | python3 tools/check_wave_hir_fixture.py --wave-source .asmobj-bootstrap-source \ @@ -159,6 +194,15 @@ jobs: '-Dhost-runner=["/bin/true"]' meson introspect --tests "$RUNNER_TEMP/whale-cross-runner" | \ python3 -c 'import json,sys; tests={t["name"]:t for t in json.load(sys.stdin)}; assert set(tests)=={"build-helper","cli-smoke"}; assert "--runner-arg=/bin/true" in tests["cli-smoke"]["cmd"]' + - name: Retain independent AMD64 oracle evidence + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: amd64-oracles-${{ github.run_id }}-${{ github.run_attempt }} + path: .ci-artifacts/amd64-*/ + include-hidden-files: true + if-no-files-found: warn + retention-days: 7 - name: Retain target-specific archives and provenance uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: diff --git a/BUILDING.md b/BUILDING.md index ab43025..6bef8e7 100644 --- a/BUILDING.md +++ b/BUILDING.md @@ -78,6 +78,13 @@ to use them. Ordinary Cargo keeps the Rust reference during the IR migration. The Wave numeric core uses two 64-bit words for 128-bit integers and exact IEEE rounding; it does not depend on host floating-point arithmetic. +Source builds also compile the shared Wave assembler and selected AMD64 module. +Prebuilt builds select them with `-Dwave-assembler-dir=...` and +`-Dwave-amd64-dir=...`; unselected ISA archives are not linked. +For focused Cargo tests, `tools/build_wave_assembler.py --module common|amd64` +produces the corresponding archive. Set `WHALE_WAVE_ASSEMBLER_DIR` and +`WHALE_WAVE_AMD64_DIR` explicitly; Cargo does not invoke Wave. + For work confined to Rust components, ordinary Cargo builds remain available: ```sh diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f2e692e..199c8f4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -17,8 +17,8 @@ executable does not need the Wave compiler at runtime. | Sources | Responsibility | | --- | --- | -| `assembler//` | Rust registers, operands, parser and encoder for that ISA | -| `assembler/src/` | Shared Rust assembly types and helpers | +| `assembler//` | ISA registers, operands, grammar and encoding, with explicit Rust data bridges | +| `assembler/*.wave`, `assembler/src/` | Shared Wave source, numeric and output helpers; Rust assembly data | | `assembler/asmobj/` | Complete Wave assembly-to-object module | | `toolchain/`, `backend-api/` | Rust composition, backend interfaces and external data calls to `asmobj` | | `ir/`, `target-spec/` | Wave IR model, text, verification, numeric semantics, passes and execution; Rust data transport and target contracts | diff --git a/assembler/amd64/address.wave b/assembler/amd64/address.wave new file mode 100644 index 0000000..e97e835 --- /dev/null +++ b/assembler/amd64/address.wave @@ -0,0 +1,107 @@ +// SPDX-License-Identifier: MPL-2.0 +// AMD64 ModRM/SIB addressing, shared with the public low-level address API. +fun amd_address(p: ptr, mem: ptr, mode: u64, + symbols: bool, output: ptr, result: ptr) -> bool { + output.mode = 0; + output.rm = 0; + output.sib = 18446744073709551615; + output.displacement = mem.disp as u64; + output.width = 0; + output.rex_b = 0; + output.rex_x = 0; + var address_mode: u64 = mem.mode; + var displacement: i64 = mem.disp; + if (mem.symbol != 18446744073709551615) { + if (!symbols) { + return amd_fail(result, 9); + } + if (mem.base != 18446744073709551615 || mem.index != 18446744073709551615) { + return amd_fail(result, 10); + } + displacement = 0; + output.displacement = 0; + if (address_mode == 0) { + address_mode = 1; + } + } + if (address_mode != 0) { + if (address_mode > 2 || mode != 64 || mem.base != 18446744073709551615 + || mem.index != 18446744073709551615 || mem.scale != 1) { + return amd_fail(result, 11); + } + if (displacement < -2147483648 || displacement > 2147483647) { + return amd_fail(result, 12); + } + output.rm = 5; + output.width = 4; + if (address_mode == 2) { + output.rm = 4; + output.sib = 37; + } + return true; + } + var base: AmdOperand; + var index: AmdOperand; + base.code = 18446744073709551615; + index.code = 18446744073709551615; + if (mem.base != 18446744073709551615 + && (!amd_register(p, mem.base, &base) || base.width != mode)) { + return amd_fail(result, 13); + } + if (mem.index != 18446744073709551615 + && (!amd_register(p, mem.index, &index) || index.width != mode)) { + return amd_fail(result, 14); + } + if (base.code == 18446744073709551615 && index.code == 18446744073709551615) { + return amd_fail(result, 15); + } + var scale: u64 = 0; + if (mem.scale == 2) { + scale = 1; + } else if (mem.scale == 4) { + scale = 2; + } else if (mem.scale == 8) { + scale = 3; + } else if (mem.scale != 1) { + return amd_fail(result, 16); + } + if (index.code == 4) { + return amd_fail(result, 17); + } + if (displacement < -2147483648 || displacement > 2147483647) { + return amd_fail(result, 18); + } + if (displacement != 0) { + output.mode = 2; + output.width = 4; + if (displacement >= -128 && displacement <= 127) { + output.mode = 1; + output.width = 1; + } + } + if (base.code != 18446744073709551615) { + output.rm = base.code & 7; + output.rex_b = (base.code >= 8) as u64; + if (output.rm == 5 && displacement == 0) { + output.mode = 1; + output.width = 1; + } + } + if (index.code != 18446744073709551615 || base.code == 18446744073709551615 + || output.rm == 4) { + output.rm = 4; + var index_low: u64 = 4; + if (index.code != 18446744073709551615) { + index_low = index.code & 7; + output.rex_x = (index.code >= 8) as u64; + } + var base_low: u64 = base.code & 7; + if (base.code == 18446744073709551615) { + base_low = 5; + output.mode = 0; + output.width = 4; + } + output.sib = (scale << 6) | (index_low << 3) | base_low; + } + return true; +} diff --git a/assembler/amd64/branch.wave b/assembler/amd64/branch.wave new file mode 100644 index 0000000..ee9006a --- /dev/null +++ b/assembler/amd64/branch.wave @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: MPL-2.0 +// Layout-aware direct transfers; local LOOP is resolved after convergence. +fun amd_relative(target: u64, source: u64, length: u64, width: u64, + displacement: ptr) -> bool { + if (length > 18446744073709551615 - source) { + return false; + } + var origin: u64 = source + length; + var maximum: u64 = 127; + if (width == 32) { + maximum = 2147483647; + } + if (target >= origin) { + var difference: u64 = target - origin; + if (difference > maximum) { + return false; + } + displacement[0] = difference; + } else { + var difference: u64 = origin - target; + if (difference > maximum + 1) { + return false; + } + displacement[0] = 0 - difference; + } + return true; +} + +fun amd_direct_branch(w: ptr, operation: u64, operand: ptr, + node_index: u64, iteration: u64) -> bool { + if (operand.kind != 2 && operand.kind != 3) { + return amd_fail(w.result, 40); + } + if (operand.low != 0 || operand.high != 0) { + return amd_fail(w.result, 41); + } + var symbol: u64 = operand.symbol; + if (symbol >= w.result.symbol_count) { + return amd_fail(w.result, 3); + } + if (operation == 12) { + return amd_emit(w, 226, 1) + && amd_relocation(w, symbol, 5, 18446744073709551615, w.count) + && amd_emit(w, 0, 1); + } + var near: u64 = 233; + var short: u64 = 235; + var length: u64 = 5; + var two: u64 = 0; + if (operation == 11) { + near = 232; + short = 0; + } else if (operation >= 64 && operation <= 79) { + near = 128 + operation - 64; + short = 112 + operation - 64; + length = 6; + two = 1; + } + var target_section: u64 = w.p.symbols[symbol].section; + var target: u64 = w.p.symbols[symbol].offset; + var source: u64 = w.count; + if (iteration != 0) { + target_section = w.p.symbols[symbol].previous_section; + target = w.p.symbols[symbol].previous_offset; + source = w.p.nodes[node_index].previous_offset; + } + if ((w.p.symbols[symbol].flags & 4) != 0 && target_section == w.section) { + var displacement: u64 = 0; + if (short != 0 && w.p.nodes[node_index].force_near == 0) { + var short_target: u64 = target; + var previous: u64 = w.p.nodes[node_index].previous_length; + if (target > source && previous > 2) { + short_target -= previous - 2; + } + if (amd_relative(short_target, source, 2, 8, &displacement)) { + return amd_emit(w, short, 1) && amd_emit(w, displacement, 1); + } + } + if (!amd_relative(target, source, length, 32, &displacement)) { + w.result.argument = symbol; + return amd_fail(w.result, 42); + } + if (two != 0 && !amd_emit(w, 15, 1)) { + return false; + } + return amd_emit(w, near, 1) && amd_emit(w, displacement, 4); + } + if (two != 0 && !amd_emit(w, 15, 1)) { + return false; + } + return amd_emit(w, near, 1) && amd_relocation(w, symbol, 4, 18446744073709551612, w.count) + && amd_emit(w, 0, 4); +} diff --git a/assembler/amd64/build.rs b/assembler/amd64/build.rs new file mode 100644 index 0000000..636e1a5 --- /dev/null +++ b/assembler/amd64/build.rs @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: MPL-2.0 +const CFG: &str = "whale_wave_amd64"; + +const ENV: &str = "WHALE_WAVE_AMD64_DIR"; + +const LIBRARY: &str = "whale_wave_amd64"; + +const METADATA: &str = "wave-amd64.meta"; + +const ROOT_UP: usize = 2; + +const SOURCES: &[&str] = &[ + "assembler/model.wave", + "assembler/declarations.wave", + "assembler/ast_model.wave", + "assembler/amd64/parser_model.wave", + "assembler/amd64/registers.wave", + "assembler/amd64/expressions.wave", + "assembler/amd64/operands.wave", + "assembler/amd64/directives.wave", + "assembler/amd64/parser.wave", + "assembler/amd64/encoder_model.wave", + "assembler/amd64/namespace.wave", + "assembler/amd64/layout.wave", + "assembler/amd64/address.wave", + "assembler/amd64/emit.wave", + "assembler/amd64/integer.wave", + "assembler/amd64/sse.wave", + "assembler/amd64/branch.wave", + "assembler/amd64/directives_encode.wave", + "assembler/amd64/encoder.wave", +]; + +const ABI_SOURCES: &[&str] = &[ + "assembler/amd64/src/ast_model.rs", + "assembler/amd64/src/parser_wave.rs", + "assembler/amd64/src/encoder_wave.rs", + "assembler/amd64/src/encoder_namespace_errors.rs", + "assembler/amd64/src/tables.rs", + "assembler/amd64/src/encoder.rs", + "assembler/amd64/src/encoding/address.rs", + "assembler/amd64/src/encoding/modrm.rs", + "assembler/amd64/src/encoding/rex.rs", + "assembler/amd64/src/encoding/sib.rs", +]; +include!("../build_support.rs"); diff --git a/assembler/amd64/directives.wave b/assembler/amd64/directives.wave new file mode 100644 index 0000000..477b80b --- /dev/null +++ b/assembler/amd64/directives.wave @@ -0,0 +1,158 @@ +// SPDX-License-Identifier: MPL-2.0 +// Directives retain their expression and byte payloads for later assembly passes. +fun amd64_directive_tag(name: ptr) -> u64 { + if (amd64_name_is(name, 119225648511347, 6, 1)) { // symbol + return 1; + } + if (amd64_name_is(name, 31084746153092467, 7, 1)) { // section + return 2; + } + if (amd64_name_is(name, 119165519096935, 6, 1)) { // global + return 3; + } + if (amd64_name_is(name, 121437607458917, 6, 1)) { // extern + return 4; + } + if (amd64_name_is(name, 474181364833, 5, 1) // align + || amd64_name_is(name, 25188, 2, 1) // db + || amd64_name_is(name, 30564, 2, 1) // dw + || amd64_name_is(name, 25700, 2, 1) // dd + || amd64_name_is(name, 29028, 2, 1) // dq + || amd64_name_is(name, 1651729778, 4, 1) // resb + || amd64_name_is(name, 2004051314, 4, 1) // resw + || amd64_name_is(name, 1685284210, 4, 1) // resd + || amd64_name_is(name, 1903388018, 4, 1)) { // resq + return 5; + } + return 0; +} + +fun amd64_parse_comma(p: ptr) -> bool { + if (amd64_token_kind(p, p.position) != 3) { + return amd64_parse_fail(p, 21, p.position); + } + p.position += 1; + return true; +} + +fun amd64_parse_directive(p: ptr, item: ptr) -> bool { + var start: u64 = p.position; + var tag: u64 = amd64_directive_tag(&p.packet.tokens[start].text); + p.position += 1; + if (tag == 1) { + item.kind = 1; + if (amd64_token_kind(p, p.position) != 0) { + return amd64_parse_fail(p, 20, p.position); + } + if (!amd64_parse_name(p, p.position, false, &item.name)) { + return false; + } + p.position += 1; + if (!amd64_parse_comma(p)) { + return false; + } + if (amd64_token_is(p, p.position, 7957695015192261990, 8)) { // function + item.aux = 1; + } else if (amd64_token_is(p, p.position, 127970252055151, 6)) { // object + item.aux = 2; + } else if (amd64_token_is(p, p.position, 111533748416366, 6)) { // notype + item.aux = 0; + } else { + return amd64_parse_fail(p, 22, p.position); + } + p.position += 1; + if (!amd64_parse_comma(p) || !amd64_parse_expression(p, 1, &item.expression) + || !amd64_parse_comma(p)) { + return false; + } + if (amd64_token_is(p, p.position, 32770348699510116, 7)) { // default + item.flags = 0; + } else if (amd64_token_is(p, p.position, 121381755054440, 6)) { // hidden + item.flags = 1; + } else { + return amd64_parse_fail(p, 23, p.position); + } + p.position += 1; + return amd64_finish_statement(p); + } + if (tag >= 2 && tag <= 4) { + if (amd64_token_kind(p, p.position) != 0) { + return amd64_parse_fail(p, 24, p.position); + } + if (!amd64_parse_name(p, p.position, false, &item.name)) { + return false; + } + p.position += 1; + item.kind = 4; + if (tag == 3) { + item.kind = 6; + } else if (tag == 4) { + item.kind = 7; + } + if (tag == 2 && amd64_token_kind(p, p.position) == 3) { + p.position += 1; + item.kind = 5; + if (amd64_token_is(p, p.position, 1954047348, 4)) { // text + item.aux = 0; + } else if (amd64_token_is(p, p.position, 1635017060, 4)) { // data + item.aux = 1; + } else if (amd64_token_is(p, p.position, 107152478072690, 6)) { // rodata + item.aux = 2; + } else if (amd64_token_is(p, p.position, 7566178, 3)) { // bss + item.aux = 3; + } else { + return amd64_parse_fail(p, 25, p.position); + } + p.position += 1; + } + return amd64_finish_statement(p); + } + if (tag != 5) { + return amd64_parse_backend(p); + } + item.kind = 2; + if (!amd64_parse_name(p, start, true, &item.name)) { + return false; + } + item.first = p.result.values; + while (true) { + if (!amd64_parse_charge(p, 1)) { + return false; + } + var kind: u64 = amd64_token_kind(p, p.position); + if (kind == 18446744073709551615 || kind == 11) { + return amd64_parse_fail(p, 26, p.position); + } + var value: AsmDirectiveValue; + value.kind = 0; + value.bytes = null; + value.count = 0; + amd64_expr_clear(&value.expression); + if (kind == 2) { + value.kind = 1; + value.bytes = p.packet.tokens[p.position].text.bytes; + value.count = p.packet.tokens[p.position].text.count; + p.position += 1; + } else if (!amd64_parse_expression(p, 1, &value.expression)) { + return false; + } + if (p.packet.mode != 0) { + if (p.result.values >= p.output.value_capacity) { + return amd64_parse_backend(p); + } + p.output.values[p.result.values] = value; + } + p.result.values += 1; + if (amd64_token_kind(p, p.position) != 3) { + break; + } + var comma: u64 = p.position; + p.position += 1; + kind = amd64_token_kind(p, p.position); + if (kind == 18446744073709551615 || kind == 11) { + return amd64_parse_fail(p, 27, comma); + } + } + item.count = p.result.values - item.first; + return amd64_finish_statement(p); +} diff --git a/assembler/amd64/directives_encode.wave b/assembler/amd64/directives_encode.wave new file mode 100644 index 0000000..ba5590c --- /dev/null +++ b/assembler/amd64/directives_encode.wave @@ -0,0 +1,230 @@ +// SPDX-License-Identifier: MPL-2.0 +// Sparse storage and checked data directives share the final section writer. +fun amd_directive_number(w: ptr, node: u64, value: ptr, + output: ptr) -> bool { + if (value.kind != 0) { + return amd_namespace_fail(w.result, 151, 0, 18446744073709551615); + } + return amd_evaluated_expression(w.p, w.p.nodes[node].scope, &value.expression, output, w.result); +} + +fun amd_reservation(w: ptr, node: u64, unit: u64, + output: ptr) -> bool { + var item: ptr = &w.p.items[node]; + if (item.count != 1) { + return amd_namespace_fail(w.result, 152, 0, 18446744073709551615); + } + var value: ptr = &w.p.values[item.first]; + if (value.kind != 0) { + return amd_namespace_fail(w.result, 153, 0, 18446744073709551615); + } + var number: AsmExpr; + if (!amd_evaluated_expression(w.p, w.p.nodes[node].scope, &value.expression, &number, w.result)) { + return false; + } + if (number.kind != 0) { + return amd_namespace_fail(w.result, 154, number.name, 18446744073709551615); + } + if (number.high >= 9223372036854775808) { + return amd_namespace_fail(w.result, 155, 0, 18446744073709551615); + } + if (number.high != 0 || number.low > 18446744073709551615 / unit) { + return amd_namespace_fail(w.result, 156, 0, 18446744073709551615); + } + output[0] = number.low * unit; + return true; +} + +fun amd_directive(w: ptr, node: u64) -> bool { + var alignment: AsmExpr; + var growth: AsmOutputGrowth; + var padded: u64; + var fill: u64; + var value: ptr; + var extra: u64; + var at: u64; + var expression: AsmExpr; + var kind: u64; + var item: ptr = &w.p.items[node]; + var bss: bool = w.p.sections[w.section].kind == 3; + if (amd_word(w.p.names, w.p.name_count, item.name, 474181364833, 5)) { + if (item.count != 1) { + return amd_namespace_fail(w.result, 157, 0, 18446744073709551615); + } + if (w.p.values[item.first].kind != 0) { + return amd_namespace_fail(w.result, 158, 0, 18446744073709551615); + } + + if (!amd_evaluated_expression(w.p, w.p.nodes[node].scope, + &w.p.values[item.first].expression, &alignment, w.result)) { + return false; + } + if (alignment.kind != 0) { + return amd_namespace_fail(w.result, 159, 0, 18446744073709551615); + } + if (alignment.high != 0 || !asm_power_two(alignment.low)) { + return amd_namespace_fail(w.result, 160, 0, 18446744073709551615); + } + + var status: i32 = asm_output_align(w.materialized, w.count, alignment.low, + w.p.max_output, bss as u64, &growth); + if (status == 1) { + return amd_namespace_fail(w.result, 161, 0, 18446744073709551615); + } + if (status != 0) { + return amd_fail(w.result, 2); + } + padded = growth.section; + if (alignment.low > w.p.sections[w.section].align) { + w.p.sections[w.section].align = alignment.low; + } + if (bss) { + w.count = padded; + return true; + } + fill = 0; + if (w.p.sections[w.section].kind == 0) { + fill = 144; + } + return amd_fill(w, padded - w.count, fill); + } + var unit: u64 = 0; + if (amd_word(w.p.names, w.p.name_count, item.name, 1651729778, 4)) { + unit = 1; + } else if (amd_word(w.p.names, w.p.name_count, item.name, 2004051314, 4)) { + unit = 2; + } else if (amd_word(w.p.names, w.p.name_count, item.name, 1685284210, 4)) { + unit = 4; + } else if (amd_word(w.p.names, w.p.name_count, item.name, 1903388018, 4)) { + unit = 8; + } + var size: u64 = 0; + if (unit != 0) { + if (!amd_reservation(w, node, unit, &size)) { + return false; + } + if (bss) { + + if (asm_output_grow(w.materialized, w.count, size, w.p.max_output, 1, &growth) != 0) { + return amd_namespace_fail(w.result, 162, 0, 18446744073709551615); + } + w.count = growth.section; + return true; + } + return amd_fill(w, size, 0); + } + var width: u64 = 0; + if (amd_word(w.p.names, w.p.name_count, item.name, 25188, 2)) { + width = 1; + } else if (amd_word(w.p.names, w.p.name_count, item.name, 30564, 2)) { + width = 2; + } else if (amd_word(w.p.names, w.p.name_count, item.name, 25700, 2)) { + width = 4; + } else if (amd_word(w.p.names, w.p.name_count, item.name, 29028, 2)) { + width = 8; + } else { + return amd_namespace_fail(w.result, 163, item.name, 18446744073709551615); + } + var index: u64 = 0; + while (index < item.count) { + if (!amd_charge(w.p, w.result)) { + return false; + } + value = &w.p.values[item.first + index]; + extra = width; + if (value.kind == 1) { + if (width != 1) { + var error: u64 = 164; + if (width == 4) { + error = 169; + } else if (width == 8) { + error = 170; + } + return amd_namespace_fail(w.result, error, 0, 18446744073709551615); + } + extra = value.count; + } else if (value.kind != 0) { + return amd_fail(w.result, 3); + } + if (extra > 18446744073709551615 - size) { + return amd_namespace_fail(w.result, 165, 0, 18446744073709551615); + } + size += extra; + index += 1; + } + + var status: i32 = asm_output_grow(w.materialized, w.count, size, + w.p.max_output, bss as u64, &growth); + if (status != 0) { + if (bss) { + return amd_namespace_fail(w.result, 162, 0, 18446744073709551615); + } + return amd_fail(w.result, 2); + } + index = 0; + while (index < item.count) { + if (!amd_charge(w.p, w.result)) { + return false; + } + value = &w.p.values[item.first + index]; + if (value.kind == 1) { + at = 0; + while (at < value.count) { + if (!amd_charge(w.p, w.result)) { + return false; + } + if (bss) { + if (value.bytes[at] != 0) { + return amd_namespace_fail(w.result, 166, 0, 18446744073709551615); + } + } else if (!amd_emit(w, value.bytes[at] as u64, 1)) { + return false; + } + at += 1; + } + } else { + + if (!amd_evaluated_expression(w.p, w.p.nodes[node].scope, &value.expression, + &expression, w.result)) { + return false; + } + if (bss) { + if (expression.kind != 0 || expression.low != 0 || expression.high != 0) { + return amd_namespace_fail(w.result, 166, 0, 18446744073709551615); + } + } else if (expression.kind == 0) { + if (!amd_fits(expression.low, expression.high, width * 8, false)) { + var error: u64 = 167; + if (width == 2) { + error = 171; + } else if (width == 4) { + error = 172; + } else if (width == 8) { + error = 173; + } + return amd_namespace_fail(w.result, error, 0, 18446744073709551615); + } + if (!amd_emit(w, expression.low, width)) { + return false; + } + } else { + if (width != 4 && width != 8) { + return amd_namespace_fail(w.result, 168, 0, 18446744073709551615); + } + kind = 0; + if (width == 4) { + kind = 1; + } + if (!amd_relocation(w, expression.name, kind, expression.low, w.count) + || !amd_emit(w, 0, width)) { + return false; + } + } + } + index += 1; + } + if (bss) { + w.count += size; + } + return true; +} diff --git a/assembler/amd64/emit.wave b/assembler/amd64/emit.wave new file mode 100644 index 0000000..9fe69ad --- /dev/null +++ b/assembler/amd64/emit.wave @@ -0,0 +1,178 @@ +// SPDX-License-Identifier: MPL-2.0 +// Bounded byte and relocation emission shared by every instruction family. +fun amd_emit(w: ptr, value: u64, width: u64) -> bool { + var growth: AsmOutputGrowth; + var status: i32 = asm_output_grow(w.materialized, w.count, width, w.p.max_output, 0, &growth); + if (status != 0) { + if (status == 1 || status == 2) { + return amd_fail(w.result, 2); + } + return amd_fail(w.result, 3); + } + if (w.measuring == 0) { + var first: u64 = w.p.sections[w.section].first; + if (first > w.p.byte_capacity || w.count > w.p.byte_capacity - first + || width > w.p.byte_capacity - first - w.count) { + return amd_fail(w.result, 3); + } + var at: u64 = 0; + while (at < width) { + w.p.bytes[first + w.count + at] = (value >> (at * 8)) as u8; + at += 1; + } + } + w.count = growth.section; + w.materialized = growth.materialized; + return true; +} + +fun amd_fill(w: ptr, count: u64, value: u64) -> bool { + var growth: AsmOutputGrowth; + var status: i32 = asm_output_grow(w.materialized, w.count, count, w.p.max_output, 0, &growth); + if (status != 0) { + if (status == 1 || status == 2) { + return amd_fail(w.result, 2); + } + return amd_fail(w.result, 3); + } + if (w.measuring == 0) { + var first: u64 = w.p.sections[w.section].first; + if (first > w.p.byte_capacity || w.count > w.p.byte_capacity - first + || count > w.p.byte_capacity - first - w.count) { + return amd_fail(w.result, 3); + } + var at: u64 = 0; + while (at < count) { + if (!amd_charge(w.p, w.result)) { + return false; + } + w.p.bytes[first + w.count + at] = value as u8; + at += 1; + } + } + w.count = growth.section; + w.materialized = growth.materialized; + return true; +} + +fun amd_relocation(w: ptr, symbol: u64, kind: u64, addend: u64, + offset: u64) -> bool { + if (w.result.relocation_count >= w.p.relocation_capacity) { + return amd_fail(w.result, 3); + } + var at: u64 = w.result.relocation_count; + w.p.relocations[at].section = w.section; + w.p.relocations[at].offset = offset; + w.p.relocations[at].symbol = symbol; + w.p.relocations[at].kind = kind; + w.p.relocations[at].addend = addend; + w.p.relocations[at].node = w.result.node; + w.result.relocation_count += 1; + return true; +} + +fun amd_prefix(w: ptr, width: u64) -> bool { + if (width == 16) { + return amd_emit(w, 102, 1); + } + return true; +} + +fun amd_rex(w: ptr, width: u64, r: u64, x: u64, b: u64, + flags: u64) -> bool { + var bits: u64 = (r << 2) | (x << 1) | b; + if (width == 64) { + bits = bits | 8; + } + if (bits != 0 || (flags & 2) != 0) { + if ((flags & 1) != 0) { + return amd_fail(w.result, 4); + } + return amd_emit(w, 64 | bits, 1); + } + return true; +} + +fun amd_modrm(w: ptr, mode: u64, reg: u64, rm: u64) -> bool { + return amd_emit(w, ((mode & 3) << 6) | ((reg & 7) << 3) | (rm & 7), 1); +} + +fun amd_register_pair(w: ptr, opcode: u64, dst: ptr, + src: ptr) -> bool { + if (dst.kind != 0 || src.kind != 0 || dst.width == 128 || src.width == 128) { + return amd_fail(w.result, 5); + } + if (dst.width != src.width) { + return amd_fail(w.result, 6); + } + return amd_prefix(w, dst.width) + && amd_rex(w, dst.width, (src.code >= 8) as u64, 0, (dst.code >= 8) as u64, + dst.flags | src.flags) + && amd_emit(w, opcode, 1) && amd_modrm(w, 3, src.code, dst.code); +} + +fun amd_memory(w: ptr, opcode: u64, two: u64, reg: ptr, + mem: ptr, width: u64, trailing: u64) -> bool { + var address: AmdAddress; + if (!amd_address(w.p, mem, 64, true, &address, w.result)) { + return false; + } + if (!amd_rex(w, width, (reg.code >= 8) as u64, address.rex_x, address.rex_b, reg.flags)) { + return false; + } + if (two != 0 && !amd_emit(w, 15, 1)) { + return false; + } + if (!amd_emit(w, opcode, 1) || !amd_modrm(w, address.mode, reg.code, address.rm)) { + return false; + } + if (mem.symbol != 18446744073709551615) { + var addend: i64 = mem.disp; + var kind: u64 = 2; + if (mem.mode != 2) { + kind = 3; + var adjustment: u64 = 4 + trailing; + if (addend < (-9223372036854775807 - 1) + (adjustment as i64)) { + return amd_fail(w.result, 7); + } + addend -= adjustment as i64; + } + var at: u64 = w.count; + if (address.sib != 18446744073709551615) { + at += 1; + } + if (!amd_relocation(w, mem.symbol, kind, addend as u64, at)) { + return false; + } + } + if (address.sib != 18446744073709551615 && !amd_emit(w, address.sib, 1)) { + return false; + } + return amd_emit(w, address.displacement, address.width); +} + +fun amd_mem_width(w: ptr, mem: ptr, width: u64) -> bool { + if (mem.memwidth != 18446744073709551615 && mem.memwidth != width) { + return amd_fail(w.result, 8); + } + return true; +} + +fun amd_reg_mem(w: ptr, opcode: u64, two: u64, reg: ptr, + mem: ptr) -> bool { + if (reg.kind != 0 || reg.width == 128 || mem.kind != 4) { + return amd_fail(w.result, 5); + } + return amd_mem_width(w, mem, reg.width) && amd_prefix(w, reg.width) + && amd_memory(w, opcode, two, reg, mem, reg.width, 0); +} + +export(c) fun whale_amd64_bits(op: u64, a: u64, b: u64, c: u64, d: u64) -> u64 { + if (op == 0) { + return ((a & 3) << 6) | ((b & 7) << 3) | (c & 7); + } + if (op == 1) { + return 64 | ((a & 1) << 3) | ((b & 1) << 2) | ((c & 1) << 1) | (d & 1); + } + return ((a & 3) << 6) | ((b & 7) << 3) | (c & 7); +} diff --git a/assembler/amd64/encoder.wave b/assembler/amd64/encoder.wave new file mode 100644 index 0000000..68dc329 --- /dev/null +++ b/assembler/amd64/encoder.wave @@ -0,0 +1,386 @@ +// SPDX-License-Identifier: MPL-2.0 +// Typed AST adaptation and complete integer/scalar-SSE instruction dispatch. +fun amd_operand(p: ptr, scope: u64, raw: ptr, + output: ptr, result: ptr) -> bool { + output.kind = raw.kind; + output.code = 0; + output.width = 0; + output.flags = 0; + output.low = raw.low; + output.high = raw.high; + output.mode = raw.mode; + output.memwidth = raw.width; + output.base = raw.base; + output.index = raw.index; + output.scale = raw.scale; + output.disp = raw.disp as i64; + output.symbol = 18446744073709551615; + if (raw.kind == 0) { + if (!amd_register(p, raw.name, output)) { + return amd_fail(result, 5); + } + } else if (raw.kind == 2 || raw.kind == 3) { + var expression: AsmExpr; + expression.kind = 1; + expression.name = raw.name; + expression.low = raw.low; + expression.high = raw.high; + if (raw.kind == 2) { + expression.low = 0; + expression.high = 0; + } + var resolved: AsmExpr; + if (!amd_expression(p, scope, &expression, &resolved, result)) { + return false; + } + output.low = resolved.low; + output.high = resolved.high; + if (resolved.kind == 0) { + output.kind = 1; + } else { + output.symbol = resolved.name; + } + } else if (raw.kind == 4 && raw.symbol != 18446744073709551615) { + var expression: AsmExpr; + expression.kind = 1; + expression.name = raw.symbol; + expression.low = raw.disp; + expression.high = 0; + if ((raw.disp as i64) < 0) { + expression.high = 18446744073709551615; + } + var resolved: AsmExpr; + if (!amd_expression(p, scope, &expression, &resolved, result)) { + return false; + } + if (resolved.kind == 0) { + if (!amd_signed64(resolved.low, resolved.high)) { + return amd_fail(result, 43); + } + output.disp = resolved.low as i64; + } else { + output.symbol = resolved.name; + } + } else if (raw.kind > 4) { + return amd_fail(result, 3); + } + return true; +} + +fun amd_encode_instruction(w: ptr, node: u64, iteration: u64) -> bool { + var item: AsmItem = w.p.items[node]; + var operation: u64 = amd_mnemonic(w.p, item.name); + if (operation == 255) { + w.result.argument = item.name; + return amd_fail(w.result, 44); + } + var count: u64 = 2; + if ((operation >= 13 && operation <= 16) || (operation >= 26 && operation <= 28)) { + count = 0; + } else if ((operation >= 8 && operation <= 12) || (operation >= 19 && operation <= 22) + || (operation >= 64 && operation <= 95)) { + count = 1; + } + if (operation == 7 && item.count == 3) { + count = 3; + } + if (item.count != count) { + w.result.argument = count; + return amd_fail(w.result, 45); + } + var a: AmdOperand; + var b: AmdOperand; + var c: AmdOperand; + a.kind = 255; + b.kind = 255; + c.kind = 255; + if (count > 0 && !amd_operand(w.p, w.p.nodes[node].scope, + &w.p.operands[item.first], &a, w.result)) { + return false; + } + if (count > 1 && !amd_operand(w.p, w.p.nodes[node].scope, + &w.p.operands[item.first + 1], &b, w.result)) { + return false; + } + if (count > 2 && !amd_operand(w.p, w.p.nodes[node].scope, + &w.p.operands[item.first + 2], &c, w.result)) { + return false; + } + if (operation == 0) { + return amd_mov(w, &a, &b); + } + if (operation >= 1 && operation <= 6) { + var opcode: u64 = 0; + var extension: u64 = 0; + if (operation == 2) { + opcode = 40; + extension = 5; + } else if (operation == 3) { + opcode = 32; + extension = 4; + } else if (operation == 4) { + opcode = 8; + extension = 1; + } else if (operation == 5) { + opcode = 48; + extension = 6; + } else if (operation == 6) { + opcode = 56; + extension = 7; + } + return amd_binary(w, &a, &b, opcode, extension); + } + if (operation == 7) { + return amd_imul(w, &a, &b, &c, count); + } + if (operation == 8 || operation == 9) { + if (operation == 8 && a.kind == 1) { + var tail: u64 = 4; + var opcode: u64 = 104; + if (amd_fits(a.low, a.high, 8, true)) { + tail = 1; + opcode = 106; + } else if (!amd_fits(a.low, a.high, 32, true)) { + return amd_fail(w.result, 46); + } + return amd_emit(w, opcode, 1) && amd_emit(w, a.low, tail); + } + if (a.kind != 0 || (a.width != 16 && a.width != 64)) { + return amd_fail(w.result, 47); + } + var opcode: u64 = 80; + if (operation == 9) { + opcode = 88; + } + return amd_prefix(w, a.width) && amd_rex(w, 0, 0, 0, (a.code >= 8) as u64, 0) + && amd_emit(w, opcode + (a.code & 7), 1); + } + if (operation == 10 || operation == 11 || operation == 12 + || (operation >= 64 && operation <= 79)) { + if ((operation == 10 || operation == 11) && (a.kind == 0 || a.kind == 4)) { + var extension: u64 = 4; + if (operation == 11) { + extension = 2; + } + return amd_group(w, &a, 64, 0, 255, 0, extension); + } + return amd_direct_branch(w, operation, &a, node, iteration); + } + if (operation == 13) { + return amd_emit(w, 195, 1); + } + if (operation == 14) { + return amd_emit(w, 144, 1); + } + if (operation == 15) { + return amd_emit(w, 1295, 2); + } + if (operation == 16) { + return amd_emit(w, 204, 1); + } + if (operation == 17) { + if (a.kind != 0 || (a.width != 32 && a.width != 64) || b.kind != 4) { + return amd_fail(w.result, 48); + } + return amd_reg_mem(w, 141, 0, &a, &b); + } + if (operation == 18 || operation == 32 || operation == 33) { + var opcode: u64 = 132; + if (operation == 32) { + opcode = 16; + } else if (operation == 33) { + opcode = 24; + } + if (a.width != 8) { + opcode += 1; + } + return amd_register_pair(w, opcode, &a, &b); + } + if (operation >= 19 && operation <= 22) { + if (a.kind != 0 || a.width == 128) { + return amd_fail(w.result, 5); + } + var extension: u64 = operation - 17; + if (operation >= 21) { + extension = operation - 15; + } + var opcode: u64 = 247; + if (a.width == 8) { + opcode = 246; + } + return amd_group(w, &a, a.width, a.width, opcode, 0, extension); + } + if (operation >= 23 && operation <= 25) { + return amd_shift(w, operation, &a, &b); + } + if (operation >= 26 && operation <= 28) { + if (operation == 26 && !amd_emit(w, 102, 1)) { + return false; + } + if (operation == 28 && !amd_emit(w, 72, 1)) { + return false; + } + return amd_emit(w, 153, 1); + } + if (operation >= 29 && operation <= 31) { + return amd_extension(w, operation, &a, &b); + } + if (operation >= 34 && operation <= 43) { + return amd_scalar_sse(w, operation, &a, &b); + } + if (operation >= 80 && operation <= 95) { + return amd_group(w, &a, 8, 8, 144 + operation - 80, 1, 0); + } + if (operation >= 96 && operation <= 111) { + if (a.kind != 0 || b.kind != 0 || a.width != b.width + || (a.width != 16 && a.width != 32 && a.width != 64)) { + return amd_fail(w.result, 49); + } + return amd_prefix(w, a.width) + && amd_rex(w, a.width, (a.code >= 8) as u64, 0, (b.code >= 8) as u64, 0) + && amd_emit(w, 15, 1) && amd_emit(w, 64 + operation - 96, 1) + && amd_modrm(w, 3, a.code, b.code); + } + return amd_fail(w.result, 44); +} + +fun amd_result_reset(result: ptr) { + result.status = 0; + result.error = 0; + result.node = 0; + result.previous = 18446744073709551615; + result.argument = 18446744073709551615; + result.section_count = 0; + result.symbol_count = 0; + result.output_symbols = 0; + result.relocation_count = 0; + result.bytes = 0; + result.iterations = 0; + result.work = 0; +} + +fun amd_input_valid(p: ptr, result: ptr) -> bool { + if (p == null || p.item_count == 18446744073709551615 + || p.name_count == 18446744073709551615 + || p.section_capacity < p.item_count + 1 || p.symbol_capacity < p.name_count + 1 + || p.table_capacity < 2 || p.symbol_capacity > p.table_capacity / 2 + || (p.table_capacity & (p.table_capacity - 1)) != 0 + || !asm_span_valid(p.names as ptr, p.name_count, 16) + || !asm_span_valid(p.items as ptr, p.item_count, 80) + || !asm_span_valid(p.operands as ptr, p.operand_count, 88) + || !asm_span_valid(p.values as ptr, p.value_count, 56) + || !asm_span_valid(p.sections as ptr, p.section_capacity, 48) + || !asm_span_valid(p.symbols as ptr, p.symbol_capacity, 184) + || !asm_span_valid(p.table as ptr, p.table_capacity, 8) + || !asm_span_valid(p.nodes as ptr, p.item_count, 64) + || !asm_span_valid(p.queue as ptr, p.symbol_capacity, 8) + || !asm_span_valid(p.relocations as ptr, p.relocation_capacity, 48) + || !asm_span_valid(p.bytes, p.byte_capacity, 1)) { + return amd_fail(result, 3); + } + var index: u64 = 0; + var item: AsmItem; + while (index < p.name_count) { + if (!amd_charge(p, result)) { + return false; + } + if (!asm_span_valid(p.names[index].bytes, p.names[index].count, 1)) { + return amd_fail(result, 3); + } + index += 1; + } + index = 0; + while (index < p.item_count) { + if (!amd_charge(p, result)) { + return false; + } + item = p.items[index]; + if (item.kind > 8 || item.name >= p.name_count) { + return amd_fail(result, 3); + } + if (item.kind == 0 && (item.first > p.operand_count + || item.count > p.operand_count - item.first)) { + return amd_fail(result, 3); + } + if (item.kind == 2 && (item.first > p.value_count || item.count > p.value_count - item.first)) { + return amd_fail(result, 3); + } + index += 1; + } + return true; +} + +export(c) fun whale_amd64_encode(p: ptr, emission: u64, + result: ptr) -> i32 { + if (result == null) { + return 1; + } + if (emission == 0) { + amd_result_reset(result); + } + if (emission > 1 || !amd_input_valid(p, result)) { + amd_fail(result, 3); + return 1; + } + var writer: AmdWriter; + writer.p = p; + writer.result = result; + writer.section = 0; + writer.count = 0; + writer.materialized = 0; + writer.measuring = 1 - emission; + if (!amd_layout(&writer, emission)) { + if (result.status == 0) { + amd_fail(result, 3); + } + return result.status as i32; + } + return 0; +} + +export(c) fun whale_amd64_address(names: ptr, name_count: u64, + raw: ptr, mode: u64, output: ptr, result: ptr) -> i32 { + if (raw == null || output == null || result == null + || !asm_span_valid(names as ptr, name_count, 16)) { + return 1; + } + amd_result_reset(result); + var p: AmdEncodeInput; + p.names = names; + p.name_count = name_count; + var mem: AmdOperand; + mem.mode = raw.mode; + mem.memwidth = raw.width; + mem.base = raw.base; + mem.index = raw.index; + mem.scale = raw.scale; + mem.disp = raw.disp as i64; + mem.symbol = raw.symbol; + var at: u64 = 0; + while (at < name_count) { + if (!asm_span_valid(names[at].bytes, names[at].count, 1)) { + return 1; + } + at += 1; + } + if (!amd_address(&p, &mem, mode, false, output, result)) { + return result.status as i32; + } + return 0; +} + +export(c) fun whale_amd64_condition(name: ptr, output: ptr) -> i32 { + if (name == null || output == null || !asm_span_valid(name.bytes, name.count, 1)) { + return 2; + } + output[0] = 0; + var p: AmdEncodeInput; + p.names = name; + p.name_count = 1; + var operation: u64 = amd_mnemonic(&p, 0); + if (operation >= 64 && operation <= 79) { + output[0] = operation - 64; + return 0; + } + return 1; +} diff --git a/assembler/amd64/encoder_model.wave b/assembler/amd64/encoder_model.wave new file mode 100644 index 0000000..d172934 --- /dev/null +++ b/assembler/amd64/encoder_model.wave @@ -0,0 +1,744 @@ +// SPDX-License-Identifier: MPL-2.0 +// Callback-free, caller-owned encoder transport. Missing indexes use u64::MAX. +struct AmdSection { + name: u64; + kind: u64; + align: u64; + first: u64; + size: u64; + zero_fill: u64; +} + +struct AmdSymbol { + prefix: u64; + name: u64; + flags: u64; + label_site: u64; + extern_site: u64; + global_site: u64; + constant_site: u64; + metadata_site: u64; + section: u64; + offset: u64; + previous_section: u64; + previous_offset: u64; + low: u64; + high: u64; + dependency: u64; + add_low: u64; + add_high: u64; + symbol_kind: u64; + size: u64; + visibility: u64; + order: u64; + users: u64; + next: u64; +} + +struct AmdNode { + scope: u64; + symbol: u64; + section: u64; + offset: u64; + length: u64; + previous_offset: u64; + previous_length: u64; + force_near: u64; +} + +struct AmdRelocation { + section: u64; + offset: u64; + symbol: u64; + kind: u64; + addend: u64; + node: u64; +} + +struct AmdEncodeInput { + names: ptr; + name_count: u64; + items: ptr; + item_count: u64; + operands: ptr; + operand_count: u64; + values: ptr; + value_count: u64; + sections: ptr; + section_capacity: u64; + symbols: ptr; + symbol_capacity: u64; + table: ptr; + table_capacity: u64; + nodes: ptr; + queue: ptr; + relocations: ptr; + relocation_capacity: u64; + bytes: ptr; + byte_capacity: u64; + max_output: u64; + max_iterations: u64; + max_work: u64; +} + +struct AmdEncodeResult { + status: u64; + error: u64; + node: u64; + previous: u64; + argument: u64; + section_count: u64; + symbol_count: u64; + output_symbols: u64; + relocation_count: u64; + bytes: u64; + iterations: u64; + work: u64; +} + +struct AmdWriter { + p: ptr; + result: ptr; + section: u64; + count: u64; + materialized: u64; + measuring: u64; +} + +struct AmdOperand { + kind: u64; + code: u64; + width: u64; + flags: u64; + low: u64; + high: u64; + mode: u64; + memwidth: u64; + base: u64; + index: u64; + scale: u64; + disp: i64; + symbol: u64; +} + +struct AmdAddress { + mode: u64; + rm: u64; + sib: u64; + displacement: u64; + width: u64; + rex_b: u64; + rex_x: u64; +} + +fun amd_fail(result: ptr, error: u64) -> bool { + result.status = 1; + result.error = error; + return false; +} + +fun amd_charge(p: ptr, result: ptr) -> bool { + if (result.work >= p.max_work) { + return amd_fail(result, 1); + } + result.work += 1; + return true; +} + +fun amd_word(names: ptr, count: u64, name: u64, word: u64, length: u64) -> bool { + if (name >= count || names[name].count != length) { + return false; + } + var at: u64 = 0; + while (at < length) { + if (names[name].bytes[at] != ((word >> (at * 8)) & 255) as u8) { + return false; + } + at += 1; + } + return true; +} + +fun amd_fits(low: u64, high: u64, width: u64, signed_only: bool) -> bool { + if (width == 64) { + if (high == 18446744073709551615) { + return (low as i64) < 0; + } + return high == 0 && (!signed_only || low <= 9223372036854775807); + } + if (width != 8 && width != 16 && width != 32) { + return false; + } + var sign: u64 = (1 as u64) << (width - 1); + if (high == 18446744073709551615) { + return (low as i64) >= -(sign as i64) && (low as i64) < 0; + } + var maximum: u64 = (sign << 1) - 1; + if (signed_only) { + maximum = sign - 1; + } + return high == 0 && low <= maximum; +} + +fun amd_signed64(low: u64, high: u64) -> bool { + return (high == 0 && low <= 9223372036854775807) + || (high == 18446744073709551615 && low >= 9223372036854775808); +} + +fun amd_register(p: ptr, name: u64, output: ptr) -> bool { + if (name >= p.name_count) { + return false; + } + var register: Amd64Register; + if (!amd64_register(&p.names[name], 0, ®ister)) { + return false; + } + output.code = register.code; + output.width = register.width; + output.flags = register.high8 | (register.rex8 << 1) | (register.kind << 2); + return true; +} + +fun amd_mnemonic(p: ptr, name: u64) -> u64 { + // mov + if (amd_word(p.names, p.name_count, name, 7761773, 3)) { + return 0; + } + // add + if (amd_word(p.names, p.name_count, name, 6579297, 3)) { + return 1; + } + // sub + if (amd_word(p.names, p.name_count, name, 6452595, 3)) { + return 2; + } + // and + if (amd_word(p.names, p.name_count, name, 6581857, 3)) { + return 3; + } + // or + if (amd_word(p.names, p.name_count, name, 29295, 2)) { + return 4; + } + // xor + if (amd_word(p.names, p.name_count, name, 7499640, 3)) { + return 5; + } + // cmp + if (amd_word(p.names, p.name_count, name, 7368035, 3)) { + return 6; + } + // imul + if (amd_word(p.names, p.name_count, name, 1819635049, 4)) { + return 7; + } + // push + if (amd_word(p.names, p.name_count, name, 1752397168, 4)) { + return 8; + } + // pop + if (amd_word(p.names, p.name_count, name, 7368560, 3)) { + return 9; + } + // jmp + if (amd_word(p.names, p.name_count, name, 7368042, 3)) { + return 10; + } + // call + if (amd_word(p.names, p.name_count, name, 1819042147, 4)) { + return 11; + } + // loop + if (amd_word(p.names, p.name_count, name, 1886351212, 4)) { + return 12; + } + // ret + if (amd_word(p.names, p.name_count, name, 7628146, 3)) { + return 13; + } + // nop + if (amd_word(p.names, p.name_count, name, 7368558, 3)) { + return 14; + } + // syscall + if (amd_word(p.names, p.name_count, name, 30518463020890483, 7)) { + return 15; + } + // int3 + if (amd_word(p.names, p.name_count, name, 863268457, 4)) { + return 16; + } + // lea + if (amd_word(p.names, p.name_count, name, 6382956, 3)) { + return 17; + } + // test + if (amd_word(p.names, p.name_count, name, 1953719668, 4)) { + return 18; + } + // not + if (amd_word(p.names, p.name_count, name, 7630702, 3)) { + return 19; + } + // neg + if (amd_word(p.names, p.name_count, name, 6776174, 3)) { + return 20; + } + // div + if (amd_word(p.names, p.name_count, name, 7760228, 3)) { + return 21; + } + // idiv + if (amd_word(p.names, p.name_count, name, 1986618473, 4)) { + return 22; + } + // shl + if (amd_word(p.names, p.name_count, name, 7104627, 3)) { + return 23; + } + // shr + if (amd_word(p.names, p.name_count, name, 7497843, 3)) { + return 24; + } + // sar + if (amd_word(p.names, p.name_count, name, 7496051, 3)) { + return 25; + } + // cwd + if (amd_word(p.names, p.name_count, name, 6584163, 3)) { + return 26; + } + // cdq + if (amd_word(p.names, p.name_count, name, 7431267, 3)) { + return 27; + } + // cqo + if (amd_word(p.names, p.name_count, name, 7303523, 3)) { + return 28; + } + // movzx + if (amd_word(p.names, p.name_count, name, 517450657645, 5)) { + return 29; + } + // movsx + if (amd_word(p.names, p.name_count, name, 517333217133, 5)) { + return 30; + } + // movsxd + if (amd_word(p.names, p.name_count, name, 110468495994733, 6)) { + return 31; + } + // adc + if (amd_word(p.names, p.name_count, name, 6513761, 3)) { + return 32; + } + // sbb + if (amd_word(p.names, p.name_count, name, 6447731, 3)) { + return 33; + } + // movss + if (amd_word(p.names, p.name_count, name, 495858380653, 5)) { + return 34; + } + // movsd + if (amd_word(p.names, p.name_count, name, 431433871213, 5)) { + return 35; + } + // addss + if (amd_word(p.names, p.name_count, name, 495857198177, 5)) { + return 36; + } + // addsd + if (amd_word(p.names, p.name_count, name, 431432688737, 5)) { + return 37; + } + // subss + if (amd_word(p.names, p.name_count, name, 495857071475, 5)) { + return 38; + } + // subsd + if (amd_word(p.names, p.name_count, name, 431432562035, 5)) { + return 39; + } + // mulss + if (amd_word(p.names, p.name_count, name, 495857726829, 5)) { + return 40; + } + // mulsd + if (amd_word(p.names, p.name_count, name, 431433217389, 5)) { + return 41; + } + // divss + if (amd_word(p.names, p.name_count, name, 495858379108, 5)) { + return 42; + } + // divsd + if (amd_word(p.names, p.name_count, name, 431433869668, 5)) { + return 43; + } + // sal + if (amd_word(p.names, p.name_count, name, 7102835, 3)) { + return 23; + } + // jo + if (amd_word(p.names, p.name_count, name, 28522, 2)) { + return 64; + } + // seto + if (amd_word(p.names, p.name_count, name, 1869899123, 4)) { + return 80; + } + // cmovo + if (amd_word(p.names, p.name_count, name, 478728383843, 5)) { + return 96; + } + // jno + if (amd_word(p.names, p.name_count, name, 7302762, 3)) { + return 65; + } + // setno + if (amd_word(p.names, p.name_count, name, 478594491763, 5)) { + return 81; + } + // cmovno + if (amd_word(p.names, p.name_count, name, 122520224099683, 6)) { + return 97; + } + // jb + if (amd_word(p.names, p.name_count, name, 25194, 2)) { + return 66; + } + // setb + if (amd_word(p.names, p.name_count, name, 1651795315, 4)) { + return 82; + } + // cmovb + if (amd_word(p.names, p.name_count, name, 422893808995, 5)) { + return 98; + } + // jc + if (amd_word(p.names, p.name_count, name, 25450, 2)) { + return 66; + } + // setc + if (amd_word(p.names, p.name_count, name, 1668572531, 4)) { + return 82; + } + // cmovc + if (amd_word(p.names, p.name_count, name, 427188776291, 5)) { + return 98; + } + // jnae + if (amd_word(p.names, p.name_count, name, 1700884074, 4)) { + return 66; + } + // setnae + if (amd_word(p.names, p.name_count, name, 111469139354995, 6)) { + return 82; + } + // cmovnae + if (amd_word(p.names, p.name_count, name, 28536099709087075, 7)) { + return 98; + } + // jae + if (amd_word(p.names, p.name_count, name, 6644074, 3)) { + return 67; + } + // setae + if (amd_word(p.names, p.name_count, name, 435426714995, 5)) { + return 83; + } + // cmovae + if (amd_word(p.names, p.name_count, name, 111469273247075, 6)) { + return 99; + } + // jnb + if (amd_word(p.names, p.name_count, name, 6450794, 3)) { + return 67; + } + // setnb + if (amd_word(p.names, p.name_count, name, 422759916915, 5)) { + return 83; + } + // cmovnb + if (amd_word(p.names, p.name_count, name, 108226572938595, 6)) { + return 99; + } + // jnc + if (amd_word(p.names, p.name_count, name, 6516330, 3)) { + return 67; + } + // setnc + if (amd_word(p.names, p.name_count, name, 427054884211, 5)) { + return 83; + } + // cmovnc + if (amd_word(p.names, p.name_count, name, 109326084566371, 6)) { + return 99; + } + // je + if (amd_word(p.names, p.name_count, name, 25962, 2)) { + return 68; + } + // sete + if (amd_word(p.names, p.name_count, name, 1702126963, 4)) { + return 84; + } + // cmove + if (amd_word(p.names, p.name_count, name, 435778710883, 5)) { + return 100; + } + // jz + if (amd_word(p.names, p.name_count, name, 31338, 2)) { + return 68; + } + // setz + if (amd_word(p.names, p.name_count, name, 2054448499, 4)) { + return 84; + } + // cmovz + if (amd_word(p.names, p.name_count, name, 525973024099, 5)) { + return 100; + } + // jne + if (amd_word(p.names, p.name_count, name, 6647402, 3)) { + return 69; + } + // setne + if (amd_word(p.names, p.name_count, name, 435644818803, 5)) { + return 85; + } + // cmovne + if (amd_word(p.names, p.name_count, name, 111525107821923, 6)) { + return 101; + } + // jnz + if (amd_word(p.names, p.name_count, name, 8023658, 3)) { + return 69; + } + // setnz + if (amd_word(p.names, p.name_count, name, 525839132019, 5)) { + return 85; + } + // cmovnz + if (amd_word(p.names, p.name_count, name, 134614852005219, 6)) { + return 101; + } + // jbe + if (amd_word(p.names, p.name_count, name, 6644330, 3)) { + return 70; + } + // setbe + if (amd_word(p.names, p.name_count, name, 435443492211, 5)) { + return 86; + } + // cmovbe + if (amd_word(p.names, p.name_count, name, 111473568214371, 6)) { + return 102; + } + // jna + if (amd_word(p.names, p.name_count, name, 6385258, 3)) { + return 70; + } + // setna + if (amd_word(p.names, p.name_count, name, 418464949619, 5)) { + return 86; + } + // cmovna + if (amd_word(p.names, p.name_count, name, 107127061310819, 6)) { + return 102; + } + // ja + if (amd_word(p.names, p.name_count, name, 24938, 2)) { + return 71; + } + // seta + if (amd_word(p.names, p.name_count, name, 1635018099, 4)) { + return 87; + } + // cmova + if (amd_word(p.names, p.name_count, name, 418598841699, 5)) { + return 103; + } + // jnbe + if (amd_word(p.names, p.name_count, name, 1700949610, 4)) { + return 71; + } + // setnbe + if (amd_word(p.names, p.name_count, name, 111473434322291, 6)) { + return 87; + } + // cmovnbe + if (amd_word(p.names, p.name_count, name, 28537199220714851, 7)) { + return 103; + } + // js + if (amd_word(p.names, p.name_count, name, 29546, 2)) { + return 72; + } + // sets + if (amd_word(p.names, p.name_count, name, 1937007987, 4)) { + return 88; + } + // cmovs + if (amd_word(p.names, p.name_count, name, 495908253027, 5)) { + return 104; + } + // jns + if (amd_word(p.names, p.name_count, name, 7564906, 3)) { + return 73; + } + // setns + if (amd_word(p.names, p.name_count, name, 495774360947, 5)) { + return 89; + } + // cmovns + if (amd_word(p.names, p.name_count, name, 126918270610787, 6)) { + return 105; + } + // jp + if (amd_word(p.names, p.name_count, name, 28778, 2)) { + return 74; + } + // setp + if (amd_word(p.names, p.name_count, name, 1886676339, 4)) { + return 90; + } + // cmovp + if (amd_word(p.names, p.name_count, name, 483023351139, 5)) { + return 106; + } + // jpe + if (amd_word(p.names, p.name_count, name, 6647914, 3)) { + return 74; + } + // setpe + if (amd_word(p.names, p.name_count, name, 435678373235, 5)) { + return 90; + } + // cmovpe + if (amd_word(p.names, p.name_count, name, 111533697756515, 6)) { + return 106; + } + // jnp + if (amd_word(p.names, p.name_count, name, 7368298, 3)) { + return 75; + } + // setnp + if (amd_word(p.names, p.name_count, name, 482889459059, 5)) { + return 91; + } + // cmovnp + if (amd_word(p.names, p.name_count, name, 123619735727459, 6)) { + return 107; + } + // jpo + if (amd_word(p.names, p.name_count, name, 7303274, 3)) { + return 75; + } + // setpo + if (amd_word(p.names, p.name_count, name, 478628046195, 5)) { + return 91; + } + // cmovpo + if (amd_word(p.names, p.name_count, name, 122528814034275, 6)) { + return 107; + } + // jl + if (amd_word(p.names, p.name_count, name, 27754, 2)) { + return 76; + } + // setl + if (amd_word(p.names, p.name_count, name, 1819567475, 4)) { + return 92; + } + // cmovl + if (amd_word(p.names, p.name_count, name, 465843481955, 5)) { + return 108; + } + // jnge + if (amd_word(p.names, p.name_count, name, 1701277290, 4)) { + return 76; + } + // setnge + if (amd_word(p.names, p.name_count, name, 111494909158771, 6)) { + return 92; + } + // cmovnge + if (amd_word(p.names, p.name_count, name, 28542696778853731, 7)) { + return 108; + } + // jge + if (amd_word(p.names, p.name_count, name, 6645610, 3)) { + return 77; + } + // setge + if (amd_word(p.names, p.name_count, name, 435527378291, 5)) { + return 93; + } + // cmovge + if (amd_word(p.names, p.name_count, name, 111495043050851, 6)) { + return 109; + } + // jnl + if (amd_word(p.names, p.name_count, name, 7106154, 3)) { + return 77; + } + // setnl + if (amd_word(p.names, p.name_count, name, 465709589875, 5)) { + return 93; + } + // cmovnl + if (amd_word(p.names, p.name_count, name, 119221689216355, 6)) { + return 109; + } + // jle + if (amd_word(p.names, p.name_count, name, 6646890, 3)) { + return 78; + } + // setle + if (amd_word(p.names, p.name_count, name, 435611264371, 5)) { + return 94; + } + // cmovle + if (amd_word(p.names, p.name_count, name, 111516517887331, 6)) { + return 110; + } + // jng + if (amd_word(p.names, p.name_count, name, 6778474, 3)) { + return 78; + } + // setng + if (amd_word(p.names, p.name_count, name, 444234753395, 5)) { + return 94; + } + // cmovng + if (amd_word(p.names, p.name_count, name, 113724131077475, 6)) { + return 110; + } + // jg + if (amd_word(p.names, p.name_count, name, 26474, 2)) { + return 79; + } + // setg + if (amd_word(p.names, p.name_count, name, 1735681395, 4)) { + return 95; + } + // cmovg + if (amd_word(p.names, p.name_count, name, 444368645475, 5)) { + return 111; + } + // jnle + if (amd_word(p.names, p.name_count, name, 1701604970, 4)) { + return 79; + } + // setnle + if (amd_word(p.names, p.name_count, name, 111516383995251, 6)) { + return 95; + } + // cmovnle + if (amd_word(p.names, p.name_count, name, 28548194336992611, 7)) { + return 111; + } + return 255; +} diff --git a/assembler/amd64/expressions.wave b/assembler/amd64/expressions.wave new file mode 100644 index 0000000..347d581 --- /dev/null +++ b/assembler/amd64/expressions.wave @@ -0,0 +1,206 @@ +// SPDX-License-Identifier: MPL-2.0 +// Single-symbol, checked signed-128 expressions; no host numeric callbacks. +fun amd64_parse_fail(p: ptr, error: u64, index: u64) -> bool { + p.result.status = 1; + p.result.error = error; + p.result.index = index; + return false; +} + +fun amd64_parse_backend(p: ptr) -> bool { + p.result.status = 2; + p.result.index = p.position; + return false; +} + +fun amd64_parse_charge(p: ptr, count: u64) -> bool { + if (count > p.packet.max_work - p.result.work) { + p.result.status = 3; + p.result.index = p.position; + return false; + } + p.result.work += count; + return true; +} + +fun amd64_token_kind(p: ptr, at: u64) -> u64 { + if (at >= p.packet.count) { + return 18446744073709551615; + } + return p.packet.tokens[at].kind; +} + +fun amd64_token_is(p: ptr, at: u64, key: u64, count: u64) -> bool { + return at < p.packet.count && p.packet.tokens[at].kind == 0 + && amd64_name_is(&p.packet.tokens[at].text, key, count, 1); +} + +fun amd64_parse_name(p: ptr, token: u64, lower: bool, output: ptr) -> bool { + if (token >= p.packet.count || p.packet.tokens[token].kind != 0) { + return amd64_parse_backend(p); + } + var name: AsmName = p.packet.tokens[token].text; + var first: u64 = p.result.bytes; + if (lower) { + if (!amd64_parse_charge(p, name.count) || name.count > 18446744073709551615 - first) { + return false; + } + if (p.packet.mode != 0) { + if (first > p.output.byte_capacity || name.count > p.output.byte_capacity - first) { + return amd64_parse_backend(p); + } + var index: u64 = 0; + while (index < name.count) { + p.output.bytes[first + index] = amd64_lower_byte(name.bytes[index]); + index += 1; + } + name.bytes = &p.output.bytes[first]; + } + p.result.bytes += name.count; + } + output[0] = p.result.names; + if (p.packet.mode != 0) { + if (p.result.names >= p.output.name_capacity) { + return amd64_parse_backend(p); + } + p.output.names[p.result.names] = name; + } + p.result.names += 1; + return true; +} + +fun amd64_expr_clear(expression: ptr) { + expression.kind = 0; + expression.name = 18446744073709551615; + expression.low = 0; + expression.high = 0; +} + +fun amd64_expr_add(p: ptr, left: ptr, right: ptr, at: u64) -> bool { + if (left.kind != 0 && right.kind != 0) { + return amd64_parse_fail(p, 36, at); + } + var a: AsmWide; + var b: AsmWide; + var sum: AsmWide; + a.low = left.low; + a.high = left.high; + b.low = right.low; + b.high = right.high; + if (!asm_number_add_checked(&a, &b, &sum)) { + if (left.kind != 0 || right.kind != 0) { + return amd64_parse_fail(p, 35, at); + } + return amd64_parse_fail(p, 28, at); + } + if (right.kind != 0) { + left.kind = right.kind; + left.name = right.name; + } + left.low = sum.low; + left.high = sum.high; + return true; +} + +// Stop mode0: newline; mode1: comma or newline. +fun amd64_parse_expression(p: ptr, stop: u64, output: ptr) -> bool { + var have: bool = false; + var expect_term: bool = true; + var negative: bool = false; + amd64_expr_clear(output); + while (p.position < p.packet.count) { + var token: ptr = &p.packet.tokens[p.position]; + if (token.kind == 11 || (stop == 1 && token.kind == 3)) { + break; + } + if (!amd64_parse_charge(p, 1)) { + return false; + } + if (expect_term) { + if (token.kind == 7) { + p.position += 1; + } else if (token.kind == 8) { + negative = !negative; + p.position += 1; + } else if (token.kind == 1 || token.kind == 0) { + var term: AsmExpr; + amd64_expr_clear(&term); + if (token.kind == 1) { + term.low = token.low; + term.high = token.high; + if (negative) { + var value: AsmWide; + var negated: AsmWide; + value.low = term.low; + value.high = term.high; + if (!asm_number_neg_checked(&value, &negated)) { + return amd64_parse_fail(p, 28, p.position); + } + term.low = negated.low; + term.high = negated.high; + } + } else { + if (negative) { + return amd64_parse_fail(p, 29, p.position); + } + term.kind = 1; + if (!amd64_parse_name(p, p.position, false, &term.name)) { + return false; + } + } + if (!have) { + output[0] = term; + have = true; + } else if (!amd64_expr_add(p, output, &term, p.position)) { + return false; + } + p.position += 1; + negative = false; + expect_term = false; + } else { + return amd64_parse_fail(p, 30, p.position); + } + } else { + if (token.kind != 7 && token.kind != 8) { + return amd64_parse_fail(p, 31, p.position); + } + negative = token.kind == 8; + expect_term = true; + p.position += 1; + } + } + if (expect_term && have) { + return amd64_parse_fail(p, 32, p.position); + } + if (!have) { + return amd64_parse_fail(p, 33, p.position); + } + if (output.kind == 0) { + var negative_value: bool = (output.high >> 63) != 0; + var valid: bool = output.high == 0; + if (negative_value) { + valid = output.high == 18446744073709551615 && output.low >= 9223372036854775808; + } + if (!valid) { + var at: u64 = p.position; + if (at != 0) { + at -= 1; + } + return amd64_parse_fail(p, 34, at); + } + } + return true; +} + +fun amd64_finish_statement(p: ptr) -> bool { + if (p.position < p.packet.count && amd64_token_kind(p, p.position) != 11) { + return amd64_parse_fail(p, 7, p.position); + } + while (amd64_token_kind(p, p.position) == 11) { + if (!amd64_parse_charge(p, 1)) { + return false; + } + p.position += 1; + } + return true; +} diff --git a/assembler/amd64/integer.wave b/assembler/amd64/integer.wave new file mode 100644 index 0000000..5426b26 --- /dev/null +++ b/assembler/amd64/integer.wave @@ -0,0 +1,306 @@ +// SPDX-License-Identifier: MPL-2.0 +// Integer instruction forms. Register and memory policies are shared helpers. +fun amd_memory_immediate(w: ptr, mem: ptr, imm: ptr, + operation: u64) -> bool { + var width: u64 = mem.memwidth; + if (width == 18446744073709551615) { + return amd_fail(w.result, 19); + } + var encoded_width: u64 = width; + if (width == 64) { + encoded_width = 32; + } + if (!amd_fits(imm.low, imm.high, encoded_width, width == 64)) { + return amd_fail(w.result, 20); + } + var short: bool = operation != 18446744073709551615 && width != 8 + && amd_fits(imm.low, imm.high, 8, true); + var tail: u64 = encoded_width / 8; + var opcode: u64 = 199; + if (operation == 18446744073709551615) { + if (width == 8) { + opcode = 198; + } + operation = 0; + } else { + opcode = 129; + if (width == 8) { + opcode = 128; + } else if (short) { + opcode = 131; + } + } + if (short) { + tail = 1; + } + var group: AmdOperand; + group.code = operation; + group.flags = 0; + return amd_prefix(w, width) && amd_memory(w, opcode, 0, &group, mem, width, tail) + && amd_emit(w, imm.low, tail); +} + +fun amd_mov(w: ptr, a: ptr, b: ptr) -> bool { + if (a.kind == 0 && a.width != 128) { + if (b.kind == 1) { + if (!amd_fits(b.low, b.high, a.width, false)) { + w.result.argument = a.width; + return amd_fail(w.result, 21); + } + var opcode: u64 = 184; + if (a.width == 8) { + opcode = 176; + } + return amd_prefix(w, a.width) + && amd_rex(w, a.width, 0, 0, (a.code >= 8) as u64, a.flags) + && amd_emit(w, opcode + (a.code & 7), 1) && amd_emit(w, b.low, a.width / 8); + } + if (b.kind == 2 || b.kind == 3) { + if (a.width != 32 && a.width != 64) { + return amd_fail(w.result, 22); + } + if (!amd_signed64(b.low, b.high)) { + return amd_fail(w.result, 23); + } + if (!amd_rex(w, a.width, 0, 0, (a.code >= 8) as u64, 0) + || !amd_emit(w, 184 + (a.code & 7), 1)) { + return false; + } + var kind: u64 = 0; + if (a.width == 32) { + kind = 1; + } + return amd_relocation(w, b.symbol, kind, b.low, w.count) + && amd_emit(w, 0, a.width / 8); + } + if (b.kind == 0) { + var opcode: u64 = 137; + if (a.width == 8) { + opcode = 136; + } + return amd_register_pair(w, opcode, a, b); + } + if (b.kind == 4) { + var opcode: u64 = 139; + if (a.width == 8) { + opcode = 138; + } + return amd_reg_mem(w, opcode, 0, a, b); + } + } + if (a.kind == 4 && b.kind == 0) { + var opcode: u64 = 137; + if (b.width == 8) { + opcode = 136; + } + return amd_reg_mem(w, opcode, 0, b, a); + } + if (a.kind == 4 && b.kind == 1) { + return amd_memory_immediate(w, a, b, 18446744073709551615); + } + return amd_fail(w.result, 24); +} + +fun amd_binary(w: ptr, a: ptr, b: ptr, + opcode: u64, extension: u64) -> bool { + if (a.kind == 0 && a.width != 128) { + if (b.kind == 0) { + var selected: u64 = opcode + 1; + if (a.width == 8) { + selected = opcode; + } + return amd_register_pair(w, selected, a, b); + } + if (b.kind == 1) { + var width: u64 = a.width; + var tail: u64 = width / 8; + var selected: u64 = 129; + if (width == 64) { + tail = 4; + } + if (!amd_fits(b.low, b.high, tail * 8, width == 64)) { + w.result.argument = width; + return amd_fail(w.result, 21); + } + if (width == 8) { + selected = 128; + } else if (amd_fits(b.low, b.high, 8, true)) { + selected = 131; + tail = 1; + } + return amd_prefix(w, width) + && amd_rex(w, width, 0, 0, (a.code >= 8) as u64, a.flags) + && amd_emit(w, selected, 1) && amd_modrm(w, 3, extension, a.code) + && amd_emit(w, b.low, tail); + } + if (b.kind == 2 || b.kind == 3) { + return amd_fail(w.result, 25); + } + if (b.kind == 4) { + var selected: u64 = opcode + 3; + if (a.width == 8) { + selected = opcode + 2; + } + return amd_reg_mem(w, selected, 0, a, b); + } + } + if (a.kind == 4 && b.kind == 0) { + var selected: u64 = opcode + 1; + if (b.width == 8) { + selected = opcode; + } + return amd_reg_mem(w, selected, 0, b, a); + } + if (a.kind == 4 && b.kind == 1) { + return amd_memory_immediate(w, a, b, extension); + } + return amd_fail(w.result, 26); +} + +fun amd_group(w: ptr, operand: ptr, width: u64, + rex_width: u64, opcode: u64, two: u64, extension: u64) -> bool { + if (!amd_prefix(w, width)) { + return false; + } + if (operand.kind == 0 && operand.width != 128) { + if (operand.width != width) { + return amd_fail(w.result, 27); + } + if (!amd_rex(w, rex_width, 0, 0, (operand.code >= 8) as u64, operand.flags)) { + return false; + } + if (two != 0 && !amd_emit(w, 15, 1)) { + return false; + } + return amd_emit(w, opcode, 1) && amd_modrm(w, 3, extension, operand.code); + } + if (operand.kind == 4) { + var group: AmdOperand; + group.code = extension; + group.flags = 0; + return amd_mem_width(w, operand, width) + && amd_memory(w, opcode, two, &group, operand, rex_width, 0); + } + return amd_fail(w.result, 28); +} + +fun amd_extension(w: ptr, operation: u64, a: ptr, + b: ptr) -> bool { + if (a.kind != 0 || a.width == 128) { + return amd_fail(w.result, 5); + } + var source_width: u64 = b.width; + if (b.kind == 4) { + source_width = b.memwidth; + if (source_width == 18446744073709551615) { + return amd_fail(w.result, 29); + } + } else if (b.kind != 0 || b.width == 128) { + return amd_fail(w.result, 30); + } + var valid: bool = (source_width == 8 && (a.width == 16 || a.width == 32 || a.width == 64)) + || (source_width == 16 && (a.width == 32 || a.width == 64)); + if (operation == 31) { + valid = a.width == 64 && source_width == 32; + } + if (!valid) { + return amd_fail(w.result, 31); + } + var opcode: u64 = 182; + var two: u64 = 1; + if (source_width == 16) { + opcode += 1; + } + if (operation == 30) { + opcode += 8; + } + if (operation == 31) { + opcode = 99; + two = 0; + } + if (!amd_prefix(w, a.width)) { + return false; + } + if (b.kind == 4) { + return amd_memory(w, opcode, two, a, b, a.width, 0); + } + if (!amd_rex(w, a.width, (a.code >= 8) as u64, 0, (b.code >= 8) as u64, b.flags)) { + return false; + } + if (two != 0 && !amd_emit(w, 15, 1)) { + return false; + } + return amd_emit(w, opcode, 1) && amd_modrm(w, 3, a.code, b.code); +} + +fun amd_imul(w: ptr, a: ptr, b: ptr, + c: ptr, count: u64) -> bool { + if (a.kind != 0 || a.width == 8 || a.width == 128) { + return amd_fail(w.result, 32); + } + if (count == 3) { + if (b.kind != 0 || a.width != b.width || b.width == 128) { + return amd_fail(w.result, 33); + } + if (c.kind != 1) { + return amd_fail(w.result, 34); + } + var tail: u64 = 4; + if (a.width == 16) { + tail = 2; + } + if (!amd_fits(c.low, c.high, tail * 8, a.width == 64)) { + return amd_fail(w.result, 35); + } + var opcode: u64 = 105; + if (amd_fits(c.low, c.high, 8, true)) { + opcode = 107; + tail = 1; + } + return amd_prefix(w, a.width) + && amd_rex(w, a.width, (a.code >= 8) as u64, 0, (b.code >= 8) as u64, 0) + && amd_emit(w, opcode, 1) && amd_modrm(w, 3, a.code, b.code) + && amd_emit(w, c.low, tail); + } + if (b.kind == 4) { + return amd_reg_mem(w, 175, 1, a, b); + } + if (b.kind != 0 || a.width != b.width || b.width == 128) { + return amd_fail(w.result, 6); + } + return amd_prefix(w, a.width) + && amd_rex(w, a.width, (a.code >= 8) as u64, 0, (b.code >= 8) as u64, 0) + && amd_emit(w, 15, 1) && amd_emit(w, 175, 1) && amd_modrm(w, 3, a.code, b.code); +} + +fun amd_shift(w: ptr, operation: u64, a: ptr, + b: ptr) -> bool { + if (a.kind != 0 || a.width == 128) { + return amd_fail(w.result, 5); + } + var opcode: u64 = 208; + var tail: u64 = 0; + if (b.kind == 1 && b.high == 0 && b.low <= 255) { + if (b.low != 1) { + opcode = 192; + tail = 1; + } + } else if (b.kind == 0 && b.code == 1 && b.width == 8 && b.flags == 0) { + opcode = 210; + } else { + return amd_fail(w.result, 36); + } + if (a.width != 8) { + opcode += 1; + } + var extension: u64 = 4; + if (operation == 24) { + extension = 5; + } else if (operation == 25) { + extension = 7; + } + return amd_prefix(w, a.width) + && amd_rex(w, a.width, 0, 0, (a.code >= 8) as u64, a.flags) + && amd_emit(w, opcode, 1) && amd_modrm(w, 3, extension, a.code) + && amd_emit(w, b.low, tail); +} diff --git a/assembler/amd64/layout.wave b/assembler/amd64/layout.wave new file mode 100644 index 0000000..33a9bb6 --- /dev/null +++ b/assembler/amd64/layout.wave @@ -0,0 +1,411 @@ +// SPDX-License-Identifier: MPL-2.0 +// Layout reaches a checked fixed point before publishing grouped section bytes. +fun amd_raw_name_equal(p: ptr, left: u64, right: u64, + result: ptr) -> bool { + if (left == right) { + return true; + } + if (left == 18446744073709551615) { + return amd_word(p.names, p.name_count, right, 500236121134, 5); + } + if (right == 18446744073709551615) { + return amd_word(p.names, p.name_count, left, 500236121134, 5); + } + if (p.names[left].count != p.names[right].count) { + return false; + } + var at: u64 = 0; + while (at < p.names[left].count) { + if (!amd_charge(p, result) || p.names[left].bytes[at] != p.names[right].bytes[at]) { + return false; + } + at += 1; + } + return true; +} + +fun amd_section_kind(p: ptr, name: u64) -> u64 { + if (amd_word(p.names, p.name_count, name, 500236121134, 5)) { + return 0; + } + if (amd_word(p.names, p.name_count, name, 27431034386608686, 7)) { + return 2; + } + if (amd_word(p.names, p.name_count, name, 1936941614, 4)) { + return 3; + } + return 1; +} + +fun amd_section_standard(p: ptr, name: u64) -> bool { + return amd_word(p.names, p.name_count, name, 500236121134, 5) + || amd_word(p.names, p.name_count, name, 418564367406, 5) + || amd_word(p.names, p.name_count, name, 27431034386608686, 7) + || amd_word(p.names, p.name_count, name, 1936941614, 4); +} + +fun amd_select_section(w: ptr, item: ptr) -> bool { + var index: u64 = 0; + while (index < w.result.section_count) { + if (!amd_charge(w.p, w.result)) { + return false; + } + if (amd_raw_name_equal(w.p, item.name, w.p.sections[index].name, w.result)) { + if (item.kind == 5 && item.aux != w.p.sections[index].kind) { + return amd_namespace_fail(w.result, 119, item.name, 18446744073709551615); + } + w.section = index; + return true; + } + if (w.result.status != 0) { + return false; + } + index += 1; + } + if (index >= w.p.section_capacity) { + return amd_fail(w.result, 3); + } + var kind: u64 = amd_section_kind(w.p, item.name); + if (item.kind == 5) { + if (amd_section_standard(w.p, item.name) && kind != item.aux) { + return amd_namespace_fail(w.result, 120, item.name, 18446744073709551615); + } + kind = item.aux; + } + var section: ptr = &w.p.sections[index]; + section.name = item.name; + section.kind = kind; + section.align = 1; + if (kind == 0) { + section.align = 16; + } + section.size = 0; + section.zero_fill = 0; + if (w.measuring != 0) { + section.first = 0; + } + w.result.section_count += 1; + w.section = index; + return true; +} + +fun amd_validate_symbols(w: ptr) -> bool { + var symbol: ptr; + var section: ptr; + var extent: u64; + var relocation: ptr; + var missing: u64 = 18446744073709551615; + var index: u64 = 0; + while (index < w.result.symbol_count) { + if (!amd_charge(w.p, w.result)) { + return false; + } + symbol = &w.p.symbols[index]; + if ((symbol.flags & 1) != 0 && (symbol.flags & 6) == 0) { + if (missing == 18446744073709551615 + || amd_name_compare(w.p, index, missing, w.result) < 0) { + missing = index; + } + } + index += 1; + } + if (w.result.status != 0) { + return false; + } + if (missing != 18446744073709551615) { + w.result.node = w.p.symbols[missing].global_site; + return amd_namespace_fail(w.result, 113, missing, 18446744073709551615); + } + index = 0; + while (index < w.result.symbol_count) { + if (!amd_charge(w.p, w.result)) { + return false; + } + symbol = &w.p.symbols[index]; + if ((symbol.flags & 16) != 0) { + w.result.node = symbol.metadata_site; + if ((symbol.flags & 6) == 0) { + return amd_namespace_fail(w.result, 115, index, 18446744073709551615); + } + if (symbol.section != 18446744073709551615) { + section = &w.p.sections[symbol.section]; + extent = section.size; + if (section.kind == 3) { + extent = section.zero_fill; + } + if (symbol.offset > extent || symbol.size > extent - symbol.offset) { + return amd_namespace_fail(w.result, 118, index, 18446744073709551615); + } + } + } + index += 1; + } + index = 0; + while (index < w.result.relocation_count) { + if (!amd_charge(w.p, w.result)) { + return false; + } + relocation = &w.p.relocations[index]; + if (relocation.symbol >= w.result.symbol_count) { + return amd_fail(w.result, 3); + } + if ((w.p.symbols[relocation.symbol].flags & 6) == 0) { + w.result.node = relocation.node; + return amd_namespace_fail(w.result, 123, relocation.symbol, 18446744073709551615); + } + index += 1; + } + return true; +} + +fun amd_resolve_loops(w: ptr) -> bool { + var relocation: AmdRelocation; + var symbol: ptr; + var displacement: u64; + var section: ptr; + var retained: u64 = 0; + var index: u64 = 0; + while (index < w.result.relocation_count) { + if (!amd_charge(w.p, w.result)) { + return false; + } + relocation = w.p.relocations[index]; + symbol = &w.p.symbols[relocation.symbol]; + if (relocation.kind == 5 && (symbol.flags & 4) != 0 + && symbol.section == relocation.section) { + w.result.node = relocation.node; + displacement = 0; + if (relocation.addend != 18446744073709551615) { + return amd_fail(w.result, 3); + } + if (!amd_relative(symbol.offset, relocation.offset, 1, 8, &displacement)) { + return amd_namespace_fail(w.result, 124, relocation.symbol, 18446744073709551615); + } + if (w.measuring == 0) { + section = &w.p.sections[relocation.section]; + if (relocation.offset >= section.size || section.first >= w.p.byte_capacity + || relocation.offset >= w.p.byte_capacity - section.first) { + return amd_fail(w.result, 3); + } + w.p.bytes[section.first + relocation.offset] = displacement as u8; + } + } else { + w.p.relocations[retained] = relocation; + retained += 1; + } + index += 1; + } + w.result.relocation_count = retained; + return true; +} + +fun amd_layout_pass(w: ptr, iteration: u64) -> bool { + var item: ptr; + var node: ptr; + var id: u64; + var symbol: ptr; + var size: AsmExpr; + var operation: u64; + var index: u64 = 0; + while (index < w.result.symbol_count) { + if (!amd_charge(w.p, w.result)) { + return false; + } + w.p.symbols[index].previous_section = w.p.symbols[index].section; + w.p.symbols[index].previous_offset = w.p.symbols[index].offset; + index += 1; + } + index = 0; + while (index < w.p.item_count) { + w.p.nodes[index].previous_offset = w.p.nodes[index].offset; + w.p.nodes[index].previous_length = w.p.nodes[index].length; + index += 1; + } + w.result.section_count = 1; + w.result.output_symbols = 0; + w.result.relocation_count = 0; + var initial: ptr = &w.p.sections[0]; + initial.name = 18446744073709551615; + initial.kind = 0; + initial.align = 16; + initial.size = 0; + initial.zero_fill = 0; + if (w.measuring != 0) { + initial.first = 0; + } + w.section = 0; + w.count = 0; + w.materialized = 0; + index = 0; + while (index < w.p.item_count) { + if (!amd_charge(w.p, w.result)) { + return false; + } + w.result.node = index; + w.result.previous = 18446744073709551615; + item = &w.p.items[index]; + node = &w.p.nodes[index]; + node.section = w.section; + w.count = w.p.sections[w.section].size; + if (w.p.sections[w.section].kind == 3) { + w.count = w.p.sections[w.section].zero_fill; + } + if (item.kind == 4 || item.kind == 5) { + if (!amd_select_section(w, item)) { + return false; + } + } else if (item.kind == 6 || item.kind == 7 || item.kind == 1 || item.kind == 3) { + id = node.symbol; + if (id == 18446744073709551615) { + id = amd_intern(w.p, node.scope, item.name, w.result); + if (id >= w.p.symbol_capacity) { + return false; + } + node.symbol = id; + } + symbol = &w.p.symbols[id]; + if (item.kind == 6) { + symbol.flags = symbol.flags | 1; + if (symbol.global_site == 18446744073709551615) { + symbol.global_site = index; + } + } else if (item.kind == 7) { + if ((symbol.flags & 4) != 0 && symbol.label_site < index) { + return amd_namespace_fail(w.result, 111, id, symbol.label_site); + } + symbol.flags = symbol.flags | 3; + if (symbol.extern_site == index) { + symbol.order = w.result.output_symbols; + w.result.output_symbols += 1; + } + } else if (item.kind == 3) { + if ((symbol.flags & 2) != 0 && symbol.extern_site < index) { + return amd_namespace_fail(w.result, 112, id, symbol.extern_site); + } + if (symbol.label_site != index) { + return amd_namespace_fail(w.result, 110, id, symbol.label_site); + } + symbol.flags = symbol.flags | 4; + symbol.section = w.section; + symbol.offset = w.count; + symbol.order = w.result.output_symbols; + w.result.output_symbols += 1; + } else { + + if (!amd_evaluated_expression(w.p, node.scope, &item.expression, &size, w.result)) { + return false; + } + if (size.kind != 0) { + return amd_namespace_fail(w.result, 116, id, 18446744073709551615); + } + if (size.high != 0) { + return amd_namespace_fail(w.result, 117, id, 18446744073709551615); + } + if (symbol.metadata_site != 18446744073709551615 && symbol.metadata_site != index) { + return amd_namespace_fail(w.result, 114, id, symbol.metadata_site); + } + symbol.metadata_site = index; + symbol.flags = symbol.flags | 16; + symbol.size = size.low; + symbol.symbol_kind = item.aux; + symbol.visibility = item.flags; + } + } else if (item.kind == 0) { + if (w.p.sections[w.section].kind == 3) { + return amd_namespace_fail(w.result, 121, 0, 18446744073709551615); + } + node.offset = w.count; + if (!amd_encode_instruction(w, index, iteration)) { + return false; + } + node.length = w.count - node.offset; + operation = amd_mnemonic(w.p, item.name); + if (node.previous_length == 2 && node.length > 2 + && (operation == 10 || (operation >= 64 && operation <= 79))) { + node.force_near = 1; + } + } else if (item.kind == 2) { + if (!amd_directive(w, index)) { + return false; + } + } else if (item.kind != 8) { + return amd_fail(w.result, 3); + } + if (item.kind != 4 && item.kind != 5) { + if (w.p.sections[w.section].kind == 3) { + w.p.sections[w.section].zero_fill = w.count; + } else { + w.p.sections[w.section].size = w.count; + } + } + index += 1; + } + w.result.bytes = w.materialized; + return amd_validate_symbols(w); +} + +fun amd_layout(w: ptr, emission: u64) -> bool { + var expected: u64; + var stable: bool; + var index: u64; + var symbol: ptr; + var first: u64; + if (emission == 1) { + expected = w.result.bytes; + if (w.result.iterations == 0 + || !amd_layout_pass(w, w.result.iterations - 1)) { + return false; + } + if (w.result.bytes != expected) { + return amd_fail(w.result, 3); + } + return amd_resolve_loops(w); + } + if (!amd_constants(w.p, w.result)) { + return false; + } + var iteration: u64 = 0; + while (iteration < w.p.max_iterations) { + if (!amd_layout_pass(w, iteration)) { + return false; + } + w.result.iterations = iteration + 1; + stable = iteration != 0; + index = 0; + while (index < w.result.symbol_count) { + if (!amd_charge(w.p, w.result)) { + return false; + } + symbol = &w.p.symbols[index]; + if ((symbol.flags & 4) != 0 && (symbol.section != symbol.previous_section + || symbol.offset != symbol.previous_offset)) { + stable = false; + } + index += 1; + } + index = 0; + while (index < w.p.item_count) { + if (!amd_charge(w.p, w.result)) { + return false; + } + if (w.p.nodes[index].offset != w.p.nodes[index].previous_offset + || w.p.nodes[index].length != w.p.nodes[index].previous_length) { + stable = false; + } + index += 1; + } + if (stable) { + first = 0; + index = 0; + while (index < w.result.section_count) { + w.p.sections[index].first = first; + first += w.p.sections[index].size; + index += 1; + } + return amd_resolve_loops(w); + } + iteration += 1; + } + w.result.node = 18446744073709551615; + return amd_namespace_fail(w.result, 122, w.p.max_iterations, 18446744073709551615); +} diff --git a/assembler/amd64/meson.build b/assembler/amd64/meson.build new file mode 100644 index 0000000..dfb376d --- /dev/null +++ b/assembler/amd64/meson.build @@ -0,0 +1,68 @@ +# SPDX-License-Identifier: MPL-2.0 +wave_amd64_dependencies = [] +wave_amd64_directory = get_option('wave-amd64-dir') +if wave_amd64_directory == '' and wave_source != '' + wave_amd64_directory = meson.current_build_dir() + module_target = cargo_host_target + if module_target == '' + target_os = {'linux': 'unknown-linux-gnu', 'darwin': 'apple-darwin', 'windows': 'pc-windows-msvc'} + module_target = host_machine.cpu_family() + '-' + target_os[host_machine.system()] + endif + archive_name = module_target.contains('msvc') ? 'whale_wave_amd64.lib' : 'libwhale_wave_amd64.a' + arguments = ['--module', 'amd64', '--wave-source', wave_source, '--out-dir', '@OUTDIR@', + '--bootstrap-dir', wave_cache, '--target', module_target, + '--rust-toolchain', get_option('wave-rust-toolchain')] + if get_option('wave-allow-network') + arguments += ['--allow-network'] + endif + wave_amd64_module = custom_target('wave-amd64', + output: [archive_name, 'wave-amd64.meta', 'provenance.json'], + command: [python, files('../../tools/build_wave_assembler.py'), arguments], + depend_files: files( + '../model.wave', + '../declarations.wave', + '../ast_model.wave', + 'parser_model.wave', + 'registers.wave', + 'expressions.wave', + 'operands.wave', + 'directives.wave', + 'parser.wave', + 'encoder_model.wave', + 'namespace.wave', + 'layout.wave', + 'address.wave', + 'emit.wave', + 'integer.wave', + 'sse.wave', + 'branch.wave', + 'directives_encode.wave', + 'encoder.wave', + 'src/ast_model.rs', + 'src/parser_wave.rs', + 'src/encoder_wave.rs', + 'src/encoder_namespace_errors.rs', + 'src/tables.rs', + 'src/encoder.rs', + 'src/encoding/address.rs', + 'src/encoding/modrm.rs', + 'src/encoding/rex.rs', + 'src/encoding/sib.rs', + '../../tools/build_wave_assembler.py', + '../../tools/wave_bootstrap.py', + '../build_support.rs', + ), + depends: wave_bootstrap, console: true) + wave_amd64_dependencies += [wave_amd64_module] +elif wave_amd64_directory != '' + if not fs.is_absolute(wave_amd64_directory) + error('-Dwave-amd64-dir must be absolute.') + endif + archive_name = host_machine.system() == 'windows' ? 'whale_wave_amd64.lib' : 'libwhale_wave_amd64.a' + foreach artifact : [archive_name, 'wave-amd64.meta', 'provenance.json'] + if not fs.is_file(wave_amd64_directory / artifact) + error('Missing Wave amd64 artifact: ' + (wave_amd64_directory / artifact)) + endif + endforeach +endif +wave_assembler_all_dependencies += wave_amd64_dependencies diff --git a/assembler/amd64/namespace.wave b/assembler/amd64/namespace.wave new file mode 100644 index 0000000..d950658 --- /dev/null +++ b/assembler/amd64/namespace.wave @@ -0,0 +1,393 @@ +// SPDX-License-Identifier: MPL-2.0 +// Canonical scoped names and nonrecursive constant dependency evaluation. +fun amd_namespace_fail(result: ptr, error: u64, + argument: u64, previous: u64) -> bool { + result.error = error; + result.argument = argument; + result.previous = previous; + result.status = 1; + return false; +} + +fun amd_name_length(p: ptr, prefix: u64, name: u64) -> u64 { + var count: u64 = p.names[name].count; + if (prefix != 18446744073709551615) { + count += p.names[prefix].count; + } + return count; +} + +fun amd_name_octet(p: ptr, prefix: u64, name: u64, at: u64) -> u8 { + if (prefix != 18446744073709551615) { + if (at < p.names[prefix].count) { + return p.names[prefix].bytes[at]; + } + at -= p.names[prefix].count; + } + return p.names[name].bytes[at]; +} + +fun amd_name_compare(p: ptr, left: u64, right: u64, + result: ptr) -> i32 { + var av: u8; + var bv: u8; + var a: ptr = &p.symbols[left]; + var b: ptr = &p.symbols[right]; + var al: u64 = amd_name_length(p, a.prefix, a.name); + var bl: u64 = amd_name_length(p, b.prefix, b.name); + var at: u64 = 0; + while (at < al && at < bl) { + if (!amd_charge(p, result)) { + return 0; + } + av = amd_name_octet(p, a.prefix, a.name, at); + bv = amd_name_octet(p, b.prefix, b.name, at); + if (av < bv) { + return -1; + } + if (av > bv) { + return 1; + } + at += 1; + } + if (al < bl) { + return -1; + } + if (al > bl) { + return 1; + } + return 0; +} + +fun amd_intern(p: ptr, prefix: u64, name: u64, + result: ptr) -> u64 { + var existing: u64; + var index: u64; + var symbol: ptr; + var equal: bool; + if (name >= p.name_count || (prefix != 18446744073709551615 && prefix >= p.name_count)) { + amd_fail(result, 3); + return p.symbol_capacity; + } + if (p.names[name].count == 0 || p.names[name].bytes[0] != 46) { + prefix = 18446744073709551615; + } else if (prefix == 18446744073709551615) { + amd_namespace_fail(result, 100, name, 18446744073709551615); + return p.symbol_capacity; + } + var length: u64 = amd_name_length(p, prefix, name); + var hash: u64 = 14695981039346656037; + var at: u64 = 0; + while (at < length) { + if (!amd_charge(p, result)) { + return p.symbol_capacity; + } + hash = (hash ^ (amd_name_octet(p, prefix, name, at) as u64)) * 1099511628211; + at += 1; + } + var slot: u64 = hash & (p.table_capacity - 1); + var attempts: u64 = 0; + while (attempts < p.table_capacity) { + if (!amd_charge(p, result)) { + return p.symbol_capacity; + } + existing = p.table[slot]; + if (existing == 18446744073709551615) { + if (result.symbol_count >= p.symbol_capacity) { + amd_fail(result, 3); + return p.symbol_capacity; + } + index = result.symbol_count; + symbol = &p.symbols[index]; + symbol.prefix = prefix; + symbol.name = name; + symbol.flags = 0; + symbol.label_site = 18446744073709551615; + symbol.extern_site = 18446744073709551615; + symbol.global_site = 18446744073709551615; + symbol.constant_site = 18446744073709551615; + symbol.metadata_site = 18446744073709551615; + symbol.section = 18446744073709551615; + symbol.offset = 0; + symbol.previous_section = 18446744073709551615; + symbol.previous_offset = 0; + symbol.low = 0; + symbol.high = 0; + symbol.dependency = 18446744073709551615; + symbol.add_low = 0; + symbol.add_high = 0; + symbol.symbol_kind = 0; + symbol.size = 0; + symbol.visibility = 0; + symbol.order = 18446744073709551615; + symbol.users = 18446744073709551615; + symbol.next = 18446744073709551615; + p.table[slot] = index; + result.symbol_count += 1; + return index; + } + if (existing >= result.symbol_count) { + amd_fail(result, 3); + return p.symbol_capacity; + } + symbol = &p.symbols[existing]; + equal = amd_name_length(p, symbol.prefix, symbol.name) == length; + at = 0; + while (equal && at < length) { + if (!amd_charge(p, result)) { + return p.symbol_capacity; + } + equal = amd_name_octet(p, prefix, name, at) + == amd_name_octet(p, symbol.prefix, symbol.name, at); + at += 1; + } + if (equal) { + return existing; + } + slot = (slot + 1) & (p.table_capacity - 1); + attempts += 1; + } + amd_fail(result, 3); + return p.symbol_capacity; +} + +fun amd_expression_add(a_low: u64, a_high: u64, b_low: u64, b_high: u64, + output: ptr) -> bool { + var a: AsmWide; + var b: AsmWide; + a.low = a_low; + a.high = a_high; + b.low = b_low; + b.high = b_high; + if (!asm_number_add_checked(&a, &b, output)) { + return false; + } + return output.high == 0 || (output.high == 18446744073709551615 + && output.low >= 9223372036854775808); +} + +fun amd_expression(p: ptr, scope: u64, expression: ptr, + output: ptr, result: ptr) -> bool { + var value: AsmWide; + output[0] = expression[0]; + if (expression.kind == 0) { + return true; + } + if (expression.kind != 1) { + return amd_fail(result, 3); + } + var symbol: u64 = amd_intern(p, scope, expression.name, result); + if (symbol >= p.symbol_capacity) { + return false; + } + output.name = symbol; + if ((p.symbols[symbol].flags & 32) != 0) { + + if (!amd_expression_add(p.symbols[symbol].low, p.symbols[symbol].high, + expression.low, expression.high, &value)) { + return amd_namespace_fail(result, 104, symbol, 18446744073709551615); + } + output.kind = 0; + output.low = value.low; + output.high = value.high; + return true; + } + return true; +} + +fun amd_evaluated_expression(p: ptr, scope: u64, + expression: ptr, output: ptr, result: ptr) -> bool { + if (!amd_expression(p, scope, expression, output, result)) { + return false; + } + if (output.kind == 1 && !amd_signed64(output.low, output.high)) { + return amd_namespace_fail(result, 106, output.name, 18446744073709551615); + } + return true; +} + +fun amd_constants(p: ptr, result: ptr) -> bool { + var item: ptr; + var node: ptr; + var symbol: u64; + var entry: ptr; + var previous: u64; + var primary: u64; + var dependency: u64; + var dependency_entry: ptr; + var value: AsmWide; + var user: u64; + result.symbol_count = 0; + var at: u64 = 0; + while (at < p.table_capacity) { + if (!amd_charge(p, result)) { + return false; + } + p.table[at] = 18446744073709551615; + at += 1; + } + var scope: u64 = 18446744073709551615; + var index: u64 = 0; + while (index < p.item_count) { + result.node = index; + result.previous = 18446744073709551615; + if (!amd_charge(p, result)) { + return false; + } + item = &p.items[index]; + node = &p.nodes[index]; + node.scope = scope; + node.symbol = 18446744073709551615; + node.section = 0; + node.offset = 0; + node.length = 0; + node.previous_offset = 0; + node.previous_length = 0; + node.force_near = 0; + if (item.kind == 3 || item.kind == 7 || item.kind == 8) { + symbol = amd_intern(p, scope, item.name, result); + if (symbol >= p.symbol_capacity) { + return false; + } + node.symbol = symbol; + entry = &p.symbols[symbol]; + if (item.kind == 3) { + entry.flags = entry.flags | 128; + if (entry.label_site == 18446744073709551615) { + entry.label_site = index; + } + if (p.names[item.name].count == 0 || p.names[item.name].bytes[0] != 46) { + scope = item.name; + } + } else if (item.kind == 7) { + entry.flags = entry.flags | 256; + if (entry.extern_site == 18446744073709551615) { + entry.extern_site = index; + } + } else { + if ((entry.flags & 8) != 0) { + return amd_namespace_fail(result, 101, symbol, entry.constant_site); + } + entry.flags = entry.flags | 8; + entry.constant_site = index; + entry.low = item.expression.low; + entry.high = item.expression.high; + if (item.expression.kind == 1) { + dependency = amd_intern(p, node.scope, + item.expression.name, result); + if (dependency >= p.symbol_capacity) { + return false; + } + entry.dependency = dependency; + entry.add_low = item.expression.low; + entry.add_high = item.expression.high; + } else if (item.expression.kind != 0) { + return amd_fail(result, 3); + } + } + } + index += 1; + } + index = 0; + while (index < p.item_count) { + item = &p.items[index]; + if (item.kind == 8) { + result.node = index; + symbol = p.nodes[index].symbol; + entry = &p.symbols[symbol]; + if ((entry.flags & 384) != 0) { + previous = entry.label_site; + if (entry.extern_site < previous) { + previous = entry.extern_site; + } + primary = index; + if (previous > index) { + primary = previous; + previous = index; + } + result.node = primary; + return amd_namespace_fail(result, 102, symbol, previous); + } + if (entry.dependency != 18446744073709551615 + && (p.symbols[entry.dependency].flags & 8) == 0) { + return amd_namespace_fail(result, 103, entry.dependency, + 18446744073709551615); + } + } + if (!amd_charge(p, result)) { + return false; + } + index += 1; + } + // Reverse insertion preserves each dependency's source-order user list. + index = p.item_count; + while (index > 0) { + index -= 1; + if (!amd_charge(p, result)) { + return false; + } + if (p.items[index].kind == 8) { + symbol = p.nodes[index].symbol; + dependency = p.symbols[symbol].dependency; + if (dependency != 18446744073709551615) { + p.symbols[symbol].next = p.symbols[dependency].users; + p.symbols[dependency].users = symbol; + } + } + } + var head: u64 = 0; + var tail: u64 = 0; + index = 0; + while (index < p.item_count) { + if (p.items[index].kind == 8) { + symbol = p.nodes[index].symbol; + if (p.symbols[symbol].dependency == 18446744073709551615) { + p.queue[tail] = symbol; + tail += 1; + } + } + index += 1; + } + while (head < tail) { + if (!amd_charge(p, result)) { + return false; + } + symbol = p.queue[head]; + head += 1; + entry = &p.symbols[symbol]; + result.node = entry.constant_site; + if (entry.dependency != 18446744073709551615) { + dependency_entry = &p.symbols[entry.dependency]; + + if (!amd_expression_add(dependency_entry.low, dependency_entry.high, + entry.add_low, entry.add_high, &value)) { + return amd_namespace_fail(result, 104, entry.dependency, + 18446744073709551615); + } + entry.low = value.low; + entry.high = value.high; + } + entry.flags = entry.flags | 32; + user = entry.users; + while (user != 18446744073709551615) { + if (!amd_charge(p, result) || tail >= p.symbol_capacity) { + return false; + } + p.queue[tail] = user; + tail += 1; + user = p.symbols[user].next; + } + } + index = 0; + while (index < p.item_count) { + if (p.items[index].kind == 8) { + symbol = p.nodes[index].symbol; + if ((p.symbols[symbol].flags & 32) == 0) { + result.node = index; + return amd_namespace_fail(result, 105, symbol, 18446744073709551615); + } + } + index += 1; + } + return true; +} diff --git a/assembler/amd64/operands.wave b/assembler/amd64/operands.wave new file mode 100644 index 0000000..6152239 --- /dev/null +++ b/assembler/amd64/operands.wave @@ -0,0 +1,226 @@ +// SPDX-License-Identifier: MPL-2.0 +// Operand grammar keeps register recognition separate from encoding constraints. +fun amd64_operand_clear(operand: ptr) { + operand.kind = 0; + operand.name = 18446744073709551615; + operand.low = 0; + operand.high = 0; + operand.mode = 0; + operand.width = 18446744073709551615; + operand.base = 18446744073709551615; + operand.index = 18446744073709551615; + operand.scale = 1; + operand.disp = 0; + operand.symbol = 18446744073709551615; +} + +fun amd64_memory_width(name: ptr) -> u64 { + // byte, word, dword, qword + if (amd64_name_is(name, 1702132066, 4, 1)) { // byte + return 8; + } + if (amd64_name_is(name, 1685221239, 4, 1)) { // word + return 16; + } + if (amd64_name_is(name, 431416637284, 5, 1)) { // dword + return 32; + } + if (amd64_name_is(name, 431416637297, 5, 1)) { // qword + return 64; + } + return 18446744073709551615; +} + +fun amd64_memory_number(p: ptr, negative: bool, output: ptr) -> bool { + var value: AsmWide; + var signed_value: AsmWide; + var previous: AsmWide; + var sum: AsmWide; + value.low = p.packet.tokens[p.position].low; + value.high = p.packet.tokens[p.position].high; + signed_value = value; + if (negative && !asm_number_neg_checked(&value, &signed_value)) { + return amd64_parse_fail(p, 15, p.position); + } + if (!asm_number_fits_signed(&signed_value, 64)) { + return amd64_parse_fail(p, 15, p.position); + } + previous.low = output.disp; + previous.high = 0; + if ((output.disp >> 63) != 0) { + previous.high = 18446744073709551615; + } + if (!asm_number_add_checked(&previous, &signed_value, &sum) + || !asm_number_fits_signed(&sum, 64)) { + return amd64_parse_fail(p, 15, p.position); + } + output.disp = sum.low; + p.position += 1; + return true; +} + +fun amd64_parse_memory(p: ptr, output: ptr) -> bool { + amd64_operand_clear(output); + output.kind = 4; + p.position += 1; + var token: ptr = null; + if (p.position < p.packet.count) { + token = &p.packet.tokens[p.position]; + } + if (token != null && token.kind == 0 && p.position + 1 < p.packet.count) { + var next: ptr = &p.packet.tokens[p.position + 1]; + var separated: bool = next.position > token.end && next.kind != 6 && next.kind != 11; + // The unseparated forms [rel], [abs+4] retain their symbol meanings. + if (separated && (amd64_name_is(&token.text, 7103858, 3, 1) // rel + || amd64_name_is(&token.text, 7561825, 3, 1))) { // abs + output.mode = 1; + if (amd64_name_is(&token.text, 7561825, 3, 1)) { // abs + output.mode = 2; + } + p.position += 1; + } + } + var negative: bool = false; + if (amd64_token_kind(p, p.position) == 7) { + p.position += 1; + } else if (amd64_token_kind(p, p.position) == 8) { + negative = true; + p.position += 1; + } + while (true) { + if (!amd64_parse_charge(p, 1)) { + return false; + } + var term: u64 = p.position; + var kind: u64 = amd64_token_kind(p, p.position); + if (kind == 18446744073709551615 || kind == 11) { + return amd64_parse_fail(p, 10, p.position); + } + if (kind == 0) { + if (negative) { + return amd64_parse_fail(p, 11, p.position); + } + var register: Amd64Register; + if (amd64_register(&p.packet.tokens[p.position].text, 1, ®ister)) { + var scaled: bool = amd64_token_kind(p, p.position + 1) == 9; + if (output.base == 18446744073709551615 && !scaled) { + if (!amd64_parse_name(p, p.position, true, &output.base)) { + return false; + } + p.position += 1; + } else if (output.index == 18446744073709551615) { + if (!amd64_parse_name(p, p.position, true, &output.index)) { + return false; + } + p.position += 1; + if (amd64_token_kind(p, p.position) == 9) { + p.position += 1; + if (amd64_token_kind(p, p.position) != 1) { + return amd64_parse_fail(p, 12, p.position); + } + var scale: ptr = &p.packet.tokens[p.position]; + if (scale.high != 0 || (scale.low != 1 && scale.low != 2 + && scale.low != 4 && scale.low != 8)) { + return amd64_parse_fail(p, 12, p.position); + } + output.scale = scale.low; + p.position += 1; + } + } else { + return amd64_parse_fail(p, 13, term); + } + } else if (output.symbol == 18446744073709551615) { + if (!amd64_parse_name(p, p.position, false, &output.symbol)) { + return false; + } + p.position += 1; + } else { + return amd64_parse_fail(p, 14, term); + } + } else if (kind == 1) { + if (!amd64_memory_number(p, negative, output)) { + return false; + } + } else { + return amd64_parse_fail(p, 16, p.position); + } + var next: u64 = amd64_token_kind(p, p.position); + if (next == 6) { + p.position += 1; + if (output.mode != 0 && (output.base != 18446744073709551615 + || output.index != 18446744073709551615)) { + return amd64_parse_fail(p, 17, term); + } + return true; + } + if (next == 7 || next == 8) { + negative = next == 8; + p.position += 1; + } else if (next == 18446744073709551615 || next == 11) { + return amd64_parse_fail(p, 10, p.position); + } else { + return amd64_parse_fail(p, 18, p.position); + } + } + return false; +} + +fun amd64_parse_operand(p: ptr, output: ptr) -> bool { + amd64_operand_clear(output); + var kind: u64 = amd64_token_kind(p, p.position); + if (kind == 0) { + var width: u64 = amd64_memory_width(&p.packet.tokens[p.position].text); + if (width != 18446744073709551615) { + p.position += 1; + if (amd64_token_kind(p, p.position) != 5) { + return amd64_parse_fail(p, 9, p.position); + } + if (!amd64_parse_memory(p, output)) { + return false; + } + output.width = width; + return true; + } + } + if (kind == 5) { + return amd64_parse_memory(p, output); + } + if (kind == 0) { + var register: Amd64Register; + var next: u64 = amd64_token_kind(p, p.position + 1); + if (next != 7 && next != 8 + && amd64_register(&p.packet.tokens[p.position].text, 1, ®ister)) { + if (!amd64_parse_name(p, p.position, true, &output.name)) { + return false; + } + p.position += 1; + return true; + } + } + var expression: AsmExpr; + if (!amd64_parse_expression(p, 1, &expression)) { + return false; + } + output.low = expression.low; + output.high = expression.high; + output.kind = 1; + if (expression.kind != 0) { + output.name = expression.name; + output.kind = 3; + if (expression.low == 0 && expression.high == 0) { + output.kind = 2; + } + } + return true; +} + +fun amd64_emit_operand(p: ptr, operand: ptr) -> bool { + if (p.packet.mode != 0) { + if (p.result.operands >= p.output.operand_capacity) { + return amd64_parse_backend(p); + } + p.output.operands[p.result.operands] = operand[0]; + } + p.result.operands += 1; + return true; +} diff --git a/assembler/amd64/parser.wave b/assembler/amd64/parser.wave new file mode 100644 index 0000000..d94a8e0 --- /dev/null +++ b/assembler/amd64/parser.wave @@ -0,0 +1,174 @@ +// SPDX-License-Identifier: MPL-2.0 +// Complete AMD64 statement grammar with caller-owned transactional output. +fun amd64_item_clear(item: ptr) { + item.kind = 0; + item.name = 18446744073709551615; + item.aux = 0; + item.flags = 0; + amd64_expr_clear(&item.expression); + item.first = 0; + item.count = 0; +} + +fun amd64_parse_instruction(p: ptr, item: ptr) -> bool { + var mnemonic: u64 = p.position; + item.kind = 0; + if (!amd64_parse_name(p, mnemonic, true, &item.name)) { + return false; + } + p.position += 1; + if (p.position < p.packet.count && amd64_token_kind(p, p.position) != 11) { + var name: ptr = &p.packet.tokens[mnemonic].text; + if (amd64_name_is(name, 6584163, 3, 1) // cwd + || amd64_name_is(name, 7431267, 3, 1) // cdq + || amd64_name_is(name, 7303523, 3, 1)) { // cqo + p.result.detail = 0; + if (amd64_name_is(name, 7431267, 3, 1)) { // cdq + p.result.detail = 1; + } else if (amd64_name_is(name, 7303523, 3, 1)) { // cqo + p.result.detail = 2; + } + return amd64_parse_fail(p, 5, p.position); + } + } + item.first = p.result.operands; + if (p.position < p.packet.count && amd64_token_kind(p, p.position) != 11) { + while (true) { + var operand: AsmOperand; + if (!amd64_parse_operand(p, &operand) || !amd64_emit_operand(p, &operand)) { + return false; + } + if (amd64_token_kind(p, p.position) != 3) { + break; + } + var comma: u64 = p.position; + p.position += 1; + var next: u64 = amd64_token_kind(p, p.position); + if (next == 18446744073709551615 || next == 11) { + return amd64_parse_fail(p, 8, comma); + } + } + } + item.count = p.result.operands - item.first; + return amd64_finish_statement(p); +} + +fun amd64_parse_constant(p: ptr, item: ptr) -> bool { + item.kind = 8; + if (!amd64_parse_name(p, p.position, false, &item.name)) { + return false; + } + p.position += 2; + if (!amd64_parse_expression(p, 0, &item.expression)) { + return false; + } + while (amd64_token_kind(p, p.position) == 11) { + if (!amd64_parse_charge(p, 1)) { + return false; + } + p.position += 1; + } + return true; +} + +export(c) fun whale_amd64_parse(packet: ptr, output: ptr, + result: ptr) -> i32 { + if (result == null) { + return 2; + } + result.status = 2; + result.error = 0; + result.index = 0; + result.detail = 0; + result.items = 0; + result.operands = 0; + result.values = 0; + result.names = 0; + result.bytes = 0; + result.work = 0; + if (packet == null || output == null || packet.mode > 1 + || !asm_span_valid(packet.tokens as ptr, packet.count, 56)) { + return 2; + } + if (packet.mode != 0 + && (!asm_span_valid(output.items as ptr, output.item_capacity, 80) + || !asm_span_valid(output.spans as ptr, output.span_capacity, 16) + || !asm_span_valid(output.operands as ptr, output.operand_capacity, 88) + || !asm_span_valid(output.values as ptr, output.value_capacity, 56) + || !asm_span_valid(output.names as ptr, output.name_capacity, 16) + || !asm_span_valid(output.bytes, output.byte_capacity, 1))) { + return 2; + } + var parser: AsmParser; + parser.packet = packet; + parser.output = output; + parser.result = result; + parser.position = 0; + result.status = 0; + var index: u64 = 0; + while (index < packet.count) { + var token: ptr = &packet.tokens[index]; + if (!amd64_parse_charge(&parser, 1)) { + return result.status as i32; + } + if (token.kind > 11 || !asm_span_valid(token.text.bytes, token.text.count, 1)) { + result.status = 2; + result.index = index; + return 2; + } + index += 1; + } + while (parser.position < packet.count) { + if (!amd64_parse_charge(&parser, 1)) { + return result.status as i32; + } + var start: u64 = parser.position; + var kind: u64 = amd64_token_kind(&parser, start); + if (kind == 11) { + parser.position += 1; + continue; + } + if (kind != 0) { + amd64_parse_fail(&parser, 2, start); + return 1; + } + var item: AsmItem; + amd64_item_clear(&item); + if (amd64_token_kind(&parser, start + 1) == 4) { + item.kind = 3; + if (!amd64_parse_name(&parser, start, false, &item.name)) { + return result.status as i32; + } + parser.position += 2; + } else if (amd64_token_is(&parser, start + 1, 7696741, 3)) { // equ + if (!amd64_parse_constant(&parser, &item)) { + return result.status as i32; + } + } else if (amd64_directive_tag(&packet.tokens[start].text) != 0) { + if (!amd64_parse_directive(&parser, &item)) { + return result.status as i32; + } + } else if (!amd64_parse_instruction(&parser, &item)) { + return result.status as i32; + } + var end: u64 = parser.position; + while (end > start && packet.tokens[end - 1].kind == 11) { + end -= 1; + } + if (end == start) { + amd64_parse_backend(&parser); + return 2; + } + if (packet.mode != 0) { + if (result.items >= output.item_capacity || result.items >= output.span_capacity) { + amd64_parse_backend(&parser); + return 2; + } + output.items[result.items] = item; + output.spans[result.items].start = start; + output.spans[result.items].end = end; + } + result.items += 1; + } + return 0; +} diff --git a/assembler/amd64/parser_model.wave b/assembler/amd64/parser_model.wave new file mode 100644 index 0000000..acfb3b6 --- /dev/null +++ b/assembler/amd64/parser_model.wave @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: MPL-2.0 +struct AsmParseToken { + kind: u64; + position: u64; + end: u64; + text: AsmName; + low: u64; + high: u64; +} + +struct AsmParseSpan { + start: u64; + end: u64; +} + +struct AsmParseInput { + tokens: ptr; + count: u64; + mode: u64; + max_work: u64; +} + +struct AsmParseOutput { + items: ptr; + item_capacity: u64; + spans: ptr; + span_capacity: u64; + operands: ptr; + operand_capacity: u64; + values: ptr; + value_capacity: u64; + names: ptr; + name_capacity: u64; + bytes: ptr; + byte_capacity: u64; +} + +struct AsmParseResult { + status: u64; + error: u64; + index: u64; + detail: u64; + items: u64; + operands: u64; + values: u64; + names: u64; + bytes: u64; + work: u64; +} + +struct AsmParser { + packet: ptr; + output: ptr; + result: ptr; + position: u64; +} diff --git a/assembler/amd64/registers.wave b/assembler/amd64/registers.wave new file mode 100644 index 0000000..b0f033e --- /dev/null +++ b/assembler/amd64/registers.wave @@ -0,0 +1,589 @@ +// SPDX-License-Identifier: MPL-2.0 +// Register classification is shared by parsing and native encoding. +struct Amd64Register { + kind: u64; + code: u64; + width: u64; + high8: u64; + rex8: u64; +} + +fun amd64_lower_byte(value: u8) -> u8 { + if (value >= 65 && value <= 90) { + return value + 32; + } + return value; +} + +fun amd64_name_is(name: ptr, key: u64, count: u64, fold: u64) -> bool { + if (name.count != count) { + return false; + } + var index: u64 = 0; + while (index < count) { + var value: u8 = name.bytes[index]; + if (fold != 0) { + value = amd64_lower_byte(value); + } + if (value != ((key >> (index * 8)) & 255) as u8) { + return false; + } + index += 1; + } + return true; +} + +fun amd64_register(name: ptr, fold: u64, output: ptr) -> bool { + if (name == null || output == null || fold > 1 || name.count > 8) { + return false; + } + output.kind = 0; + output.high8 = 0; + output.rex8 = 0; + // rax + if (amd64_name_is(name, 7889266, 3, fold)) { + output.code = 0; + output.width = 64; + return true; + } + // rcx + if (amd64_name_is(name, 7889778, 3, fold)) { + output.code = 1; + output.width = 64; + return true; + } + // rdx + if (amd64_name_is(name, 7890034, 3, fold)) { + output.code = 2; + output.width = 64; + return true; + } + // rbx + if (amd64_name_is(name, 7889522, 3, fold)) { + output.code = 3; + output.width = 64; + return true; + } + // rsp + if (amd64_name_is(name, 7369586, 3, fold)) { + output.code = 4; + output.width = 64; + return true; + } + // rbp + if (amd64_name_is(name, 7365234, 3, fold)) { + output.code = 5; + output.width = 64; + return true; + } + // rsi + if (amd64_name_is(name, 6910834, 3, fold)) { + output.code = 6; + output.width = 64; + return true; + } + // rdi + if (amd64_name_is(name, 6906994, 3, fold)) { + output.code = 7; + output.width = 64; + return true; + } + // r8 + if (amd64_name_is(name, 14450, 2, fold)) { + output.code = 8; + output.width = 64; + return true; + } + // r9 + if (amd64_name_is(name, 14706, 2, fold)) { + output.code = 9; + output.width = 64; + return true; + } + // r10 + if (amd64_name_is(name, 3158386, 3, fold)) { + output.code = 10; + output.width = 64; + return true; + } + // r11 + if (amd64_name_is(name, 3223922, 3, fold)) { + output.code = 11; + output.width = 64; + return true; + } + // r12 + if (amd64_name_is(name, 3289458, 3, fold)) { + output.code = 12; + output.width = 64; + return true; + } + // r13 + if (amd64_name_is(name, 3354994, 3, fold)) { + output.code = 13; + output.width = 64; + return true; + } + // r14 + if (amd64_name_is(name, 3420530, 3, fold)) { + output.code = 14; + output.width = 64; + return true; + } + // r15 + if (amd64_name_is(name, 3486066, 3, fold)) { + output.code = 15; + output.width = 64; + return true; + } + // eax + if (amd64_name_is(name, 7889253, 3, fold)) { + output.code = 0; + output.width = 32; + return true; + } + // ecx + if (amd64_name_is(name, 7889765, 3, fold)) { + output.code = 1; + output.width = 32; + return true; + } + // edx + if (amd64_name_is(name, 7890021, 3, fold)) { + output.code = 2; + output.width = 32; + return true; + } + // ebx + if (amd64_name_is(name, 7889509, 3, fold)) { + output.code = 3; + output.width = 32; + return true; + } + // esp + if (amd64_name_is(name, 7369573, 3, fold)) { + output.code = 4; + output.width = 32; + return true; + } + // ebp + if (amd64_name_is(name, 7365221, 3, fold)) { + output.code = 5; + output.width = 32; + return true; + } + // esi + if (amd64_name_is(name, 6910821, 3, fold)) { + output.code = 6; + output.width = 32; + return true; + } + // edi + if (amd64_name_is(name, 6906981, 3, fold)) { + output.code = 7; + output.width = 32; + return true; + } + // r8d + if (amd64_name_is(name, 6568050, 3, fold)) { + output.code = 8; + output.width = 32; + return true; + } + // r9d + if (amd64_name_is(name, 6568306, 3, fold)) { + output.code = 9; + output.width = 32; + return true; + } + // r10d + if (amd64_name_is(name, 1680879986, 4, fold)) { + output.code = 10; + output.width = 32; + return true; + } + // r11d + if (amd64_name_is(name, 1680945522, 4, fold)) { + output.code = 11; + output.width = 32; + return true; + } + // r12d + if (amd64_name_is(name, 1681011058, 4, fold)) { + output.code = 12; + output.width = 32; + return true; + } + // r13d + if (amd64_name_is(name, 1681076594, 4, fold)) { + output.code = 13; + output.width = 32; + return true; + } + // r14d + if (amd64_name_is(name, 1681142130, 4, fold)) { + output.code = 14; + output.width = 32; + return true; + } + // r15d + if (amd64_name_is(name, 1681207666, 4, fold)) { + output.code = 15; + output.width = 32; + return true; + } + // ax + if (amd64_name_is(name, 30817, 2, fold)) { + output.code = 0; + output.width = 16; + return true; + } + // cx + if (amd64_name_is(name, 30819, 2, fold)) { + output.code = 1; + output.width = 16; + return true; + } + // dx + if (amd64_name_is(name, 30820, 2, fold)) { + output.code = 2; + output.width = 16; + return true; + } + // bx + if (amd64_name_is(name, 30818, 2, fold)) { + output.code = 3; + output.width = 16; + return true; + } + // sp + if (amd64_name_is(name, 28787, 2, fold)) { + output.code = 4; + output.width = 16; + return true; + } + // bp + if (amd64_name_is(name, 28770, 2, fold)) { + output.code = 5; + output.width = 16; + return true; + } + // si + if (amd64_name_is(name, 26995, 2, fold)) { + output.code = 6; + output.width = 16; + return true; + } + // di + if (amd64_name_is(name, 26980, 2, fold)) { + output.code = 7; + output.width = 16; + return true; + } + // r8w + if (amd64_name_is(name, 7813234, 3, fold)) { + output.code = 8; + output.width = 16; + return true; + } + // r9w + if (amd64_name_is(name, 7813490, 3, fold)) { + output.code = 9; + output.width = 16; + return true; + } + // r10w + if (amd64_name_is(name, 1999647090, 4, fold)) { + output.code = 10; + output.width = 16; + return true; + } + // r11w + if (amd64_name_is(name, 1999712626, 4, fold)) { + output.code = 11; + output.width = 16; + return true; + } + // r12w + if (amd64_name_is(name, 1999778162, 4, fold)) { + output.code = 12; + output.width = 16; + return true; + } + // r13w + if (amd64_name_is(name, 1999843698, 4, fold)) { + output.code = 13; + output.width = 16; + return true; + } + // r14w + if (amd64_name_is(name, 1999909234, 4, fold)) { + output.code = 14; + output.width = 16; + return true; + } + // r15w + if (amd64_name_is(name, 1999974770, 4, fold)) { + output.code = 15; + output.width = 16; + return true; + } + // spl + if (amd64_name_is(name, 7106675, 3, fold)) { + output.code = 4; + output.width = 8; + output.rex8 = 1; + return true; + } + // bpl + if (amd64_name_is(name, 7106658, 3, fold)) { + output.code = 5; + output.width = 8; + output.rex8 = 1; + return true; + } + // sil + if (amd64_name_is(name, 7104883, 3, fold)) { + output.code = 6; + output.width = 8; + output.rex8 = 1; + return true; + } + // dil + if (amd64_name_is(name, 7104868, 3, fold)) { + output.code = 7; + output.width = 8; + output.rex8 = 1; + return true; + } + // al + if (amd64_name_is(name, 27745, 2, fold)) { + output.code = 0; + output.width = 8; + return true; + } + // cl + if (amd64_name_is(name, 27747, 2, fold)) { + output.code = 1; + output.width = 8; + return true; + } + // dl + if (amd64_name_is(name, 27748, 2, fold)) { + output.code = 2; + output.width = 8; + return true; + } + // bl + if (amd64_name_is(name, 27746, 2, fold)) { + output.code = 3; + output.width = 8; + return true; + } + // ah + if (amd64_name_is(name, 26721, 2, fold)) { + output.code = 4; + output.width = 8; + output.high8 = 1; + return true; + } + // ch + if (amd64_name_is(name, 26723, 2, fold)) { + output.code = 5; + output.width = 8; + output.high8 = 1; + return true; + } + // dh + if (amd64_name_is(name, 26724, 2, fold)) { + output.code = 6; + output.width = 8; + output.high8 = 1; + return true; + } + // bh + if (amd64_name_is(name, 26722, 2, fold)) { + output.code = 7; + output.width = 8; + output.high8 = 1; + return true; + } + // r8b + if (amd64_name_is(name, 6436978, 3, fold)) { + output.code = 8; + output.width = 8; + return true; + } + // r9b + if (amd64_name_is(name, 6437234, 3, fold)) { + output.code = 9; + output.width = 8; + return true; + } + // r10b + if (amd64_name_is(name, 1647325554, 4, fold)) { + output.code = 10; + output.width = 8; + return true; + } + // r11b + if (amd64_name_is(name, 1647391090, 4, fold)) { + output.code = 11; + output.width = 8; + return true; + } + // r12b + if (amd64_name_is(name, 1647456626, 4, fold)) { + output.code = 12; + output.width = 8; + return true; + } + // r13b + if (amd64_name_is(name, 1647522162, 4, fold)) { + output.code = 13; + output.width = 8; + return true; + } + // r14b + if (amd64_name_is(name, 1647587698, 4, fold)) { + output.code = 14; + output.width = 8; + return true; + } + // r15b + if (amd64_name_is(name, 1647653234, 4, fold)) { + output.code = 15; + output.width = 8; + return true; + } + // xmm0 + if (amd64_name_is(name, 812477816, 4, fold)) { + output.code = 0; + output.width = 128; + output.kind = 1; + return true; + } + // xmm1 + if (amd64_name_is(name, 829255032, 4, fold)) { + output.code = 1; + output.width = 128; + output.kind = 1; + return true; + } + // xmm2 + if (amd64_name_is(name, 846032248, 4, fold)) { + output.code = 2; + output.width = 128; + output.kind = 1; + return true; + } + // xmm3 + if (amd64_name_is(name, 862809464, 4, fold)) { + output.code = 3; + output.width = 128; + output.kind = 1; + return true; + } + // xmm4 + if (amd64_name_is(name, 879586680, 4, fold)) { + output.code = 4; + output.width = 128; + output.kind = 1; + return true; + } + // xmm5 + if (amd64_name_is(name, 896363896, 4, fold)) { + output.code = 5; + output.width = 128; + output.kind = 1; + return true; + } + // xmm6 + if (amd64_name_is(name, 913141112, 4, fold)) { + output.code = 6; + output.width = 128; + output.kind = 1; + return true; + } + // xmm7 + if (amd64_name_is(name, 929918328, 4, fold)) { + output.code = 7; + output.width = 128; + output.kind = 1; + return true; + } + // xmm8 + if (amd64_name_is(name, 946695544, 4, fold)) { + output.code = 8; + output.width = 128; + output.kind = 1; + return true; + } + // xmm9 + if (amd64_name_is(name, 963472760, 4, fold)) { + output.code = 9; + output.width = 128; + output.kind = 1; + return true; + } + // xmm10 + if (amd64_name_is(name, 206987685240, 5, fold)) { + output.code = 10; + output.width = 128; + output.kind = 1; + return true; + } + // xmm11 + if (amd64_name_is(name, 211282652536, 5, fold)) { + output.code = 11; + output.width = 128; + output.kind = 1; + return true; + } + // xmm12 + if (amd64_name_is(name, 215577619832, 5, fold)) { + output.code = 12; + output.width = 128; + output.kind = 1; + return true; + } + // xmm13 + if (amd64_name_is(name, 219872587128, 5, fold)) { + output.code = 13; + output.width = 128; + output.kind = 1; + return true; + } + // xmm14 + if (amd64_name_is(name, 224167554424, 5, fold)) { + output.code = 14; + output.width = 128; + output.kind = 1; + return true; + } + // xmm15 + if (amd64_name_is(name, 228462521720, 5, fold)) { + output.code = 15; + output.width = 128; + output.kind = 1; + return true; + } + return false; +} + +export(c) fun whale_amd64_register(name: ptr, fold: u64, + output: ptr) -> i32 { + if (name == null || output == null || fold > 1 + || !asm_span_valid(name.bytes, name.count, 1)) { + return 2; + } + output.kind = 0; + output.code = 0; + output.width = 0; + output.high8 = 0; + output.rex8 = 0; + if (amd64_register(name, fold, output)) { + return 0; + } + return 1; +} diff --git a/assembler/amd64/src/ast_model.rs b/assembler/amd64/src/ast_model.rs new file mode 100644 index 0000000..bd72182 --- /dev/null +++ b/assembler/amd64/src/ast_model.rs @@ -0,0 +1,262 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Structural data packets; instruction and expression policy lives in Wave. +use assembler::ast::*; + +use assembler::{AsmError, SymbolKind, SymbolVisibility}; + +use std::marker::PhantomData; + +pub(crate) const MISSING: u64 = u64::MAX; + +#[repr(C)] +#[derive(Clone, Copy)] +pub(crate) struct Name { + pub(crate) bytes: *const u8, + pub(crate) count: u64, +} + +impl Default for Name { + fn default() -> Self { + Self { bytes: std::ptr::null(), count: 0 } + } +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +pub(crate) struct Expr { + pub(crate) kind: u64, + pub(crate) name: u64, + pub(crate) low: u64, + pub(crate) high: u64, +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +pub(crate) struct OperandRecord { + pub(crate) kind: u64, + pub(crate) name: u64, + pub(crate) low: u64, + pub(crate) high: u64, + pub(crate) mode: u64, + pub(crate) width: u64, + pub(crate) base: u64, + pub(crate) index: u64, + pub(crate) scale: u64, + pub(crate) disp: u64, + pub(crate) symbol: u64, +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +pub(crate) struct Item { + pub(crate) kind: u64, + pub(crate) name: u64, + pub(crate) aux: u64, + pub(crate) flags: u64, + pub(crate) expression: Expr, + pub(crate) first: u64, + pub(crate) count: u64, +} + +#[repr(C)] +#[derive(Clone, Copy)] +pub(crate) struct DirectiveRecord { + pub(crate) kind: u64, + pub(crate) expression: Expr, + pub(crate) bytes: *const u8, + pub(crate) count: u64, +} + +impl Default for DirectiveRecord { + fn default() -> Self { + Self { kind: 0, expression: Expr::default(), bytes: std::ptr::null(), count: 0 } + } +} + +pub(crate) fn transport() -> AsmError { + AsmError::Backend("AMD64 AST transport") +} + +pub(crate) fn push(values: &mut Vec, value: T) -> Result { + values.try_reserve(1).map_err(|_| transport())?; + let index = values.len() as u64; + values.push(value); + Ok(index) +} + +pub(crate) struct Packet<'a> { + pub(crate) names: Vec, + pub(crate) items: Vec, + pub(crate) operands: Vec, + pub(crate) values: Vec, + borrowed: PhantomData<&'a AST>, +} + +impl<'a> Packet<'a> { + pub(crate) fn new() -> Self { + Self { + names: Vec::new(), + items: Vec::new(), + operands: Vec::new(), + values: Vec::new(), + borrowed: PhantomData, + } + } + + fn name(&mut self, bytes: &'a [u8]) -> Result { + push(&mut self.names, Name { bytes: bytes.as_ptr(), count: bytes.len() as u64 }) + } + + fn expression(&mut self, expression: &'a ExprValue) -> Result { + let (kind, name, bits) = match expression { + ExprValue::Number(number) => (0, MISSING, *number as u128), + ExprValue::Symbol { name, addend } => (1, self.name(name.as_bytes())?, *addend as u128), + }; + Ok(Expr { kind, name, low: bits as u64, high: (bits >> 64) as u64 }) + } + + fn operand(&mut self, operand: &'a Operand) -> Result { + let mut raw = OperandRecord { + name: MISSING, + base: MISSING, + index: MISSING, + symbol: MISSING, + width: MISSING, + scale: 1, + ..OperandRecord::default() + }; + match operand { + Operand::Register(name) => { + raw.kind = 0; + raw.name = self.name(name.as_bytes())?; + }, + Operand::Immediate(value) => { + raw.kind = 1; + raw.low = *value as u128 as u64; + raw.high = ((*value as u128) >> 64) as u64; + }, + Operand::Label(name) => { + raw.kind = 2; + raw.name = self.name(name.as_bytes())?; + }, + Operand::SymbolExpr { name, addend } => { + raw.kind = 3; + raw.name = self.name(name.as_bytes())?; + raw.low = *addend as u128 as u64; + raw.high = ((*addend as u128) >> 64) as u64; + }, + Operand::Memory(memory) => { + raw.kind = 4; + raw.mode = match memory.address_mode { + MemoryAddressMode::Default => 0, + MemoryAddressMode::Relative => 1, + MemoryAddressMode::Absolute => 2, + }; + raw.width = memory.width.map_or(MISSING, u64::from); + raw.base = memory + .base + .as_ref() + .map(|name| self.name(name.as_bytes())) + .transpose()? + .unwrap_or(MISSING); + raw.index = memory + .index + .as_ref() + .map(|name| self.name(name.as_bytes())) + .transpose()? + .unwrap_or(MISSING); + raw.symbol = memory + .symbol + .as_ref() + .map(|name| self.name(name.as_bytes())) + .transpose()? + .unwrap_or(MISSING); + raw.scale = u64::from(memory.scale); + raw.disp = memory.disp as u64; + }, + } + Ok(raw) + } + + pub(crate) fn from_ast(ast: &'a AST) -> Result { + let mut packet = Self::new(); + for item in &ast.items { + let mut raw = Item { name: MISSING, ..Item::default() }; + match item { + ASTNode::Instruction(instruction) => { + raw.name = packet.name(instruction.mnemonic.as_bytes())?; + raw.first = packet.operands.len() as u64; + raw.count = instruction.operands.len() as u64; + for operand in &instruction.operands { + let native = packet.operand(operand)?; + push(&mut packet.operands, native)?; + } + }, + ASTNode::SymbolMetadata { name, kind, size, visibility } => { + raw.kind = 1; + raw.name = packet.name(name.as_bytes())?; + raw.aux = match kind { + SymbolKind::NoType => 0, + SymbolKind::Function => 1, + SymbolKind::Object => 2, + }; + raw.flags = match visibility { + SymbolVisibility::Default => 0, + SymbolVisibility::Hidden => 1, + }; + raw.expression = packet.expression(size)?; + }, + ASTNode::Directive(directive) => { + raw.kind = 2; + raw.name = packet.name(directive.name.as_bytes())?; + raw.first = packet.values.len() as u64; + raw.count = directive.values.len() as u64; + for value in &directive.values { + let native = match value { + DirectiveValue::Expr(expression) => DirectiveRecord { + expression: packet.expression(expression)?, + ..DirectiveRecord::default() + }, + DirectiveValue::StringLiteral(bytes) => DirectiveRecord { + kind: 1, + bytes: bytes.as_ptr(), + count: bytes.len() as u64, + ..DirectiveRecord::default() + }, + }; + push(&mut packet.values, native)?; + } + }, + ASTNode::Label(name) + | ASTNode::Section(name) + | ASTNode::Global(name) + | ASTNode::Extern(name) => { + raw.kind = match item { + ASTNode::Label(_) => 3, + ASTNode::Section(_) => 4, + ASTNode::Global(_) => 6, + _ => 7, + }; + raw.name = packet.name(name.as_bytes())?; + }, + ASTNode::SectionAttributes { name, kind } => { + raw.kind = 5; + raw.name = packet.name(name.as_bytes())?; + raw.aux = match kind { + AsmSectionKind::Text => 0, + AsmSectionKind::Data => 1, + AsmSectionKind::ReadOnlyData => 2, + AsmSectionKind::Bss => 3, + }; + }, + ASTNode::Const { name, expr } => { + raw.kind = 8; + raw.name = packet.name(name.as_bytes())?; + raw.expression = packet.expression(expr)?; + }, + } + push(&mut packet.items, raw)?; + } + Ok(packet) + } +} diff --git a/assembler/amd64/src/encoder.rs b/assembler/amd64/src/encoder.rs index 2e66cbe..8a133e1 100644 --- a/assembler/amd64/src/encoder.rs +++ b/assembler/amd64/src/encoder.rs @@ -1,2161 +1,122 @@ -use std::collections::{HashMap, HashSet, VecDeque}; +// SPDX-License-Identifier: MPL-2.0 +//! AMD64 assembly encoding. Product semantics execute in the pinned Wave module. +use assembler::{ast::AST, AsmError, AssemblerOutput, AssemblyLimits}; -use assembler::assembler::{AsmSection, AsmSymbol, AssemblerOutput, RelocKind, Relocation}; +#[cfg(any(test, not(whale_wave_amd64)))] +#[path = "encoder_reference.rs"] +mod reference; -use assembler::ast::*; +#[cfg(whale_wave_amd64)] +#[path = "encoder_wave.rs"] +pub(crate) mod wave; -use assembler::error::AsmError; - -use crate::encoding::{encode_address, DispKind, EncodedAddress, ModRM, REX}; - -use crate::tables::*; - -type LabelLocations = HashMap; - -#[derive(PartialEq, Eq)] -struct EncodingLayout { - labels: LabelLocations, - instruction_lengths: Vec, - instruction_offsets: Vec, -} - -struct EncodingPass { - output: AssemblerOutput, - layout: EncodingLayout, - relocation_sites: HashMap<(usize, usize), usize>, -} - -// Resolve the one-symbol constant dependency graph before encoding any use. -// Worklist traversal avoids recursion and repeated whole-source rescans. -fn resolve_constants(ast: &AST) -> Result, AsmError> { - let mut definitions = Vec::new(); - let mut positions = HashMap::new(); - let mut reserved = HashSet::new(); - let mut scope = None; - let mut constant_sites = HashMap::::new(); - let mut reserved_sites = HashMap::::new(); - for (node_index, node) in ast.items.iter().enumerate() { - match node { - ASTNode::Label(name) => { - let resolved = resolve_symbol_name(name, &scope) - .map_err(|error| ast.error_at(error, node_index, None))?; - reserved_sites.entry(resolved.clone()).or_insert(node_index); - reserved.insert(resolved.clone()); - if !name.starts_with('.') { - scope = Some(resolved); - } - }, - ASTNode::Extern(name) => { - let resolved = resolve_symbol_name(name, &scope) - .map_err(|error| ast.error_at(error, node_index, None))?; - reserved_sites.entry(resolved.clone()).or_insert(node_index); - reserved.insert(resolved); - }, - ASTNode::Const { name, expr } => { - let name = resolve_symbol_name(name, &scope) - .map_err(|error| ast.error_at(error, node_index, None))?; - if positions.insert(name.clone(), definitions.len()).is_some() { - return Err(ast.error_at( - AsmError::SymbolError(format!("Duplicate constant definition '{name}'")), - node_index, - constant_sites.get(&name).copied(), - )); - } - constant_sites.insert(name.clone(), node_index); - definitions.push(( - name, - resolve_expr_symbols(expr, &scope) - .map_err(|error| ast.error_at(error, node_index, None))?, - )); - }, - _ => {}, - } - } - let mut dependents = vec![Vec::new(); definitions.len()]; - let mut ready = VecDeque::new(); - for (position, (name, expr)) in definitions.iter().enumerate() { - if reserved.contains(name) { - let declaration = constant_sites[name]; - let previous = reserved_sites[name]; - return Err(ast.error_at( - AsmError::SymbolError(format!( - "Constant '{name}' conflicts with a label or extern symbol" - )), - declaration.max(previous), - Some(declaration.min(previous)), - )); - } - match expr { - ExprValue::Number(_) => ready.push_back(position), - ExprValue::Symbol { name: dependency, .. } => { - let dependency = positions.get(dependency).ok_or_else(|| { - ast.error_at( - AsmError::SymbolError(format!( - "equ requires a constant expression; unresolved symbol '{dependency}'" - )), - constant_sites[name], - None, - ) - })?; - dependents[*dependency].push(position); - }, - } - } - let mut values = HashMap::new(); - while let Some(position) = ready.pop_front() { - let (name, expr) = &definitions[position]; - let EvaluatedExpr::Number(value) = eval_expr(expr, &values) - .map_err(|error| ast.error_at(error, constant_sites[name], None))? - else { - return Err(ast.error_at( - AsmError::SymbolError(format!("Unresolved constant dependency for '{name}'")), - constant_sites[name], - None, - )); - }; - values.insert(name.clone(), value); - ready.extend(dependents[position].iter().copied()); - } - if let Some((name, _)) = definitions.iter().find(|(name, _)| !values.contains_key(name)) { - return Err(ast.error_at( - AsmError::SymbolError(format!("Constant dependency cycle prevents resolving '{name}'")), - constant_sites[name], - None, - )); - } - Ok(values) -} +#[cfg(whale_wave_amd64)] +#[path = "encoder_namespace_errors.rs"] +mod namespace_errors; pub fn encode(ast: &AST) -> Result { - encode_with_limits(ast, &assembler::AssemblyLimits::default()) + encode_with_limits(ast, &AssemblyLimits::default()) } -pub fn encode_with_limits( - ast: &AST, - limits: &assembler::AssemblyLimits, -) -> Result { - let consts = resolve_constants(ast)?; - let mut prev_label_locs = None; - let mut forced_near = HashSet::new(); - for _ in 0..limits.max_relax_iterations { - let mut pass = - encode_once(ast, prev_label_locs.as_ref(), &consts, limits, &mut forced_near)?; - if prev_label_locs.as_ref() == Some(&pass.layout) { - resolve_loops(ast, &mut pass)?; - return Ok(pass.output); - } - prev_label_locs = Some(pass.layout); - } - Err(AsmError::EncodeError(format!( - "Branch relaxation did not converge within {} passes", - limits.max_relax_iterations - ))) +pub fn encode_with_limits(ast: &AST, limits: &AssemblyLimits) -> Result { + #[cfg(whale_wave_amd64)] + return wave::encode(ast, limits); + #[cfg(not(whale_wave_amd64))] + reference::encode_with_limits(ast, limits) } -fn encode_once( - ast: &AST, - jump_hint_layout: Option<&EncodingLayout>, - consts: &HashMap, - limits: &assembler::AssemblyLimits, - forced_near: &mut HashSet, -) -> Result { - let mut materialized = 0usize; - let mut sections = Vec::new(); - let mut symbols = Vec::new(); - - let mut defined_labels = HashSet::::new(); - let mut label_locs = HashMap::::new(); - let mut jump_known_locs = - jump_hint_layout.map(|layout| layout.labels.clone()).unwrap_or_default(); - let mut instruction_lengths = vec![0; ast.items.len()]; - let mut instruction_offsets = vec![0; ast.items.len()]; - let mut extern_symbols = HashSet::::new(); - let mut global_symbols = HashSet::::new(); - let mut label_sites = HashMap::::new(); - let mut extern_sites = HashMap::::new(); - let mut global_sites = HashMap::::new(); - let mut relocation_sites = HashMap::new(); - let mut symbol_metadata = HashMap::new(); - let mut metadata_sites = HashMap::::new(); - - sections.push(AsmSection { - kind: AsmSectionKind::Text, - align: 16, - name: ".text".to_string(), - data: Vec::new(), - zero_fill: 0, - relocs: Vec::new(), - }); - - let mut current_section_idx = 0usize; - let mut current_nonlocal_label: Option = None; - - for (node_index, node) in ast.items.iter().enumerate() { - let original_section = current_section_idx; - let relocation_start = sections[original_section].relocs.len(); - (|| -> Result<(), AsmError> { - match node { - ASTNode::Section(name) | ASTNode::SectionAttributes { name, .. } => { - let explicit = match node { - ASTNode::SectionAttributes { kind, .. } => Some(*kind), - _ => None, - }; - if let Some(idx) = sections.iter().position(|s| s.name == *name) { - if explicit.is_some_and(|kind| kind != sections[idx].kind) { - return Err(AsmError::EncodeError(format!( - "Incompatible section redeclaration '{name}'" - ))); - } - current_section_idx = idx; - } else { - let default = AsmSectionKind::default_for_name(name); - let kind = explicit.unwrap_or(default); - if matches!(name.as_str(), ".text" | ".data" | ".rodata" | ".bss") - && kind != default - { - return Err(AsmError::EncodeError(format!( - "Standard section '{name}' has incompatible kind" - ))); - } - sections.push(AsmSection { - name: name.clone(), - kind, - align: kind.default_alignment(), - data: Vec::new(), - zero_fill: 0, - relocs: Vec::new(), - }); - current_section_idx = sections.len() - 1; - } - }, - ASTNode::Global(name) => { - let resolved = resolve_symbol_name(name, ¤t_nonlocal_label)?; - global_sites.entry(resolved.clone()).or_insert(node_index); - global_symbols.insert(resolved); - }, - ASTNode::Extern(name) => { - let resolved = resolve_symbol_name(name, ¤t_nonlocal_label)?; - if defined_labels.contains(&resolved) { - return Err(ast.error_at( - AsmError::SymbolError(format!( - "Extern symbol '{}' was already defined in this file", - resolved - )), - node_index, - label_sites.get(&resolved).copied(), - )); - } - extern_sites.entry(resolved.clone()).or_insert(node_index); - if extern_symbols.insert(resolved.clone()) { - symbols.push(AsmSymbol { - kind: assembler::SymbolKind::NoType, - size: 0, - visibility: assembler::SymbolVisibility::Default, - name: resolved, - section_index: None, - offset: 0, - is_global: true, - }); - } - }, - ASTNode::SymbolMetadata { name, kind, size, visibility } => { - let name = resolve_symbol_name(name, ¤t_nonlocal_label)?; - let size = resolve_expr_symbols(size, ¤t_nonlocal_label)?; - let EvaluatedExpr::Number(size) = eval_expr(&size, consts)? else { - return Err(AsmError::SymbolError(format!( - "symbol '{name}' size must be a constant" - ))); - }; - let size = u64::try_from(size).map_err(|_| { - AsmError::SymbolError(format!( - "symbol '{name}' size must be a nonnegative u64" - )) - })?; - if symbol_metadata.insert(name.clone(), (*kind, size, *visibility)).is_some() { - return Err(ast.error_at( - AsmError::SymbolError(format!( - "Duplicate symbol metadata for '{name}'" - )), - node_index, - metadata_sites.get(&name).copied(), - )); - } - metadata_sites.insert(name, node_index); - }, - ASTNode::Const { .. } => {}, - ASTNode::Label(name) => { - let resolved = resolve_symbol_name(name, ¤t_nonlocal_label)?; - if !name.starts_with('.') { - current_nonlocal_label = Some(resolved.clone()); - } - if extern_symbols.contains(&resolved) { - return Err(ast.error_at( - AsmError::SymbolError(format!( - "Label '{}' conflicts with extern declaration", - resolved - )), - node_index, - extern_sites.get(&resolved).copied(), - )); - } - if consts.contains_key(&resolved) { - return Err(AsmError::SymbolError(format!( - "Label '{}' conflicts with constant definition", - resolved - ))); - } - if !defined_labels.insert(resolved.clone()) { - return Err(ast.error_at( - AsmError::SymbolError(format!( - "Duplicate label definition '{}'", - resolved - )), - node_index, - label_sites.get(&resolved).copied(), - )); - } - label_sites.insert(resolved.clone(), node_index); - let section = §ions[current_section_idx]; - let offset = (section.data.len() as u64) - .checked_add(section.zero_fill) - .ok_or_else(|| AsmError::EncodeError("section size overflow".into()))?; - label_locs.insert(resolved.clone(), (current_section_idx, offset)); - jump_known_locs.insert(resolved.clone(), (current_section_idx, offset)); - symbols.push(AsmSymbol { - kind: assembler::SymbolKind::NoType, - size: 0, - visibility: assembler::SymbolVisibility::Default, - name: resolved.clone(), - section_index: Some(current_section_idx), - offset, - is_global: global_symbols.contains(&resolved), - }); - }, - ASTNode::Instruction(ins) => { - let scoped = resolve_instruction_symbols(ins, ¤t_nonlocal_label)?; - let inst = resolve_instruction_consts(&scoped, consts)?; - let sec = &mut sections[current_section_idx]; - if sec.kind == AsmSectionKind::Bss { - return Err(AsmError::EncodeError( - "instructions are not valid in BSS".into(), - )); - } - let cur_off = sec.data.len(); - let mut instruction_bytes = Vec::new(); - let mut instruction_relocs = Vec::new(); - encode_instruction( - &inst, - &mut instruction_bytes, - &mut instruction_relocs, - current_section_idx, - jump_hint_layout - .map(|layout| layout.instruction_offsets[node_index]) - .unwrap_or(cur_off), - jump_hint_layout.map(|layout| &layout.labels).unwrap_or(&jump_known_locs), - BranchRelaxation { - previous_len: jump_hint_layout - .map(|layout| layout.instruction_lengths[node_index]) - .unwrap_or(0), - force_near: forced_near.contains(&node_index), - }, - )?; - // Alignment padding can offset an earlier shrink. Once a short - // branch must grow, keep it near: each branch changes size at most - // twice, so relaxation cannot oscillate around alignment edges. - if jump_hint_layout - .is_some_and(|layout| layout.instruction_lengths[node_index] == 2) - && instruction_bytes.len() > 2 - && (inst.mnemonic == "jmp" || condition_code(&inst.mnemonic).is_some()) - { - forced_near.insert(node_index); - } - instruction_lengths[node_index] = instruction_bytes.len(); - instruction_offsets[node_index] = cur_off; - reserve_output( - &mut sec.data, - instruction_bytes.len(), - &mut materialized, - limits, - )?; - sec.data.extend_from_slice(&instruction_bytes); - for reloc in &mut instruction_relocs { - reloc.offset += cur_off; - } - sec.relocs.extend(instruction_relocs); - }, - ASTNode::Directive(dir) => { - let scoped = resolve_directive_symbols(dir, ¤t_nonlocal_label)?; - let sec = &mut sections[current_section_idx]; - if scoped.name == "align" { - let alignment = alignment_value(&scoped, consts)?; - sec.align = sec.align.max(alignment); - let offset = (sec.data.len() as u64) - .checked_add(sec.zero_fill) - .ok_or_else(|| AsmError::EncodeError("Section size overflow".into()))?; - let padding = offset.wrapping_neg() & (alignment - 1); - offset.checked_add(padding).ok_or_else(|| { - AsmError::EncodeError("Alignment size overflow".into()) - })?; - if sec.kind == AsmSectionKind::Bss { - sec.zero_fill = - sec.zero_fill.checked_add(padding).ok_or_else(|| { - AsmError::EncodeError("BSS alignment overflow".into()) - })?; - } else { - let extra = usize::try_from(padding).map_err(|_| { - AsmError::EncodeError("Alignment exceeds host capacity".into()) - })?; - reserve_output(&mut sec.data, extra, &mut materialized, limits)?; - let fill = if sec.kind == AsmSectionKind::Text { 0x90 } else { 0 }; - sec.data.resize(sec.data.len() + extra, fill); - } - } else if sec.kind == AsmSectionKind::Bss { - encode_bss_directive(&scoped, sec, consts)?; - } else { - let extra = directive_size(&scoped, consts)?; - reserve_output(&mut sec.data, extra, &mut materialized, limits)?; - encode_directive(&scoped, &mut sec.data, &mut sec.relocs, consts)?; - } - }, - } - Ok(()) - })() - .map_err(|error| ast.error_at(error, node_index, None))?; - for relocation in relocation_start..sections[original_section].relocs.len() { - relocation_sites.insert((original_section, relocation), node_index); - } - } - - // `global` plus `extern` intentionally exports an undefined external; - // an ordinary global must have a label definition in this file. - if let Some(name) = global_symbols - .iter() - .filter(|name| !defined_labels.contains(*name) && !extern_symbols.contains(*name)) - .min() - { - return Err(ast.error_at( - AsmError::SymbolError(format!( - "Global symbol '{name}' has no definition or extern declaration" - )), - global_sites[name], - None, - )); - } +#[cfg(all(test, whale_wave_amd64))] +mod tests { + use super::*; - let symbol_names: HashSet<_> = symbols.iter().map(|s| &s.name).collect(); - for name in symbol_metadata.keys() { - if !symbol_names.contains(name) { - return Err(ast.error_at( - AsmError::SymbolError(format!( - "Metadata symbol '{name}' has no label or extern declaration" - )), - metadata_sites[name], - None, + fn snapshot(output: AssemblerOutput) -> String { + let mut value = String::new(); + for section in output.sections { + value.push_str(&format!( + "{:?}|{}|{}|{}|{:?}|", + section.kind, section.name, section.align, section.zero_fill, section.data )); - } - } - for sym in &mut symbols { - if let Some((kind, size, visibility)) = symbol_metadata.get(&sym.name) { - sym.kind = *kind; - sym.size = *size; - sym.visibility = *visibility; - if let Some(index) = sym.section_index { - let section = §ions[index]; - let extent = (section.data.len() as u64) - .checked_add(section.zero_fill) - .ok_or_else(|| AsmError::SymbolError("symbol section size overflow".into()))?; - if sym.offset.checked_add(*size).is_none_or(|end| end > extent) { - return Err(ast.error_at( - AsmError::SymbolError(format!( - "Symbol '{}' size exceeds its section", - sym.name - )), - metadata_sites[&sym.name], - None, - )); - } - } - } - if global_symbols.contains(&sym.name) { - sym.is_global = true; - } - } - - for (section_index, sec) in sections.iter().enumerate() { - for (relocation_index, reloc) in sec.relocs.iter().enumerate() { - if !defined_labels.contains(&reloc.symbol) && !extern_symbols.contains(&reloc.symbol) { - return Err(ast.error_at(AsmError::SymbolError(format!("Undefined symbol '{}' (define it, declare with extern, or define with equ)",reloc.symbol)),relocation_sites[&(section_index,relocation_index)],None)); - } - } - } - - Ok(EncodingPass { - output: AssemblerOutput { sections, symbols }, - layout: EncodingLayout { labels: label_locs, instruction_lengths, instruction_offsets }, - relocation_sites, - }) -} - -// LOOP has a fixed length, so its displacement cannot affect relaxation. Resolve -// local PC8 fields only after the whole layout stabilizes; an intermediate near -// JMP/Jcc or alignment change must not trigger a premature range diagnostic. -fn resolve_loops(ast: &AST, pass: &mut EncodingPass) -> Result<(), AsmError> { - for (section_index, section) in pass.output.sections.iter_mut().enumerate() { - let mut retained = 0; - for index in 0..section.relocs.len() { - let relocation = §ion.relocs[index]; - let target = pass.layout.labels.get(&relocation.symbol); - if let Some((_, target_offset)) = target.filter(|(target_section, _)| { - matches!(relocation.kind, RelocKind::Relative8) && *target_section == section_index - }) { - let displacement = i128::from(*target_offset) - relocation.offset as i128 - + i128::from(relocation.addend); - let displacement = i8::try_from(displacement).map_err(|_| { - ast.error_at( - AsmError::EncodeError(format!( - "loop target '{}' is out of 8-bit range", - relocation.symbol - )), - pass.relocation_sites[&(section_index, index)], - None, - ) - })?; - section.data[relocation.offset] = displacement as u8; - } else { - section.relocs.swap(retained, index); - retained += 1; - } - } - section.relocs.truncate(retained); - } - Ok(()) -} - -#[derive(Clone)] -struct RegInfo { - code: u8, - width: u8, - high8: bool, - rex8: bool, -} - -#[derive(Clone)] -enum EvaluatedExpr { - Number(i128), - Symbol { name: String, addend: i64 }, -} - -fn resolve_symbol_name( - raw: &str, - current_nonlocal_label: &Option, -) -> Result { - if raw.starts_with('.') { - if let Some(base) = current_nonlocal_label { - return Ok(format!("{}{}", base, raw)); - } - return Err(AsmError::SymbolError(format!( - "Local label '{}' has no parent non-local label in scope", - raw - ))); - } - Ok(raw.to_string()) -} - -fn resolve_expr_symbols( - expr: &ExprValue, - current_nonlocal_label: &Option, -) -> Result { - match expr { - ExprValue::Number(n) => Ok(ExprValue::Number(*n)), - ExprValue::Symbol { name, addend } => Ok(ExprValue::Symbol { - name: resolve_symbol_name(name, current_nonlocal_label)?, - addend: *addend, - }), - } -} - -fn eval_expr(expr: &ExprValue, consts: &HashMap) -> Result { - Ok(match expr { - ExprValue::Number(n) => EvaluatedExpr::Number(*n), - ExprValue::Symbol { name, addend } => { - if let Some(c) = consts.get(name) { - EvaluatedExpr::Number(checked_expression_add(*c, *addend, name)?) - } else { - EvaluatedExpr::Symbol { - name: name.clone(), - addend: i64::try_from(*addend) - .map_err(|_| AsmError::EncodeError("Symbol addend overflow".into()))?, - } + for relocation in section.relocs { + value.push_str(&format!( + "{}|{}|{:?}|{}|", + relocation.offset, relocation.symbol, relocation.kind, relocation.addend + )); } - }, - }) -} - -fn checked_expression_add(a: i128, b: i128, symbol: &str) -> Result { - a.checked_add(b).filter(|n| (i64::MIN as i128..=u64::MAX as i128).contains(n)).ok_or_else( - || AsmError::EncodeError(format!("Signed expression overflow while resolving {symbol:?}")), - ) -} - -fn relative_addend(displacement: i64) -> Result { - displacement - .checked_sub(4) - .ok_or_else(|| AsmError::EncodeError("Relative relocation addend overflow".into())) -} - -fn resolve_instruction_symbols( - ins: &Instruction, - current_nonlocal_label: &Option, -) -> Result { - let mut resolved_ops = Vec::with_capacity(ins.operands.len()); - for op in &ins.operands { - match op { - Operand::Label(sym) => { - resolved_ops.push(Operand::Label(resolve_symbol_name(sym, current_nonlocal_label)?)) - }, - Operand::SymbolExpr { name, addend } => { - resolved_ops.push(Operand::SymbolExpr { - name: resolve_symbol_name(name, current_nonlocal_label)?, - addend: *addend, - }); - }, - Operand::Memory(mem) => { - let mut mem = mem.clone(); - if let Some(sym) = &mem.symbol { - mem.symbol = Some(resolve_symbol_name(sym, current_nonlocal_label)?); - } - resolved_ops.push(Operand::Memory(mem)); - }, - _ => resolved_ops.push(op.clone()), - } - } - Ok(Instruction { mnemonic: ins.mnemonic.clone(), operands: resolved_ops }) -} - -fn resolve_instruction_consts( - ins: &Instruction, - consts: &HashMap, -) -> Result { - let mut resolved_ops = Vec::with_capacity(ins.operands.len()); - for op in &ins.operands { - match op { - Operand::Label(name) => { - if let Some(v) = consts.get(name) { - resolved_ops.push(Operand::Immediate(*v)); - } else { - resolved_ops.push(op.clone()); - } - }, - Operand::SymbolExpr { name, addend } => { - if let Some(v) = consts.get(name) { - resolved_ops - .push(Operand::Immediate(checked_expression_add(*v, *addend, name)?)); - } else { - resolved_ops.push(op.clone()); - } - }, - Operand::Memory(mem) => { - let mut mem = mem.clone(); - if let Some(sym) = &mem.symbol { - if let Some(v) = consts.get(sym) { - mem.disp = - i64::try_from(checked_expression_add(*v, mem.disp as i128, sym)?) - .map_err(|_| { - AsmError::EncodeError("Memory displacement overflow".into()) - })?; - mem.symbol = None; - } - } - resolved_ops.push(Operand::Memory(mem)); - }, - _ => resolved_ops.push(op.clone()), - } - } - Ok(Instruction { mnemonic: ins.mnemonic.clone(), operands: resolved_ops }) -} - -fn resolve_directive_symbols( - dir: &Directive, - current_nonlocal_label: &Option, -) -> Result { - let mut out_values = Vec::with_capacity(dir.values.len()); - for v in &dir.values { - match v { - DirectiveValue::StringLiteral(s) => { - out_values.push(DirectiveValue::StringLiteral(s.clone())) - }, - DirectiveValue::Expr(expr) => out_values - .push(DirectiveValue::Expr(resolve_expr_symbols(expr, current_nonlocal_label)?)), - } - } - Ok(Directive { name: dir.name.clone(), values: out_values }) -} - -fn lookup_reg(name: &str) -> Option { - if let Some((_, code)) = REGISTERS_64.iter().find(|(n, _)| *n == name) { - return Some(RegInfo { code: *code, width: 64, high8: false, rex8: false }); - } - if let Some((_, code)) = REGISTERS_32.iter().find(|(n, _)| *n == name) { - return Some(RegInfo { code: *code, width: 32, high8: false, rex8: false }); - } - if let Some((_, code)) = REGISTERS_16.iter().find(|(n, _)| *n == name) { - return Some(RegInfo { code: *code, width: 16, high8: false, rex8: false }); - } - if let Some((reg, code)) = REGISTERS_8.iter().find(|(n, _)| *n == name) { - return Some(RegInfo { - code: *code, - width: 8, - high8: matches!(*reg, "ah" | "bh" | "ch" | "dh"), - rex8: matches!(*reg, "spl" | "bpl" | "sil" | "dil"), - }); - } - None -} - -fn emit_operand_size_prefix(bytes: &mut Vec, width: u8) { - if width == 16 { - bytes.push(0x66); - } -} - -fn emit_rex( - bytes: &mut Vec, - width: u8, - rex_r: bool, - rex_x: bool, - rex_b: bool, - any_high8: bool, - force: bool, -) -> Result<(), AsmError> { - let mut rex = REX::new(); - rex.w = width == 64; - rex.r = rex_r; - rex.x = rex_x; - rex.b = rex_b; - - let needed = force || rex.w || rex.r || rex.x || rex.b; - if any_high8 && needed { - return Err(AsmError::EncodeError( - "AH/CH/DH/BH cannot be encoded with a REX prefix".into(), - )); - } - if needed { - bytes.push(rex.encode()); - } - Ok(()) -} - -fn emit_disp(bytes: &mut Vec, disp: Option) { - if let Some(d) = disp { - match d { - DispKind::Disp8(v) => bytes.push(v as u8), - DispKind::Disp32(v) => bytes.extend_from_slice(&v.to_le_bytes()), - } - } -} - -fn emit_addr_tail(bytes: &mut Vec, addr: &EncodedAddress) { - if let Some((scale, index, base)) = addr.sib { - bytes.push((scale << 6) | (index << 3) | base); - } - emit_disp(bytes, addr.disp.clone()); -} - -fn emit_reg_reg( - bytes: &mut Vec, - opcode: u8, - dst: &RegInfo, - src: &RegInfo, -) -> Result<(), AsmError> { - emit_operand_size_prefix(bytes, dst.width); - emit_rex( - bytes, - dst.width, - src.code >= 8, - false, - dst.code >= 8, - dst.high8 || src.high8, - dst.rex8 || src.rex8, - )?; - bytes.push(opcode); - bytes.push(ModRM::new(0b11, src.code, dst.code).encode()); - Ok(()) -} - -fn validate_memory_width(mem: &MemoryOperand, width: u8) -> Result<(), AsmError> { - if mem.width.is_some_and(|explicit| explicit != width) { - return Err(AsmError::EncodeError( - "Memory width conflicts with register-derived width".into(), - )); - } - Ok(()) -} - -fn memory_address(mem: &MemoryOperand) -> Result { - if mem.symbol.is_none() { - return encode_address(mem, 64); - } - if mem.base.is_some() || mem.index.is_some() { - return Err(AsmError::EncodeError( - "symbol + register memory form is not implemented yet".into(), - )); - } - let mut address = mem.clone(); - address.symbol = None; - address.disp = 0; // The linker applies the checked symbol value plus addend. - if address.address_mode == MemoryAddressMode::Default { - address.address_mode = MemoryAddressMode::Relative; - } - encode_address(&address, 64) -} - -// Prefix selection belongs to each instruction; addressing and relocation -// offsets share one path, including instructions with a trailing immediate. -fn emit_memory_operation( - bytes: &mut Vec, - relocs: &mut Vec, - opcodes: &[u8], - reg: &RegInfo, - mem: &MemoryOperand, - rex_width: u8, - trailing: u8, -) -> Result<(), AsmError> { - let addr = memory_address(mem)?; - emit_rex(bytes, rex_width, reg.code >= 8, addr.rex_x, addr.rex_b, reg.high8, reg.rex8)?; - bytes.extend_from_slice(opcodes); - bytes.push(ModRM::new(addr.mod_bits, reg.code, addr.rm_bits).encode()); - if let Some(symbol) = &mem.symbol { - let absolute = mem.address_mode == MemoryAddressMode::Absolute; - let addend = if absolute { - mem.disp - } else { - relative_addend(mem.disp)?.checked_sub(i64::from(trailing)).ok_or_else(|| { - AsmError::EncodeError("Relative relocation addend overflow".into()) - })? - }; - relocs.push(Relocation { - offset: bytes.len() + usize::from(addr.sib.is_some()), - symbol: symbol.clone(), - kind: if absolute { RelocKind::SignedAbsolute32 } else { RelocKind::Relative32 }, - addend, - }); - } - emit_addr_tail(bytes, &addr); - Ok(()) -} - -fn emit_reg_mem( - bytes: &mut Vec, - relocs: &mut Vec, - opcode: u8, - reg: &RegInfo, - mem: &MemoryOperand, -) -> Result<(), AsmError> { - validate_memory_width(mem, reg.width)?; - emit_operand_size_prefix(bytes, reg.width); - emit_memory_operation(bytes, relocs, &[opcode], reg, mem, reg.width, 0) -} - -fn emit_mem_reg( - bytes: &mut Vec, - relocs: &mut Vec, - opcode: u8, - mem: &MemoryOperand, - reg: &RegInfo, -) -> Result<(), AsmError> { - emit_reg_mem(bytes, relocs, opcode, reg, mem) -} - -#[derive(Clone, Copy)] -struct BranchRelaxation { - previous_len: usize, - force_near: bool, -} - -fn encode_instruction( - ins: &Instruction, - bytes: &mut Vec, - relocs: &mut Vec, - current_section: usize, - current_offset: usize, - label_locs: &HashMap, - relaxation: BranchRelaxation, -) -> Result<(), AsmError> { - match ins.mnemonic.as_str() { - "ret" | "nop" | "syscall" | "int3" | "cwd" | "cdq" | "cqo" if !ins.operands.is_empty() => { - Err(AsmError::EncodeError(format!("{} expects 0 operands", ins.mnemonic))) - }, - "movss" | "movsd" | "addss" | "addsd" | "subss" | "subsd" | "mulss" | "mulsd" | "divss" - | "divsd" => encode_scalar_sse(ins, bytes, relocs), - "mov" => encode_mov(ins, bytes, relocs), - "movzx" | "movsx" | "movsxd" => encode_extension(ins, bytes, relocs), - "adc" => encode_carry(ins, 0x10, 0x11, bytes), - "sbb" => encode_carry(ins, 0x18, 0x19, bytes), - mnemonic if prefixed_condition(mnemonic, "set").is_some() => { - encode_setcc(ins, prefixed_condition(mnemonic, "set").unwrap(), bytes, relocs) - }, - mnemonic if prefixed_condition(mnemonic, "cmov").is_some() => { - encode_cmovcc(ins, prefixed_condition(mnemonic, "cmov").unwrap(), bytes) - }, - "add" => encode_binop(ins, 0x00, 0x01, 0x02, 0x03, 0, bytes, relocs), - "sub" => encode_binop(ins, 0x28, 0x29, 0x2A, 0x2B, 5, bytes, relocs), - "and" => encode_binop(ins, 0x20, 0x21, 0x22, 0x23, 4, bytes, relocs), - "or" => encode_binop(ins, 0x08, 0x09, 0x0A, 0x0B, 1, bytes, relocs), - "xor" => encode_binop(ins, 0x30, 0x31, 0x32, 0x33, 6, bytes, relocs), - "cmp" => encode_binop(ins, 0x38, 0x39, 0x3A, 0x3B, 7, bytes, relocs), - "imul" => encode_imul(ins, bytes, relocs), - "lea" => encode_lea(ins, bytes, relocs), - "test" => encode_test(ins, bytes), - "not" => encode_unary_register(ins, 2, bytes), - "neg" => encode_unary_register(ins, 3, bytes), - "div" => encode_unary_register(ins, 6, bytes), - "idiv" => encode_unary_register(ins, 7, bytes), - "shl" | "sal" => encode_shift(ins, 4, bytes), - "shr" => encode_shift(ins, 5, bytes), - "sar" => encode_shift(ins, 7, bytes), - "cwd" => { - bytes.extend_from_slice(&[0x66, 0x99]); - Ok(()) - }, - "cdq" => { - bytes.push(0x99); - Ok(()) - }, - "cqo" => { - bytes.extend_from_slice(&[0x48, 0x99]); - Ok(()) - }, - "push" if matches!(ins.operands.first(), Some(Operand::Immediate(_))) => { - encode_push_immediate(ins, bytes) - }, - "push" => encode_push_pop(ins, 0x50, bytes), - "pop" => encode_push_pop(ins, 0x58, bytes), - "jmp" | "call" - if matches!(ins.operands.first(), Some(Operand::Register(_) | Operand::Memory(_))) => - { - encode_indirect_branch(ins, bytes, relocs) - }, - "jmp" => encode_jump( - ins, - JumpSpec { - previous_len: relaxation.previous_len, - force_near: relaxation.force_near, - near_opcode: JumpOpcode::One(0xE9), - short_opcode: Some(0xEB), - reloc_kind: RelocKind::Branch32, - reloc_addend: -4, - near_len: 5, - }, - bytes, - relocs, - current_section, - current_offset, - label_locs, - ), - "call" => encode_jump( - ins, - JumpSpec { - previous_len: relaxation.previous_len, - force_near: relaxation.force_near, - near_opcode: JumpOpcode::One(0xE8), - short_opcode: None, - reloc_kind: RelocKind::Branch32, - reloc_addend: -4, - near_len: 5, - }, - bytes, - relocs, - current_section, - current_offset, - label_locs, - ), - condition if condition_code(condition).is_some() => encode_jump( - ins, - JumpSpec { - previous_len: relaxation.previous_len, - force_near: relaxation.force_near, - near_opcode: JumpOpcode::Two(0x0F, 0x80 + condition_code(condition).unwrap()), - short_opcode: Some(0x70 + condition_code(condition).unwrap()), - reloc_kind: RelocKind::Branch32, - reloc_addend: -4, - near_len: 6, - }, - bytes, - relocs, - current_section, - current_offset, - label_locs, - ), - "loop" => encode_loop(ins, bytes, relocs), - "ret" => { - bytes.push(0xC3); - Ok(()) - }, - "nop" => { - bytes.push(0x90); - Ok(()) - }, - "syscall" => { - bytes.push(0x0F); - bytes.push(0x05); - Ok(()) - }, - "int3" => { - bytes.push(0xCC); - Ok(()) - }, - _ => Err(AsmError::EncodeError(format!("Unknown mnemonic {}", ins.mnemonic))), - } -} - -fn symbol_operand(op: &Operand) -> Option<(String, i128)> { - match op { - Operand::Label(name) => Some((name.clone(), 0)), - Operand::SymbolExpr { name, addend } => Some((name.clone(), *addend)), - _ => None, - } -} - -fn xmm_operand(operand: &Operand) -> Result { - if let Operand::Register(name) = operand { - if let Some(code) = xmm_register_code(name) { - return Ok(code); } - } - Err(AsmError::EncodeError("Expected XMM0-XMM15 register".into())) -} - -fn encode_scalar_sse( - ins: &Instruction, - bytes: &mut Vec, - relocs: &mut Vec, -) -> Result<(), AsmError> { - if ins.operands.len() != 2 { - return Err(AsmError::EncodeError(format!("{} expects 2 operands", ins.mnemonic))); - } - let single = ins.mnemonic.ends_with("ss"); - let (prefix, width) = if single { (0xf3, 32) } else { (0xf2, 64) }; - let move_instruction = matches!(ins.mnemonic.as_str(), "movss" | "movsd"); - let opcode = match ins.mnemonic.as_str() { - "movss" | "movsd" => 0x10, - "addss" | "addsd" => 0x58, - "subss" | "subsd" => 0x5c, - "mulss" | "mulsd" => 0x59, - "divss" | "divsd" => 0x5e, - _ => unreachable!(), - }; - // XMM registers are 128-bit registers. The scalar access width chooses the - // mandatory prefix, never REX.W or the integer operand-size prefix 66. - if let Operand::Memory(mem) = &ins.operands[0] { - if !move_instruction { - return Err(AsmError::EncodeError( - "Scalar SSE arithmetic destination must be XMM".into(), + for symbol in output.symbols { + value.push_str(&format!( + "{}|{:?}|{}|{}|{:?}|{}|{:?}|", + symbol.name, + symbol.section_index, + symbol.offset, + symbol.is_global, + symbol.kind, + symbol.size, + symbol.visibility )); } - let code = xmm_operand(&ins.operands[1])?; - validate_memory_width(mem, width)?; - bytes.push(prefix); - let reg = RegInfo { code, width, high8: false, rex8: false }; - return emit_memory_operation(bytes, relocs, &[0x0f, 0x11], ®, mem, 0, 0); - } - let code = xmm_operand(&ins.operands[0])?; - match &ins.operands[1] { - Operand::Register(_) => { - let source = xmm_operand(&ins.operands[1])?; - bytes.push(prefix); - emit_rex(bytes, 0, code >= 8, false, source >= 8, false, false)?; - bytes.extend_from_slice(&[0x0f, opcode]); - bytes.push(ModRM::new(3, code, source).encode()); - Ok(()) - }, - Operand::Memory(mem) => { - validate_memory_width(mem, width)?; - bytes.push(prefix); - let reg = RegInfo { code, width, high8: false, rex8: false }; - emit_memory_operation(bytes, relocs, &[0x0f, opcode], ®, mem, 0, 0) - }, - _ => Err(AsmError::EncodeError( - "Scalar SSE source must be XMM or matching scalar memory".into(), - )), - } -} - -fn encode_mov( - ins: &Instruction, - bytes: &mut Vec, - relocs: &mut Vec, -) -> Result<(), AsmError> { - if ins.operands.len() != 2 { - return Err(AsmError::EncodeError("mov expects 2 operands".into())); - } - let dst = &ins.operands[0]; - let src = &ins.operands[1]; - - match (dst, src) { - (Operand::Register(dst_name), Operand::Immediate(imm)) => { - let reg = - lookup_reg(dst_name).ok_or(AsmError::EncodeError("Invalid register".into()))?; - match reg.width { - 8 => { - if !(-128..=255).contains(imm) { - return Err(AsmError::EncodeError("imm8 out of range".into())); - } - emit_rex(bytes, reg.width, false, false, reg.code >= 8, reg.high8, reg.rex8)?; - bytes.push(0xB0 + (reg.code & 7)); - bytes.push(*imm as u8); - }, - 16 => { - if !(-32768..=65535).contains(imm) { - return Err(AsmError::EncodeError("imm16 out of range".into())); - } - emit_operand_size_prefix(bytes, reg.width); - emit_rex(bytes, reg.width, false, false, reg.code >= 8, false, false)?; - bytes.push(0xB8 + (reg.code & 7)); - bytes.extend_from_slice(&(*imm as i16).to_le_bytes()); - }, - 32 => { - if !(*imm >= i32::MIN as i128 && *imm <= u32::MAX as i128) { - return Err(AsmError::EncodeError("imm32 out of range".into())); - } - emit_rex(bytes, reg.width, false, false, reg.code >= 8, false, false)?; - bytes.push(0xB8 + (reg.code & 7)); - bytes.extend_from_slice(&(*imm as u32).to_le_bytes()); - }, - 64 => { - emit_rex(bytes, reg.width, false, false, reg.code >= 8, false, false)?; - bytes.push(0xB8 + (reg.code & 7)); - if !(i64::MIN as i128..=u64::MAX as i128).contains(imm) { - return Err(AsmError::EncodeError("imm64 out of range".into())); + value + } + + #[test] + fn actual_wave_encoder_matches_retained_reference_for_existing_source_fixtures() { + for source in [ + include_str!("../test/test1.asm"), + include_str!("../test/mem_test.asm"), + include_str!("../test/competitor_test.asm"), + include_str!("../test/full_test.asm"), + include_str!("../test/msg.asm"), + ] { + let tokens = assembler::tokens::tokenize(source).unwrap(); + let ast = crate::parser::parse(&tokens).unwrap(); + let actual = encode(&ast); + let expected = reference::encode_with_limits(&ast, &AssemblyLimits::default()); + match (actual, expected) { + (Ok(actual), Ok(expected)) => assert_eq!(snapshot(actual), snapshot(expected)), + (Err(_), Err(_)) => {}, + (actual, expected) => panic!( + "status differs: Wave={}, reference={}", + actual.is_ok(), + expected.is_ok() + ), + } + } + } + + #[test] + fn full_gpr_sib_and_scalar_sse_matrix_matches_independent_reference() { + for base in crate::tables::REGISTERS_64.iter().map(|(name, _)| *name) { + for index in crate::tables::REGISTERS_64.iter().map(|(name, _)| *name) { + for scale in [1, 2, 4, 8] { + for displacement in [-129, -128, 0, 127, 128] { + let tail = if displacement < 0 { + format!(" - {}", -displacement) + } else { + format!(" + {displacement}") + }; + let source = format!("mov r9, [{base} + {index}*{scale}{tail}]\nmovsd xmm12, [{base} + {index}*{scale}{tail}]\n"); + let tokens = assembler::tokens::tokenize(&source).unwrap(); + let ast = match crate::parser::parse(&tokens) { + Ok(ast) => ast, + Err(_) => continue, + }; + match ( + encode(&ast), + reference::encode_with_limits(&ast, &AssemblyLimits::default()), + ) { + (Ok(actual), Ok(expected)) => { + assert_eq!(snapshot(actual), snapshot(expected), "{source}") + }, + (Err(_), Err(_)) => {}, + (actual, expected) => panic!( + "{source}: Wave={}, reference={}", + actual.is_ok(), + expected.is_ok() + ), + } } - bytes.extend_from_slice(&(*imm as u64).to_le_bytes()); - }, - _ => return Err(AsmError::EncodeError("Unsupported register width".into())), - } - Ok(()) - }, - (Operand::Register(dst_name), _) if symbol_operand(src).is_some() => { - let (label, addend) = symbol_operand(src).unwrap(); - let reg = - lookup_reg(dst_name).ok_or(AsmError::EncodeError("Invalid register".into()))?; - match reg.width { - 64 => { - emit_rex(bytes, reg.width, false, false, reg.code >= 8, false, false)?; - bytes.push(0xB8 + (reg.code & 7)); - relocs.push(Relocation { - offset: bytes.len(), - symbol: label, - kind: RelocKind::Absolute64, - addend: i64::try_from(addend) - .map_err(|_| AsmError::EncodeError("Symbol addend overflow".into()))?, - }); - bytes.extend_from_slice(&0i64.to_le_bytes()); - }, - 32 => { - emit_rex(bytes, reg.width, false, false, reg.code >= 8, false, false)?; - bytes.push(0xB8 + (reg.code & 7)); - relocs.push(Relocation { - offset: bytes.len(), - symbol: label, - kind: RelocKind::Absolute32, - addend: i64::try_from(addend) - .map_err(|_| AsmError::EncodeError("Symbol addend overflow".into()))?, - }); - bytes.extend_from_slice(&0u32.to_le_bytes()); - }, - _ => { - return Err(AsmError::EncodeError( - "Symbol move is supported only for r32/r64".into(), - )) - }, - } - Ok(()) - }, - (Operand::Register(dst_name), Operand::Register(src_name)) => { - let dst_reg = - lookup_reg(dst_name).ok_or(AsmError::EncodeError("Invalid dst register".into()))?; - let src_reg = - lookup_reg(src_name).ok_or(AsmError::EncodeError("Invalid src register".into()))?; - if dst_reg.width != src_reg.width { - return Err(AsmError::EncodeError("Register width mismatch".into())); - } - let opcode = if dst_reg.width == 8 { 0x88 } else { 0x89 }; - emit_reg_reg(bytes, opcode, &dst_reg, &src_reg) - }, - (Operand::Register(dst_name), Operand::Memory(mem)) => { - let reg = - lookup_reg(dst_name).ok_or(AsmError::EncodeError("Invalid register".into()))?; - let opcode = if reg.width == 8 { 0x8A } else { 0x8B }; - emit_reg_mem(bytes, relocs, opcode, ®, mem) - }, - (Operand::Memory(mem), Operand::Register(src_name)) => { - let reg = - lookup_reg(src_name).ok_or(AsmError::EncodeError("Invalid register".into()))?; - let opcode = if reg.width == 8 { 0x88 } else { 0x89 }; - emit_mem_reg(bytes, relocs, opcode, mem, ®) - }, - (Operand::Memory(mem), Operand::Immediate(imm)) => { - encode_memory_immediate(mem, *imm, None, bytes, relocs) - }, - _ => Err(AsmError::EncodeError("Unsupported mov form".into())), - } -} - -// The five opcode fields describe the existing instruction table explicitly. -#[allow(clippy::too_many_arguments)] -fn encode_binop( - ins: &Instruction, - opcode_rm_r_8: u8, - opcode_rm_r: u8, - opcode_r_rm_8: u8, - opcode_r_rm: u8, - imm_op_ext: u8, - bytes: &mut Vec, - relocs: &mut Vec, -) -> Result<(), AsmError> { - if ins.operands.len() != 2 { - return Err(AsmError::EncodeError(format!("{} expects 2 operands", ins.mnemonic))); - } - let dst = &ins.operands[0]; - let src = &ins.operands[1]; - - match (dst, src) { - (Operand::Register(dst_name), Operand::Register(src_name)) => { - let dst_reg = - lookup_reg(dst_name).ok_or(AsmError::EncodeError("Invalid dst register".into()))?; - let src_reg = - lookup_reg(src_name).ok_or(AsmError::EncodeError("Invalid src register".into()))?; - if dst_reg.width != src_reg.width { - return Err(AsmError::EncodeError("Register width mismatch".into())); - } - let opcode = if dst_reg.width == 8 { opcode_rm_r_8 } else { opcode_rm_r }; - emit_reg_reg(bytes, opcode, &dst_reg, &src_reg) - }, - (Operand::Register(dst_name), Operand::Immediate(imm)) => { - let dst_reg = - lookup_reg(dst_name).ok_or(AsmError::EncodeError("Invalid dst register".into()))?; - emit_operand_size_prefix(bytes, dst_reg.width); - emit_rex( - bytes, - dst_reg.width, - false, - false, - dst_reg.code >= 8, - dst_reg.high8, - dst_reg.rex8, - )?; - - if dst_reg.width == 8 { - if !(-128..=255).contains(imm) { - return Err(AsmError::EncodeError("imm8 out of range".into())); } - bytes.push(0x80); - bytes.push(ModRM::new(0b11, imm_op_ext, dst_reg.code).encode()); - bytes.push(*imm as u8); - return Ok(()); - } - - if (-128..=127).contains(imm) { - bytes.push(0x83); - bytes.push(ModRM::new(0b11, imm_op_ext, dst_reg.code).encode()); - bytes.push(*imm as u8); - return Ok(()); - } - - bytes.push(0x81); - bytes.push(ModRM::new(0b11, imm_op_ext, dst_reg.code).encode()); - match dst_reg.width { - 16 => { - if !(-32768..=65535).contains(imm) { - return Err(AsmError::EncodeError("imm16 out of range".into())); - } - bytes.extend_from_slice(&(*imm as i16).to_le_bytes()); - }, - 32 => { - if !(*imm >= i32::MIN as i128 && *imm <= u32::MAX as i128) { - return Err(AsmError::EncodeError("imm32 out of range".into())); - } - bytes.extend_from_slice(&(*imm as u32).to_le_bytes()); - }, - 64 => { - if !(*imm >= i32::MIN as i128 && *imm <= i32::MAX as i128) { - return Err(AsmError::EncodeError( - "imm32-sign-extended out of range for r64".into(), - )); - } - bytes.extend_from_slice(&(*imm as i32).to_le_bytes()); - }, - _ => return Err(AsmError::EncodeError("Unsupported register width".into())), - } - Ok(()) - }, - (Operand::Register(_), _) if symbol_operand(src).is_some() => { - Err(AsmError::EncodeError(format!( - "{} with symbolic immediate is not supported; use equ or mov reg, symbol", - ins.mnemonic - ))) - }, - (Operand::Register(dst_name), Operand::Memory(mem)) => { - let reg = - lookup_reg(dst_name).ok_or(AsmError::EncodeError("Invalid register".into()))?; - let opcode = if reg.width == 8 { opcode_r_rm_8 } else { opcode_r_rm }; - emit_reg_mem(bytes, relocs, opcode, ®, mem) - }, - (Operand::Memory(mem), Operand::Register(src_name)) => { - let reg = - lookup_reg(src_name).ok_or(AsmError::EncodeError("Invalid register".into()))?; - let opcode = if reg.width == 8 { opcode_rm_r_8 } else { opcode_rm_r }; - emit_mem_reg(bytes, relocs, opcode, mem, ®) - }, - (Operand::Memory(mem), Operand::Immediate(imm)) => { - encode_memory_immediate(mem, *imm, Some(imm_op_ext), bytes, relocs) - }, - _ => Err(AsmError::EncodeError(format!("Unsupported {} form", ins.mnemonic))), - } -} - -fn encode_memory_immediate( - mem: &MemoryOperand, - imm: i128, - operation: Option, - bytes: &mut Vec, - relocs: &mut Vec, -) -> Result<(), AsmError> { - let width = mem.width.ok_or_else(|| { - AsmError::EncodeError("Ambiguous memory immediate; specify byte/word/dword/qword".into()) - })?; - let encoded_width = if width == 64 { 32 } else { width }; - let valid = match width { - 8 => (-128..=255).contains(&imm), - 16 => (-32768..=65535).contains(&imm), - 32 => (i32::MIN as i128..=u32::MAX as i128).contains(&imm), - 64 => (i32::MIN as i128..=i32::MAX as i128).contains(&imm), - _ => false, - }; - if !valid { - return Err(AsmError::EncodeError( - "Memory immediate out of range for selected width (qword requires signed imm32)".into(), - )); - } - let short = operation.is_some() && width != 8 && (-128..=127).contains(&imm); - let tail = if short { 1 } else { encoded_width / 8 }; - let opcode = match operation { - None => { - if width == 8 { - 0xc6 - } else { - 0xc7 - } - }, - Some(_) => { - if width == 8 { - 0x80 - } else if short { - 0x83 - } else { - 0x81 - } - }, - }; - emit_operand_size_prefix(bytes, width); - let group = RegInfo { code: operation.unwrap_or(0), width, high8: false, rex8: false }; - emit_memory_operation(bytes, relocs, &[opcode], &group, mem, width, tail)?; - bytes.extend_from_slice(&(imm as u64).to_le_bytes()[..tail as usize]); - Ok(()) -} - -fn encode_imul( - ins: &Instruction, - bytes: &mut Vec, - relocs: &mut Vec, -) -> Result<(), AsmError> { - if ins.operands.len() == 3 { - return encode_imul_immediate(ins, bytes); - } - if ins.operands.len() != 2 { - return Err(AsmError::EncodeError("imul expects 2 or 3 operands".into())); - } - let dst = &ins.operands[0]; - let src = &ins.operands[1]; - - let Operand::Register(dst_name) = dst else { - return Err(AsmError::EncodeError("imul form supported: imul reg, reg/mem".into())); - }; - let dst_reg = - lookup_reg(dst_name).ok_or(AsmError::EncodeError("Invalid dst register".into()))?; - - if dst_reg.width == 8 { - return Err(AsmError::EncodeError( - "imul reg, reg/mem is not supported for 8-bit operands".into(), - )); - } - - match src { - Operand::Register(src_name) => { - let src_reg = - lookup_reg(src_name).ok_or(AsmError::EncodeError("Invalid src register".into()))?; - if src_reg.width != dst_reg.width { - return Err(AsmError::EncodeError("Register width mismatch".into())); - } - emit_operand_size_prefix(bytes, dst_reg.width); - emit_rex( - bytes, - dst_reg.width, - dst_reg.code >= 8, - false, - src_reg.code >= 8, - false, - false, - )?; - bytes.push(0x0F); - bytes.push(0xAF); - bytes.push(ModRM::new(0b11, dst_reg.code, src_reg.code).encode()); - Ok(()) - }, - Operand::Memory(mem) => { - validate_memory_width(mem, dst_reg.width)?; - emit_operand_size_prefix(bytes, dst_reg.width); - emit_memory_operation(bytes, relocs, &[0x0f, 0xaf], &dst_reg, mem, dst_reg.width, 0)?; - Ok(()) - }, - _ => Err(AsmError::EncodeError("imul form supported: imul reg, reg/mem".into())), - } -} - -fn register_operand(op: &Operand) -> Result { - match op { - Operand::Register(name) => { - lookup_reg(name).ok_or_else(|| AsmError::EncodeError("Invalid register".into())) - }, - _ => Err(AsmError::EncodeError("Expected register operand".into())), - } -} - -fn encode_lea( - ins: &Instruction, - bytes: &mut Vec, - relocs: &mut Vec, -) -> Result<(), AsmError> { - if ins.operands.len() != 2 { - return Err(AsmError::EncodeError("lea expects 2 operands".into())); - } - let reg = register_operand(&ins.operands[0])?; - if !matches!(reg.width, 32 | 64) { - return Err(AsmError::EncodeError("lea destination must be r32 or r64".into())); - } - let Operand::Memory(mem) = &ins.operands[1] else { - return Err(AsmError::EncodeError("lea source must be memory address".into())); - }; - emit_reg_mem(bytes, relocs, 0x8d, ®, mem) -} - -fn encode_test(ins: &Instruction, bytes: &mut Vec) -> Result<(), AsmError> { - if ins.operands.len() != 2 { - return Err(AsmError::EncodeError("test expects 2 operands".into())); - } - let dst = register_operand(&ins.operands[0])?; - let src = register_operand(&ins.operands[1])?; - if dst.width != src.width { - return Err(AsmError::EncodeError("Register width mismatch".into())); - } - emit_reg_reg(bytes, if dst.width == 8 { 0x84 } else { 0x85 }, &dst, &src) -} - -fn encode_unary_register( - ins: &Instruction, - extension: u8, - bytes: &mut Vec, -) -> Result<(), AsmError> { - if ins.operands.len() != 1 { - return Err(AsmError::EncodeError(format!("{} expects 1 operand", ins.mnemonic))); - } - let reg = register_operand(&ins.operands[0])?; - emit_operand_size_prefix(bytes, reg.width); - emit_rex(bytes, reg.width, false, false, reg.code >= 8, reg.high8, reg.rex8)?; - bytes.push(if reg.width == 8 { 0xf6 } else { 0xf7 }); - bytes.push(ModRM::new(3, extension, reg.code).encode()); - Ok(()) -} - -fn encode_shift(ins: &Instruction, extension: u8, bytes: &mut Vec) -> Result<(), AsmError> { - if ins.operands.len() != 2 { - return Err(AsmError::EncodeError(format!("{} expects 2 operands", ins.mnemonic))); - } - let reg = register_operand(&ins.operands[0])?; - let (opcode, immediate) = match &ins.operands[1] { - Operand::Immediate(1) => (if reg.width == 8 { 0xd0 } else { 0xd1 }, None), - Operand::Immediate(count) if (0..=255).contains(count) => { - (if reg.width == 8 { 0xc0 } else { 0xc1 }, Some(*count as u8)) - }, - Operand::Register(count) if count == "cl" => { - (if reg.width == 8 { 0xd2 } else { 0xd3 }, None) - }, - _ => return Err(AsmError::EncodeError("Shift count must be CL or unsigned imm8".into())), - }; - emit_operand_size_prefix(bytes, reg.width); - emit_rex(bytes, reg.width, false, false, reg.code >= 8, reg.high8, reg.rex8)?; - bytes.push(opcode); - bytes.push(ModRM::new(3, extension, reg.code).encode()); - if let Some(count) = immediate { - bytes.push(count); - } - Ok(()) -} - -fn encode_imul_immediate(ins: &Instruction, bytes: &mut Vec) -> Result<(), AsmError> { - let dst = register_operand(&ins.operands[0])?; - let src = register_operand(&ins.operands[1])?; - let Operand::Immediate(imm) = ins.operands[2] else { - return Err(AsmError::EncodeError("imul third operand must be immediate".into())); - }; - if dst.width != src.width || !matches!(dst.width, 16 | 32 | 64) { - return Err(AsmError::EncodeError("imul requires matching r16/r32/r64 operands".into())); - } - let short = (-128..=127).contains(&imm); - let valid = match dst.width { - 16 => (-32768..=65535).contains(&imm), - 32 => (i32::MIN as i128..=u32::MAX as i128).contains(&imm), - 64 => (i32::MIN as i128..=i32::MAX as i128).contains(&imm), - _ => false, - }; - if !valid { - return Err(AsmError::EncodeError( - "imul immediate out of range (imm16/imm32; r64 sign extends imm32)".into(), - )); - } - emit_operand_size_prefix(bytes, dst.width); - emit_rex(bytes, dst.width, dst.code >= 8, false, src.code >= 8, false, false)?; - bytes.push(if short { 0x6b } else { 0x69 }); - bytes.push(ModRM::new(3, dst.code, src.code).encode()); - if short { - bytes.push(imm as u8); - } else if dst.width == 16 { - bytes.extend_from_slice(&(imm as u16).to_le_bytes()); - } else { - bytes.extend_from_slice(&(imm as u32).to_le_bytes()); - } - Ok(()) -} - -fn prefixed_condition(mnemonic: &str, prefix: &str) -> Option { - let suffix = mnemonic.strip_prefix(prefix)?; - CONDITION_CODES - .iter() - .find(|(name, _)| name.strip_prefix('j') == Some(suffix)) - .map(|(_, code)| *code) -} - -fn encode_carry( - ins: &Instruction, - byte_opcode: u8, - wide_opcode: u8, - bytes: &mut Vec, -) -> Result<(), AsmError> { - if ins.operands.len() != 2 { - return Err(AsmError::EncodeError(format!("{} expects 2 register operands", ins.mnemonic))); - } - let dst = register_operand(&ins.operands[0])?; - let src = register_operand(&ins.operands[1])?; - if dst.width != src.width { - return Err(AsmError::EncodeError("Register width mismatch".into())); - } - emit_reg_reg(bytes, if dst.width == 8 { byte_opcode } else { wide_opcode }, &dst, &src) -} - -fn encode_setcc( - ins: &Instruction, - condition: u8, - bytes: &mut Vec, - relocs: &mut Vec, -) -> Result<(), AsmError> { - if ins.operands.len() != 1 { - return Err(AsmError::EncodeError("setcc expects 1 byte operand".into())); - } - emit_group_operand(&ins.operands[0], 8, 8, &[0x0f, 0x90 + condition], 0, bytes, relocs) -} - -fn encode_cmovcc(ins: &Instruction, condition: u8, bytes: &mut Vec) -> Result<(), AsmError> { - if ins.operands.len() != 2 { - return Err(AsmError::EncodeError("cmovcc expects 2 register operands".into())); - } - let dst = register_operand(&ins.operands[0])?; - let src = register_operand(&ins.operands[1])?; - if dst.width != src.width || !matches!(dst.width, 16 | 32 | 64) { - return Err(AsmError::EncodeError("cmovcc requires matching r16/r32/r64 registers".into())); - } - emit_operand_size_prefix(bytes, dst.width); - emit_rex(bytes, dst.width, dst.code >= 8, false, src.code >= 8, false, false)?; - bytes.extend_from_slice(&[0x0f, 0x40 + condition]); - bytes.push(ModRM::new(3, dst.code, src.code).encode()); - Ok(()) -} - -fn encode_indirect_branch( - ins: &Instruction, - bytes: &mut Vec, - relocs: &mut Vec, -) -> Result<(), AsmError> { - if ins.operands.len() != 1 { - return Err(AsmError::EncodeError(format!("{} expects 1 operand", ins.mnemonic))); - } - // Near indirect branches default to 64-bit in long mode; REX.W is unnecessary. - emit_group_operand( - &ins.operands[0], - 64, - 0, - &[0xff], - if ins.mnemonic == "call" { 2 } else { 4 }, - bytes, - relocs, - ) -} - -fn emit_group_operand( - operand: &Operand, - width: u8, - rex_width: u8, - opcodes: &[u8], - extension: u8, - bytes: &mut Vec, - relocs: &mut Vec, -) -> Result<(), AsmError> { - emit_operand_size_prefix(bytes, width); - match operand { - Operand::Register(_) => { - let reg = register_operand(operand)?; - if reg.width != width { - return Err(AsmError::EncodeError( - "Register width does not match instruction".into(), - )); } - emit_rex(bytes, rex_width, false, false, reg.code >= 8, reg.high8, reg.rex8)?; - bytes.extend_from_slice(opcodes); - bytes.push(ModRM::new(3, extension, reg.code).encode()); - }, - Operand::Memory(mem) => { - validate_memory_width(mem, width)?; - let group = RegInfo { code: extension, width, high8: false, rex8: false }; - emit_memory_operation(bytes, relocs, opcodes, &group, mem, rex_width, 0)?; - }, - _ => return Err(AsmError::EncodeError("Expected register or memory operand".into())), - } - Ok(()) -} - -fn encode_extension( - ins: &Instruction, - bytes: &mut Vec, - relocs: &mut Vec, -) -> Result<(), AsmError> { - if ins.operands.len() != 2 { - return Err(AsmError::EncodeError(format!("{} expects 2 operands", ins.mnemonic))); - } - let dst = register_operand(&ins.operands[0])?; - let src_width = match &ins.operands[1] { - Operand::Register(_) => register_operand(&ins.operands[1])?.width, - Operand::Memory(mem) => mem.width.ok_or_else(|| { - AsmError::EncodeError("Extension memory source requires byte/word/dword width".into()) - })?, - _ => { - return Err(AsmError::EncodeError("Extension source must be register or memory".into())) - }, - }; - let valid = if ins.mnemonic == "movsxd" { - dst.width == 64 && src_width == 32 - } else { - (src_width == 8 && matches!(dst.width, 16 | 32 | 64)) - || (src_width == 16 && matches!(dst.width, 32 | 64)) - }; - if !valid { - return Err(AsmError::EncodeError( - "Invalid extension source/destination width pair".into(), - )); - } - let opcode = if ins.mnemonic == "movsxd" { - vec![0x63] - } else { - vec![ - 0x0f, - match (ins.mnemonic.as_str(), src_width) { - ("movzx", 8) => 0xb6, - ("movzx", 16) => 0xb7, - ("movsx", 8) => 0xbe, - _ => 0xbf, - }, - ] - }; - emit_operand_size_prefix(bytes, dst.width); - match &ins.operands[1] { - Operand::Register(_) => { - let src = register_operand(&ins.operands[1])?; - emit_rex(bytes, dst.width, dst.code >= 8, false, src.code >= 8, src.high8, src.rex8)?; - bytes.extend_from_slice(&opcode); - bytes.push(ModRM::new(3, dst.code, src.code).encode()); - }, - Operand::Memory(mem) => { - emit_memory_operation(bytes, relocs, &opcode, &dst, mem, dst.width, 0)?; - }, - _ => unreachable!(), - } - Ok(()) -} - -fn encode_push_immediate(ins: &Instruction, bytes: &mut Vec) -> Result<(), AsmError> { - if ins.operands.len() != 1 { - return Err(AsmError::EncodeError("push expects 1 operand".into())); - } - let Operand::Immediate(imm) = ins.operands[0] else { unreachable!() }; - if (-128..=127).contains(&imm) { - bytes.extend_from_slice(&[0x6a, imm as u8]); - } else if (i32::MIN as i128..=i32::MAX as i128).contains(&imm) { - bytes.push(0x68); - bytes.extend_from_slice(&(imm as i32).to_le_bytes()); - } else { - return Err(AsmError::EncodeError( - "push immediate requires signed imm8 or signed imm32 in AMD64 mode".into(), - )); - } - Ok(()) -} - -fn encode_push_pop( - ins: &Instruction, - base_opcode: u8, - bytes: &mut Vec, -) -> Result<(), AsmError> { - if ins.operands.len() != 1 { - return Err(AsmError::EncodeError(format!("{} expects 1 operand", ins.mnemonic))); - } - if let Operand::Register(name) = &ins.operands[0] { - let reg = lookup_reg(name).ok_or(AsmError::EncodeError("Invalid register".into()))?; - if reg.width == 16 { - bytes.push(0x66); - } else if reg.width != 64 { - return Err(AsmError::EncodeError( - "push/pop currently support only r16/r64 in amd64 mode".into(), - )); - } - emit_rex(bytes, 0, false, false, reg.code >= 8, false, false)?; - bytes.push(base_opcode + (reg.code & 7)); - Ok(()) - } else { - Err(AsmError::EncodeError(format!("{} only supports registers for now", ins.mnemonic))) - } -} - -enum JumpOpcode { - One(u8), - Two(u8, u8), -} - -struct JumpSpec { - previous_len: usize, - force_near: bool, - near_opcode: JumpOpcode, - short_opcode: Option, - reloc_kind: RelocKind, - reloc_addend: i64, - near_len: usize, -} - -fn emit_near_opcode(bytes: &mut Vec, opcode: &JumpOpcode) { - match opcode { - JumpOpcode::One(b) => bytes.push(*b), - JumpOpcode::Two(a, b) => { - bytes.push(*a); - bytes.push(*b); - }, - } -} - -fn encode_jump( - ins: &Instruction, - spec: JumpSpec, - bytes: &mut Vec, - relocs: &mut Vec, - current_section: usize, - current_offset: usize, - label_locs: &HashMap, -) -> Result<(), AsmError> { - if ins.operands.len() != 1 { - return Err(AsmError::EncodeError(format!("{} expects 1 operand", ins.mnemonic))); - } - let Some((label, addend)) = symbol_operand(&ins.operands[0]) else { - return Err(AsmError::EncodeError(format!( - "{} only supports labels for now", - ins.mnemonic - ))); - }; - if addend != 0 { - return Err(AsmError::EncodeError(format!( - "{} does not support label addends", - ins.mnemonic - ))); - } - - if let Some((target_sec, target_off)) = label_locs.get(&label) { - if *target_sec == current_section { - if let Some(short_op) = spec.short_opcode.filter(|_| !spec.force_near) { - let short_len = 2i64; - // A forward target moves when this branch itself shrinks. - // Its previous encoded length keeps the inclusive +127 edge - // available without ever truncating an out-of-range count. - let own_shrink = if *target_off > current_offset as u64 { - spec.previous_len.saturating_sub(short_len as usize) as i64 - } else { - 0 - }; - let disp_short = - *target_off as i64 - own_shrink - (current_offset as i64 + short_len); - if (-128..=127).contains(&disp_short) { - bytes.push(short_op); - bytes.push(disp_short as i8 as u8); - return Ok(()); - } - } - - let disp_near = *target_off as i64 - (current_offset as i64 + spec.near_len as i64); - if !(i32::MIN as i64..=i32::MAX as i64).contains(&disp_near) { - return Err(AsmError::EncodeError(format!( - "{} target '{}' is out of 32-bit relative range", - ins.mnemonic, label - ))); - } - - emit_near_opcode(bytes, &spec.near_opcode); - bytes.extend_from_slice(&(disp_near as i32).to_le_bytes()); - return Ok(()); } } - - emit_near_opcode(bytes, &spec.near_opcode); - relocs.push(Relocation { - offset: bytes.len(), - symbol: label, - kind: spec.reloc_kind, - addend: spec.reloc_addend, - }); - bytes.extend_from_slice(&0i32.to_le_bytes()); - Ok(()) -} - -fn encode_loop( - ins: &Instruction, - bytes: &mut Vec, - relocs: &mut Vec, -) -> Result<(), AsmError> { - if ins.operands.len() != 1 { - return Err(AsmError::EncodeError("loop expects 1 operand".into())); - } - let Some((label, addend)) = symbol_operand(&ins.operands[0]) else { - return Err(AsmError::EncodeError("loop only supports labels for now".into())); - }; - if addend != 0 { - return Err(AsmError::EncodeError("loop does not support label addends".into())); - } - - bytes.push(0xE2); - - relocs.push(Relocation { - offset: bytes.len(), - symbol: label, - kind: RelocKind::Relative8, - addend: -1, - }); - bytes.push(0); - Ok(()) -} - -fn eval_directive_expr( - expr: &ExprValue, - consts: &HashMap, -) -> Result { - eval_expr(expr, consts) -} - -fn encode_data_expr( - eval: EvaluatedExpr, - width: usize, - bytes: &mut Vec, - relocs: &mut Vec, -) -> Result<(), AsmError> { - match eval { - EvaluatedExpr::Number(n) => { - match width { - 1 => { - if !(-128..=255).contains(&n) { - return Err(AsmError::EncodeError("db value out of range".into())); - } - bytes.push(n as u8); - }, - 2 => { - if !(-32768..=65535).contains(&n) { - return Err(AsmError::EncodeError("dw value out of range".into())); - } - bytes.extend_from_slice(&(n as i16).to_le_bytes()); - }, - 4 => { - if !(i32::MIN as i128..=u32::MAX as i128).contains(&n) { - return Err(AsmError::EncodeError("dd value out of range".into())); - } - bytes.extend_from_slice(&(n as u32).to_le_bytes()); - }, - 8 => { - if !(i64::MIN as i128..=u64::MAX as i128).contains(&n) { - return Err(AsmError::EncodeError("dq value out of range".into())); - } - bytes.extend_from_slice(&(n as u64).to_le_bytes()); - }, - _ => return Err(AsmError::EncodeError("Unsupported data width".into())), - } - Ok(()) - }, - EvaluatedExpr::Symbol { name, addend } => match width { - 4 => { - relocs.push(Relocation { - offset: bytes.len(), - symbol: name, - kind: RelocKind::Absolute32, - addend, - }); - bytes.extend_from_slice(&0u32.to_le_bytes()); - Ok(()) - }, - 8 => { - relocs.push(Relocation { - offset: bytes.len(), - symbol: name, - kind: RelocKind::Absolute64, - addend, - }); - bytes.extend_from_slice(&0u64.to_le_bytes()); - Ok(()) - }, - _ => Err(AsmError::EncodeError("Only dd/dq support symbolic expressions".into())), - }, - } -} - -fn alignment_value(dir: &Directive, consts: &HashMap) -> Result { - if dir.values.len() != 1 { - return Err(AsmError::EncodeError("align expects one power-of-two operand".into())); - } - let DirectiveValue::Expr(expr) = &dir.values[0] else { - return Err(AsmError::EncodeError("align requires numeric expression".into())); - }; - let EvaluatedExpr::Number(number) = eval_expr(expr, consts)? else { - return Err(AsmError::EncodeError("align requires a resolved constant".into())); - }; - let value = u64::try_from(number) - .ok() - .filter(|value| value.is_power_of_two()) - .ok_or_else(|| AsmError::EncodeError("align requires a positive power of two".into()))?; - Ok(value) -} - -fn reservation_size( - unit: u64, - values: &[DirectiveValue], - consts: &HashMap, -) -> Result { - if values.len() != 1 { - return Err(AsmError::EncodeError("res* expects exactly one count operand".into())); - } - - let count = match &values[0] { - DirectiveValue::Expr(expr) => match eval_directive_expr(expr, consts)? { - EvaluatedExpr::Number(v) => v, - EvaluatedExpr::Symbol { name, .. } => { - return Err(AsmError::EncodeError(format!( - "res* count must be constant; unresolved symbol '{}'", - name - ))) - }, - }, - DirectiveValue::StringLiteral(_) => { - return Err(AsmError::EncodeError("res* count must be numeric expression".into())) - }, - }; - - if count < 0 { - return Err(AsmError::EncodeError("res* count must be non-negative".into())); - } - u64::try_from(count) - .map_err(|_| AsmError::EncodeError("res* size overflow".into()))? - .checked_mul(unit) - .ok_or_else(|| AsmError::EncodeError("res* size overflow".into())) -} - -fn reserve_bytes( - bytes: &mut Vec, - unit: u64, - values: &[DirectiveValue], - consts: &HashMap, -) -> Result<(), AsmError> { - let extra = usize::try_from(reservation_size(unit, values, consts)?) - .map_err(|_| AsmError::EncodeError("res* size exceeds host capacity".into()))?; - let new_len = bytes - .len() - .checked_add(extra) - .ok_or_else(|| AsmError::EncodeError("res* size overflow".into()))?; - bytes.try_reserve(extra).map_err(|_| AsmError::EncodeError("res* allocation failed".into()))?; - bytes.resize(new_len, 0); - Ok(()) -} - -fn reserve_output( - bytes: &mut Vec, - extra: usize, - materialized: &mut usize, - limits: &assembler::AssemblyLimits, -) -> Result<(), AsmError> { - let total = materialized - .checked_add(extra) - .ok_or_else(|| AsmError::EncodeError("Assembly output size overflow".into()))?; - let section_size = bytes - .len() - .checked_add(extra) - .ok_or_else(|| AsmError::EncodeError("Section output size overflow".into()))?; - if total > limits.max_output_bytes || section_size > isize::MAX as usize { - return Err(AsmError::EncodeError(format!( - "Assembly output limit exceeded (limit {} bytes)", - limits.max_output_bytes - ))); - } - bytes - .try_reserve(extra) - .map_err(|_| AsmError::EncodeError("Assembly output allocation failed".into()))?; - *materialized = total; - Ok(()) -} - -fn directive_size(dir: &Directive, consts: &HashMap) -> Result { - if let Some(unit) = match dir.name.as_str() { - "resb" => Some(1), - "resw" => Some(2), - "resd" => Some(4), - "resq" => Some(8), - _ => None, - } { - return usize::try_from(reservation_size(unit, &dir.values, consts)?) - .map_err(|_| AsmError::EncodeError("Reservation size exceeds host capacity".into())); - } - let width = match dir.name.as_str() { - "db" => 1, - "dw" => 2, - "dd" => 4, - "dq" => 8, - _ => return Err(AsmError::EncodeError(format!("Unknown directive {}", dir.name))), - }; - dir.values.iter().try_fold(0usize, |size, value| { - let extra = match value { - DirectiveValue::StringLiteral(s) if width == 1 => s.len(), - DirectiveValue::StringLiteral(_) => { - return Err(AsmError::EncodeError(format!( - "{} only supports numeric expressions", - dir.name - ))) - }, - _ => width, - }; - size.checked_add(extra) - .ok_or_else(|| AsmError::EncodeError("Directive output size overflow".into())) - }) -} - -fn encode_bss_directive( - dir: &Directive, - section: &mut AsmSection, - consts: &HashMap, -) -> Result<(), AsmError> { - let extra = match dir.name.as_str() { - "resb" => reservation_size(1, &dir.values, consts)?, - "resw" => reservation_size(2, &dir.values, consts)?, - "resd" => reservation_size(4, &dir.values, consts)?, - "resq" => reservation_size(8, &dir.values, consts)?, - _ => { - let size = directive_size(dir, consts)?; - for value in &dir.values { - let zero = match value { - DirectiveValue::StringLiteral(s) => s.as_slice().iter().all(|b| *b == 0), - DirectiveValue::Expr(expr) => { - matches!(eval_directive_expr(expr, consts)?, EvaluatedExpr::Number(0)) - }, - }; - if !zero { - return Err(AsmError::EncodeError( - "BSS has a nonzero initializer or relocation".into(), - )); - } - } - size as u64 - }, - }; - section.zero_fill = section - .zero_fill - .checked_add(extra) - .ok_or_else(|| AsmError::EncodeError("BSS size overflow".into()))?; - Ok(()) -} - -fn encode_directive( - dir: &Directive, - bytes: &mut Vec, - relocs: &mut Vec, - consts: &HashMap, -) -> Result<(), AsmError> { - match dir.name.as_str() { - "db" => { - for v in &dir.values { - match v { - DirectiveValue::StringLiteral(s) => bytes.extend_from_slice(s.as_slice()), - DirectiveValue::Expr(expr) => { - let eval = eval_directive_expr(expr, consts)?; - encode_data_expr(eval, 1, bytes, relocs)?; - }, - } - } - Ok(()) - }, - "dw" => { - for v in &dir.values { - let DirectiveValue::Expr(expr) = v else { - return Err(AsmError::EncodeError( - "dw only supports numeric expressions".into(), - )); - }; - let eval = eval_directive_expr(expr, consts)?; - encode_data_expr(eval, 2, bytes, relocs)?; - } - Ok(()) - }, - "dd" => { - for v in &dir.values { - let DirectiveValue::Expr(expr) = v else { - return Err(AsmError::EncodeError( - "dd only supports numeric expressions".into(), - )); - }; - let eval = eval_directive_expr(expr, consts)?; - encode_data_expr(eval, 4, bytes, relocs)?; - } - Ok(()) - }, - "dq" => { - for v in &dir.values { - let DirectiveValue::Expr(expr) = v else { - return Err(AsmError::EncodeError( - "dq only supports numeric expressions".into(), - )); - }; - let eval = eval_directive_expr(expr, consts)?; - encode_data_expr(eval, 8, bytes, relocs)?; - } - Ok(()) - }, - "resb" => reserve_bytes(bytes, 1, &dir.values, consts), - "resw" => reserve_bytes(bytes, 2, &dir.values, consts), - "resd" => reserve_bytes(bytes, 4, &dir.values, consts), - "resq" => reserve_bytes(bytes, 8, &dir.values, consts), - _ => Err(AsmError::EncodeError(format!("Unknown directive {}", dir.name))), - } } diff --git a/assembler/amd64/src/encoder_namespace_errors.rs b/assembler/amd64/src/encoder_namespace_errors.rs new file mode 100644 index 0000000..e418ac2 --- /dev/null +++ b/assembler/amd64/src/encoder_namespace_errors.rs @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Rendering of native namespace/layout errors; decisions remain in Wave. +use assembler::AsmError; + +pub(super) fn message(code: u64, symbol: &str, limit: usize) -> AsmError { + let text = match code { + 100 => format!("Local label '{symbol}' has no parent non-local label in scope"), + 101 => format!("Duplicate constant definition '{symbol}'"), + 102 => format!("Constant '{symbol}' conflicts with a label or extern symbol"), + 103 => format!("equ requires a constant expression; unresolved symbol '{symbol}'"), + 104 => format!("Signed expression overflow while resolving {symbol:?}"), + 105 => format!("Constant dependency cycle prevents resolving '{symbol}'"), + 106 => "Symbol addend overflow".into(), + 110 => format!("Duplicate label definition '{symbol}'"), + 111 => format!("Extern symbol '{symbol}' was already defined in this file"), + 112 => format!("Label '{symbol}' conflicts with extern declaration"), + 113 => format!("Global symbol '{symbol}' has no definition or extern declaration"), + 114 => format!("Duplicate symbol metadata for '{symbol}'"), + 115 => format!("Metadata symbol '{symbol}' has no label or extern declaration"), + 116 => format!("symbol '{symbol}' size must be a constant"), + 117 => format!("symbol '{symbol}' size must be a nonnegative u64"), + 118 => format!("Symbol '{symbol}' size exceeds its section"), + 119 => format!("Incompatible section redeclaration '{symbol}'"), + 120 => format!("Standard section '{symbol}' has incompatible kind"), + 121 => "instructions are not valid in BSS".into(), + 122 => format!("Branch relaxation did not converge within {limit} passes"), + 123 => format!( + "Undefined symbol '{symbol}' (define it, declare with extern, or define with equ)" + ), + 124 => format!("loop target '{symbol}' is out of 8-bit range"), + 151 => "directive requires numeric expression".into(), + 152 => "res* expects exactly one count operand".into(), + 153 => "res* count must be numeric expression".into(), + 154 => format!("res* count must be constant; unresolved symbol '{symbol}'"), + 155 => "res* count must be non-negative".into(), + 156 => "res* size overflow".into(), + 157 => "align expects one power-of-two operand".into(), + 158 => "align requires numeric expression".into(), + 159 => "align requires a resolved constant".into(), + 160 => "align requires a positive power of two".into(), + 161 => "Alignment size overflow".into(), + 162 => "BSS size overflow".into(), + 163 => format!("Unknown directive {symbol}"), + 164 => "dw only supports numeric expressions".into(), + 165 => "Directive output size overflow".into(), + 166 => "BSS has a nonzero initializer or relocation".into(), + 167 => "db value out of range".into(), + 168 => "Only dd/dq support symbolic expressions".into(), + 169 => "dd only supports numeric expressions".into(), + 170 => "dq only supports numeric expressions".into(), + 171 => "dw value out of range".into(), + 172 => "dd value out of range".into(), + 173 => "dq value out of range".into(), + _ => return AsmError::Backend("AMD64 namespace diagnostic transport"), + }; + if matches!(code, 100..=103 | 105 | 110..=118 | 123) { + AsmError::SymbolError(text) + } else { + AsmError::EncodeError(text) + } +} diff --git a/assembler/amd64/src/encoder_reference.rs b/assembler/amd64/src/encoder_reference.rs new file mode 100644 index 0000000..d317481 --- /dev/null +++ b/assembler/amd64/src/encoder_reference.rs @@ -0,0 +1,2210 @@ +use std::collections::{HashMap, HashSet, VecDeque}; + +use assembler::assembler::{AsmSection, AsmSymbol, AssemblerOutput, RelocKind, Relocation}; + +use assembler::ast::*; + +use assembler::error::AsmError; + +use crate::encoding::address::reference::encode_address; + +use crate::encoding::{DispKind, EncodedAddress}; + +use reference_modrm::ModRM; + +use reference_rex::Rex; + +use crate::tables::*; + +#[cfg(whale_wave_amd64)] +use crate::tables::{ + condition_code_reference as condition_code, xmm_register_code_reference as xmm_register_code, +}; + +type LabelLocations = HashMap; + +#[derive(PartialEq, Eq)] +struct EncodingLayout { + labels: LabelLocations, + instruction_lengths: Vec, + instruction_offsets: Vec, +} + +struct EncodingPass { + output: AssemblerOutput, + layout: EncodingLayout, + relocation_sites: HashMap<(usize, usize), usize>, +} + +// Resolve the one-symbol constant dependency graph before encoding any use. +// Worklist traversal avoids recursion and repeated whole-source rescans. +fn resolve_constants(ast: &AST) -> Result, AsmError> { + let mut definitions = Vec::new(); + let mut positions = HashMap::new(); + let mut reserved = HashSet::new(); + let mut scope = None; + let mut constant_sites = HashMap::::new(); + let mut reserved_sites = HashMap::::new(); + for (node_index, node) in ast.items.iter().enumerate() { + match node { + ASTNode::Label(name) => { + let resolved = resolve_symbol_name(name, &scope) + .map_err(|error| ast.error_at(error, node_index, None))?; + reserved_sites.entry(resolved.clone()).or_insert(node_index); + reserved.insert(resolved.clone()); + if !name.starts_with('.') { + scope = Some(resolved); + } + }, + ASTNode::Extern(name) => { + let resolved = resolve_symbol_name(name, &scope) + .map_err(|error| ast.error_at(error, node_index, None))?; + reserved_sites.entry(resolved.clone()).or_insert(node_index); + reserved.insert(resolved); + }, + ASTNode::Const { name, expr } => { + let name = resolve_symbol_name(name, &scope) + .map_err(|error| ast.error_at(error, node_index, None))?; + if positions.insert(name.clone(), definitions.len()).is_some() { + return Err(ast.error_at( + AsmError::SymbolError(format!("Duplicate constant definition '{name}'")), + node_index, + constant_sites.get(&name).copied(), + )); + } + constant_sites.insert(name.clone(), node_index); + definitions.push(( + name, + resolve_expr_symbols(expr, &scope) + .map_err(|error| ast.error_at(error, node_index, None))?, + )); + }, + _ => {}, + } + } + let mut dependents = vec![Vec::new(); definitions.len()]; + let mut ready = VecDeque::new(); + for (position, (name, expr)) in definitions.iter().enumerate() { + if reserved.contains(name) { + let declaration = constant_sites[name]; + let previous = reserved_sites[name]; + return Err(ast.error_at( + AsmError::SymbolError(format!( + "Constant '{name}' conflicts with a label or extern symbol" + )), + declaration.max(previous), + Some(declaration.min(previous)), + )); + } + match expr { + ExprValue::Number(_) => ready.push_back(position), + ExprValue::Symbol { name: dependency, .. } => { + let dependency = positions.get(dependency).ok_or_else(|| { + ast.error_at( + AsmError::SymbolError(format!( + "equ requires a constant expression; unresolved symbol '{dependency}'" + )), + constant_sites[name], + None, + ) + })?; + dependents[*dependency].push(position); + }, + } + } + let mut values = HashMap::new(); + while let Some(position) = ready.pop_front() { + let (name, expr) = &definitions[position]; + let EvaluatedExpr::Number(value) = eval_expr(expr, &values) + .map_err(|error| ast.error_at(error, constant_sites[name], None))? + else { + return Err(ast.error_at( + AsmError::SymbolError(format!("Unresolved constant dependency for '{name}'")), + constant_sites[name], + None, + )); + }; + values.insert(name.clone(), value); + ready.extend(dependents[position].iter().copied()); + } + if let Some((name, _)) = definitions.iter().find(|(name, _)| !values.contains_key(name)) { + return Err(ast.error_at( + AsmError::SymbolError(format!("Constant dependency cycle prevents resolving '{name}'")), + constant_sites[name], + None, + )); + } + Ok(values) +} + +pub fn encode_with_limits( + ast: &AST, + limits: &assembler::AssemblyLimits, +) -> Result { + let consts = resolve_constants(ast)?; + let mut prev_label_locs = None; + let mut forced_near = HashSet::new(); + for _ in 0..limits.max_relax_iterations { + let mut pass = + encode_once(ast, prev_label_locs.as_ref(), &consts, limits, &mut forced_near)?; + if prev_label_locs.as_ref() == Some(&pass.layout) { + resolve_loops(ast, &mut pass)?; + return Ok(pass.output); + } + prev_label_locs = Some(pass.layout); + } + Err(AsmError::EncodeError(format!( + "Branch relaxation did not converge within {} passes", + limits.max_relax_iterations + ))) +} + +fn encode_once( + ast: &AST, + jump_hint_layout: Option<&EncodingLayout>, + consts: &HashMap, + limits: &assembler::AssemblyLimits, + forced_near: &mut HashSet, +) -> Result { + let mut materialized = 0usize; + let mut sections = Vec::new(); + let mut symbols = Vec::new(); + + let mut defined_labels = HashSet::::new(); + let mut label_locs = HashMap::::new(); + let mut jump_known_locs = + jump_hint_layout.map(|layout| layout.labels.clone()).unwrap_or_default(); + let mut instruction_lengths = vec![0; ast.items.len()]; + let mut instruction_offsets = vec![0; ast.items.len()]; + let mut extern_symbols = HashSet::::new(); + let mut global_symbols = HashSet::::new(); + let mut label_sites = HashMap::::new(); + let mut extern_sites = HashMap::::new(); + let mut global_sites = HashMap::::new(); + let mut relocation_sites = HashMap::new(); + let mut symbol_metadata = HashMap::new(); + let mut metadata_sites = HashMap::::new(); + + sections.push(AsmSection { + kind: AsmSectionKind::Text, + align: 16, + name: ".text".to_string(), + data: Vec::new(), + zero_fill: 0, + relocs: Vec::new(), + }); + + let mut current_section_idx = 0usize; + let mut current_nonlocal_label: Option = None; + + for (node_index, node) in ast.items.iter().enumerate() { + let original_section = current_section_idx; + let relocation_start = sections[original_section].relocs.len(); + (|| -> Result<(), AsmError> { + match node { + ASTNode::Section(name) | ASTNode::SectionAttributes { name, .. } => { + let explicit = match node { + ASTNode::SectionAttributes { kind, .. } => Some(*kind), + _ => None, + }; + if let Some(idx) = sections.iter().position(|s| s.name == *name) { + if explicit.is_some_and(|kind| kind != sections[idx].kind) { + return Err(AsmError::EncodeError(format!( + "Incompatible section redeclaration '{name}'" + ))); + } + current_section_idx = idx; + } else { + let default = AsmSectionKind::default_for_name(name); + let kind = explicit.unwrap_or(default); + if matches!(name.as_str(), ".text" | ".data" | ".rodata" | ".bss") + && kind != default + { + return Err(AsmError::EncodeError(format!( + "Standard section '{name}' has incompatible kind" + ))); + } + sections.push(AsmSection { + name: name.clone(), + kind, + align: kind.default_alignment(), + data: Vec::new(), + zero_fill: 0, + relocs: Vec::new(), + }); + current_section_idx = sections.len() - 1; + } + }, + ASTNode::Global(name) => { + let resolved = resolve_symbol_name(name, ¤t_nonlocal_label)?; + global_sites.entry(resolved.clone()).or_insert(node_index); + global_symbols.insert(resolved); + }, + ASTNode::Extern(name) => { + let resolved = resolve_symbol_name(name, ¤t_nonlocal_label)?; + if defined_labels.contains(&resolved) { + return Err(ast.error_at( + AsmError::SymbolError(format!( + "Extern symbol '{}' was already defined in this file", + resolved + )), + node_index, + label_sites.get(&resolved).copied(), + )); + } + extern_sites.entry(resolved.clone()).or_insert(node_index); + if extern_symbols.insert(resolved.clone()) { + symbols.push(AsmSymbol { + kind: assembler::SymbolKind::NoType, + size: 0, + visibility: assembler::SymbolVisibility::Default, + name: resolved, + section_index: None, + offset: 0, + is_global: true, + }); + } + }, + ASTNode::SymbolMetadata { name, kind, size, visibility } => { + let name = resolve_symbol_name(name, ¤t_nonlocal_label)?; + let size = resolve_expr_symbols(size, ¤t_nonlocal_label)?; + let EvaluatedExpr::Number(size) = eval_expr(&size, consts)? else { + return Err(AsmError::SymbolError(format!( + "symbol '{name}' size must be a constant" + ))); + }; + let size = u64::try_from(size).map_err(|_| { + AsmError::SymbolError(format!( + "symbol '{name}' size must be a nonnegative u64" + )) + })?; + if symbol_metadata.insert(name.clone(), (*kind, size, *visibility)).is_some() { + return Err(ast.error_at( + AsmError::SymbolError(format!( + "Duplicate symbol metadata for '{name}'" + )), + node_index, + metadata_sites.get(&name).copied(), + )); + } + metadata_sites.insert(name, node_index); + }, + ASTNode::Const { .. } => {}, + ASTNode::Label(name) => { + let resolved = resolve_symbol_name(name, ¤t_nonlocal_label)?; + if !name.starts_with('.') { + current_nonlocal_label = Some(resolved.clone()); + } + if extern_symbols.contains(&resolved) { + return Err(ast.error_at( + AsmError::SymbolError(format!( + "Label '{}' conflicts with extern declaration", + resolved + )), + node_index, + extern_sites.get(&resolved).copied(), + )); + } + if consts.contains_key(&resolved) { + return Err(AsmError::SymbolError(format!( + "Label '{}' conflicts with constant definition", + resolved + ))); + } + if !defined_labels.insert(resolved.clone()) { + return Err(ast.error_at( + AsmError::SymbolError(format!( + "Duplicate label definition '{}'", + resolved + )), + node_index, + label_sites.get(&resolved).copied(), + )); + } + label_sites.insert(resolved.clone(), node_index); + let section = §ions[current_section_idx]; + let offset = (section.data.len() as u64) + .checked_add(section.zero_fill) + .ok_or_else(|| AsmError::EncodeError("section size overflow".into()))?; + label_locs.insert(resolved.clone(), (current_section_idx, offset)); + jump_known_locs.insert(resolved.clone(), (current_section_idx, offset)); + symbols.push(AsmSymbol { + kind: assembler::SymbolKind::NoType, + size: 0, + visibility: assembler::SymbolVisibility::Default, + name: resolved.clone(), + section_index: Some(current_section_idx), + offset, + is_global: global_symbols.contains(&resolved), + }); + }, + ASTNode::Instruction(ins) => { + let scoped = resolve_instruction_symbols(ins, ¤t_nonlocal_label)?; + let inst = resolve_instruction_consts(&scoped, consts)?; + let sec = &mut sections[current_section_idx]; + if sec.kind == AsmSectionKind::Bss { + return Err(AsmError::EncodeError( + "instructions are not valid in BSS".into(), + )); + } + let cur_off = sec.data.len(); + let mut instruction_bytes = Vec::new(); + let mut instruction_relocs = Vec::new(); + encode_instruction( + &inst, + &mut instruction_bytes, + &mut instruction_relocs, + current_section_idx, + jump_hint_layout + .map(|layout| layout.instruction_offsets[node_index]) + .unwrap_or(cur_off), + jump_hint_layout.map(|layout| &layout.labels).unwrap_or(&jump_known_locs), + BranchRelaxation { + previous_len: jump_hint_layout + .map(|layout| layout.instruction_lengths[node_index]) + .unwrap_or(0), + force_near: forced_near.contains(&node_index), + }, + )?; + // Alignment padding can offset an earlier shrink. Once a short + // branch must grow, keep it near: each branch changes size at most + // twice, so relaxation cannot oscillate around alignment edges. + if jump_hint_layout + .is_some_and(|layout| layout.instruction_lengths[node_index] == 2) + && instruction_bytes.len() > 2 + && (inst.mnemonic == "jmp" || condition_code(&inst.mnemonic).is_some()) + { + forced_near.insert(node_index); + } + instruction_lengths[node_index] = instruction_bytes.len(); + instruction_offsets[node_index] = cur_off; + reserve_output( + &mut sec.data, + instruction_bytes.len(), + &mut materialized, + limits, + )?; + sec.data.extend_from_slice(&instruction_bytes); + for reloc in &mut instruction_relocs { + reloc.offset += cur_off; + } + sec.relocs.extend(instruction_relocs); + }, + ASTNode::Directive(dir) => { + let scoped = resolve_directive_symbols(dir, ¤t_nonlocal_label)?; + let sec = &mut sections[current_section_idx]; + if scoped.name == "align" { + let alignment = alignment_value(&scoped, consts)?; + sec.align = sec.align.max(alignment); + let offset = (sec.data.len() as u64) + .checked_add(sec.zero_fill) + .ok_or_else(|| AsmError::EncodeError("Section size overflow".into()))?; + let padding = offset.wrapping_neg() & (alignment - 1); + offset.checked_add(padding).ok_or_else(|| { + AsmError::EncodeError("Alignment size overflow".into()) + })?; + if sec.kind == AsmSectionKind::Bss { + sec.zero_fill = + sec.zero_fill.checked_add(padding).ok_or_else(|| { + AsmError::EncodeError("BSS alignment overflow".into()) + })?; + } else { + let extra = usize::try_from(padding).map_err(|_| { + AsmError::EncodeError("Alignment exceeds host capacity".into()) + })?; + reserve_output(&mut sec.data, extra, &mut materialized, limits)?; + let fill = if sec.kind == AsmSectionKind::Text { 0x90 } else { 0 }; + sec.data.resize(sec.data.len() + extra, fill); + } + } else if sec.kind == AsmSectionKind::Bss { + encode_bss_directive(&scoped, sec, consts)?; + } else { + let extra = directive_size(&scoped, consts)?; + reserve_output(&mut sec.data, extra, &mut materialized, limits)?; + encode_directive(&scoped, &mut sec.data, &mut sec.relocs, consts)?; + } + }, + } + Ok(()) + })() + .map_err(|error| ast.error_at(error, node_index, None))?; + for relocation in relocation_start..sections[original_section].relocs.len() { + relocation_sites.insert((original_section, relocation), node_index); + } + } + + // `global` plus `extern` intentionally exports an undefined external; + // an ordinary global must have a label definition in this file. + if let Some(name) = global_symbols + .iter() + .filter(|name| !defined_labels.contains(*name) && !extern_symbols.contains(*name)) + .min() + { + return Err(ast.error_at( + AsmError::SymbolError(format!( + "Global symbol '{name}' has no definition or extern declaration" + )), + global_sites[name], + None, + )); + } + + let symbol_names: HashSet<_> = symbols.iter().map(|s| &s.name).collect(); + for name in symbol_metadata.keys() { + if !symbol_names.contains(name) { + return Err(ast.error_at( + AsmError::SymbolError(format!( + "Metadata symbol '{name}' has no label or extern declaration" + )), + metadata_sites[name], + None, + )); + } + } + for sym in &mut symbols { + if let Some((kind, size, visibility)) = symbol_metadata.get(&sym.name) { + sym.kind = *kind; + sym.size = *size; + sym.visibility = *visibility; + if let Some(index) = sym.section_index { + let section = §ions[index]; + let extent = (section.data.len() as u64) + .checked_add(section.zero_fill) + .ok_or_else(|| AsmError::SymbolError("symbol section size overflow".into()))?; + if sym.offset.checked_add(*size).is_none_or(|end| end > extent) { + return Err(ast.error_at( + AsmError::SymbolError(format!( + "Symbol '{}' size exceeds its section", + sym.name + )), + metadata_sites[&sym.name], + None, + )); + } + } + } + if global_symbols.contains(&sym.name) { + sym.is_global = true; + } + } + + for (section_index, sec) in sections.iter().enumerate() { + for (relocation_index, reloc) in sec.relocs.iter().enumerate() { + if !defined_labels.contains(&reloc.symbol) && !extern_symbols.contains(&reloc.symbol) { + return Err(ast.error_at(AsmError::SymbolError(format!("Undefined symbol '{}' (define it, declare with extern, or define with equ)",reloc.symbol)),relocation_sites[&(section_index,relocation_index)],None)); + } + } + } + + Ok(EncodingPass { + output: AssemblerOutput { sections, symbols }, + layout: EncodingLayout { labels: label_locs, instruction_lengths, instruction_offsets }, + relocation_sites, + }) +} + +// LOOP has a fixed length, so its displacement cannot affect relaxation. Resolve +// local PC8 fields only after the whole layout stabilizes; an intermediate near +// JMP/Jcc or alignment change must not trigger a premature range diagnostic. +fn resolve_loops(ast: &AST, pass: &mut EncodingPass) -> Result<(), AsmError> { + for (section_index, section) in pass.output.sections.iter_mut().enumerate() { + let mut retained = 0; + for index in 0..section.relocs.len() { + let relocation = §ion.relocs[index]; + let target = pass.layout.labels.get(&relocation.symbol); + if let Some((_, target_offset)) = target.filter(|(target_section, _)| { + matches!(relocation.kind, RelocKind::Relative8) && *target_section == section_index + }) { + let displacement = i128::from(*target_offset) - relocation.offset as i128 + + i128::from(relocation.addend); + let displacement = i8::try_from(displacement).map_err(|_| { + ast.error_at( + AsmError::EncodeError(format!( + "loop target '{}' is out of 8-bit range", + relocation.symbol + )), + pass.relocation_sites[&(section_index, index)], + None, + ) + })?; + section.data[relocation.offset] = displacement as u8; + } else { + section.relocs.swap(retained, index); + retained += 1; + } + } + section.relocs.truncate(retained); + } + Ok(()) +} + +#[derive(Clone)] +struct RegInfo { + code: u8, + width: u8, + high8: bool, + rex8: bool, +} + +#[derive(Clone)] +enum EvaluatedExpr { + Number(i128), + Symbol { name: String, addend: i64 }, +} + +fn resolve_symbol_name( + raw: &str, + current_nonlocal_label: &Option, +) -> Result { + if raw.starts_with('.') { + if let Some(base) = current_nonlocal_label { + return Ok(format!("{}{}", base, raw)); + } + return Err(AsmError::SymbolError(format!( + "Local label '{}' has no parent non-local label in scope", + raw + ))); + } + Ok(raw.to_string()) +} + +fn resolve_expr_symbols( + expr: &ExprValue, + current_nonlocal_label: &Option, +) -> Result { + match expr { + ExprValue::Number(n) => Ok(ExprValue::Number(*n)), + ExprValue::Symbol { name, addend } => Ok(ExprValue::Symbol { + name: resolve_symbol_name(name, current_nonlocal_label)?, + addend: *addend, + }), + } +} + +fn eval_expr(expr: &ExprValue, consts: &HashMap) -> Result { + Ok(match expr { + ExprValue::Number(n) => EvaluatedExpr::Number(*n), + ExprValue::Symbol { name, addend } => { + if let Some(c) = consts.get(name) { + EvaluatedExpr::Number(checked_expression_add(*c, *addend, name)?) + } else { + EvaluatedExpr::Symbol { + name: name.clone(), + addend: i64::try_from(*addend) + .map_err(|_| AsmError::EncodeError("Symbol addend overflow".into()))?, + } + } + }, + }) +} + +fn checked_expression_add(a: i128, b: i128, symbol: &str) -> Result { + a.checked_add(b).filter(|n| (i64::MIN as i128..=u64::MAX as i128).contains(n)).ok_or_else( + || AsmError::EncodeError(format!("Signed expression overflow while resolving {symbol:?}")), + ) +} + +fn relative_addend(displacement: i64) -> Result { + displacement + .checked_sub(4) + .ok_or_else(|| AsmError::EncodeError("Relative relocation addend overflow".into())) +} + +fn resolve_instruction_symbols( + ins: &Instruction, + current_nonlocal_label: &Option, +) -> Result { + let mut resolved_ops = Vec::with_capacity(ins.operands.len()); + for op in &ins.operands { + match op { + Operand::Label(sym) => { + resolved_ops.push(Operand::Label(resolve_symbol_name(sym, current_nonlocal_label)?)) + }, + Operand::SymbolExpr { name, addend } => { + resolved_ops.push(Operand::SymbolExpr { + name: resolve_symbol_name(name, current_nonlocal_label)?, + addend: *addend, + }); + }, + Operand::Memory(mem) => { + let mut mem = mem.clone(); + if let Some(sym) = &mem.symbol { + mem.symbol = Some(resolve_symbol_name(sym, current_nonlocal_label)?); + } + resolved_ops.push(Operand::Memory(mem)); + }, + _ => resolved_ops.push(op.clone()), + } + } + Ok(Instruction { mnemonic: ins.mnemonic.clone(), operands: resolved_ops }) +} + +fn resolve_instruction_consts( + ins: &Instruction, + consts: &HashMap, +) -> Result { + let mut resolved_ops = Vec::with_capacity(ins.operands.len()); + for op in &ins.operands { + match op { + Operand::Label(name) => { + if let Some(v) = consts.get(name) { + resolved_ops.push(Operand::Immediate(*v)); + } else { + resolved_ops.push(op.clone()); + } + }, + Operand::SymbolExpr { name, addend } => { + if let Some(v) = consts.get(name) { + resolved_ops + .push(Operand::Immediate(checked_expression_add(*v, *addend, name)?)); + } else { + resolved_ops.push(op.clone()); + } + }, + Operand::Memory(mem) => { + let mut mem = mem.clone(); + if let Some(sym) = &mem.symbol { + if let Some(v) = consts.get(sym) { + mem.disp = + i64::try_from(checked_expression_add(*v, mem.disp as i128, sym)?) + .map_err(|_| { + AsmError::EncodeError("Memory displacement overflow".into()) + })?; + mem.symbol = None; + } + } + resolved_ops.push(Operand::Memory(mem)); + }, + _ => resolved_ops.push(op.clone()), + } + } + Ok(Instruction { mnemonic: ins.mnemonic.clone(), operands: resolved_ops }) +} + +fn resolve_directive_symbols( + dir: &Directive, + current_nonlocal_label: &Option, +) -> Result { + let mut out_values = Vec::with_capacity(dir.values.len()); + for v in &dir.values { + match v { + DirectiveValue::StringLiteral(s) => { + out_values.push(DirectiveValue::StringLiteral(s.clone())) + }, + DirectiveValue::Expr(expr) => out_values + .push(DirectiveValue::Expr(resolve_expr_symbols(expr, current_nonlocal_label)?)), + } + } + Ok(Directive { name: dir.name.clone(), values: out_values }) +} + +fn lookup_reg(name: &str) -> Option { + if let Some((_, code)) = REGISTERS_64.iter().find(|(n, _)| *n == name) { + return Some(RegInfo { code: *code, width: 64, high8: false, rex8: false }); + } + if let Some((_, code)) = REGISTERS_32.iter().find(|(n, _)| *n == name) { + return Some(RegInfo { code: *code, width: 32, high8: false, rex8: false }); + } + if let Some((_, code)) = REGISTERS_16.iter().find(|(n, _)| *n == name) { + return Some(RegInfo { code: *code, width: 16, high8: false, rex8: false }); + } + if let Some((reg, code)) = REGISTERS_8.iter().find(|(n, _)| *n == name) { + return Some(RegInfo { + code: *code, + width: 8, + high8: matches!(*reg, "ah" | "bh" | "ch" | "dh"), + rex8: matches!(*reg, "spl" | "bpl" | "sil" | "dil"), + }); + } + None +} + +fn emit_operand_size_prefix(bytes: &mut Vec, width: u8) { + if width == 16 { + bytes.push(0x66); + } +} + +fn emit_rex( + bytes: &mut Vec, + width: u8, + rex_r: bool, + rex_x: bool, + rex_b: bool, + any_high8: bool, + force: bool, +) -> Result<(), AsmError> { + let mut rex = Rex::new(); + rex.w = width == 64; + rex.r = rex_r; + rex.x = rex_x; + rex.b = rex_b; + + let needed = force || rex.w || rex.r || rex.x || rex.b; + if any_high8 && needed { + return Err(AsmError::EncodeError( + "AH/CH/DH/BH cannot be encoded with a REX prefix".into(), + )); + } + if needed { + bytes.push(rex.encode()); + } + Ok(()) +} + +fn emit_disp(bytes: &mut Vec, disp: Option) { + if let Some(d) = disp { + match d { + DispKind::Disp8(v) => bytes.push(v as u8), + DispKind::Disp32(v) => bytes.extend_from_slice(&v.to_le_bytes()), + } + } +} + +fn emit_addr_tail(bytes: &mut Vec, addr: &EncodedAddress) { + if let Some((scale, index, base)) = addr.sib { + bytes.push((scale << 6) | (index << 3) | base); + } + emit_disp(bytes, addr.disp.clone()); +} + +fn emit_reg_reg( + bytes: &mut Vec, + opcode: u8, + dst: &RegInfo, + src: &RegInfo, +) -> Result<(), AsmError> { + emit_operand_size_prefix(bytes, dst.width); + emit_rex( + bytes, + dst.width, + src.code >= 8, + false, + dst.code >= 8, + dst.high8 || src.high8, + dst.rex8 || src.rex8, + )?; + bytes.push(opcode); + bytes.push(ModRM::new(0b11, src.code, dst.code).encode()); + Ok(()) +} + +fn validate_memory_width(mem: &MemoryOperand, width: u8) -> Result<(), AsmError> { + if mem.width.is_some_and(|explicit| explicit != width) { + return Err(AsmError::EncodeError( + "Memory width conflicts with register-derived width".into(), + )); + } + Ok(()) +} + +fn memory_address(mem: &MemoryOperand) -> Result { + if mem.symbol.is_none() { + return encode_address(mem, 64); + } + if mem.base.is_some() || mem.index.is_some() { + return Err(AsmError::EncodeError( + "symbol + register memory form is not implemented yet".into(), + )); + } + let mut address = mem.clone(); + address.symbol = None; + address.disp = 0; // The linker applies the checked symbol value plus addend. + if address.address_mode == MemoryAddressMode::Default { + address.address_mode = MemoryAddressMode::Relative; + } + encode_address(&address, 64) +} + +// Prefix selection belongs to each instruction; addressing and relocation +// offsets share one path, including instructions with a trailing immediate. +fn emit_memory_operation( + bytes: &mut Vec, + relocs: &mut Vec, + opcodes: &[u8], + reg: &RegInfo, + mem: &MemoryOperand, + rex_width: u8, + trailing: u8, +) -> Result<(), AsmError> { + let addr = memory_address(mem)?; + emit_rex(bytes, rex_width, reg.code >= 8, addr.rex_x, addr.rex_b, reg.high8, reg.rex8)?; + bytes.extend_from_slice(opcodes); + bytes.push(ModRM::new(addr.mod_bits, reg.code, addr.rm_bits).encode()); + if let Some(symbol) = &mem.symbol { + let absolute = mem.address_mode == MemoryAddressMode::Absolute; + let addend = if absolute { + mem.disp + } else { + relative_addend(mem.disp)?.checked_sub(i64::from(trailing)).ok_or_else(|| { + AsmError::EncodeError("Relative relocation addend overflow".into()) + })? + }; + relocs.push(Relocation { + offset: bytes.len() + usize::from(addr.sib.is_some()), + symbol: symbol.clone(), + kind: if absolute { RelocKind::SignedAbsolute32 } else { RelocKind::Relative32 }, + addend, + }); + } + emit_addr_tail(bytes, &addr); + Ok(()) +} + +fn emit_reg_mem( + bytes: &mut Vec, + relocs: &mut Vec, + opcode: u8, + reg: &RegInfo, + mem: &MemoryOperand, +) -> Result<(), AsmError> { + validate_memory_width(mem, reg.width)?; + emit_operand_size_prefix(bytes, reg.width); + emit_memory_operation(bytes, relocs, &[opcode], reg, mem, reg.width, 0) +} + +fn emit_mem_reg( + bytes: &mut Vec, + relocs: &mut Vec, + opcode: u8, + mem: &MemoryOperand, + reg: &RegInfo, +) -> Result<(), AsmError> { + emit_reg_mem(bytes, relocs, opcode, reg, mem) +} + +#[derive(Clone, Copy)] +struct BranchRelaxation { + previous_len: usize, + force_near: bool, +} + +fn encode_instruction( + ins: &Instruction, + bytes: &mut Vec, + relocs: &mut Vec, + current_section: usize, + current_offset: usize, + label_locs: &HashMap, + relaxation: BranchRelaxation, +) -> Result<(), AsmError> { + match ins.mnemonic.as_str() { + "ret" | "nop" | "syscall" | "int3" | "cwd" | "cdq" | "cqo" if !ins.operands.is_empty() => { + Err(AsmError::EncodeError(format!("{} expects 0 operands", ins.mnemonic))) + }, + "movss" | "movsd" | "addss" | "addsd" | "subss" | "subsd" | "mulss" | "mulsd" | "divss" + | "divsd" => encode_scalar_sse(ins, bytes, relocs), + "mov" => encode_mov(ins, bytes, relocs), + "movzx" | "movsx" | "movsxd" => encode_extension(ins, bytes, relocs), + "adc" => encode_carry(ins, 0x10, 0x11, bytes), + "sbb" => encode_carry(ins, 0x18, 0x19, bytes), + mnemonic if prefixed_condition(mnemonic, "set").is_some() => { + encode_setcc(ins, prefixed_condition(mnemonic, "set").unwrap(), bytes, relocs) + }, + mnemonic if prefixed_condition(mnemonic, "cmov").is_some() => { + encode_cmovcc(ins, prefixed_condition(mnemonic, "cmov").unwrap(), bytes) + }, + "add" => encode_binop(ins, 0x00, 0x01, 0x02, 0x03, 0, bytes, relocs), + "sub" => encode_binop(ins, 0x28, 0x29, 0x2A, 0x2B, 5, bytes, relocs), + "and" => encode_binop(ins, 0x20, 0x21, 0x22, 0x23, 4, bytes, relocs), + "or" => encode_binop(ins, 0x08, 0x09, 0x0A, 0x0B, 1, bytes, relocs), + "xor" => encode_binop(ins, 0x30, 0x31, 0x32, 0x33, 6, bytes, relocs), + "cmp" => encode_binop(ins, 0x38, 0x39, 0x3A, 0x3B, 7, bytes, relocs), + "imul" => encode_imul(ins, bytes, relocs), + "lea" => encode_lea(ins, bytes, relocs), + "test" => encode_test(ins, bytes), + "not" => encode_unary_register(ins, 2, bytes), + "neg" => encode_unary_register(ins, 3, bytes), + "div" => encode_unary_register(ins, 6, bytes), + "idiv" => encode_unary_register(ins, 7, bytes), + "shl" | "sal" => encode_shift(ins, 4, bytes), + "shr" => encode_shift(ins, 5, bytes), + "sar" => encode_shift(ins, 7, bytes), + "cwd" => { + bytes.extend_from_slice(&[0x66, 0x99]); + Ok(()) + }, + "cdq" => { + bytes.push(0x99); + Ok(()) + }, + "cqo" => { + bytes.extend_from_slice(&[0x48, 0x99]); + Ok(()) + }, + "push" if matches!(ins.operands.first(), Some(Operand::Immediate(_))) => { + encode_push_immediate(ins, bytes) + }, + "push" => encode_push_pop(ins, 0x50, bytes), + "pop" => encode_push_pop(ins, 0x58, bytes), + "jmp" | "call" + if matches!(ins.operands.first(), Some(Operand::Register(_) | Operand::Memory(_))) => + { + encode_indirect_branch(ins, bytes, relocs) + }, + "jmp" => encode_jump( + ins, + JumpSpec { + previous_len: relaxation.previous_len, + force_near: relaxation.force_near, + near_opcode: JumpOpcode::One(0xE9), + short_opcode: Some(0xEB), + reloc_kind: RelocKind::Branch32, + reloc_addend: -4, + near_len: 5, + }, + bytes, + relocs, + current_section, + current_offset, + label_locs, + ), + "call" => encode_jump( + ins, + JumpSpec { + previous_len: relaxation.previous_len, + force_near: relaxation.force_near, + near_opcode: JumpOpcode::One(0xE8), + short_opcode: None, + reloc_kind: RelocKind::Branch32, + reloc_addend: -4, + near_len: 5, + }, + bytes, + relocs, + current_section, + current_offset, + label_locs, + ), + condition if condition_code(condition).is_some() => encode_jump( + ins, + JumpSpec { + previous_len: relaxation.previous_len, + force_near: relaxation.force_near, + near_opcode: JumpOpcode::Two(0x0F, 0x80 + condition_code(condition).unwrap()), + short_opcode: Some(0x70 + condition_code(condition).unwrap()), + reloc_kind: RelocKind::Branch32, + reloc_addend: -4, + near_len: 6, + }, + bytes, + relocs, + current_section, + current_offset, + label_locs, + ), + "loop" => encode_loop(ins, bytes, relocs), + "ret" => { + bytes.push(0xC3); + Ok(()) + }, + "nop" => { + bytes.push(0x90); + Ok(()) + }, + "syscall" => { + bytes.push(0x0F); + bytes.push(0x05); + Ok(()) + }, + "int3" => { + bytes.push(0xCC); + Ok(()) + }, + _ => Err(AsmError::EncodeError(format!("Unknown mnemonic {}", ins.mnemonic))), + } +} + +fn symbol_operand(op: &Operand) -> Option<(String, i128)> { + match op { + Operand::Label(name) => Some((name.clone(), 0)), + Operand::SymbolExpr { name, addend } => Some((name.clone(), *addend)), + _ => None, + } +} + +fn xmm_operand(operand: &Operand) -> Result { + if let Operand::Register(name) = operand { + if let Some(code) = xmm_register_code(name) { + return Ok(code); + } + } + Err(AsmError::EncodeError("Expected XMM0-XMM15 register".into())) +} + +fn encode_scalar_sse( + ins: &Instruction, + bytes: &mut Vec, + relocs: &mut Vec, +) -> Result<(), AsmError> { + if ins.operands.len() != 2 { + return Err(AsmError::EncodeError(format!("{} expects 2 operands", ins.mnemonic))); + } + let single = ins.mnemonic.ends_with("ss"); + let (prefix, width) = if single { (0xf3, 32) } else { (0xf2, 64) }; + let move_instruction = matches!(ins.mnemonic.as_str(), "movss" | "movsd"); + let opcode = match ins.mnemonic.as_str() { + "movss" | "movsd" => 0x10, + "addss" | "addsd" => 0x58, + "subss" | "subsd" => 0x5c, + "mulss" | "mulsd" => 0x59, + "divss" | "divsd" => 0x5e, + _ => unreachable!(), + }; + // XMM registers are 128-bit registers. The scalar access width chooses the + // mandatory prefix, never REX.W or the integer operand-size prefix 66. + if let Operand::Memory(mem) = &ins.operands[0] { + if !move_instruction { + return Err(AsmError::EncodeError( + "Scalar SSE arithmetic destination must be XMM".into(), + )); + } + let code = xmm_operand(&ins.operands[1])?; + validate_memory_width(mem, width)?; + bytes.push(prefix); + let reg = RegInfo { code, width, high8: false, rex8: false }; + return emit_memory_operation(bytes, relocs, &[0x0f, 0x11], ®, mem, 0, 0); + } + let code = xmm_operand(&ins.operands[0])?; + match &ins.operands[1] { + Operand::Register(_) => { + let source = xmm_operand(&ins.operands[1])?; + bytes.push(prefix); + emit_rex(bytes, 0, code >= 8, false, source >= 8, false, false)?; + bytes.extend_from_slice(&[0x0f, opcode]); + bytes.push(ModRM::new(3, code, source).encode()); + Ok(()) + }, + Operand::Memory(mem) => { + validate_memory_width(mem, width)?; + bytes.push(prefix); + let reg = RegInfo { code, width, high8: false, rex8: false }; + emit_memory_operation(bytes, relocs, &[0x0f, opcode], ®, mem, 0, 0) + }, + _ => Err(AsmError::EncodeError( + "Scalar SSE source must be XMM or matching scalar memory".into(), + )), + } +} + +fn encode_mov( + ins: &Instruction, + bytes: &mut Vec, + relocs: &mut Vec, +) -> Result<(), AsmError> { + if ins.operands.len() != 2 { + return Err(AsmError::EncodeError("mov expects 2 operands".into())); + } + let dst = &ins.operands[0]; + let src = &ins.operands[1]; + + match (dst, src) { + (Operand::Register(dst_name), Operand::Immediate(imm)) => { + let reg = + lookup_reg(dst_name).ok_or(AsmError::EncodeError("Invalid register".into()))?; + match reg.width { + 8 => { + if !(-128..=255).contains(imm) { + return Err(AsmError::EncodeError("imm8 out of range".into())); + } + emit_rex(bytes, reg.width, false, false, reg.code >= 8, reg.high8, reg.rex8)?; + bytes.push(0xB0 + (reg.code & 7)); + bytes.push(*imm as u8); + }, + 16 => { + if !(-32768..=65535).contains(imm) { + return Err(AsmError::EncodeError("imm16 out of range".into())); + } + emit_operand_size_prefix(bytes, reg.width); + emit_rex(bytes, reg.width, false, false, reg.code >= 8, false, false)?; + bytes.push(0xB8 + (reg.code & 7)); + bytes.extend_from_slice(&(*imm as i16).to_le_bytes()); + }, + 32 => { + if !(*imm >= i32::MIN as i128 && *imm <= u32::MAX as i128) { + return Err(AsmError::EncodeError("imm32 out of range".into())); + } + emit_rex(bytes, reg.width, false, false, reg.code >= 8, false, false)?; + bytes.push(0xB8 + (reg.code & 7)); + bytes.extend_from_slice(&(*imm as u32).to_le_bytes()); + }, + 64 => { + emit_rex(bytes, reg.width, false, false, reg.code >= 8, false, false)?; + bytes.push(0xB8 + (reg.code & 7)); + if !(i64::MIN as i128..=u64::MAX as i128).contains(imm) { + return Err(AsmError::EncodeError("imm64 out of range".into())); + } + bytes.extend_from_slice(&(*imm as u64).to_le_bytes()); + }, + _ => return Err(AsmError::EncodeError("Unsupported register width".into())), + } + Ok(()) + }, + (Operand::Register(dst_name), _) if symbol_operand(src).is_some() => { + let (label, addend) = symbol_operand(src).unwrap(); + let reg = + lookup_reg(dst_name).ok_or(AsmError::EncodeError("Invalid register".into()))?; + match reg.width { + 64 => { + emit_rex(bytes, reg.width, false, false, reg.code >= 8, false, false)?; + bytes.push(0xB8 + (reg.code & 7)); + relocs.push(Relocation { + offset: bytes.len(), + symbol: label, + kind: RelocKind::Absolute64, + addend: i64::try_from(addend) + .map_err(|_| AsmError::EncodeError("Symbol addend overflow".into()))?, + }); + bytes.extend_from_slice(&0i64.to_le_bytes()); + }, + 32 => { + emit_rex(bytes, reg.width, false, false, reg.code >= 8, false, false)?; + bytes.push(0xB8 + (reg.code & 7)); + relocs.push(Relocation { + offset: bytes.len(), + symbol: label, + kind: RelocKind::Absolute32, + addend: i64::try_from(addend) + .map_err(|_| AsmError::EncodeError("Symbol addend overflow".into()))?, + }); + bytes.extend_from_slice(&0u32.to_le_bytes()); + }, + _ => { + return Err(AsmError::EncodeError( + "Symbol move is supported only for r32/r64".into(), + )) + }, + } + Ok(()) + }, + (Operand::Register(dst_name), Operand::Register(src_name)) => { + let dst_reg = + lookup_reg(dst_name).ok_or(AsmError::EncodeError("Invalid dst register".into()))?; + let src_reg = + lookup_reg(src_name).ok_or(AsmError::EncodeError("Invalid src register".into()))?; + if dst_reg.width != src_reg.width { + return Err(AsmError::EncodeError("Register width mismatch".into())); + } + let opcode = if dst_reg.width == 8 { 0x88 } else { 0x89 }; + emit_reg_reg(bytes, opcode, &dst_reg, &src_reg) + }, + (Operand::Register(dst_name), Operand::Memory(mem)) => { + let reg = + lookup_reg(dst_name).ok_or(AsmError::EncodeError("Invalid register".into()))?; + let opcode = if reg.width == 8 { 0x8A } else { 0x8B }; + emit_reg_mem(bytes, relocs, opcode, ®, mem) + }, + (Operand::Memory(mem), Operand::Register(src_name)) => { + let reg = + lookup_reg(src_name).ok_or(AsmError::EncodeError("Invalid register".into()))?; + let opcode = if reg.width == 8 { 0x88 } else { 0x89 }; + emit_mem_reg(bytes, relocs, opcode, mem, ®) + }, + (Operand::Memory(mem), Operand::Immediate(imm)) => { + encode_memory_immediate(mem, *imm, None, bytes, relocs) + }, + _ => Err(AsmError::EncodeError("Unsupported mov form".into())), + } +} + +// The five opcode fields describe the existing instruction table explicitly. +#[allow(clippy::too_many_arguments)] +fn encode_binop( + ins: &Instruction, + opcode_rm_r_8: u8, + opcode_rm_r: u8, + opcode_r_rm_8: u8, + opcode_r_rm: u8, + imm_op_ext: u8, + bytes: &mut Vec, + relocs: &mut Vec, +) -> Result<(), AsmError> { + if ins.operands.len() != 2 { + return Err(AsmError::EncodeError(format!("{} expects 2 operands", ins.mnemonic))); + } + let dst = &ins.operands[0]; + let src = &ins.operands[1]; + + match (dst, src) { + (Operand::Register(dst_name), Operand::Register(src_name)) => { + let dst_reg = + lookup_reg(dst_name).ok_or(AsmError::EncodeError("Invalid dst register".into()))?; + let src_reg = + lookup_reg(src_name).ok_or(AsmError::EncodeError("Invalid src register".into()))?; + if dst_reg.width != src_reg.width { + return Err(AsmError::EncodeError("Register width mismatch".into())); + } + let opcode = if dst_reg.width == 8 { opcode_rm_r_8 } else { opcode_rm_r }; + emit_reg_reg(bytes, opcode, &dst_reg, &src_reg) + }, + (Operand::Register(dst_name), Operand::Immediate(imm)) => { + let dst_reg = + lookup_reg(dst_name).ok_or(AsmError::EncodeError("Invalid dst register".into()))?; + emit_operand_size_prefix(bytes, dst_reg.width); + emit_rex( + bytes, + dst_reg.width, + false, + false, + dst_reg.code >= 8, + dst_reg.high8, + dst_reg.rex8, + )?; + + if dst_reg.width == 8 { + if !(-128..=255).contains(imm) { + return Err(AsmError::EncodeError("imm8 out of range".into())); + } + bytes.push(0x80); + bytes.push(ModRM::new(0b11, imm_op_ext, dst_reg.code).encode()); + bytes.push(*imm as u8); + return Ok(()); + } + + if (-128..=127).contains(imm) { + bytes.push(0x83); + bytes.push(ModRM::new(0b11, imm_op_ext, dst_reg.code).encode()); + bytes.push(*imm as u8); + return Ok(()); + } + + bytes.push(0x81); + bytes.push(ModRM::new(0b11, imm_op_ext, dst_reg.code).encode()); + match dst_reg.width { + 16 => { + if !(-32768..=65535).contains(imm) { + return Err(AsmError::EncodeError("imm16 out of range".into())); + } + bytes.extend_from_slice(&(*imm as i16).to_le_bytes()); + }, + 32 => { + if !(*imm >= i32::MIN as i128 && *imm <= u32::MAX as i128) { + return Err(AsmError::EncodeError("imm32 out of range".into())); + } + bytes.extend_from_slice(&(*imm as u32).to_le_bytes()); + }, + 64 => { + if !(*imm >= i32::MIN as i128 && *imm <= i32::MAX as i128) { + return Err(AsmError::EncodeError( + "imm32-sign-extended out of range for r64".into(), + )); + } + bytes.extend_from_slice(&(*imm as i32).to_le_bytes()); + }, + _ => return Err(AsmError::EncodeError("Unsupported register width".into())), + } + Ok(()) + }, + (Operand::Register(_), _) if symbol_operand(src).is_some() => { + Err(AsmError::EncodeError(format!( + "{} with symbolic immediate is not supported; use equ or mov reg, symbol", + ins.mnemonic + ))) + }, + (Operand::Register(dst_name), Operand::Memory(mem)) => { + let reg = + lookup_reg(dst_name).ok_or(AsmError::EncodeError("Invalid register".into()))?; + let opcode = if reg.width == 8 { opcode_r_rm_8 } else { opcode_r_rm }; + emit_reg_mem(bytes, relocs, opcode, ®, mem) + }, + (Operand::Memory(mem), Operand::Register(src_name)) => { + let reg = + lookup_reg(src_name).ok_or(AsmError::EncodeError("Invalid register".into()))?; + let opcode = if reg.width == 8 { opcode_rm_r_8 } else { opcode_rm_r }; + emit_mem_reg(bytes, relocs, opcode, mem, ®) + }, + (Operand::Memory(mem), Operand::Immediate(imm)) => { + encode_memory_immediate(mem, *imm, Some(imm_op_ext), bytes, relocs) + }, + _ => Err(AsmError::EncodeError(format!("Unsupported {} form", ins.mnemonic))), + } +} + +fn encode_memory_immediate( + mem: &MemoryOperand, + imm: i128, + operation: Option, + bytes: &mut Vec, + relocs: &mut Vec, +) -> Result<(), AsmError> { + let width = mem.width.ok_or_else(|| { + AsmError::EncodeError("Ambiguous memory immediate; specify byte/word/dword/qword".into()) + })?; + let encoded_width = if width == 64 { 32 } else { width }; + let valid = match width { + 8 => (-128..=255).contains(&imm), + 16 => (-32768..=65535).contains(&imm), + 32 => (i32::MIN as i128..=u32::MAX as i128).contains(&imm), + 64 => (i32::MIN as i128..=i32::MAX as i128).contains(&imm), + _ => false, + }; + if !valid { + return Err(AsmError::EncodeError( + "Memory immediate out of range for selected width (qword requires signed imm32)".into(), + )); + } + let short = operation.is_some() && width != 8 && (-128..=127).contains(&imm); + let tail = if short { 1 } else { encoded_width / 8 }; + let opcode = match operation { + None => { + if width == 8 { + 0xc6 + } else { + 0xc7 + } + }, + Some(_) => { + if width == 8 { + 0x80 + } else if short { + 0x83 + } else { + 0x81 + } + }, + }; + emit_operand_size_prefix(bytes, width); + let group = RegInfo { code: operation.unwrap_or(0), width, high8: false, rex8: false }; + emit_memory_operation(bytes, relocs, &[opcode], &group, mem, width, tail)?; + bytes.extend_from_slice(&(imm as u64).to_le_bytes()[..tail as usize]); + Ok(()) +} + +fn encode_imul( + ins: &Instruction, + bytes: &mut Vec, + relocs: &mut Vec, +) -> Result<(), AsmError> { + if ins.operands.len() == 3 { + return encode_imul_immediate(ins, bytes); + } + if ins.operands.len() != 2 { + return Err(AsmError::EncodeError("imul expects 2 or 3 operands".into())); + } + let dst = &ins.operands[0]; + let src = &ins.operands[1]; + + let Operand::Register(dst_name) = dst else { + return Err(AsmError::EncodeError("imul form supported: imul reg, reg/mem".into())); + }; + let dst_reg = + lookup_reg(dst_name).ok_or(AsmError::EncodeError("Invalid dst register".into()))?; + + if dst_reg.width == 8 { + return Err(AsmError::EncodeError( + "imul reg, reg/mem is not supported for 8-bit operands".into(), + )); + } + + match src { + Operand::Register(src_name) => { + let src_reg = + lookup_reg(src_name).ok_or(AsmError::EncodeError("Invalid src register".into()))?; + if src_reg.width != dst_reg.width { + return Err(AsmError::EncodeError("Register width mismatch".into())); + } + emit_operand_size_prefix(bytes, dst_reg.width); + emit_rex( + bytes, + dst_reg.width, + dst_reg.code >= 8, + false, + src_reg.code >= 8, + false, + false, + )?; + bytes.push(0x0F); + bytes.push(0xAF); + bytes.push(ModRM::new(0b11, dst_reg.code, src_reg.code).encode()); + Ok(()) + }, + Operand::Memory(mem) => { + validate_memory_width(mem, dst_reg.width)?; + emit_operand_size_prefix(bytes, dst_reg.width); + emit_memory_operation(bytes, relocs, &[0x0f, 0xaf], &dst_reg, mem, dst_reg.width, 0)?; + Ok(()) + }, + _ => Err(AsmError::EncodeError("imul form supported: imul reg, reg/mem".into())), + } +} + +fn register_operand(op: &Operand) -> Result { + match op { + Operand::Register(name) => { + lookup_reg(name).ok_or_else(|| AsmError::EncodeError("Invalid register".into())) + }, + _ => Err(AsmError::EncodeError("Expected register operand".into())), + } +} + +fn encode_lea( + ins: &Instruction, + bytes: &mut Vec, + relocs: &mut Vec, +) -> Result<(), AsmError> { + if ins.operands.len() != 2 { + return Err(AsmError::EncodeError("lea expects 2 operands".into())); + } + let reg = register_operand(&ins.operands[0])?; + if !matches!(reg.width, 32 | 64) { + return Err(AsmError::EncodeError("lea destination must be r32 or r64".into())); + } + let Operand::Memory(mem) = &ins.operands[1] else { + return Err(AsmError::EncodeError("lea source must be memory address".into())); + }; + emit_reg_mem(bytes, relocs, 0x8d, ®, mem) +} + +fn encode_test(ins: &Instruction, bytes: &mut Vec) -> Result<(), AsmError> { + if ins.operands.len() != 2 { + return Err(AsmError::EncodeError("test expects 2 operands".into())); + } + let dst = register_operand(&ins.operands[0])?; + let src = register_operand(&ins.operands[1])?; + if dst.width != src.width { + return Err(AsmError::EncodeError("Register width mismatch".into())); + } + emit_reg_reg(bytes, if dst.width == 8 { 0x84 } else { 0x85 }, &dst, &src) +} + +fn encode_unary_register( + ins: &Instruction, + extension: u8, + bytes: &mut Vec, +) -> Result<(), AsmError> { + if ins.operands.len() != 1 { + return Err(AsmError::EncodeError(format!("{} expects 1 operand", ins.mnemonic))); + } + let reg = register_operand(&ins.operands[0])?; + emit_operand_size_prefix(bytes, reg.width); + emit_rex(bytes, reg.width, false, false, reg.code >= 8, reg.high8, reg.rex8)?; + bytes.push(if reg.width == 8 { 0xf6 } else { 0xf7 }); + bytes.push(ModRM::new(3, extension, reg.code).encode()); + Ok(()) +} + +fn encode_shift(ins: &Instruction, extension: u8, bytes: &mut Vec) -> Result<(), AsmError> { + if ins.operands.len() != 2 { + return Err(AsmError::EncodeError(format!("{} expects 2 operands", ins.mnemonic))); + } + let reg = register_operand(&ins.operands[0])?; + let (opcode, immediate) = match &ins.operands[1] { + Operand::Immediate(1) => (if reg.width == 8 { 0xd0 } else { 0xd1 }, None), + Operand::Immediate(count) if (0..=255).contains(count) => { + (if reg.width == 8 { 0xc0 } else { 0xc1 }, Some(*count as u8)) + }, + Operand::Register(count) if count == "cl" => { + (if reg.width == 8 { 0xd2 } else { 0xd3 }, None) + }, + _ => return Err(AsmError::EncodeError("Shift count must be CL or unsigned imm8".into())), + }; + emit_operand_size_prefix(bytes, reg.width); + emit_rex(bytes, reg.width, false, false, reg.code >= 8, reg.high8, reg.rex8)?; + bytes.push(opcode); + bytes.push(ModRM::new(3, extension, reg.code).encode()); + if let Some(count) = immediate { + bytes.push(count); + } + Ok(()) +} + +fn encode_imul_immediate(ins: &Instruction, bytes: &mut Vec) -> Result<(), AsmError> { + let dst = register_operand(&ins.operands[0])?; + let src = register_operand(&ins.operands[1])?; + let Operand::Immediate(imm) = ins.operands[2] else { + return Err(AsmError::EncodeError("imul third operand must be immediate".into())); + }; + if dst.width != src.width || !matches!(dst.width, 16 | 32 | 64) { + return Err(AsmError::EncodeError("imul requires matching r16/r32/r64 operands".into())); + } + let short = (-128..=127).contains(&imm); + let valid = match dst.width { + 16 => (-32768..=65535).contains(&imm), + 32 => (i32::MIN as i128..=u32::MAX as i128).contains(&imm), + 64 => (i32::MIN as i128..=i32::MAX as i128).contains(&imm), + _ => false, + }; + if !valid { + return Err(AsmError::EncodeError( + "imul immediate out of range (imm16/imm32; r64 sign extends imm32)".into(), + )); + } + emit_operand_size_prefix(bytes, dst.width); + emit_rex(bytes, dst.width, dst.code >= 8, false, src.code >= 8, false, false)?; + bytes.push(if short { 0x6b } else { 0x69 }); + bytes.push(ModRM::new(3, dst.code, src.code).encode()); + if short { + bytes.push(imm as u8); + } else if dst.width == 16 { + bytes.extend_from_slice(&(imm as u16).to_le_bytes()); + } else { + bytes.extend_from_slice(&(imm as u32).to_le_bytes()); + } + Ok(()) +} + +fn prefixed_condition(mnemonic: &str, prefix: &str) -> Option { + let suffix = mnemonic.strip_prefix(prefix)?; + CONDITION_CODES + .iter() + .find(|(name, _)| name.strip_prefix('j') == Some(suffix)) + .map(|(_, code)| *code) +} + +fn encode_carry( + ins: &Instruction, + byte_opcode: u8, + wide_opcode: u8, + bytes: &mut Vec, +) -> Result<(), AsmError> { + if ins.operands.len() != 2 { + return Err(AsmError::EncodeError(format!("{} expects 2 register operands", ins.mnemonic))); + } + let dst = register_operand(&ins.operands[0])?; + let src = register_operand(&ins.operands[1])?; + if dst.width != src.width { + return Err(AsmError::EncodeError("Register width mismatch".into())); + } + emit_reg_reg(bytes, if dst.width == 8 { byte_opcode } else { wide_opcode }, &dst, &src) +} + +fn encode_setcc( + ins: &Instruction, + condition: u8, + bytes: &mut Vec, + relocs: &mut Vec, +) -> Result<(), AsmError> { + if ins.operands.len() != 1 { + return Err(AsmError::EncodeError("setcc expects 1 byte operand".into())); + } + emit_group_operand(&ins.operands[0], 8, 8, &[0x0f, 0x90 + condition], 0, bytes, relocs) +} + +fn encode_cmovcc(ins: &Instruction, condition: u8, bytes: &mut Vec) -> Result<(), AsmError> { + if ins.operands.len() != 2 { + return Err(AsmError::EncodeError("cmovcc expects 2 register operands".into())); + } + let dst = register_operand(&ins.operands[0])?; + let src = register_operand(&ins.operands[1])?; + if dst.width != src.width || !matches!(dst.width, 16 | 32 | 64) { + return Err(AsmError::EncodeError("cmovcc requires matching r16/r32/r64 registers".into())); + } + emit_operand_size_prefix(bytes, dst.width); + emit_rex(bytes, dst.width, dst.code >= 8, false, src.code >= 8, false, false)?; + bytes.extend_from_slice(&[0x0f, 0x40 + condition]); + bytes.push(ModRM::new(3, dst.code, src.code).encode()); + Ok(()) +} + +fn encode_indirect_branch( + ins: &Instruction, + bytes: &mut Vec, + relocs: &mut Vec, +) -> Result<(), AsmError> { + if ins.operands.len() != 1 { + return Err(AsmError::EncodeError(format!("{} expects 1 operand", ins.mnemonic))); + } + // Near indirect branches default to 64-bit in long mode; REX.W is unnecessary. + emit_group_operand( + &ins.operands[0], + 64, + 0, + &[0xff], + if ins.mnemonic == "call" { 2 } else { 4 }, + bytes, + relocs, + ) +} + +fn emit_group_operand( + operand: &Operand, + width: u8, + rex_width: u8, + opcodes: &[u8], + extension: u8, + bytes: &mut Vec, + relocs: &mut Vec, +) -> Result<(), AsmError> { + emit_operand_size_prefix(bytes, width); + match operand { + Operand::Register(_) => { + let reg = register_operand(operand)?; + if reg.width != width { + return Err(AsmError::EncodeError( + "Register width does not match instruction".into(), + )); + } + emit_rex(bytes, rex_width, false, false, reg.code >= 8, reg.high8, reg.rex8)?; + bytes.extend_from_slice(opcodes); + bytes.push(ModRM::new(3, extension, reg.code).encode()); + }, + Operand::Memory(mem) => { + validate_memory_width(mem, width)?; + let group = RegInfo { code: extension, width, high8: false, rex8: false }; + emit_memory_operation(bytes, relocs, opcodes, &group, mem, rex_width, 0)?; + }, + _ => return Err(AsmError::EncodeError("Expected register or memory operand".into())), + } + Ok(()) +} + +fn encode_extension( + ins: &Instruction, + bytes: &mut Vec, + relocs: &mut Vec, +) -> Result<(), AsmError> { + if ins.operands.len() != 2 { + return Err(AsmError::EncodeError(format!("{} expects 2 operands", ins.mnemonic))); + } + let dst = register_operand(&ins.operands[0])?; + let src_width = match &ins.operands[1] { + Operand::Register(_) => register_operand(&ins.operands[1])?.width, + Operand::Memory(mem) => mem.width.ok_or_else(|| { + AsmError::EncodeError("Extension memory source requires byte/word/dword width".into()) + })?, + _ => { + return Err(AsmError::EncodeError("Extension source must be register or memory".into())) + }, + }; + let valid = if ins.mnemonic == "movsxd" { + dst.width == 64 && src_width == 32 + } else { + (src_width == 8 && matches!(dst.width, 16 | 32 | 64)) + || (src_width == 16 && matches!(dst.width, 32 | 64)) + }; + if !valid { + return Err(AsmError::EncodeError( + "Invalid extension source/destination width pair".into(), + )); + } + let opcode = if ins.mnemonic == "movsxd" { + vec![0x63] + } else { + vec![ + 0x0f, + match (ins.mnemonic.as_str(), src_width) { + ("movzx", 8) => 0xb6, + ("movzx", 16) => 0xb7, + ("movsx", 8) => 0xbe, + _ => 0xbf, + }, + ] + }; + emit_operand_size_prefix(bytes, dst.width); + match &ins.operands[1] { + Operand::Register(_) => { + let src = register_operand(&ins.operands[1])?; + emit_rex(bytes, dst.width, dst.code >= 8, false, src.code >= 8, src.high8, src.rex8)?; + bytes.extend_from_slice(&opcode); + bytes.push(ModRM::new(3, dst.code, src.code).encode()); + }, + Operand::Memory(mem) => { + emit_memory_operation(bytes, relocs, &opcode, &dst, mem, dst.width, 0)?; + }, + _ => unreachable!(), + } + Ok(()) +} + +fn encode_push_immediate(ins: &Instruction, bytes: &mut Vec) -> Result<(), AsmError> { + if ins.operands.len() != 1 { + return Err(AsmError::EncodeError("push expects 1 operand".into())); + } + let Operand::Immediate(imm) = ins.operands[0] else { unreachable!() }; + if (-128..=127).contains(&imm) { + bytes.extend_from_slice(&[0x6a, imm as u8]); + } else if (i32::MIN as i128..=i32::MAX as i128).contains(&imm) { + bytes.push(0x68); + bytes.extend_from_slice(&(imm as i32).to_le_bytes()); + } else { + return Err(AsmError::EncodeError( + "push immediate requires signed imm8 or signed imm32 in AMD64 mode".into(), + )); + } + Ok(()) +} + +fn encode_push_pop( + ins: &Instruction, + base_opcode: u8, + bytes: &mut Vec, +) -> Result<(), AsmError> { + if ins.operands.len() != 1 { + return Err(AsmError::EncodeError(format!("{} expects 1 operand", ins.mnemonic))); + } + if let Operand::Register(name) = &ins.operands[0] { + let reg = lookup_reg(name).ok_or(AsmError::EncodeError("Invalid register".into()))?; + if reg.width == 16 { + bytes.push(0x66); + } else if reg.width != 64 { + return Err(AsmError::EncodeError( + "push/pop currently support only r16/r64 in amd64 mode".into(), + )); + } + emit_rex(bytes, 0, false, false, reg.code >= 8, false, false)?; + bytes.push(base_opcode + (reg.code & 7)); + Ok(()) + } else { + Err(AsmError::EncodeError(format!("{} only supports registers for now", ins.mnemonic))) + } +} + +enum JumpOpcode { + One(u8), + Two(u8, u8), +} + +struct JumpSpec { + previous_len: usize, + force_near: bool, + near_opcode: JumpOpcode, + short_opcode: Option, + reloc_kind: RelocKind, + reloc_addend: i64, + near_len: usize, +} + +fn emit_near_opcode(bytes: &mut Vec, opcode: &JumpOpcode) { + match opcode { + JumpOpcode::One(b) => bytes.push(*b), + JumpOpcode::Two(a, b) => { + bytes.push(*a); + bytes.push(*b); + }, + } +} + +fn encode_jump( + ins: &Instruction, + spec: JumpSpec, + bytes: &mut Vec, + relocs: &mut Vec, + current_section: usize, + current_offset: usize, + label_locs: &HashMap, +) -> Result<(), AsmError> { + if ins.operands.len() != 1 { + return Err(AsmError::EncodeError(format!("{} expects 1 operand", ins.mnemonic))); + } + let Some((label, addend)) = symbol_operand(&ins.operands[0]) else { + return Err(AsmError::EncodeError(format!( + "{} only supports labels for now", + ins.mnemonic + ))); + }; + if addend != 0 { + return Err(AsmError::EncodeError(format!( + "{} does not support label addends", + ins.mnemonic + ))); + } + + if let Some((target_sec, target_off)) = label_locs.get(&label) { + if *target_sec == current_section { + if let Some(short_op) = spec.short_opcode.filter(|_| !spec.force_near) { + let short_len = 2i64; + // A forward target moves when this branch itself shrinks. + // Its previous encoded length keeps the inclusive +127 edge + // available without ever truncating an out-of-range count. + let own_shrink = if *target_off > current_offset as u64 { + spec.previous_len.saturating_sub(short_len as usize) as i64 + } else { + 0 + }; + let disp_short = + *target_off as i64 - own_shrink - (current_offset as i64 + short_len); + if (-128..=127).contains(&disp_short) { + bytes.push(short_op); + bytes.push(disp_short as i8 as u8); + return Ok(()); + } + } + + let disp_near = *target_off as i64 - (current_offset as i64 + spec.near_len as i64); + if !(i32::MIN as i64..=i32::MAX as i64).contains(&disp_near) { + return Err(AsmError::EncodeError(format!( + "{} target '{}' is out of 32-bit relative range", + ins.mnemonic, label + ))); + } + + emit_near_opcode(bytes, &spec.near_opcode); + bytes.extend_from_slice(&(disp_near as i32).to_le_bytes()); + return Ok(()); + } + } + + emit_near_opcode(bytes, &spec.near_opcode); + relocs.push(Relocation { + offset: bytes.len(), + symbol: label, + kind: spec.reloc_kind, + addend: spec.reloc_addend, + }); + bytes.extend_from_slice(&0i32.to_le_bytes()); + Ok(()) +} + +fn encode_loop( + ins: &Instruction, + bytes: &mut Vec, + relocs: &mut Vec, +) -> Result<(), AsmError> { + if ins.operands.len() != 1 { + return Err(AsmError::EncodeError("loop expects 1 operand".into())); + } + let Some((label, addend)) = symbol_operand(&ins.operands[0]) else { + return Err(AsmError::EncodeError("loop only supports labels for now".into())); + }; + if addend != 0 { + return Err(AsmError::EncodeError("loop does not support label addends".into())); + } + + bytes.push(0xE2); + + relocs.push(Relocation { + offset: bytes.len(), + symbol: label, + kind: RelocKind::Relative8, + addend: -1, + }); + bytes.push(0); + Ok(()) +} + +fn eval_directive_expr( + expr: &ExprValue, + consts: &HashMap, +) -> Result { + eval_expr(expr, consts) +} + +fn encode_data_expr( + eval: EvaluatedExpr, + width: usize, + bytes: &mut Vec, + relocs: &mut Vec, +) -> Result<(), AsmError> { + match eval { + EvaluatedExpr::Number(n) => { + match width { + 1 => { + if !(-128..=255).contains(&n) { + return Err(AsmError::EncodeError("db value out of range".into())); + } + bytes.push(n as u8); + }, + 2 => { + if !(-32768..=65535).contains(&n) { + return Err(AsmError::EncodeError("dw value out of range".into())); + } + bytes.extend_from_slice(&(n as i16).to_le_bytes()); + }, + 4 => { + if !(i32::MIN as i128..=u32::MAX as i128).contains(&n) { + return Err(AsmError::EncodeError("dd value out of range".into())); + } + bytes.extend_from_slice(&(n as u32).to_le_bytes()); + }, + 8 => { + if !(i64::MIN as i128..=u64::MAX as i128).contains(&n) { + return Err(AsmError::EncodeError("dq value out of range".into())); + } + bytes.extend_from_slice(&(n as u64).to_le_bytes()); + }, + _ => return Err(AsmError::EncodeError("Unsupported data width".into())), + } + Ok(()) + }, + EvaluatedExpr::Symbol { name, addend } => match width { + 4 => { + relocs.push(Relocation { + offset: bytes.len(), + symbol: name, + kind: RelocKind::Absolute32, + addend, + }); + bytes.extend_from_slice(&0u32.to_le_bytes()); + Ok(()) + }, + 8 => { + relocs.push(Relocation { + offset: bytes.len(), + symbol: name, + kind: RelocKind::Absolute64, + addend, + }); + bytes.extend_from_slice(&0u64.to_le_bytes()); + Ok(()) + }, + _ => Err(AsmError::EncodeError("Only dd/dq support symbolic expressions".into())), + }, + } +} + +fn alignment_value(dir: &Directive, consts: &HashMap) -> Result { + if dir.values.len() != 1 { + return Err(AsmError::EncodeError("align expects one power-of-two operand".into())); + } + let DirectiveValue::Expr(expr) = &dir.values[0] else { + return Err(AsmError::EncodeError("align requires numeric expression".into())); + }; + let EvaluatedExpr::Number(number) = eval_expr(expr, consts)? else { + return Err(AsmError::EncodeError("align requires a resolved constant".into())); + }; + let value = u64::try_from(number) + .ok() + .filter(|value| value.is_power_of_two()) + .ok_or_else(|| AsmError::EncodeError("align requires a positive power of two".into()))?; + Ok(value) +} + +fn reservation_size( + unit: u64, + values: &[DirectiveValue], + consts: &HashMap, +) -> Result { + if values.len() != 1 { + return Err(AsmError::EncodeError("res* expects exactly one count operand".into())); + } + + let count = match &values[0] { + DirectiveValue::Expr(expr) => match eval_directive_expr(expr, consts)? { + EvaluatedExpr::Number(v) => v, + EvaluatedExpr::Symbol { name, .. } => { + return Err(AsmError::EncodeError(format!( + "res* count must be constant; unresolved symbol '{}'", + name + ))) + }, + }, + DirectiveValue::StringLiteral(_) => { + return Err(AsmError::EncodeError("res* count must be numeric expression".into())) + }, + }; + + if count < 0 { + return Err(AsmError::EncodeError("res* count must be non-negative".into())); + } + u64::try_from(count) + .map_err(|_| AsmError::EncodeError("res* size overflow".into()))? + .checked_mul(unit) + .ok_or_else(|| AsmError::EncodeError("res* size overflow".into())) +} + +fn reserve_bytes( + bytes: &mut Vec, + unit: u64, + values: &[DirectiveValue], + consts: &HashMap, +) -> Result<(), AsmError> { + let extra = usize::try_from(reservation_size(unit, values, consts)?) + .map_err(|_| AsmError::EncodeError("res* size exceeds host capacity".into()))?; + let new_len = bytes + .len() + .checked_add(extra) + .ok_or_else(|| AsmError::EncodeError("res* size overflow".into()))?; + bytes.try_reserve(extra).map_err(|_| AsmError::EncodeError("res* allocation failed".into()))?; + bytes.resize(new_len, 0); + Ok(()) +} + +fn reserve_output( + bytes: &mut Vec, + extra: usize, + materialized: &mut usize, + limits: &assembler::AssemblyLimits, +) -> Result<(), AsmError> { + let total = materialized + .checked_add(extra) + .ok_or_else(|| AsmError::EncodeError("Assembly output size overflow".into()))?; + let section_size = bytes + .len() + .checked_add(extra) + .ok_or_else(|| AsmError::EncodeError("Section output size overflow".into()))?; + if total > limits.max_output_bytes || section_size > isize::MAX as usize { + return Err(AsmError::EncodeError(format!( + "Assembly output limit exceeded (limit {} bytes)", + limits.max_output_bytes + ))); + } + bytes + .try_reserve(extra) + .map_err(|_| AsmError::EncodeError("Assembly output allocation failed".into()))?; + *materialized = total; + Ok(()) +} + +fn directive_size(dir: &Directive, consts: &HashMap) -> Result { + if let Some(unit) = match dir.name.as_str() { + "resb" => Some(1), + "resw" => Some(2), + "resd" => Some(4), + "resq" => Some(8), + _ => None, + } { + return usize::try_from(reservation_size(unit, &dir.values, consts)?) + .map_err(|_| AsmError::EncodeError("Reservation size exceeds host capacity".into())); + } + let width = match dir.name.as_str() { + "db" => 1, + "dw" => 2, + "dd" => 4, + "dq" => 8, + _ => return Err(AsmError::EncodeError(format!("Unknown directive {}", dir.name))), + }; + dir.values.iter().try_fold(0usize, |size, value| { + let extra = match value { + DirectiveValue::StringLiteral(s) if width == 1 => s.len(), + DirectiveValue::StringLiteral(_) => { + return Err(AsmError::EncodeError(format!( + "{} only supports numeric expressions", + dir.name + ))) + }, + _ => width, + }; + size.checked_add(extra) + .ok_or_else(|| AsmError::EncodeError("Directive output size overflow".into())) + }) +} + +fn encode_bss_directive( + dir: &Directive, + section: &mut AsmSection, + consts: &HashMap, +) -> Result<(), AsmError> { + let extra = match dir.name.as_str() { + "resb" => reservation_size(1, &dir.values, consts)?, + "resw" => reservation_size(2, &dir.values, consts)?, + "resd" => reservation_size(4, &dir.values, consts)?, + "resq" => reservation_size(8, &dir.values, consts)?, + _ => { + let size = directive_size(dir, consts)?; + for value in &dir.values { + let zero = match value { + DirectiveValue::StringLiteral(s) => s.as_slice().iter().all(|b| *b == 0), + DirectiveValue::Expr(expr) => { + matches!(eval_directive_expr(expr, consts)?, EvaluatedExpr::Number(0)) + }, + }; + if !zero { + return Err(AsmError::EncodeError( + "BSS has a nonzero initializer or relocation".into(), + )); + } + } + size as u64 + }, + }; + section.zero_fill = section + .zero_fill + .checked_add(extra) + .ok_or_else(|| AsmError::EncodeError("BSS size overflow".into()))?; + Ok(()) +} + +fn encode_directive( + dir: &Directive, + bytes: &mut Vec, + relocs: &mut Vec, + consts: &HashMap, +) -> Result<(), AsmError> { + match dir.name.as_str() { + "db" => { + for v in &dir.values { + match v { + DirectiveValue::StringLiteral(s) => bytes.extend_from_slice(s.as_slice()), + DirectiveValue::Expr(expr) => { + let eval = eval_directive_expr(expr, consts)?; + encode_data_expr(eval, 1, bytes, relocs)?; + }, + } + } + Ok(()) + }, + "dw" => { + for v in &dir.values { + let DirectiveValue::Expr(expr) = v else { + return Err(AsmError::EncodeError( + "dw only supports numeric expressions".into(), + )); + }; + let eval = eval_directive_expr(expr, consts)?; + encode_data_expr(eval, 2, bytes, relocs)?; + } + Ok(()) + }, + "dd" => { + for v in &dir.values { + let DirectiveValue::Expr(expr) = v else { + return Err(AsmError::EncodeError( + "dd only supports numeric expressions".into(), + )); + }; + let eval = eval_directive_expr(expr, consts)?; + encode_data_expr(eval, 4, bytes, relocs)?; + } + Ok(()) + }, + "dq" => { + for v in &dir.values { + let DirectiveValue::Expr(expr) = v else { + return Err(AsmError::EncodeError( + "dq only supports numeric expressions".into(), + )); + }; + let eval = eval_directive_expr(expr, consts)?; + encode_data_expr(eval, 8, bytes, relocs)?; + } + Ok(()) + }, + "resb" => reserve_bytes(bytes, 1, &dir.values, consts), + "resw" => reserve_bytes(bytes, 2, &dir.values, consts), + "resd" => reserve_bytes(bytes, 4, &dir.values, consts), + "resq" => reserve_bytes(bytes, 8, &dir.values, consts), + _ => Err(AsmError::EncodeError(format!("Unknown directive {}", dir.name))), + } +} + +mod reference_modrm { + #[derive(Debug, Clone)] + pub struct ModRM { + pub mod_bits: u8, // 0~3 + pub reg: u8, // 0~7 + pub rm: u8, // 0~7 + } + + impl ModRM { + pub fn new(mod_bits: u8, reg: u8, rm: u8) -> Self { + Self { mod_bits, reg, rm } + } + + pub fn encode(&self) -> u8 { + (self.mod_bits << 6) | ((self.reg & 7) << 3) | (self.rm & 7) + } + } +} + +mod reference_rex { + #[derive(Debug, Clone, Default)] + pub struct Rex { + pub w: bool, + pub r: bool, + pub x: bool, + pub b: bool, + } + + impl Rex { + pub fn new() -> Self { + Self { w: false, r: false, x: false, b: false } + } + + pub fn encode(&self) -> u8 { + 0x40 | ((self.w as u8) << 3) + | ((self.r as u8) << 2) + | ((self.x as u8) << 1) + | (self.b as u8) + } + } +} diff --git a/assembler/amd64/src/encoder_wave.rs b/assembler/amd64/src/encoder_wave.rs new file mode 100644 index 0000000..c31d6aa --- /dev/null +++ b/assembler/amd64/src/encoder_wave.rs @@ -0,0 +1,778 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Allocation and typed AST/output transport. All encoding decisions run in Wave. +use crate::ast_model::{DirectiveRecord, Item, Name, OperandRecord, Packet, MISSING}; + +use crate::encoding::{DispKind, EncodedAddress}; + +use assembler::ast::{ASTNode, DirectiveValue, ExprValue, MemoryOperand, Operand, AST}; + +use assembler::{ + AsmError, AsmSection, AsmSectionKind, AsmSymbol, AssemblerOutput, AssemblyLimits, RelocKind, + Relocation, SymbolKind, SymbolVisibility, +}; + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct Section { + name: u64, + kind: u64, + align: u64, + first: u64, + size: u64, + zero_fill: u64, +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct Symbol { + prefix: u64, + name: u64, + flags: u64, + label_site: u64, + extern_site: u64, + global_site: u64, + constant_site: u64, + metadata_site: u64, + section: u64, + offset: u64, + previous_section: u64, + previous_offset: u64, + low: u64, + high: u64, + dependency: u64, + add_low: u64, + add_high: u64, + symbol_kind: u64, + size: u64, + visibility: u64, + order: u64, + users: u64, + next: u64, +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct Node { + scope: u64, + symbol: u64, + section: u64, + offset: u64, + length: u64, + previous_offset: u64, + previous_length: u64, + force_near: u64, +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct RelocationRecord { + section: u64, + offset: u64, + symbol: u64, + kind: u64, + addend: u64, + node: u64, +} + +#[repr(C)] +struct Input { + names: *const Name, + name_count: u64, + items: *const Item, + item_count: u64, + operands: *const OperandRecord, + operand_count: u64, + values: *const DirectiveRecord, + value_count: u64, + sections: *mut Section, + section_capacity: u64, + symbols: *mut Symbol, + symbol_capacity: u64, + table: *mut u64, + table_capacity: u64, + nodes: *mut Node, + queue: *mut u64, + relocations: *mut RelocationRecord, + relocation_capacity: u64, + bytes: *mut u8, + byte_capacity: u64, + max_output: u64, + max_iterations: u64, + max_work: u64, +} + +#[repr(C)] +#[derive(Default)] +struct Output { + status: u64, + error: u64, + node: u64, + previous: u64, + argument: u64, + section_count: u64, + symbol_count: u64, + output_symbols: u64, + relocation_count: u64, + bytes: u64, + iterations: u64, + work: u64, +} + +#[repr(C)] +#[derive(Default)] +struct Address { + mode: u64, + rm: u64, + sib: u64, + displacement: u64, + width: u64, + rex_b: u64, + rex_x: u64, +} + +unsafe extern "C" { + fn whale_amd64_encode(input: *const Input, emission: u64, output: *mut Output) -> i32; + + fn whale_amd64_bits(op: u64, a: u64, b: u64, c: u64, d: u64) -> u64; + + fn whale_amd64_address( + names: *const Name, + count: u64, + operand: *const OperandRecord, + mode: u64, + address: *mut Address, + output: *mut Output, + ) -> i32; +} + +fn backend() -> AsmError { + AsmError::Backend("AMD64 encoding transport") +} + +fn allocate(count: usize) -> Result, AsmError> { + let mut values = Vec::new(); + values.try_reserve_exact(count).map_err(|_| allocation())?; + values.resize(count, T::default()); + Ok(values) +} + +fn expr_names(expression: &ExprValue) -> usize { + usize::from(matches!(expression, ExprValue::Symbol { .. })) +} + +fn admission(ast: &AST) -> Result<(usize, usize, usize, usize), AsmError> { + let mut names = 0usize; + let mut operands = 0usize; + let mut values = 0usize; + for node in &ast.items { + names = names.checked_add(1).ok_or_else(backend)?; + match node { + ASTNode::Instruction(instruction) => { + operands = operands.checked_add(instruction.operands.len()).ok_or_else(backend)?; + for operand in &instruction.operands { + let count = match operand { + Operand::Register(_) | Operand::Label(_) | Operand::SymbolExpr { .. } => 1, + Operand::Memory(m) => { + usize::from(m.base.is_some()) + + usize::from(m.index.is_some()) + + usize::from(m.symbol.is_some()) + }, + Operand::Immediate(_) => 0, + }; + names = names.checked_add(count).ok_or_else(backend)?; + } + }, + ASTNode::Directive(directive) => { + values = values.checked_add(directive.values.len()).ok_or_else(backend)?; + for value in &directive.values { + if let DirectiveValue::Expr(expression) = value { + names = names.checked_add(expr_names(expression)).ok_or_else(backend)?; + } + } + }, + ASTNode::Const { expr, .. } | ASTNode::SymbolMetadata { size: expr, .. } => { + names = names.checked_add(expr_names(expr)).ok_or_else(backend)?; + }, + _ => {}, + } + } + let symbols = names + .checked_add(ast.items.len()) + .and_then(|n| n.checked_add(operands)) + .and_then(|n| n.checked_add(values)) + .and_then(|n| n.checked_add(1)) + .ok_or_else(backend)?; + let table = + symbols.checked_mul(2).and_then(usize::checked_next_power_of_two).ok_or_else(backend)?; + let sections = ast.items.len().checked_add(1).ok_or_else(backend)?; + let relocs = ast.items.len().checked_add(values).ok_or_else(backend)?; + let bytes = ast + .items + .len() + .checked_mul(160 + 64) + .and_then(|n| n.checked_add(names.checked_mul(32)?)) + .and_then(|n| n.checked_add(operands.checked_mul(176)?)) + .and_then(|n| n.checked_add(values.checked_mul(112)?)) + .and_then(|n| n.checked_add(symbols.checked_mul(184 + 8)?)) + .and_then(|n| n.checked_add(table.checked_mul(8)?)) + .and_then(|n| n.checked_add(sections.checked_mul(48)?)) + .and_then(|n| n.checked_add(relocs.checked_mul(48)?)) + .ok_or_else(backend)?; + if bytes > 128 * 1024 * 1024 { + return Err(AsmError::EncodeError("Assembly workspace limit exceeded".into())); + } + Ok((symbols, table, relocs, bytes)) +} + +fn name<'a>(packet: &'a Packet<'_>, index: u64) -> Result<&'a str, AsmError> { + let descriptor = + packet.names.get(usize::try_from(index).map_err(|_| backend())?).ok_or_else(backend)?; + let bytes = unsafe { std::slice::from_raw_parts(descriptor.bytes, descriptor.count as usize) }; + std::str::from_utf8(bytes).map_err(|_| backend()) +} + +fn symbol_name(packet: &Packet<'_>, symbols: &[Symbol], index: u64) -> Result { + let symbol = symbols.get(usize::try_from(index).map_err(|_| backend())?).ok_or_else(backend)?; + let suffix = name(packet, symbol.name)?; + let prefix = if symbol.prefix == MISSING { "" } else { name(packet, symbol.prefix)? }; + let mut value = String::new(); + let length = prefix + .len() + .checked_add(suffix.len()) + .filter(|length| *length <= 128 * 1024 * 1024) + .ok_or_else(workspace_error)?; + value.try_reserve_exact(length).map_err(|_| allocation())?; + value.push_str(prefix); + value.push_str(suffix); + Ok(value) +} + +fn error( + output: &Output, + ast: &AST, + packet: &Packet<'_>, + symbols: &[Symbol], + limits: &AssemblyLimits, +) -> AsmError { + if ast.source_name.len() > 128 * 1024 * 1024 { + return workspace_error(); + } + if let Some(ASTNode::Instruction(instruction)) = ast.items.get(output.node as usize) { + if instruction + .mnemonic + .len() + .checked_add(ast.source_name.len()) + .is_none_or(|length| length > 128 * 1024 * 1024 - 256) + { + return workspace_error(); + } + } + let limit = limits.max_output_bytes; + let message = match output.error { + 1 => "Assembly work limit exceeded".into(), + 2 => format!("Assembly output limit exceeded (limit {limit} bytes)"), + 3 => return backend(), + 4 => "AH/CH/DH/BH cannot be encoded with a REX prefix".into(), + 5 => "Invalid register or expected register operand".into(), + 6 => "Register width mismatch".into(), + 7 => "Relative relocation addend overflow".into(), + 8 => "Memory width conflicts with register-derived width".into(), + 9 => "symbol memory should be encoded via rip-relative path".into(), + 10 => "symbol + register memory form is not implemented yet".into(), + 11 => "rel/abs requires a base-less long-mode address".into(), + 12 => "rel/abs displacement is out of signed 32-bit range".into(), + 13 => "Invalid base register".into(), + 14 => "Invalid index register".into(), + 15 => "Addressing without base/index not implemented".into(), + 16 => "Scale must be 1/2/4/8".into(), + 17 => "rsp/esp cannot be used as index register".into(), + 18 => "memory displacement is out of signed 32-bit range".into(), + 19 => "Ambiguous memory immediate; specify byte/word/dword/qword".into(), + 20 => { + "Memory immediate out of range for selected width (qword requires signed imm32)".into() + }, + 21 => format!("imm{} out of range (r64 arithmetic requires signed imm32)", output.argument), + 22 => "Symbol move is supported only for r32/r64".into(), + 23 => "Symbol addend overflow".into(), + 24 => "Unsupported mov form".into(), + 25 => "symbolic immediate is not supported; use equ or mov reg, symbol".into(), + 26 => "Unsupported instruction form".into(), + 27 => "Register width does not match instruction".into(), + 28 => "Expected register or memory operand".into(), + 29 => "Extension memory source requires byte/word/dword width".into(), + 30 => "Extension source must be register or memory".into(), + 31 => "Invalid extension source/destination width pair".into(), + 32 => "imul form supported: imul reg, reg/mem (not 8-bit operands)".into(), + 33 => "imul requires matching r16/r32/r64 operands".into(), + 34 => "imul third operand must be immediate".into(), + 35 => "imul immediate out of range (imm16/imm32; r64 sign extends imm32)".into(), + 36 => "Shift count must be CL or unsigned imm8".into(), + 37 => "Scalar SSE arithmetic destination must be XMM".into(), + 38 => "Expected XMM0-XMM15 register".into(), + 39 => "Scalar SSE source must be XMM or matching scalar memory".into(), + 40 => "control transfer only supports labels for now".into(), + 41 => "control transfer does not support label addends".into(), + 42 => "branch target is out of 32-bit relative range".into(), + 43 => "Memory displacement overflow".into(), + 44 => format!( + "Unknown mnemonic {}", + ast.items + .get(output.node as usize) + .and_then(|n| match n { + ASTNode::Instruction(i) => Some(i.mnemonic.as_str()), + _ => None, + }) + .unwrap_or("?") + ), + 45 => { + let mnemonic = match ast.items.get(output.node as usize) { + Some(ASTNode::Instruction(i)) => &i.mnemonic, + _ => return backend(), + }; + format!( + "{mnemonic} expects {} operand{}", + output.argument, + if output.argument == 1 { "" } else { "s" } + ) + }, + 46 => "push immediate requires signed imm8 or signed imm32 in AMD64 mode".into(), + 47 => "push/pop currently support only r16/r64 in amd64 mode".into(), + 48 => "lea destination must be r32 or r64 and source must be memory address".into(), + 49 => "cmovcc requires matching r16/r32/r64 registers".into(), + code => { + let needs_name = matches!(code, 100..=105 | 110..=120 | 123 | 124 | 154 | 163); + let raw_name = matches!(code, 100 | 119 | 120 | 163); + let symbol = if needs_name { + let length = if raw_name { + name(packet, output.argument).map(str::len) + } else { + symbol_length(packet, symbols, output.argument) + }; + let length = match length { + Ok(value) => value, + Err(_) => return backend(), + }; + if length + .checked_mul(6) + .and_then(|n| n.checked_add(ast.source_name.len())) + .is_none_or(|n| n > 128 * 1024 * 1024 - 256) + { + return workspace_error(); + } + let value = if raw_name { + name(packet, output.argument).and_then(copy_name) + } else { + symbol_name(packet, symbols, output.argument) + }; + match value { + Ok(value) => value, + Err(error) => return error, + } + } else { + String::new() + }; + let limit = if code == 122 { limits.max_relax_iterations } else { limit }; + return ast.error_at( + super::namespace_errors::message(code, &symbol, limit), + output.node as usize, + usize::try_from(output.previous).ok().filter(|_| output.previous != MISSING), + ); + }, + }; + ast.error_at( + AsmError::EncodeError(message), + output.node as usize, + usize::try_from(output.previous).ok().filter(|_| output.previous != MISSING), + ) +} + +fn allocation() -> AsmError { + AsmError::EncodeError("Assembly allocation failed".into()) +} + +fn workspace_error() -> AsmError { + AsmError::EncodeError("Assembly workspace limit exceeded".into()) +} + +fn charge_bytes(used: &mut usize, count: usize, width: usize) -> Result<(), AsmError> { + *used = used + .checked_add(count.checked_mul(width).ok_or_else(workspace_error)?) + .filter(|total| *total <= 128 * 1024 * 1024) + .ok_or_else(workspace_error)?; + Ok(()) +} + +fn symbol_length(packet: &Packet<'_>, symbols: &[Symbol], index: u64) -> Result { + let symbol = symbols.get(usize::try_from(index).map_err(|_| backend())?).ok_or_else(backend)?; + let suffix = name(packet, symbol.name)?.len(); + let prefix = if symbol.prefix == MISSING { 0 } else { name(packet, symbol.prefix)?.len() }; + prefix.checked_add(suffix).ok_or_else(workspace_error) +} + +fn output_admission( + packet: &Packet<'_>, + sections: &[Section], + symbols: &[Symbol], + relocations: &[RelocationRecord], + output: &Output, + workspace: usize, +) -> Result<(), AsmError> { + let mut used = workspace; + // The native staging buffer is workspace. The final section payloads have + // their own caller-selected max_output_bytes ceiling; thus both copies are + // admitted without silently lowering that public output limit. + charge_bytes(&mut used, output.bytes as usize, 1)?; + charge_bytes(&mut used, output.section_count as usize, std::mem::size_of::())?; + charge_bytes( + &mut used, + output.output_symbols as usize, + std::mem::size_of::>() + std::mem::size_of::(), + )?; + charge_bytes( + &mut used, + output.relocation_count as usize, + 2 * std::mem::size_of::(), + )?; + let mut first = 0u64; + for section in sections.iter().take(output.section_count as usize) { + if section.first != first || !section.align.is_power_of_two() || section.kind > 3 { + return Err(backend()); + } + first = first.checked_add(section.size).ok_or_else(backend)?; + let length = if section.name == MISSING { 5 } else { name(packet, section.name)?.len() }; + charge_bytes(&mut used, length, 1)?; + } + if first != output.bytes { + return Err(backend()); + } + for (index, symbol) in symbols.iter().take(output.symbol_count as usize).enumerate() { + if symbol.flags & !447 != 0 { + return Err(backend()); + } + if symbol.flags & 6 != 0 { + charge_bytes(&mut used, symbol_length(packet, symbols, index as u64)?, 1)?; + } + } + for relocation in relocations.iter().take(output.relocation_count as usize) { + charge_bytes(&mut used, symbol_length(packet, symbols, relocation.symbol)?, 1)?; + } + Ok(()) +} + +fn copy_name(value: &str) -> Result { + let mut output = String::new(); + output.try_reserve_exact(value.len()).map_err(|_| allocation())?; + output.push_str(value); + Ok(output) +} + +fn valid(output: &Output, input: &Input) -> bool { + output.status == 0 + && output.section_count <= input.section_capacity + && output.symbol_count <= input.symbol_capacity + && output.output_symbols <= output.symbol_count + && output.relocation_count <= input.relocation_capacity + && output.bytes <= input.max_output + && output.work <= input.max_work + && output.iterations <= input.max_iterations +} + +pub(super) fn encode(ast: &AST, limits: &AssemblyLimits) -> Result { + let (symbol_capacity, table_capacity, relocation_capacity, workspace) = admission(ast)?; + let packet = Packet::from_ast(ast)?; + let section_capacity = ast.items.len().checked_add(1).ok_or_else(backend)?; + let mut sections = allocate::
(section_capacity)?; + let mut symbols = allocate::(symbol_capacity)?; + let mut table = allocate::(table_capacity)?; + let mut nodes = allocate::(ast.items.len())?; + let mut queue = allocate::(symbol_capacity)?; + let mut relocations = allocate::(relocation_capacity)?; + let mut input = Input { + names: packet.names.as_ptr(), + name_count: packet.names.len() as u64, + items: packet.items.as_ptr(), + item_count: packet.items.len() as u64, + operands: packet.operands.as_ptr(), + operand_count: packet.operands.len() as u64, + values: packet.values.as_ptr(), + value_count: packet.values.len() as u64, + sections: sections.as_mut_ptr(), + section_capacity: section_capacity as u64, + symbols: symbols.as_mut_ptr(), + symbol_capacity: symbol_capacity as u64, + table: table.as_mut_ptr(), + table_capacity: table_capacity as u64, + nodes: nodes.as_mut_ptr(), + queue: queue.as_mut_ptr(), + relocations: relocations.as_mut_ptr(), + relocation_capacity: relocation_capacity as u64, + bytes: std::ptr::null_mut(), + byte_capacity: 0, + max_output: limits.max_output_bytes as u64, + max_iterations: limits.max_relax_iterations as u64, + max_work: 256 * 1024 * 1024, + }; + let mut output = Output::default(); + let status = unsafe { whale_amd64_encode(&input, 0, &mut output) }; + if status != 0 { + if output.status != status as u64 { + return Err(backend()); + } + return Err(error(&output, ast, &packet, &symbols, limits)); + } + if !valid(&output, &input) { + return Err(backend()); + } + output_admission(&packet, §ions, &symbols, &relocations, &output, workspace)?; + let size = usize::try_from(output.bytes).map_err(|_| backend())?; + let mut bytes = allocate::(size)?; + input.bytes = bytes.as_mut_ptr(); + input.byte_capacity = bytes.len() as u64; + let status = unsafe { whale_amd64_encode(&input, 1, &mut output) }; + if status != 0 { + if output.status != status as u64 { + return Err(backend()); + } + return Err(error(&output, ast, &packet, &symbols, limits)); + } + if !valid(&output, &input) || output.bytes != bytes.len() as u64 { + return Err(backend()); + } + output_admission(&packet, §ions, &symbols, &relocations, &output, workspace)?; + let mut result = AssemblerOutput { sections: Vec::new(), symbols: Vec::new() }; + result.sections.try_reserve_exact(output.section_count as usize).map_err(|_| allocation())?; + for section in sections.iter().take(output.section_count as usize) { + let first = usize::try_from(section.first).map_err(|_| backend())?; + let count = usize::try_from(section.size).map_err(|_| backend())?; + let data = + bytes.get(first..first.checked_add(count).ok_or_else(backend)?).ok_or_else(backend)?; + let mut owned = Vec::new(); + owned.try_reserve_exact(count).map_err(|_| allocation())?; + owned.extend_from_slice(data); + result.sections.push(AsmSection { + kind: match section.kind { + 0 => AsmSectionKind::Text, + 1 => AsmSectionKind::Data, + 2 => AsmSectionKind::ReadOnlyData, + 3 => AsmSectionKind::Bss, + _ => return Err(backend()), + }, + align: section.align, + name: if section.name == MISSING { + copy_name(".text")? + } else { + copy_name(name(&packet, section.name)?)? + }, + data: owned, + zero_fill: section.zero_fill, + relocs: Vec::new(), + }); + } + let mut ordered = { + let mut ordered = Vec::new(); + ordered.try_reserve_exact(output.output_symbols as usize).map_err(|_| allocation())?; + ordered.resize_with(output.output_symbols as usize, || None); + ordered + }; + for (index, symbol) in symbols.iter().take(output.symbol_count as usize).enumerate() { + if symbol.flags & 6 == 0 { + continue; + } + let slot = ordered + .get_mut(usize::try_from(symbol.order).map_err(|_| backend())?) + .ok_or_else(backend)?; + if slot.is_some() { + return Err(backend()); + } + *slot = Some(AsmSymbol { + kind: match symbol.symbol_kind { + 0 => SymbolKind::NoType, + 1 => SymbolKind::Function, + 2 => SymbolKind::Object, + _ => return Err(backend()), + }, + size: symbol.size, + visibility: match symbol.visibility { + 0 => SymbolVisibility::Default, + 1 => SymbolVisibility::Hidden, + _ => return Err(backend()), + }, + name: symbol_name(&packet, &symbols, index as u64)?, + section_index: if symbol.section == MISSING { + None + } else { + let section = usize::try_from(symbol.section).map_err(|_| backend())?; + if section >= result.sections.len() { + return Err(backend()); + } + Some(section) + }, + offset: symbol.offset, + is_global: symbol.flags & 1 != 0, + }); + } + result.symbols.try_reserve_exact(ordered.len()).map_err(|_| allocation())?; + for symbol in ordered { + result.symbols.push(symbol.ok_or_else(backend)?); + } + for relocation in relocations.iter().take(output.relocation_count as usize) { + let section = result + .sections + .get_mut(usize::try_from(relocation.section).map_err(|_| backend())?) + .ok_or_else(backend)?; + section.relocs.try_reserve(1).map_err(|_| allocation())?; + section.relocs.push(Relocation { + offset: usize::try_from(relocation.offset).map_err(|_| backend())?, + symbol: symbol_name(&packet, &symbols, relocation.symbol)?, + kind: match relocation.kind { + 0 => RelocKind::Absolute64, + 1 => RelocKind::Absolute32, + 2 => RelocKind::SignedAbsolute32, + 3 => RelocKind::Relative32, + 4 => RelocKind::Branch32, + 5 => RelocKind::Relative8, + _ => return Err(backend()), + }, + addend: relocation.addend as i64, + }); + } + Ok(result) +} + +pub(crate) fn bits(op: u64, a: u64, b: u64, c: u64, d: u64) -> u8 { + u8::try_from(unsafe { whale_amd64_bits(op, a, b, c, d) }).expect("Wave AMD64 bit transport") +} + +pub(crate) fn address(memory: &MemoryOperand, mode: u8) -> Result { + let ast = AST::new(Vec::new()); + let mut packet = Packet::new(); + let mut raw = OperandRecord { + kind: 4, + name: MISSING, + width: memory.width.map_or(MISSING, u64::from), + base: MISSING, + index: MISSING, + symbol: MISSING, + scale: memory.scale.into(), + disp: memory.disp as u64, + mode: match memory.address_mode { + assembler::ast::MemoryAddressMode::Default => 0, + assembler::ast::MemoryAddressMode::Relative => 1, + assembler::ast::MemoryAddressMode::Absolute => 2, + }, + ..OperandRecord::default() + }; + for (source, target) in [ + (&memory.base, &mut raw.base), + (&memory.index, &mut raw.index), + (&memory.symbol, &mut raw.symbol), + ] { + if let Some(value) = source { + *target = crate::ast_model::push( + &mut packet.names, + Name { bytes: value.as_ptr(), count: value.len() as u64 }, + )?; + } + } + let mut output = Output::default(); + let mut address = Address::default(); + let status = unsafe { + whale_amd64_address( + packet.names.as_ptr(), + packet.names.len() as u64, + &raw, + mode.into(), + &mut address, + &mut output, + ) + }; + if status != 0 { + return Err(error(&output, &ast, &packet, &[], &AssemblyLimits::default())); + } + if address.mode > 3 + || address.rm > 7 + || address.rex_b > 1 + || address.rex_x > 1 + || address.sib != MISSING && address.sib > 255 + { + return Err(backend()); + } + Ok(EncodedAddress { + mod_bits: address.mode as u8, + rm_bits: address.rm as u8, + sib: (address.sib != MISSING).then_some(( + (address.sib >> 6) as u8, + ((address.sib >> 3) & 7) as u8, + (address.sib & 7) as u8, + )), + disp: match address.width { + 0 => None, + 1 => Some(DispKind::Disp8(address.displacement as i8)), + 4 => Some(DispKind::Disp32(address.displacement as i32)), + _ => return Err(backend()), + }, + rex_b: address.rex_b != 0, + rex_x: address.rex_x != 0, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn scoped_output_names_are_admitted_cumulatively_before_copying() { + // A small borrowed AST can describe over 128 MiB of canonical output + // names: the parent is stored once, but each local label adds it again. + let mut items = vec![ASTNode::Label("p".repeat(1024 * 1024))]; + items.extend((0..128).map(|index| ASTNode::Label(format!(".local{index}")))); + let ast = AST::new(items); + let packet = Packet::from_ast(&ast).unwrap(); + let mut symbols: Vec = (0..129) + .map(|index| Symbol { + prefix: if index == 0 { MISSING } else { 0 }, + name: index, + flags: 4, + order: index, + ..Symbol::default() + }) + .collect(); + let sections = [Section { name: MISSING, align: 16, ..Section::default() }]; + let output = Output { + section_count: 1, + symbol_count: 129, + output_symbols: 129, + ..Output::default() + }; + let (_, _, _, workspace) = admission(&ast).unwrap(); + let error = + output_admission(&packet, §ions, &symbols, &[], &output, workspace).unwrap_err(); + assert!( + matches!(error, AsmError::EncodeError(message) if message.contains("workspace limit")) + ); + // Corrupt native indexes stay backend failures rather than becoming a + // data error, even when the rest of this fixture also exceeds a budget. + symbols[0].name = packet.names.len() as u64; + assert!(matches!( + output_admission(&packet, §ions, &symbols, &[], &output, workspace), + Err(AsmError::Backend(_)) + )); + } + + #[test] + fn malformed_native_section_ranges_are_rejected_before_payload_allocation() { + let ast = AST::new(Vec::new()); + let packet = Packet::from_ast(&ast).unwrap(); + let output = Output { section_count: 1, bytes: 4, ..Output::default() }; + for section in [ + Section { name: MISSING, align: 16, first: 1, size: 4, ..Section::default() }, + Section { name: MISSING, align: 3, first: 0, size: 4, ..Section::default() }, + Section { name: MISSING, align: 16, first: 0, size: 5, ..Section::default() }, + ] { + assert!(matches!( + output_admission(&packet, &[section], &[], &[], &output, 0), + Err(AsmError::Backend(_)) + )); + } + } +} diff --git a/assembler/amd64/src/encoding/address.rs b/assembler/amd64/src/encoding/address.rs index dd94434..5d650b2 100644 --- a/assembler/amd64/src/encoding/address.rs +++ b/assembler/amd64/src/encoding/address.rs @@ -1,9 +1,7 @@ -use assembler::ast::{MemoryAddressMode, MemoryOperand}; +use assembler::ast::MemoryOperand; use assembler::error::AsmError; -use crate::tables::{REGISTERS_32, REGISTERS_64}; - #[derive(Debug, Clone)] pub enum DispKind { Disp8(i8), @@ -21,149 +19,13 @@ pub struct EncodedAddress { pub rex_x: bool, } -fn reg_code(name: &str, mode: u8) -> Option { - let regs = match mode { - 64 => REGISTERS_64, - 32 => REGISTERS_32, - _ => return None, - }; - - regs.iter().find(|(n, _)| *n == name).map(|(_, c)| *c) -} - -fn scale_bits(scale: u8) -> Option { - match scale { - 1 => Some(0), - 2 => Some(1), - 4 => Some(2), - 8 => Some(3), - _ => None, - } -} +#[cfg(any(test, not(whale_wave_amd64)))] +#[path = "address_reference.rs"] +pub(crate) mod reference; pub fn encode_address(mem: &MemoryOperand, mode: u8) -> Result { - if mem.symbol.is_some() { - return Err(AsmError::EncodeError( - "symbol memory should be encoded via rip-relative path".into(), - )); - } - - if mem.address_mode != MemoryAddressMode::Default { - if mode != 64 || mem.base.is_some() || mem.index.is_some() || mem.scale != 1 { - return Err(AsmError::EncodeError( - "rel/abs requires a base-less long-mode address".into(), - )); - } - let displacement = i32::try_from(mem.disp).map_err(|_| { - AsmError::EncodeError("rel/abs displacement is out of signed 32-bit range".into()) - })?; - return Ok(EncodedAddress { - mod_bits: 0, - rm_bits: if mem.address_mode == MemoryAddressMode::Relative { 5 } else { 4 }, - sib: if mem.address_mode == MemoryAddressMode::Absolute { - Some((0, 4, 5)) - } else { - None - }, - disp: Some(DispKind::Disp32(displacement)), - rex_b: false, - rex_x: false, - }); - } - - let base_code = mem - .base - .as_deref() - .map(|b| { - reg_code(b, mode).ok_or_else(|| AsmError::EncodeError("Invalid base register".into())) - }) - .transpose()?; - let index_code = mem - .index - .as_deref() - .map(|i| { - reg_code(i, mode).ok_or_else(|| AsmError::EncodeError("Invalid index register".into())) - }) - .transpose()?; - - if base_code.is_none() && index_code.is_none() { - return Err(AsmError::EncodeError("Addressing without base/index not implemented".into())); - } - - let scale = scale_bits(mem.scale) - .ok_or_else(|| AsmError::EncodeError("Scale must be 1/2/4/8".into()))?; - - if let Some(idx) = index_code { - if idx == 4 { - return Err(AsmError::EncodeError("rsp/esp cannot be used as index register".into())); - } - } - - let disp = mem.disp; - let disp32 = i32::try_from(disp).map_err(|_| { - AsmError::EncodeError("memory displacement is out of signed 32-bit range".into()) - })?; - let disp_kind = if disp == 0 { - None - } else if (-128..=127).contains(&disp) { - Some(DispKind::Disp8(disp as i8)) - } else { - Some(DispKind::Disp32(disp32)) - }; - - let need_sib = index_code.is_some() - || base_code.is_none() - || base_code.map(|b| (b & 7) == 4).unwrap_or(false); - - let (mod_bits, final_disp, rm_bits, sib, rex_b, rex_x) = match (base_code, index_code, need_sib) - { - (Some(base), idx, true) => { - let base_low = base & 7; - let mut mod_bits = 0; - let mut disp = disp_kind; - - if base_low == 5 && disp.is_none() { - mod_bits = 1; - disp = Some(DispKind::Disp8(0)); - } else if matches!(disp, Some(DispKind::Disp8(_))) { - mod_bits = 1; - } else if matches!(disp, Some(DispKind::Disp32(_))) { - mod_bits = 2; - } - - let index_low = idx.map(|i| i & 7).unwrap_or(4); - let base_low = base & 7; - ( - mod_bits, - disp, - 4, - Some((scale, index_low, base_low)), - base >= 8, - idx.map(|i| i >= 8).unwrap_or(false), - ) - }, - (Some(base), _, false) => { - let base_low = base & 7; - let mut mod_bits = 0; - let mut disp = disp_kind; - - if base_low == 5 && disp.is_none() { - mod_bits = 1; - disp = Some(DispKind::Disp8(0)); - } else if matches!(disp, Some(DispKind::Disp8(_))) { - mod_bits = 1; - } else if matches!(disp, Some(DispKind::Disp32(_))) { - mod_bits = 2; - } - - (mod_bits, disp, base_low, None, base >= 8, false) - }, - (None, Some(idx), _) => { - let index_low = idx & 7; - (0, Some(DispKind::Disp32(disp32)), 4, Some((scale, index_low, 5)), false, idx >= 8) - }, - _ => return Err(AsmError::EncodeError("Addressing mode is not supported yet".into())), - }; - - Ok(EncodedAddress { mod_bits, rm_bits, sib, disp: final_disp, rex_b, rex_x }) + #[cfg(whale_wave_amd64)] + return crate::encoder::wave::address(mem, mode); + #[cfg(not(whale_wave_amd64))] + reference::encode_address(mem, mode) } diff --git a/assembler/amd64/src/encoding/address_reference.rs b/assembler/amd64/src/encoding/address_reference.rs new file mode 100644 index 0000000..0bcd4c5 --- /dev/null +++ b/assembler/amd64/src/encoding/address_reference.rs @@ -0,0 +1,154 @@ +use super::{DispKind, EncodedAddress}; + +use crate::tables::{REGISTERS_32, REGISTERS_64}; + +use assembler::ast::{MemoryAddressMode, MemoryOperand}; + +use assembler::error::AsmError; + +fn reg_code(name: &str, mode: u8) -> Option { + let regs = match mode { + 64 => REGISTERS_64, + 32 => REGISTERS_32, + _ => return None, + }; + + regs.iter().find(|(n, _)| *n == name).map(|(_, c)| *c) +} + +fn scale_bits(scale: u8) -> Option { + match scale { + 1 => Some(0), + 2 => Some(1), + 4 => Some(2), + 8 => Some(3), + _ => None, + } +} + +pub fn encode_address(mem: &MemoryOperand, mode: u8) -> Result { + if mem.symbol.is_some() { + return Err(AsmError::EncodeError( + "symbol memory should be encoded via rip-relative path".into(), + )); + } + + if mem.address_mode != MemoryAddressMode::Default { + if mode != 64 || mem.base.is_some() || mem.index.is_some() || mem.scale != 1 { + return Err(AsmError::EncodeError( + "rel/abs requires a base-less long-mode address".into(), + )); + } + let displacement = i32::try_from(mem.disp).map_err(|_| { + AsmError::EncodeError("rel/abs displacement is out of signed 32-bit range".into()) + })?; + return Ok(EncodedAddress { + mod_bits: 0, + rm_bits: if mem.address_mode == MemoryAddressMode::Relative { 5 } else { 4 }, + sib: if mem.address_mode == MemoryAddressMode::Absolute { + Some((0, 4, 5)) + } else { + None + }, + disp: Some(DispKind::Disp32(displacement)), + rex_b: false, + rex_x: false, + }); + } + + let base_code = mem + .base + .as_deref() + .map(|b| { + reg_code(b, mode).ok_or_else(|| AsmError::EncodeError("Invalid base register".into())) + }) + .transpose()?; + let index_code = mem + .index + .as_deref() + .map(|i| { + reg_code(i, mode).ok_or_else(|| AsmError::EncodeError("Invalid index register".into())) + }) + .transpose()?; + + if base_code.is_none() && index_code.is_none() { + return Err(AsmError::EncodeError("Addressing without base/index not implemented".into())); + } + + let scale = scale_bits(mem.scale) + .ok_or_else(|| AsmError::EncodeError("Scale must be 1/2/4/8".into()))?; + + if let Some(idx) = index_code { + if idx == 4 { + return Err(AsmError::EncodeError("rsp/esp cannot be used as index register".into())); + } + } + + let disp = mem.disp; + let disp32 = i32::try_from(disp).map_err(|_| { + AsmError::EncodeError("memory displacement is out of signed 32-bit range".into()) + })?; + let disp_kind = if disp == 0 { + None + } else if (-128..=127).contains(&disp) { + Some(DispKind::Disp8(disp as i8)) + } else { + Some(DispKind::Disp32(disp32)) + }; + + let need_sib = index_code.is_some() + || base_code.is_none() + || base_code.map(|b| (b & 7) == 4).unwrap_or(false); + + let (mod_bits, final_disp, rm_bits, sib, rex_b, rex_x) = match (base_code, index_code, need_sib) + { + (Some(base), idx, true) => { + let base_low = base & 7; + let mut mod_bits = 0; + let mut disp = disp_kind; + + if base_low == 5 && disp.is_none() { + mod_bits = 1; + disp = Some(DispKind::Disp8(0)); + } else if matches!(disp, Some(DispKind::Disp8(_))) { + mod_bits = 1; + } else if matches!(disp, Some(DispKind::Disp32(_))) { + mod_bits = 2; + } + + let index_low = idx.map(|i| i & 7).unwrap_or(4); + let base_low = base & 7; + ( + mod_bits, + disp, + 4, + Some((scale, index_low, base_low)), + base >= 8, + idx.map(|i| i >= 8).unwrap_or(false), + ) + }, + (Some(base), _, false) => { + let base_low = base & 7; + let mut mod_bits = 0; + let mut disp = disp_kind; + + if base_low == 5 && disp.is_none() { + mod_bits = 1; + disp = Some(DispKind::Disp8(0)); + } else if matches!(disp, Some(DispKind::Disp8(_))) { + mod_bits = 1; + } else if matches!(disp, Some(DispKind::Disp32(_))) { + mod_bits = 2; + } + + (mod_bits, disp, base_low, None, base >= 8, false) + }, + (None, Some(idx), _) => { + let index_low = idx & 7; + (0, Some(DispKind::Disp32(disp32)), 4, Some((scale, index_low, 5)), false, idx >= 8) + }, + _ => return Err(AsmError::EncodeError("Addressing mode is not supported yet".into())), + }; + + Ok(EncodedAddress { mod_bits, rm_bits, sib, disp: final_disp, rex_b, rex_x }) +} diff --git a/assembler/amd64/src/encoding/modrm.rs b/assembler/amd64/src/encoding/modrm.rs index f5fb64b..9135492 100644 --- a/assembler/amd64/src/encoding/modrm.rs +++ b/assembler/amd64/src/encoding/modrm.rs @@ -11,6 +11,17 @@ impl ModRM { } pub fn encode(&self) -> u8 { - (self.mod_bits << 6) | ((self.reg & 7) << 3) | (self.rm & 7) + #[cfg(whale_wave_amd64)] + return crate::encoder::wave::bits( + 0, + u64::from(self.mod_bits), + u64::from(self.reg), + u64::from(self.rm), + 0, + ); + #[cfg(not(whale_wave_amd64))] + { + (self.mod_bits << 6) | ((self.reg & 7) << 3) | (self.rm & 7) + } } } diff --git a/assembler/amd64/src/encoding/rex.rs b/assembler/amd64/src/encoding/rex.rs index c51535e..0947791 100644 --- a/assembler/amd64/src/encoding/rex.rs +++ b/assembler/amd64/src/encoding/rex.rs @@ -12,9 +12,20 @@ impl REX { } pub fn encode(&self) -> u8 { - 0x40 | ((self.w as u8) << 3) - | ((self.r as u8) << 2) - | ((self.x as u8) << 1) - | (self.b as u8) + #[cfg(whale_wave_amd64)] + return crate::encoder::wave::bits( + 1, + u64::from(self.w), + u64::from(self.r), + u64::from(self.x), + u64::from(self.b), + ); + #[cfg(not(whale_wave_amd64))] + { + 0x40 | ((self.w as u8) << 3) + | ((self.r as u8) << 2) + | ((self.x as u8) << 1) + | (self.b as u8) + } } } diff --git a/assembler/amd64/src/encoding/sib.rs b/assembler/amd64/src/encoding/sib.rs index e3f7084..c2f1f3b 100644 --- a/assembler/amd64/src/encoding/sib.rs +++ b/assembler/amd64/src/encoding/sib.rs @@ -11,6 +11,17 @@ impl SIB { } pub fn encode(&self) -> u8 { - ((self.scale & 3) << 6) | ((self.index & 7) << 3) | (self.base & 7) + #[cfg(whale_wave_amd64)] + return crate::encoder::wave::bits( + 2, + u64::from(self.scale), + u64::from(self.index), + u64::from(self.base), + 0, + ); + #[cfg(not(whale_wave_amd64))] + { + ((self.scale & 3) << 6) | ((self.index & 7) << 3) | (self.base & 7) + } } } diff --git a/assembler/amd64/src/lib.rs b/assembler/amd64/src/lib.rs index 85dbf43..088f892 100644 --- a/assembler/amd64/src/lib.rs +++ b/assembler/amd64/src/lib.rs @@ -10,6 +10,9 @@ pub mod encoder; pub mod encoding; +#[cfg(whale_wave_amd64)] +mod ast_model; + pub mod parser; pub mod tables; diff --git a/assembler/amd64/src/parser.rs b/assembler/amd64/src/parser.rs index f68c040..ba2884d 100644 --- a/assembler/amd64/src/parser.rs +++ b/assembler/amd64/src/parser.rs @@ -1,664 +1,22 @@ -use assembler::ast::*; - -use assembler::error::AsmError; - -use assembler::tokens::{Token, TokenKind}; - -fn parser_err(tokens: &[Token], pos: usize, msg: &str) -> AsmError { - let span = if let Some(token) = tokens.get(pos) { - token.span() - } else if let Some(token) = tokens.last() { - assembler::error::SourceSpan { - start: token.end_position, - end: token.end_position, - line: token.end_line, - column: token.end_column, - } - } else { - assembler::error::SourceSpan { start: 0, end: 0, line: 1, column: 1 } - }; - AsmError::ParserError(msg.into()).at("", span, None) -} - -pub fn parse(tokens: &[Token]) -> Result { - let mut pos = 0; - let mut items = Vec::new(); - let mut spans = Vec::new(); - while pos < tokens.len() { - if matches!(tokens[pos].kind, TokenKind::Newline) { - pos += 1; - continue; - } - let start = pos; - let node = match &tokens[pos].kind { - TokenKind::Identifier(name) => { - if matches!(tokens.get(pos + 1).map(|t| &t.kind), Some(TokenKind::Colon)) { - let node = ASTNode::Label(name.clone()); - pos += 2; - node - } else if matches!(tokens.get(pos+1).map(|t|&t.kind),Some(TokenKind::Identifier(keyword))if keyword.eq_ignore_ascii_case("equ")) - { - parse_const_definition(tokens, &mut pos)? - } else if is_directive(name) { - parse_directive(tokens, &mut pos)? - } else { - parse_instruction(tokens, &mut pos)? - } - }, - _ => return Err(parser_err(tokens, pos, "Unexpected token at top level")), - }; - let last = tokens[start..pos] - .iter() - .rev() - .find(|t| !matches!(t.kind, TokenKind::Newline)) - .unwrap(); - let mut span = tokens[start].span(); - span.end = last.end_position; - spans.push(span); - items.push(node); - } - Ok(AST { items, spans, source_name: "".into() }) -} - -fn parse_const_definition(tokens: &[Token], pos: &mut usize) -> Result { - let name = match &tokens[*pos].kind { - TokenKind::Identifier(s) => s.clone(), - _ => return Err(parser_err(tokens, *pos, "Expected constant name")), - }; - *pos += 1; - - match tokens.get(*pos).map(|t| &t.kind) { - Some(TokenKind::Identifier(s)) if s.eq_ignore_ascii_case("equ") => { - *pos += 1; - }, - _ => return Err(parser_err(tokens, *pos, "Expected 'equ'")), - } - - let expr = parse_expr(tokens, pos, |k| matches!(k, TokenKind::Newline))?; - while *pos < tokens.len() && matches!(tokens[*pos].kind, TokenKind::Newline) { - *pos += 1; - } - - Ok(ASTNode::Const { name, expr }) -} - -fn parse_instruction(tokens: &[Token], pos: &mut usize) -> Result { - let mnemonic = parse_mnemonic(tokens, pos)?; - if matches!(mnemonic.as_str(), "cwd" | "cdq" | "cqo") - && *pos < tokens.len() - && !matches!(tokens[*pos].kind, TokenKind::Newline) +// SPDX-License-Identifier: MPL-2.0 +//! AMD64 grammar dispatch. Wave owns the production parser. +#[cfg(any(not(whale_wave_amd64), test))] +#[path = "parser_reference.rs"] +pub(crate) mod reference; + +#[cfg(whale_wave_amd64)] +#[path = "parser_wave.rs"] +mod wave; + +pub fn parse( + tokens: &[assembler::tokens::Token], +) -> Result { + #[cfg(whale_wave_amd64)] { - return Err(parser_err(tokens, *pos, &format!("{mnemonic} expects 0 operands"))); - } - let operands = parse_operand_list(tokens, pos)?; - Ok(ASTNode::Instruction(Instruction { mnemonic, operands })) -} - -fn parse_mnemonic(tokens: &[Token], pos: &mut usize) -> Result { - match &tokens[*pos].kind { - TokenKind::Identifier(s) => { - *pos += 1; - Ok(s.to_ascii_lowercase()) - }, - _ => Err(parser_err(tokens, *pos, "Expected mnemonic")), - } -} - -// Instructions and fixed-argument directives end at a logical newline or EOF. -// Labels are parsed separately, so `label: instruction` remains valid. -fn finish_statement(tokens: &[Token], pos: &mut usize) -> Result<(), AsmError> { - if *pos < tokens.len() && !matches!(tokens[*pos].kind, TokenKind::Newline) { - return Err(parser_err(tokens, *pos, "Expected end of statement")); - } - while *pos < tokens.len() && matches!(tokens[*pos].kind, TokenKind::Newline) { - *pos += 1; - } - Ok(()) -} - -fn parse_operand_list(tokens: &[Token], pos: &mut usize) -> Result, AsmError> { - let mut ops = Vec::new(); - if *pos < tokens.len() && !matches!(tokens[*pos].kind, TokenKind::Newline) { - loop { - ops.push(parse_operand(tokens, pos)?); - if !matches!(tokens.get(*pos).map(|t| &t.kind), Some(TokenKind::Comma)) { - break; - } - let comma = *pos; - *pos += 1; - if *pos >= tokens.len() || matches!(tokens[*pos].kind, TokenKind::Newline) { - return Err(parser_err(tokens, comma, "Expected operand after comma")); - } - } - } - finish_statement(tokens, pos)?; - Ok(ops) -} - -fn parse_operand(tokens: &[Token], pos: &mut usize) -> Result { - if let Some(TokenKind::Identifier(name)) = tokens.get(*pos).map(|t| &t.kind) { - if let Some(width) = memory_width(name) { - *pos += 1; - if !matches!(tokens.get(*pos).map(|t| &t.kind), Some(TokenKind::LBracket)) { - return Err(parser_err(tokens, *pos, "Width qualifier requires memory operand")); - } - let Operand::Memory(mut mem) = parse_memory_operand(tokens, pos)? else { - unreachable!() - }; - mem.width = Some(width); - return Ok(Operand::Memory(mem)); - } - } - if matches!(tokens[*pos].kind, TokenKind::LBracket) { - return parse_memory_operand(tokens, pos); - } - - if let TokenKind::Identifier(name) = &tokens[*pos].kind { - let reg = name.to_ascii_lowercase(); - let next_is_expr_op = *pos + 1 < tokens.len() - && matches!(tokens[*pos + 1].kind, TokenKind::Plus | TokenKind::Minus); - if is_register(®) && !next_is_expr_op { - *pos += 1; - return Ok(Operand::Register(reg)); - } - } - - let expr = parse_expr(tokens, pos, |k| matches!(k, TokenKind::Comma | TokenKind::Newline))?; - match expr { - ExprValue::Number(n) => Ok(Operand::Immediate(n)), - ExprValue::Symbol { name, addend } => { - if addend == 0 { - Ok(Operand::Label(name)) - } else { - Ok(Operand::SymbolExpr { name, addend }) - } - }, - } -} - -fn parse_memory_operand(tokens: &[Token], pos: &mut usize) -> Result { - *pos += 1; // '[' - let mut address_mode = MemoryAddressMode::Default; - if let Some(token) = tokens.get(*pos) { - if let TokenKind::Identifier(name) = &token.kind { - // A separated prefix introduces the new syntax. Existing symbols - // named rel/abs still work as [rel], [abs+4], etc. - let separated_term = tokens.get(*pos + 1).is_some_and(|next| { - next.position > token.end_position - && !matches!(next.kind, TokenKind::RBracket | TokenKind::Newline) - }); - if separated_term - && (name.eq_ignore_ascii_case("rel") || name.eq_ignore_ascii_case("abs")) - { - address_mode = if name.eq_ignore_ascii_case("rel") { - MemoryAddressMode::Relative - } else { - MemoryAddressMode::Absolute - }; - *pos += 1; - } - } - } - - let mut base = None; - let mut index = None; - let mut symbol = None; - let mut scale = 1; - let mut disp = 0i64; - let mut sign = 1i64; - - // A leading sign is allowed; subsequent signs must separate complete terms. - match tokens.get(*pos).map(|t| &t.kind) { - Some(TokenKind::Plus) => *pos += 1, - Some(TokenKind::Minus) => { - sign = -1; - *pos += 1; - }, - _ => {}, - } - - loop { - let term_pos = *pos; - let kind = tokens.get(*pos).map(|t| &t.kind); - match kind { - None | Some(TokenKind::Newline) => { - return Err(parser_err(tokens, *pos, "Missing closing ']' in memory operand")); - }, - Some(TokenKind::Identifier(name)) => { - if sign < 0 { - return Err(parser_err( - tokens, - *pos, - "Negative register or symbol terms are not supported in memory operands", - )); - } - let lower = name.to_ascii_lowercase(); - if is_register(&lower) { - let scaled = - matches!(tokens.get(*pos + 1).map(|t| &t.kind), Some(TokenKind::Multiply)); - if base.is_none() && !scaled { - base = Some(lower); - *pos += 1; - } else if index.is_none() { - index = Some(lower); - *pos += 1; - if matches!(tokens.get(*pos).map(|t| &t.kind), Some(TokenKind::Multiply)) { - *pos += 1; - match tokens.get(*pos).map(|t| &t.kind) { - Some(TokenKind::Number(n)) if matches!(*n, 1 | 2 | 4 | 8) => { - scale = *n as u8; - *pos += 1; - }, - _ => return Err(parser_err(tokens, *pos, "Scale must be 1/2/4/8")), - } - } - } else { - return Err(parser_err( - tokens, - term_pos, - "Too many registers in memory operand", - )); - } - } else if symbol.is_none() { - symbol = Some(name.clone()); - *pos += 1; - } else { - return Err(parser_err(tokens, term_pos, "Multiple symbols in memory operand")); - } - }, - Some(TokenKind::Number(n)) => { - disp = n - .checked_mul(sign as i128) - .and_then(|n| i64::try_from(n).ok()) - .and_then(|n| disp.checked_add(n)) - .ok_or_else(|| parser_err(tokens, term_pos, "Memory displacement overflow"))?; - *pos += 1; - }, - _ => return Err(parser_err(tokens, *pos, "Expected term in memory operand")), - } - - match tokens.get(*pos).map(|t| &t.kind) { - Some(TokenKind::RBracket) => { - *pos += 1; - if address_mode != MemoryAddressMode::Default && (base.is_some() || index.is_some()) - { - return Err(parser_err(tokens, term_pos, "rel/abs address requires a symbol or numeric displacement without registers")); - } - return Ok(Operand::Memory(MemoryOperand { - address_mode, - width: None, - base, - index, - scale, - disp, - symbol, - })); - }, - Some(TokenKind::Plus) => { - sign = 1; - *pos += 1; - }, - Some(TokenKind::Minus) => { - sign = -1; - *pos += 1; - }, - None | Some(TokenKind::Newline) => { - return Err(parser_err(tokens, *pos, "Missing closing ']' in memory operand")); - }, - _ => { - return Err(parser_err(tokens, *pos, "Expected '+', '-' or ']' in memory operand")) - }, - } - } -} - -fn parse_directive(tokens: &[Token], pos: &mut usize) -> Result { - let name = match &tokens[*pos].kind { - TokenKind::Identifier(s) => s.to_ascii_lowercase(), - _ => return Err(parser_err(tokens, *pos, "Expected directive name")), - }; - *pos += 1; - - if name == "symbol" { - let symbol = match tokens.get(*pos).map(|t| &t.kind) { - Some(TokenKind::Identifier(s)) => s.clone(), - _ => return Err(parser_err(tokens, *pos, "Expected symbol name")), - }; - *pos += 1; - let comma = |pos: &mut usize| -> Result<(), AsmError> { - if !matches!(tokens.get(*pos).map(|t| &t.kind), Some(TokenKind::Comma)) { - return Err(parser_err(tokens, *pos, "Expected comma in symbol declaration")); - } - *pos += 1; - Ok(()) - }; - comma(pos)?; - let kind = match tokens.get(*pos).map(|t| &t.kind) { - Some(TokenKind::Identifier(s)) if s.eq_ignore_ascii_case("function") => { - assembler::SymbolKind::Function - }, - Some(TokenKind::Identifier(s)) if s.eq_ignore_ascii_case("object") => { - assembler::SymbolKind::Object - }, - Some(TokenKind::Identifier(s)) if s.eq_ignore_ascii_case("notype") => { - assembler::SymbolKind::NoType - }, - _ => { - return Err(parser_err( - tokens, - *pos, - "Expected symbol kind function, object or notype", - )) - }, - }; - *pos += 1; - comma(pos)?; - let size = parse_expr(tokens, pos, |k| matches!(k, TokenKind::Comma | TokenKind::Newline))?; - comma(pos)?; - let visibility = match tokens.get(*pos).map(|t| &t.kind) { - Some(TokenKind::Identifier(s)) if s.eq_ignore_ascii_case("default") => { - assembler::SymbolVisibility::Default - }, - Some(TokenKind::Identifier(s)) if s.eq_ignore_ascii_case("hidden") => { - assembler::SymbolVisibility::Hidden - }, - _ => { - return Err(parser_err( - tokens, - *pos, - "Expected symbol visibility default or hidden", - )) - }, - }; - *pos += 1; - finish_statement(tokens, pos)?; - return Ok(ASTNode::SymbolMetadata { name: symbol, kind, size, visibility }); - } - if matches!(name.as_str(), "section" | "global" | "extern") { - let argument = match tokens.get(*pos).map(|t| &t.kind) { - Some(TokenKind::Identifier(s)) => s.clone(), - _ => return Err(parser_err(tokens, *pos, "Expected directive name argument")), - }; - *pos += 1; - if name == "section" && matches!(tokens.get(*pos).map(|t| &t.kind), Some(TokenKind::Comma)) - { - *pos += 1; - let kind = match tokens.get(*pos).map(|t| &t.kind) { - Some(TokenKind::Identifier(kind)) => match kind.to_ascii_lowercase().as_str() { - "text" => AsmSectionKind::Text, - "data" => AsmSectionKind::Data, - "rodata" => AsmSectionKind::ReadOnlyData, - "bss" => AsmSectionKind::Bss, - _ => { - return Err(parser_err( - tokens, - *pos, - "Expected section kind text/data/rodata/bss", - )) - }, - }, - _ => { - return Err(parser_err( - tokens, - *pos, - "Expected section kind text/data/rodata/bss", - )) - }, - }; - *pos += 1; - finish_statement(tokens, pos)?; - return Ok(ASTNode::SectionAttributes { name: argument, kind }); - } - finish_statement(tokens, pos)?; - return Ok(match name.as_str() { - "section" => ASTNode::Section(argument), - "global" => ASTNode::Global(argument), - _ => ASTNode::Extern(argument), - }); - } - - let mut values = Vec::new(); - loop { - if *pos >= tokens.len() || matches!(tokens[*pos].kind, TokenKind::Newline) { - return Err(parser_err(tokens, *pos, "Expected directive value")); - } - match &tokens[*pos].kind { - TokenKind::StringLiteral(s) => { - values.push(DirectiveValue::StringLiteral(s.clone())); - *pos += 1; - }, - _ => { - let expr = parse_expr(tokens, pos, |k| { - matches!(k, TokenKind::Comma | TokenKind::Newline) - })?; - values.push(DirectiveValue::Expr(expr)); - }, - } - if !matches!(tokens.get(*pos).map(|t| &t.kind), Some(TokenKind::Comma)) { - break; - } - let comma = *pos; - *pos += 1; - if *pos >= tokens.len() || matches!(tokens[*pos].kind, TokenKind::Newline) { - return Err(parser_err(tokens, comma, "Expected directive value after comma")); - } - } - finish_statement(tokens, pos)?; - Ok(ASTNode::Directive(Directive { name, values })) -} - -fn parse_expr(tokens: &[Token], pos: &mut usize, stop: F) -> Result -where - F: Fn(&TokenKind) -> bool, -{ - let mut acc: Option = None; - let mut expect_term = true; - let mut sign: i128 = 1; - - while *pos < tokens.len() { - let kind = &tokens[*pos].kind; - if stop(kind) { - break; - } - - if expect_term { - match kind { - TokenKind::Plus => { - *pos += 1; - }, - TokenKind::Minus => { - sign = -sign; - *pos += 1; - }, - TokenKind::Number(n) => { - let term = ExprValue::Number(sign.checked_mul(*n).ok_or_else(|| { - parser_err(tokens, *pos, "Expression arithmetic overflow") - })?); - acc = Some(combine_expr(tokens, *pos, acc, term)?); - *pos += 1; - sign = 1; - expect_term = false; - }, - TokenKind::Identifier(s) => { - if sign < 0 { - return Err(parser_err( - tokens, - *pos, - "Unary '-' before symbol is not supported", - )); - } - let term = ExprValue::Symbol { name: s.clone(), addend: 0 }; - acc = Some(combine_expr(tokens, *pos, acc, term)?); - *pos += 1; - sign = 1; - expect_term = false; - }, - _ => return Err(parser_err(tokens, *pos, "Expected expression term")), - } - } else { - match kind { - TokenKind::Plus => { - sign = 1; - expect_term = true; - *pos += 1; - }, - TokenKind::Minus => { - sign = -1; - expect_term = true; - *pos += 1; - }, - _ => return Err(parser_err(tokens, *pos, "Expected '+' or '-' in expression")), - } - } - } - - if expect_term && acc.is_some() { - return Err(parser_err(tokens, *pos, "Expression cannot end with operator")); + wave::parse(tokens) } - - let expression = acc.ok_or_else(|| parser_err(tokens, *pos, "Expected expression"))?; - // Literals are bounded when lexed; intermediate arithmetic uses i128 so - // subtraction/cancellation can produce any supported final 64-bit value. - // A symbol's addend is checked only after equ resolution or relocation use. - if let ExprValue::Number(number) = &expression { - if !(i64::MIN as i128..=u64::MAX as i128).contains(number) { - return Err(parser_err(tokens, pos.saturating_sub(1), "64-bit expression overflow")); - } - } - Ok(expression) -} - -fn combine_expr( - tokens: &[Token], - pos: usize, - left: Option, - right: ExprValue, -) -> Result { - match (left, right) { - (None, r) => Ok(r), - (Some(ExprValue::Number(a)), ExprValue::Number(b)) => { - let n = a - .checked_add(b) - .ok_or_else(|| parser_err(tokens, pos, "Expression arithmetic overflow"))?; - Ok(ExprValue::Number(n)) - }, - (Some(ExprValue::Number(a)), ExprValue::Symbol { name, addend }) => Ok(ExprValue::Symbol { - name, - addend: addend - .checked_add(a) - .ok_or_else(|| parser_err(tokens, pos, "Symbol addend overflow"))?, - }), - (Some(ExprValue::Symbol { name, addend }), ExprValue::Number(b)) => Ok(ExprValue::Symbol { - name, - addend: addend - .checked_add(b) - .ok_or_else(|| parser_err(tokens, pos, "Symbol addend overflow"))?, - }), - (Some(ExprValue::Symbol { .. }), ExprValue::Symbol { .. }) => { - Err(parser_err(tokens, pos, "Expressions with multiple symbols are not supported")) - }, - } -} - -fn memory_width(name: &str) -> Option { - match name.to_ascii_lowercase().as_str() { - "byte" => Some(8), - "word" => Some(16), - "dword" => Some(32), - "qword" => Some(64), - _ => None, + #[cfg(not(whale_wave_amd64))] + { + reference::parse(tokens) } } - -fn is_register(name: &str) -> bool { - matches!( - name, - "rax" - | "rbx" - | "rcx" - | "rdx" - | "rsi" - | "rdi" - | "rbp" - | "rsp" - | "r8" - | "r9" - | "r10" - | "r11" - | "r12" - | "r13" - | "r14" - | "r15" - | "eax" - | "ebx" - | "ecx" - | "edx" - | "esi" - | "edi" - | "ebp" - | "esp" - | "r8d" - | "r9d" - | "r10d" - | "r11d" - | "r12d" - | "r13d" - | "r14d" - | "r15d" - | "ax" - | "bx" - | "cx" - | "dx" - | "si" - | "di" - | "bp" - | "sp" - | "r8w" - | "r9w" - | "r10w" - | "r11w" - | "r12w" - | "r13w" - | "r14w" - | "r15w" - | "spl" - | "bpl" - | "sil" - | "dil" - | "al" - | "bl" - | "cl" - | "dl" - | "ah" - | "bh" - | "ch" - | "dh" - | "r8b" - | "r9b" - | "r10b" - | "r11b" - | "r12b" - | "r13b" - | "r14b" - | "r15b" - ) || crate::tables::xmm_register_code(name).is_some() -} - -fn is_directive(name: &str) -> bool { - matches!( - name.to_ascii_lowercase().as_str(), - "align" - | "db" - | "dw" - | "dd" - | "dq" - | "resb" - | "resw" - | "resd" - | "resq" - | "section" - | "global" - | "extern" - | "symbol" - ) -} diff --git a/assembler/amd64/src/parser_reference.rs b/assembler/amd64/src/parser_reference.rs new file mode 100644 index 0000000..e1b0e92 --- /dev/null +++ b/assembler/amd64/src/parser_reference.rs @@ -0,0 +1,664 @@ +use assembler::ast::*; + +use assembler::error::AsmError; + +use assembler::tokens::{Token, TokenKind}; + +fn parser_err(tokens: &[Token], pos: usize, msg: &str) -> AsmError { + let span = if let Some(token) = tokens.get(pos) { + token.span() + } else if let Some(token) = tokens.last() { + assembler::error::SourceSpan { + start: token.end_position, + end: token.end_position, + line: token.end_line, + column: token.end_column, + } + } else { + assembler::error::SourceSpan { start: 0, end: 0, line: 1, column: 1 } + }; + AsmError::ParserError(msg.into()).at("", span, None) +} + +pub fn parse(tokens: &[Token]) -> Result { + let mut pos = 0; + let mut items = Vec::new(); + let mut spans = Vec::new(); + while pos < tokens.len() { + if matches!(tokens[pos].kind, TokenKind::Newline) { + pos += 1; + continue; + } + let start = pos; + let node = match &tokens[pos].kind { + TokenKind::Identifier(name) => { + if matches!(tokens.get(pos + 1).map(|t| &t.kind), Some(TokenKind::Colon)) { + let node = ASTNode::Label(name.clone()); + pos += 2; + node + } else if matches!(tokens.get(pos+1).map(|t|&t.kind),Some(TokenKind::Identifier(keyword))if keyword.eq_ignore_ascii_case("equ")) + { + parse_const_definition(tokens, &mut pos)? + } else if is_directive(name) { + parse_directive(tokens, &mut pos)? + } else { + parse_instruction(tokens, &mut pos)? + } + }, + _ => return Err(parser_err(tokens, pos, "Unexpected token at top level")), + }; + let last = tokens[start..pos] + .iter() + .rev() + .find(|t| !matches!(t.kind, TokenKind::Newline)) + .unwrap(); + let mut span = tokens[start].span(); + span.end = last.end_position; + spans.push(span); + items.push(node); + } + Ok(AST { items, spans, source_name: "".into() }) +} + +fn parse_const_definition(tokens: &[Token], pos: &mut usize) -> Result { + let name = match &tokens[*pos].kind { + TokenKind::Identifier(s) => s.clone(), + _ => return Err(parser_err(tokens, *pos, "Expected constant name")), + }; + *pos += 1; + + match tokens.get(*pos).map(|t| &t.kind) { + Some(TokenKind::Identifier(s)) if s.eq_ignore_ascii_case("equ") => { + *pos += 1; + }, + _ => return Err(parser_err(tokens, *pos, "Expected 'equ'")), + } + + let expr = parse_expr(tokens, pos, |k| matches!(k, TokenKind::Newline))?; + while *pos < tokens.len() && matches!(tokens[*pos].kind, TokenKind::Newline) { + *pos += 1; + } + + Ok(ASTNode::Const { name, expr }) +} + +fn parse_instruction(tokens: &[Token], pos: &mut usize) -> Result { + let mnemonic = parse_mnemonic(tokens, pos)?; + if matches!(mnemonic.as_str(), "cwd" | "cdq" | "cqo") + && *pos < tokens.len() + && !matches!(tokens[*pos].kind, TokenKind::Newline) + { + return Err(parser_err(tokens, *pos, &format!("{mnemonic} expects 0 operands"))); + } + let operands = parse_operand_list(tokens, pos)?; + Ok(ASTNode::Instruction(Instruction { mnemonic, operands })) +} + +fn parse_mnemonic(tokens: &[Token], pos: &mut usize) -> Result { + match &tokens[*pos].kind { + TokenKind::Identifier(s) => { + *pos += 1; + Ok(s.to_ascii_lowercase()) + }, + _ => Err(parser_err(tokens, *pos, "Expected mnemonic")), + } +} + +// Instructions and fixed-argument directives end at a logical newline or EOF. +// Labels are parsed separately, so `label: instruction` remains valid. +fn finish_statement(tokens: &[Token], pos: &mut usize) -> Result<(), AsmError> { + if *pos < tokens.len() && !matches!(tokens[*pos].kind, TokenKind::Newline) { + return Err(parser_err(tokens, *pos, "Expected end of statement")); + } + while *pos < tokens.len() && matches!(tokens[*pos].kind, TokenKind::Newline) { + *pos += 1; + } + Ok(()) +} + +fn parse_operand_list(tokens: &[Token], pos: &mut usize) -> Result, AsmError> { + let mut ops = Vec::new(); + if *pos < tokens.len() && !matches!(tokens[*pos].kind, TokenKind::Newline) { + loop { + ops.push(parse_operand(tokens, pos)?); + if !matches!(tokens.get(*pos).map(|t| &t.kind), Some(TokenKind::Comma)) { + break; + } + let comma = *pos; + *pos += 1; + if *pos >= tokens.len() || matches!(tokens[*pos].kind, TokenKind::Newline) { + return Err(parser_err(tokens, comma, "Expected operand after comma")); + } + } + } + finish_statement(tokens, pos)?; + Ok(ops) +} + +fn parse_operand(tokens: &[Token], pos: &mut usize) -> Result { + if let Some(TokenKind::Identifier(name)) = tokens.get(*pos).map(|t| &t.kind) { + if let Some(width) = memory_width(name) { + *pos += 1; + if !matches!(tokens.get(*pos).map(|t| &t.kind), Some(TokenKind::LBracket)) { + return Err(parser_err(tokens, *pos, "Width qualifier requires memory operand")); + } + let Operand::Memory(mut mem) = parse_memory_operand(tokens, pos)? else { + unreachable!() + }; + mem.width = Some(width); + return Ok(Operand::Memory(mem)); + } + } + if matches!(tokens[*pos].kind, TokenKind::LBracket) { + return parse_memory_operand(tokens, pos); + } + + if let TokenKind::Identifier(name) = &tokens[*pos].kind { + let reg = name.to_ascii_lowercase(); + let next_is_expr_op = *pos + 1 < tokens.len() + && matches!(tokens[*pos + 1].kind, TokenKind::Plus | TokenKind::Minus); + if is_register(®) && !next_is_expr_op { + *pos += 1; + return Ok(Operand::Register(reg)); + } + } + + let expr = parse_expr(tokens, pos, |k| matches!(k, TokenKind::Comma | TokenKind::Newline))?; + match expr { + ExprValue::Number(n) => Ok(Operand::Immediate(n)), + ExprValue::Symbol { name, addend } => { + if addend == 0 { + Ok(Operand::Label(name)) + } else { + Ok(Operand::SymbolExpr { name, addend }) + } + }, + } +} + +fn parse_memory_operand(tokens: &[Token], pos: &mut usize) -> Result { + *pos += 1; // '[' + let mut address_mode = MemoryAddressMode::Default; + if let Some(token) = tokens.get(*pos) { + if let TokenKind::Identifier(name) = &token.kind { + // A separated prefix introduces the new syntax. Existing symbols + // named rel/abs still work as [rel], [abs+4], etc. + let separated_term = tokens.get(*pos + 1).is_some_and(|next| { + next.position > token.end_position + && !matches!(next.kind, TokenKind::RBracket | TokenKind::Newline) + }); + if separated_term + && (name.eq_ignore_ascii_case("rel") || name.eq_ignore_ascii_case("abs")) + { + address_mode = if name.eq_ignore_ascii_case("rel") { + MemoryAddressMode::Relative + } else { + MemoryAddressMode::Absolute + }; + *pos += 1; + } + } + } + + let mut base = None; + let mut index = None; + let mut symbol = None; + let mut scale = 1; + let mut disp = 0i64; + let mut sign = 1i64; + + // A leading sign is allowed; subsequent signs must separate complete terms. + match tokens.get(*pos).map(|t| &t.kind) { + Some(TokenKind::Plus) => *pos += 1, + Some(TokenKind::Minus) => { + sign = -1; + *pos += 1; + }, + _ => {}, + } + + loop { + let term_pos = *pos; + let kind = tokens.get(*pos).map(|t| &t.kind); + match kind { + None | Some(TokenKind::Newline) => { + return Err(parser_err(tokens, *pos, "Missing closing ']' in memory operand")); + }, + Some(TokenKind::Identifier(name)) => { + if sign < 0 { + return Err(parser_err( + tokens, + *pos, + "Negative register or symbol terms are not supported in memory operands", + )); + } + let lower = name.to_ascii_lowercase(); + if is_register(&lower) { + let scaled = + matches!(tokens.get(*pos + 1).map(|t| &t.kind), Some(TokenKind::Multiply)); + if base.is_none() && !scaled { + base = Some(lower); + *pos += 1; + } else if index.is_none() { + index = Some(lower); + *pos += 1; + if matches!(tokens.get(*pos).map(|t| &t.kind), Some(TokenKind::Multiply)) { + *pos += 1; + match tokens.get(*pos).map(|t| &t.kind) { + Some(TokenKind::Number(n)) if matches!(*n, 1 | 2 | 4 | 8) => { + scale = *n as u8; + *pos += 1; + }, + _ => return Err(parser_err(tokens, *pos, "Scale must be 1/2/4/8")), + } + } + } else { + return Err(parser_err( + tokens, + term_pos, + "Too many registers in memory operand", + )); + } + } else if symbol.is_none() { + symbol = Some(name.clone()); + *pos += 1; + } else { + return Err(parser_err(tokens, term_pos, "Multiple symbols in memory operand")); + } + }, + Some(TokenKind::Number(n)) => { + disp = n + .checked_mul(sign as i128) + .and_then(|n| i64::try_from(n).ok()) + .and_then(|n| disp.checked_add(n)) + .ok_or_else(|| parser_err(tokens, term_pos, "Memory displacement overflow"))?; + *pos += 1; + }, + _ => return Err(parser_err(tokens, *pos, "Expected term in memory operand")), + } + + match tokens.get(*pos).map(|t| &t.kind) { + Some(TokenKind::RBracket) => { + *pos += 1; + if address_mode != MemoryAddressMode::Default && (base.is_some() || index.is_some()) + { + return Err(parser_err(tokens, term_pos, "rel/abs address requires a symbol or numeric displacement without registers")); + } + return Ok(Operand::Memory(MemoryOperand { + address_mode, + width: None, + base, + index, + scale, + disp, + symbol, + })); + }, + Some(TokenKind::Plus) => { + sign = 1; + *pos += 1; + }, + Some(TokenKind::Minus) => { + sign = -1; + *pos += 1; + }, + None | Some(TokenKind::Newline) => { + return Err(parser_err(tokens, *pos, "Missing closing ']' in memory operand")); + }, + _ => { + return Err(parser_err(tokens, *pos, "Expected '+', '-' or ']' in memory operand")) + }, + } + } +} + +fn parse_directive(tokens: &[Token], pos: &mut usize) -> Result { + let name = match &tokens[*pos].kind { + TokenKind::Identifier(s) => s.to_ascii_lowercase(), + _ => return Err(parser_err(tokens, *pos, "Expected directive name")), + }; + *pos += 1; + + if name == "symbol" { + let symbol = match tokens.get(*pos).map(|t| &t.kind) { + Some(TokenKind::Identifier(s)) => s.clone(), + _ => return Err(parser_err(tokens, *pos, "Expected symbol name")), + }; + *pos += 1; + let comma = |pos: &mut usize| -> Result<(), AsmError> { + if !matches!(tokens.get(*pos).map(|t| &t.kind), Some(TokenKind::Comma)) { + return Err(parser_err(tokens, *pos, "Expected comma in symbol declaration")); + } + *pos += 1; + Ok(()) + }; + comma(pos)?; + let kind = match tokens.get(*pos).map(|t| &t.kind) { + Some(TokenKind::Identifier(s)) if s.eq_ignore_ascii_case("function") => { + assembler::SymbolKind::Function + }, + Some(TokenKind::Identifier(s)) if s.eq_ignore_ascii_case("object") => { + assembler::SymbolKind::Object + }, + Some(TokenKind::Identifier(s)) if s.eq_ignore_ascii_case("notype") => { + assembler::SymbolKind::NoType + }, + _ => { + return Err(parser_err( + tokens, + *pos, + "Expected symbol kind function, object or notype", + )) + }, + }; + *pos += 1; + comma(pos)?; + let size = parse_expr(tokens, pos, |k| matches!(k, TokenKind::Comma | TokenKind::Newline))?; + comma(pos)?; + let visibility = match tokens.get(*pos).map(|t| &t.kind) { + Some(TokenKind::Identifier(s)) if s.eq_ignore_ascii_case("default") => { + assembler::SymbolVisibility::Default + }, + Some(TokenKind::Identifier(s)) if s.eq_ignore_ascii_case("hidden") => { + assembler::SymbolVisibility::Hidden + }, + _ => { + return Err(parser_err( + tokens, + *pos, + "Expected symbol visibility default or hidden", + )) + }, + }; + *pos += 1; + finish_statement(tokens, pos)?; + return Ok(ASTNode::SymbolMetadata { name: symbol, kind, size, visibility }); + } + if matches!(name.as_str(), "section" | "global" | "extern") { + let argument = match tokens.get(*pos).map(|t| &t.kind) { + Some(TokenKind::Identifier(s)) => s.clone(), + _ => return Err(parser_err(tokens, *pos, "Expected directive name argument")), + }; + *pos += 1; + if name == "section" && matches!(tokens.get(*pos).map(|t| &t.kind), Some(TokenKind::Comma)) + { + *pos += 1; + let kind = match tokens.get(*pos).map(|t| &t.kind) { + Some(TokenKind::Identifier(kind)) => match kind.to_ascii_lowercase().as_str() { + "text" => AsmSectionKind::Text, + "data" => AsmSectionKind::Data, + "rodata" => AsmSectionKind::ReadOnlyData, + "bss" => AsmSectionKind::Bss, + _ => { + return Err(parser_err( + tokens, + *pos, + "Expected section kind text/data/rodata/bss", + )) + }, + }, + _ => { + return Err(parser_err( + tokens, + *pos, + "Expected section kind text/data/rodata/bss", + )) + }, + }; + *pos += 1; + finish_statement(tokens, pos)?; + return Ok(ASTNode::SectionAttributes { name: argument, kind }); + } + finish_statement(tokens, pos)?; + return Ok(match name.as_str() { + "section" => ASTNode::Section(argument), + "global" => ASTNode::Global(argument), + _ => ASTNode::Extern(argument), + }); + } + + let mut values = Vec::new(); + loop { + if *pos >= tokens.len() || matches!(tokens[*pos].kind, TokenKind::Newline) { + return Err(parser_err(tokens, *pos, "Expected directive value")); + } + match &tokens[*pos].kind { + TokenKind::StringLiteral(s) => { + values.push(DirectiveValue::StringLiteral(s.clone())); + *pos += 1; + }, + _ => { + let expr = parse_expr(tokens, pos, |k| { + matches!(k, TokenKind::Comma | TokenKind::Newline) + })?; + values.push(DirectiveValue::Expr(expr)); + }, + } + if !matches!(tokens.get(*pos).map(|t| &t.kind), Some(TokenKind::Comma)) { + break; + } + let comma = *pos; + *pos += 1; + if *pos >= tokens.len() || matches!(tokens[*pos].kind, TokenKind::Newline) { + return Err(parser_err(tokens, comma, "Expected directive value after comma")); + } + } + finish_statement(tokens, pos)?; + Ok(ASTNode::Directive(Directive { name, values })) +} + +fn parse_expr(tokens: &[Token], pos: &mut usize, stop: F) -> Result +where + F: Fn(&TokenKind) -> bool, +{ + let mut acc: Option = None; + let mut expect_term = true; + let mut sign: i128 = 1; + + while *pos < tokens.len() { + let kind = &tokens[*pos].kind; + if stop(kind) { + break; + } + + if expect_term { + match kind { + TokenKind::Plus => { + *pos += 1; + }, + TokenKind::Minus => { + sign = -sign; + *pos += 1; + }, + TokenKind::Number(n) => { + let term = ExprValue::Number(sign.checked_mul(*n).ok_or_else(|| { + parser_err(tokens, *pos, "Expression arithmetic overflow") + })?); + acc = Some(combine_expr(tokens, *pos, acc, term)?); + *pos += 1; + sign = 1; + expect_term = false; + }, + TokenKind::Identifier(s) => { + if sign < 0 { + return Err(parser_err( + tokens, + *pos, + "Unary '-' before symbol is not supported", + )); + } + let term = ExprValue::Symbol { name: s.clone(), addend: 0 }; + acc = Some(combine_expr(tokens, *pos, acc, term)?); + *pos += 1; + sign = 1; + expect_term = false; + }, + _ => return Err(parser_err(tokens, *pos, "Expected expression term")), + } + } else { + match kind { + TokenKind::Plus => { + sign = 1; + expect_term = true; + *pos += 1; + }, + TokenKind::Minus => { + sign = -1; + expect_term = true; + *pos += 1; + }, + _ => return Err(parser_err(tokens, *pos, "Expected '+' or '-' in expression")), + } + } + } + + if expect_term && acc.is_some() { + return Err(parser_err(tokens, *pos, "Expression cannot end with operator")); + } + + let expression = acc.ok_or_else(|| parser_err(tokens, *pos, "Expected expression"))?; + // Literals are bounded when lexed; intermediate arithmetic uses i128 so + // subtraction/cancellation can produce any supported final 64-bit value. + // A symbol's addend is checked only after equ resolution or relocation use. + if let ExprValue::Number(number) = &expression { + if !(i64::MIN as i128..=u64::MAX as i128).contains(number) { + return Err(parser_err(tokens, pos.saturating_sub(1), "64-bit expression overflow")); + } + } + Ok(expression) +} + +fn combine_expr( + tokens: &[Token], + pos: usize, + left: Option, + right: ExprValue, +) -> Result { + match (left, right) { + (None, r) => Ok(r), + (Some(ExprValue::Number(a)), ExprValue::Number(b)) => { + let n = a + .checked_add(b) + .ok_or_else(|| parser_err(tokens, pos, "Expression arithmetic overflow"))?; + Ok(ExprValue::Number(n)) + }, + (Some(ExprValue::Number(a)), ExprValue::Symbol { name, addend }) => Ok(ExprValue::Symbol { + name, + addend: addend + .checked_add(a) + .ok_or_else(|| parser_err(tokens, pos, "Symbol addend overflow"))?, + }), + (Some(ExprValue::Symbol { name, addend }), ExprValue::Number(b)) => Ok(ExprValue::Symbol { + name, + addend: addend + .checked_add(b) + .ok_or_else(|| parser_err(tokens, pos, "Symbol addend overflow"))?, + }), + (Some(ExprValue::Symbol { .. }), ExprValue::Symbol { .. }) => { + Err(parser_err(tokens, pos, "Expressions with multiple symbols are not supported")) + }, + } +} + +fn memory_width(name: &str) -> Option { + match name.to_ascii_lowercase().as_str() { + "byte" => Some(8), + "word" => Some(16), + "dword" => Some(32), + "qword" => Some(64), + _ => None, + } +} + +fn is_register(name: &str) -> bool { + matches!( + name, + "rax" + | "rbx" + | "rcx" + | "rdx" + | "rsi" + | "rdi" + | "rbp" + | "rsp" + | "r8" + | "r9" + | "r10" + | "r11" + | "r12" + | "r13" + | "r14" + | "r15" + | "eax" + | "ebx" + | "ecx" + | "edx" + | "esi" + | "edi" + | "ebp" + | "esp" + | "r8d" + | "r9d" + | "r10d" + | "r11d" + | "r12d" + | "r13d" + | "r14d" + | "r15d" + | "ax" + | "bx" + | "cx" + | "dx" + | "si" + | "di" + | "bp" + | "sp" + | "r8w" + | "r9w" + | "r10w" + | "r11w" + | "r12w" + | "r13w" + | "r14w" + | "r15w" + | "spl" + | "bpl" + | "sil" + | "dil" + | "al" + | "bl" + | "cl" + | "dl" + | "ah" + | "bh" + | "ch" + | "dh" + | "r8b" + | "r9b" + | "r10b" + | "r11b" + | "r12b" + | "r13b" + | "r14b" + | "r15b" + ) || crate::tables::xmm_register_code_reference(name).is_some() +} + +fn is_directive(name: &str) -> bool { + matches!( + name.to_ascii_lowercase().as_str(), + "align" + | "db" + | "dw" + | "dd" + | "dq" + | "resb" + | "resw" + | "resd" + | "resq" + | "section" + | "global" + | "extern" + | "symbol" + ) +} diff --git a/assembler/amd64/src/parser_wave.rs b/assembler/amd64/src/parser_wave.rs new file mode 100644 index 0000000..299c560 --- /dev/null +++ b/assembler/amd64/src/parser_wave.rs @@ -0,0 +1,745 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Borrowed token packets and typed AST materialization for the native grammar. +use crate::ast_model::{DirectiveRecord, Expr, Item, Name, OperandRecord, MISSING}; + +use assembler::ast::*; + +use assembler::error::SourceSpan; + +use assembler::tokens::{Token, TokenKind}; + +use assembler::{AsmError, SymbolKind, SymbolVisibility}; + +use std::{cell::Cell, collections::HashMap}; + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct RawToken { + kind: u64, + position: u64, + end: u64, + text: Name, + low: u64, + high: u64, +} + +#[repr(C)] +struct Input { + tokens: *const RawToken, + count: u64, + mode: u64, + max_work: u64, +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct Span { + start: u64, + end: u64, +} + +#[repr(C)] +struct Output { + items: *mut Item, + item_capacity: u64, + spans: *mut Span, + span_capacity: u64, + operands: *mut OperandRecord, + operand_capacity: u64, + values: *mut DirectiveRecord, + value_capacity: u64, + names: *mut Name, + name_capacity: u64, + bytes: *mut u8, + byte_capacity: u64, +} + +impl Default for Output { + fn default() -> Self { + Self { + items: std::ptr::null_mut(), + item_capacity: 0, + spans: std::ptr::null_mut(), + span_capacity: 0, + operands: std::ptr::null_mut(), + operand_capacity: 0, + values: std::ptr::null_mut(), + value_capacity: 0, + names: std::ptr::null_mut(), + name_capacity: 0, + bytes: std::ptr::null_mut(), + byte_capacity: 0, + } + } +} + +#[repr(C)] +#[derive(Default)] +struct ResultRecord { + status: u64, + error: u64, + index: u64, + detail: u64, + items: u64, + operands: u64, + values: u64, + names: u64, + bytes: u64, + work: u64, +} + +unsafe extern "C" { + fn whale_amd64_parse( + input: *const Input, + output: *mut Output, + result: *mut ResultRecord, + ) -> i32; +} + +fn backend() -> AsmError { + AsmError::Backend("AMD64 parser transport") +} + +fn initialized(count: u64) -> Result, AsmError> { + let count = usize::try_from(count).map_err(|_| backend())?; + let mut values = Vec::new(); + values.try_reserve_exact(count).map_err(|_| backend())?; + values.resize(count, T::default()); + Ok(values) +} + +fn source_span(tokens: &[Token], position: u64) -> Result { + let position = usize::try_from(position).map_err(|_| backend())?; + if let Some(token) = tokens.get(position) { + return Ok(token.span()); + } + if position != tokens.len() { + return Err(backend()); + } + Ok(match tokens.last() { + Some(token) => SourceSpan { + start: token.end_position, + end: token.end_position, + line: token.end_line, + column: token.end_column, + }, + None => SourceSpan { start: 0, end: 0, line: 1, column: 1 }, + }) +} + +fn grammar_error(tokens: &[Token], result: &ResultRecord) -> Result { + let message = match result.error { + 2 => "Unexpected token at top level", + 3 => "Expected constant name", + 4 => "Expected 'equ'", + 5 => match result.detail { + 0 => "cwd expects 0 operands", + 1 => "cdq expects 0 operands", + 2 => "cqo expects 0 operands", + _ => return Err(backend()), + }, + 6 => "Expected mnemonic", + 7 => "Expected end of statement", + 8 => "Expected operand after comma", + 9 => "Width qualifier requires memory operand", + 10 => "Missing closing ']' in memory operand", + 11 => "Negative register or symbol terms are not supported in memory operands", + 12 => "Scale must be 1/2/4/8", + 13 => "Too many registers in memory operand", + 14 => "Multiple symbols in memory operand", + 15 => "Memory displacement overflow", + 16 => "Expected term in memory operand", + 17 => "rel/abs address requires a symbol or numeric displacement without registers", + 18 => "Expected '+', '-' or ']' in memory operand", + 19 => "Expected directive name", + 20 => "Expected symbol name", + 21 => "Expected comma in symbol declaration", + 22 => "Expected symbol kind function, object or notype", + 23 => "Expected symbol visibility default or hidden", + 24 => "Expected directive name argument", + 25 => "Expected section kind text/data/rodata/bss", + 26 => "Expected directive value", + 27 => "Expected directive value after comma", + 28 => "Expression arithmetic overflow", + 29 => "Unary '-' before symbol is not supported", + 30 => "Expected expression term", + 31 => "Expected '+' or '-' in expression", + 32 => "Expression cannot end with operator", + 33 => "Expected expression", + 34 => "64-bit expression overflow", + 35 => "Symbol addend overflow", + 36 => "Expressions with multiple symbols are not supported", + _ => return Err(backend()), + }; + Ok(AsmError::ParserError(message.into()).at( + "", + source_span(tokens, result.index)?, + None, + )) +} + +struct Materializer<'a> { + names: &'a [Name], + bytes: &'a [u8], + identifiers: HashMap<(usize, u64), &'a [u8]>, + strings: HashMap<(usize, u64), &'a [u8]>, + remaining_bytes: Cell, +} + +impl<'a> Materializer<'a> { + fn new(tokens: &'a [Token], names: &'a [Name], bytes: &'a [u8]) -> Result { + let mut identifiers = HashMap::new(); + let mut strings = HashMap::new(); + identifiers.try_reserve(tokens.len()).map_err(|_| backend())?; + strings.try_reserve(tokens.len()).map_err(|_| backend())?; + for token in tokens { + match &token.kind { + TokenKind::Identifier(text) => { + identifiers + .insert((text.as_ptr() as usize, text.len() as u64), text.as_bytes()); + }, + TokenKind::StringLiteral(bytes) => { + strings.insert((bytes.as_ptr() as usize, bytes.len() as u64), bytes.as_slice()); + }, + _ => {}, + } + } + let payload = tokens.iter().try_fold(0u64, |total, token| { + let length = match &token.kind { + TokenKind::Identifier(text) => text.len(), + TokenKind::StringLiteral(bytes) => bytes.len(), + _ => 0, + }; + total.checked_add(length as u64).ok_or_else(backend) + })?; + Ok(Self { names, bytes, identifiers, strings, remaining_bytes: Cell::new(payload) }) + } + + fn take_bytes(&self, count: u64) -> Result<(), AsmError> { + self.remaining_bytes + .set(self.remaining_bytes.get().checked_sub(count).ok_or_else(backend)?); + Ok(()) + } + + fn name(&self, id: u64) -> Result { + let name = + self.names.get(usize::try_from(id).map_err(|_| backend())?).ok_or_else(backend)?; + let address = name.bytes as usize; + let count = usize::try_from(name.count).map_err(|_| backend())?; + let start = self.bytes.as_ptr() as usize; + let arena = address + .checked_sub(start) + .and_then(|offset| offset.checked_add(count).map(|end| (offset, end))) + .and_then(|(offset, end)| self.bytes.get(offset..end)); + let bytes = if count == 0 { + &[] + } else { + arena + .or_else(|| self.identifiers.get(&(address, name.count)).copied()) + .ok_or_else(backend)? + }; + let text = std::str::from_utf8(bytes).map_err(|_| backend())?; + self.take_bytes(name.count)?; + let mut owned = String::new(); + owned.try_reserve_exact(text.len()).map_err(|_| backend())?; + owned.push_str(text); + Ok(owned) + } + + fn optional_name(&self, id: u64) -> Result, AsmError> { + if id == MISSING { + Ok(None) + } else { + self.name(id).map(Some) + } + } + + fn expression(&self, raw: Expr) -> Result { + let value = bits(raw.low, raw.high); + match raw.kind { + 0 if raw.name == MISSING => Ok(ExprValue::Number(value)), + 1 => Ok(ExprValue::Symbol { name: self.name(raw.name)?, addend: value }), + _ => Err(backend()), + } + } + + fn operand(&self, raw: OperandRecord) -> Result { + Ok(match raw.kind { + 0 => Operand::Register(self.name(raw.name)?), + 1 => Operand::Immediate(bits(raw.low, raw.high)), + 2 => Operand::Label(self.name(raw.name)?), + 3 => { + Operand::SymbolExpr { name: self.name(raw.name)?, addend: bits(raw.low, raw.high) } + }, + 4 => Operand::Memory(MemoryOperand { + address_mode: match raw.mode { + 0 => MemoryAddressMode::Default, + 1 => MemoryAddressMode::Relative, + 2 => MemoryAddressMode::Absolute, + _ => return Err(backend()), + }, + width: if raw.width == MISSING { + None + } else { + Some(u8::try_from(raw.width).map_err(|_| backend())?) + }, + base: self.optional_name(raw.base)?, + index: self.optional_name(raw.index)?, + scale: u8::try_from(raw.scale).map_err(|_| backend())?, + disp: raw.disp as i64, + symbol: self.optional_name(raw.symbol)?, + }), + _ => return Err(backend()), + }) + } + + fn directive_value(&self, raw: DirectiveRecord) -> Result { + match raw.kind { + 0 => self.expression(raw.expression).map(DirectiveValue::Expr), + 1 => { + let bytes = self + .strings + .get(&(raw.bytes as usize, raw.count)) + .copied() + .ok_or_else(backend)?; + self.take_bytes(raw.count)?; + let mut owned = Vec::new(); + owned.try_reserve_exact(bytes.len()).map_err(|_| backend())?; + owned.extend_from_slice(bytes); + Ok(DirectiveValue::StringLiteral(owned)) + }, + _ => Err(backend()), + } + } +} + +fn bits(low: u64, high: u64) -> i128 { + (u128::from(low) | (u128::from(high) << 64)) as i128 +} + +fn range(values: &[T], first: u64, count: u64) -> Result<&[T], AsmError> { + let first = usize::try_from(first).map_err(|_| backend())?; + let end = + first.checked_add(usize::try_from(count).map_err(|_| backend())?).ok_or_else(backend)?; + values.get(first..end).ok_or_else(backend) +} + +pub(super) fn parse(tokens: &[Token]) -> Result { + let mut raw = Vec::new(); + raw.try_reserve_exact(tokens.len()).map_err(|_| backend())?; + let mut payload_bytes = 0u64; + for token in tokens { + let mut native = RawToken { + position: token.position as u64, + end: token.end_position as u64, + ..RawToken::default() + }; + native.kind = match &token.kind { + TokenKind::Identifier(text) => { + native.text = Name { bytes: text.as_ptr(), count: text.len() as u64 }; + 0 + }, + TokenKind::Number(value) => { + native.low = *value as u128 as u64; + native.high = ((*value as u128) >> 64) as u64; + 1 + }, + TokenKind::StringLiteral(bytes) => { + native.text = Name { bytes: bytes.as_ptr(), count: bytes.len() as u64 }; + 2 + }, + TokenKind::Comma => 3, + TokenKind::Colon => 4, + TokenKind::LBracket => 5, + TokenKind::RBracket => 6, + TokenKind::Plus => 7, + TokenKind::Minus => 8, + TokenKind::Multiply => 9, + TokenKind::Divide => 10, + TokenKind::Newline => 11, + }; + payload_bytes = payload_bytes.checked_add(native.text.count).ok_or_else(backend)?; + raw.push(native); + } + let max_work = (tokens.len() as u64) + .checked_add(payload_bytes) + .and_then(|n| n.checked_add(1)) + .and_then(|n| n.checked_mul(16)) + .ok_or_else(backend)?; + let mut input = Input { tokens: raw.as_ptr(), count: raw.len() as u64, mode: 0, max_work }; + let mut probe = ResultRecord::default(); + let status = unsafe { whale_amd64_parse(&input, &mut Output::default(), &mut probe) }; + if status != probe.status as i32 || probe.work > max_work { + return Err(backend()); + } + match status { + 0 => {}, + 1 => return Err(grammar_error(tokens, &probe)?), + _ => return Err(backend()), + } + if [probe.items, probe.operands, probe.values, probe.names] + .iter() + .any(|count| *count > raw.len() as u64) + || probe.bytes > payload_bytes + { + return Err(backend()); + } + let mut items = initialized::(probe.items)?; + let mut spans = initialized::(probe.items)?; + let mut operands = initialized::(probe.operands)?; + let mut values = initialized::(probe.values)?; + let mut names = initialized::(probe.names)?; + let mut bytes = initialized::(probe.bytes)?; + let mut output = Output { + items: items.as_mut_ptr(), + item_capacity: items.len() as u64, + spans: spans.as_mut_ptr(), + span_capacity: spans.len() as u64, + operands: operands.as_mut_ptr(), + operand_capacity: operands.len() as u64, + values: values.as_mut_ptr(), + value_capacity: values.len() as u64, + names: names.as_mut_ptr(), + name_capacity: names.len() as u64, + bytes: bytes.as_mut_ptr(), + byte_capacity: bytes.len() as u64, + }; + input.mode = 1; + let mut result = ResultRecord::default(); + let status = unsafe { whale_amd64_parse(&input, &mut output, &mut result) }; + if status != 0 + || result.status != 0 + || result.items != probe.items + || result.operands != probe.operands + || result.values != probe.values + || result.names != probe.names + || result.bytes != probe.bytes + || result.work != probe.work + { + return Err(backend()); + } + let materializer = Materializer::new(tokens, &names, &bytes)?; + let mut ast_items = Vec::new(); + let mut ast_spans = Vec::new(); + ast_items.try_reserve_exact(items.len()).map_err(|_| backend())?; + ast_spans.try_reserve_exact(items.len()).map_err(|_| backend())?; + for (item, span) in items.into_iter().zip(spans) { + let node = match item.kind { + 0 => { + let records = range(&operands, item.first, item.count)?; + let mut operands = Vec::new(); + operands.try_reserve_exact(records.len()).map_err(|_| backend())?; + for record in records { + operands.push(materializer.operand(*record)?); + } + ASTNode::Instruction(Instruction { + mnemonic: materializer.name(item.name)?, + operands, + }) + }, + 1 => ASTNode::SymbolMetadata { + name: materializer.name(item.name)?, + kind: match item.aux { + 0 => SymbolKind::NoType, + 1 => SymbolKind::Function, + 2 => SymbolKind::Object, + _ => return Err(backend()), + }, + size: materializer.expression(item.expression)?, + visibility: match item.flags { + 0 => SymbolVisibility::Default, + 1 => SymbolVisibility::Hidden, + _ => return Err(backend()), + }, + }, + 2 => { + let records = range(&values, item.first, item.count)?; + let mut values = Vec::new(); + values.try_reserve_exact(records.len()).map_err(|_| backend())?; + for record in records { + values.push(materializer.directive_value(*record)?); + } + ASTNode::Directive(Directive { name: materializer.name(item.name)?, values }) + }, + 3 => ASTNode::Label(materializer.name(item.name)?), + 4 => ASTNode::Section(materializer.name(item.name)?), + 5 => ASTNode::SectionAttributes { + name: materializer.name(item.name)?, + kind: match item.aux { + 0 => AsmSectionKind::Text, + 1 => AsmSectionKind::Data, + 2 => AsmSectionKind::ReadOnlyData, + 3 => AsmSectionKind::Bss, + _ => return Err(backend()), + }, + }, + 6 => ASTNode::Global(materializer.name(item.name)?), + 7 => ASTNode::Extern(materializer.name(item.name)?), + 8 => ASTNode::Const { + name: materializer.name(item.name)?, + expr: materializer.expression(item.expression)?, + }, + _ => return Err(backend()), + }; + if span.end <= span.start { + return Err(backend()); + } + let first = + tokens.get(usize::try_from(span.start).map_err(|_| backend())?).ok_or_else(backend)?; + let last = tokens + .get(usize::try_from(span.end - 1).map_err(|_| backend())?) + .ok_or_else(backend)?; + let mut source = first.span(); + source.end = last.end_position; + ast_items.push(node); + ast_spans.push(source); + } + Ok(AST { items: ast_items, spans: ast_spans, source_name: "".into() }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn compare(tokens: &[Token]) { + let actual = parse(tokens); + let expected = crate::parser::reference::parse(tokens); + match (actual, expected) { + (Ok(actual), Ok(expected)) => { + assert_eq!(format!("{actual:?}"), format!("{expected:?}"), "tokens {tokens:?}") + }, + (Err(actual), Err(expected)) => { + assert_eq!(actual.to_string(), expected.to_string(), "tokens {tokens:?}") + }, + (actual, expected) => { + panic!("parser divergence for {tokens:?}: {actual:?} / {expected:?}") + }, + } + } + + fn source(text: &str) { + compare(&assembler::tokens::tokenize(text).unwrap()); + } + + #[test] + fn native_parser_preserves_every_supported_statement_and_source_range() { + source("\nSECTION .text, TEXT\r\nGLOBAL Entry\nextern external\nEntry: .L: MOV RAX, qword [rel external + 4]\nVALUE EQU - 1 + 5\ndb \"a\\0\\xFF\", VALUE+2\nsymbol Entry, function, 1 + 2, hidden\nsection .buffer, bss\nresq 8\n"); + for register in crate::tables::REGISTERS_64 + .iter() + .chain(crate::tables::REGISTERS_32) + .chain(crate::tables::REGISTERS_16) + .chain(crate::tables::REGISTERS_8) + .chain(crate::tables::REGISTERS_XMM) + { + source(&format!( + "unknown {}, {}\nmov rax, [{} + 4]\n", + register.0.to_ascii_uppercase(), + register.0, + register.0 + )); + } + for memory in [ + "[rel]", + "[abs+4]", + "[rel +4]", + "[abs -4]", + "[REL external+8]", + "[rax+r9*8+external-7]", + "[r9*2+rbx]", + "[external+rax]", + "[rax]", + "[-9223372036854775808]", + "[2147483648]", + "[eax+ecx*4]", + ] { + source(&format!("mov rax, qword {memory}\n")); + } + for directive in [ + "align 16", + "db 1,2,\"xy\"", + "dw -1", + "dd external+4", + "dq 18446744073709551615", + "resb 4", + "resw 4", + "resd 4", + "resq 4", + "section custom", + "section custom, rodata", + "global exported", + "extern imported", + "symbol exported, notype, 0, default", + "symbol exported, object, external+4, hidden", + ] { + source(directive); + } + source( + "mov eax, rax+0\nmov rax, - - external + 1\nname equ 18446744073709551615 + 2 - 3\n", + ); + source("cwd\nCDQ\ncqo\nret"); + source("라벨: db \"안녕\", 기호+4\n"); + } + + #[test] + fn native_parser_matches_reference_errors_and_exact_eof_locations() { + for text in [ + "1", + "]", + "mov ,", + "mov rax,", + "mov rax,\n", + "cwd rax", + "CDQ ,", + "cqo 1", + "mov byte rax", + "mov []", + "mov [rax", + "mov [-rax]", + "mov [rax*3]", + "mov [rax+rbx+rcx]", + "mov [foo+bar]", + "mov [9223372036854775808]", + "mov [rax 1]", + "mov [rel rax]", + "mov [rax,rbx]", + "mov 1 2", + "mov foo+bar", + "mov -foo", + "mov +", + "mov 1+", + "mov 18446744073709551615+1", + "section", + "global 1", + "section .x, nope", + "section .x extra", + "symbol", + "symbol foo function", + "symbol foo, nope, 0, hidden", + "symbol foo, object, 1", + "symbol foo, object, 1, nope", + "symbol foo, object, , hidden", + "db", + "db 1,", + "db 1,\r\n", + "name equ", + "name equ 1+", + "mov [rax+--4]", + ] { + source(text); + } + compare(&[]); + } + + fn manual(kinds: Vec) { + let tokens: Vec<_> = kinds + .into_iter() + .enumerate() + .map(|(index, kind)| Token { + kind, + position: 100 + index * 7, + end_position: 104 + index * 7, + line: 9, + column: 2 + index, + end_line: 9, + end_column: 3 + index, + }) + .collect(); + compare(&tokens); + } + + #[test] + fn manual_token_full_signed128_values_keep_checked_arithmetic_and_spans() { + for value in + [i128::MIN, i128::MIN + 1, i64::MIN as i128, -1, 0, 1, u64::MAX as i128, i128::MAX] + { + for sign in [TokenKind::Plus, TokenKind::Minus] { + manual(vec![TokenKind::Identifier("mov".into()), sign, TokenKind::Number(value)]); + } + for right in [i128::MIN, -1, 1, i128::MAX] { + manual(vec![ + TokenKind::Identifier("x".into()), + TokenKind::Identifier("EQU".into()), + TokenKind::Number(value), + TokenKind::Plus, + TokenKind::Number(right), + ]); + manual(vec![ + TokenKind::Identifier("mov".into()), + TokenKind::Identifier("symbol".into()), + TokenKind::Plus, + TokenKind::Number(value), + TokenKind::Plus, + TokenKind::Number(right), + ]); + } + } + manual(vec![TokenKind::Identifier("mov".into()), TokenKind::Divide]); + manual(vec![TokenKind::Identifier(String::new()), TokenKind::Identifier("RAX".into())]); + } + + #[test] + fn deterministic_token_mutations_match_independent_parser() { + let atoms = [ + "mov", + "RAX", + "word", + "rax", + "rel", + "abs", + "xmm15", + "name", + "equ", + "section", + "symbol", + "db", + "1", + "18446744073709551615", + "+", + "-", + "*", + "[", + "]", + ",", + ":", + "\n", + "\"hi\"", + ]; + let mut random = 0x0357_1280_0001_u64; + for _ in 0..20_000 { + random ^= random << 13; + random ^= random >> 7; + random ^= random << 17; + let length = (random % 24) as usize; + let mut text = String::new(); + for _ in 0..length { + random ^= random << 13; + random ^= random >> 7; + random ^= random << 17; + text.push_str(atoms[random as usize % atoms.len()]); + text.push(' '); + } + source(&text); + } + } + + #[test] + fn malformed_native_spans_and_exhausted_work_are_distinct_from_syntax() { + let mut input = Input { tokens: std::ptr::null(), count: u64::MAX, mode: 0, max_work: 1 }; + let mut output = Output::default(); + let mut result = ResultRecord::default(); + assert_eq!(unsafe { whale_amd64_parse(&input, &mut output, &mut result) }, 2); + assert_eq!(result.status, 2); + let name = b"nop"; + let token = + RawToken { text: Name { bytes: name.as_ptr(), count: 3 }, ..RawToken::default() }; + input.tokens = &token; + input.count = 1; + input.max_work = 0; + assert_eq!(unsafe { whale_amd64_parse(&input, &mut output, &mut result) }, 3); + assert_eq!(result.work, 0); + assert_eq!(result.error, 0); + input.max_work = 100; + input.mode = 1; + assert_eq!(unsafe { whale_amd64_parse(&input, &mut output, &mut result) }, 2); + } +} diff --git a/assembler/amd64/src/tables.rs b/assembler/amd64/src/tables.rs index ec7ccc5..b9b5e5a 100644 --- a/assembler/amd64/src/tables.rs +++ b/assembler/amd64/src/tables.rs @@ -128,7 +128,8 @@ pub const CONDITION_CODES: &[(&str, u8)] = &[ ("jnle", 15), ]; -pub fn condition_code(mnemonic: &str) -> Option { +#[cfg(any(not(whale_wave_amd64), test))] +pub(crate) fn condition_code_reference(mnemonic: &str) -> Option { CONDITION_CODES.iter().find(|(name, _)| *name == mnemonic).map(|(_, code)| *code) } @@ -152,6 +153,123 @@ pub const REGISTERS_XMM: &[(&str, u8)] = &[ ("xmm15", 15), ]; -pub fn xmm_register_code(name: &str) -> Option { +#[cfg(any(not(whale_wave_amd64), test))] +pub(crate) fn xmm_register_code_reference(name: &str) -> Option { REGISTERS_XMM.iter().find(|(register, _)| *register == name).map(|(_, code)| *code) } + +/// AMD64 condition code, preserving the exact case-sensitive public contract. +pub fn condition_code(mnemonic: &str) -> Option { + #[cfg(whale_wave_amd64)] + { + native::condition(mnemonic) + } + #[cfg(not(whale_wave_amd64))] + { + condition_code_reference(mnemonic) + } +} + +/// Legacy scalar SSE register code. +pub fn xmm_register_code(name: &str) -> Option { + #[cfg(whale_wave_amd64)] + { + native::xmm(name) + } + #[cfg(not(whale_wave_amd64))] + { + xmm_register_code_reference(name) + } +} + +#[cfg(whale_wave_amd64)] +mod native { + use crate::ast_model::Name; + + #[repr(C)] + #[derive(Default)] + struct Register { + kind: u64, + code: u64, + width: u64, + high8: u64, + rex8: u64, + } + + unsafe extern "C" { + fn whale_amd64_register(name: *const Name, fold: u64, output: *mut Register) -> i32; + + fn whale_amd64_condition(name: *const Name, output: *mut u64) -> i32; + } + + pub(super) fn xmm(text: &str) -> Option { + let name = Name { bytes: text.as_ptr(), count: text.len() as u64 }; + let mut output = Register::default(); + match unsafe { whale_amd64_register(&name, 0, &mut output) } { + 0 if output.kind == 1 + && output.code < 16 + && output.width == 128 + && output.high8 == 0 + && output.rex8 == 0 => + { + Some(output.code as u8) + }, + 0 if output.kind == 0 + && output.code < 16 + && matches!(output.width, 8 | 16 | 32 | 64) + && output.high8 <= 1 + && output.rex8 <= 1 + && (output.high8 == 0 + || (output.width == 8 + && (4..8).contains(&output.code) + && output.rex8 == 0)) + && (output.rex8 == 0 + || (output.width == 8 + && (4..8).contains(&output.code) + && output.high8 == 0)) => + { + None + }, + 1 => None, + _ => panic!("AMD64 register classification transport"), + } + } + + pub(super) fn condition(text: &str) -> Option { + let name = Name { bytes: text.as_ptr(), count: text.len() as u64 }; + let mut output = 0; + match unsafe { whale_amd64_condition(&name, &mut output) } { + 0 if output < 16 => Some(output as u8), + 1 => None, + _ => panic!("AMD64 condition classification transport"), + } + } +} + +#[cfg(all(test, whale_wave_amd64))] +mod native_tests { + use super::*; + + #[test] + fn public_native_classifiers_match_independent_reference_tables() { + for (name, _) in REGISTERS_64 + .iter() + .chain(REGISTERS_32) + .chain(REGISTERS_16) + .chain(REGISTERS_8) + .chain(REGISTERS_XMM) + { + assert_eq!(xmm_register_code(name), xmm_register_code_reference(name)); + assert_eq!(xmm_register_code(&name.to_ascii_uppercase()), None); + } + for (name, expected) in CONDITION_CODES { + assert_eq!(condition_code(name), Some(*expected)); + assert_eq!(condition_code(name), condition_code_reference(name)); + assert_eq!(condition_code(&name.to_ascii_uppercase()), None); + } + for name in ["", "xmm16", "xmm01", "r16", "j", "jn", "cmove", "seto", "라벨"] { + assert_eq!(condition_code(name), condition_code_reference(name)); + assert_eq!(xmm_register_code(name), xmm_register_code_reference(name)); + } + } +} diff --git a/assembler/amd64/sse.wave b/assembler/amd64/sse.wave new file mode 100644 index 0000000..dd699f1 --- /dev/null +++ b/assembler/amd64/sse.wave @@ -0,0 +1,45 @@ +// SPDX-License-Identifier: MPL-2.0 +// Legacy scalar SSE; no packed or AVX encoding is implied. +fun amd_scalar_sse(w: ptr, operation: u64, a: ptr, + b: ptr) -> bool { + var width: u64 = 32; + var prefix: u64 = 243; + if ((operation & 1) != 0) { + width = 64; + prefix = 242; + } + var opcode: u64 = 16; + if (operation >= 36 && operation <= 37) { + opcode = 88; + } else if (operation >= 38 && operation <= 39) { + opcode = 92; + } else if (operation >= 40 && operation <= 41) { + opcode = 89; + } else if (operation >= 42) { + opcode = 94; + } + if (a.kind == 4) { + if (operation > 35) { + return amd_fail(w.result, 37); + } + if (b.kind != 0 || b.width != 128) { + return amd_fail(w.result, 38); + } + return amd_mem_width(w, a, width) && amd_emit(w, prefix, 1) + && amd_memory(w, 17, 1, b, a, 0, 0); + } + if (a.kind != 0 || a.width != 128) { + return amd_fail(w.result, 38); + } + if (b.kind == 0 && b.width == 128) { + return amd_emit(w, prefix, 1) + && amd_rex(w, 0, (a.code >= 8) as u64, 0, (b.code >= 8) as u64, 0) + && amd_emit(w, 15, 1) && amd_emit(w, opcode, 1) + && amd_modrm(w, 3, a.code, b.code); + } + if (b.kind == 4) { + return amd_mem_width(w, b, width) && amd_emit(w, prefix, 1) + && amd_memory(w, opcode, 1, a, b, 0, 0); + } + return amd_fail(w.result, 39); +} diff --git a/assembler/ast_model.wave b/assembler/ast_model.wave new file mode 100644 index 0000000..5799e62 --- /dev/null +++ b/assembler/ast_model.wave @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: MPL-2.0 +// Borrowed structural AST records shared by AMD64 parsing and encoding. +struct AsmName { + bytes: ptr; + count: u64; +} + +struct AsmExpr { + kind: u64; + name: u64; + low: u64; + high: u64; +} + +struct AsmOperand { + kind: u64; + name: u64; + low: u64; + high: u64; + mode: u64; + width: u64; + base: u64; + index: u64; + scale: u64; + disp: u64; + symbol: u64; +} + +struct AsmItem { + kind: u64; + name: u64; + aux: u64; + flags: u64; + expression: AsmExpr; + first: u64; + count: u64; +} + +struct AsmDirectiveValue { + kind: u64; + expression: AsmExpr; + bytes: ptr; + count: u64; +} diff --git a/assembler/build.rs b/assembler/build.rs new file mode 100644 index 0000000..af6eb65 --- /dev/null +++ b/assembler/build.rs @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: MPL-2.0 +const CFG: &str = "whale_wave_assembler"; + +const ENV: &str = "WHALE_WAVE_ASSEMBLER_DIR"; + +const LIBRARY: &str = "whale_wave_assembler"; + +const METADATA: &str = "wave-assembler.meta"; + +const ROOT_UP: usize = 1; + +const SOURCES: &[&str] = &[ + "assembler/model.wave", + "assembler/unicode.wave", + "assembler/numeric.wave", + "assembler/output.wave", + "assembler/lexer.wave", +]; + +const ABI_SOURCES: &[&str] = &["assembler/src/tokens.rs", "assembler/src/tokens_wave.rs"]; +include!("build_support.rs"); diff --git a/assembler/build_support.rs b/assembler/build_support.rs new file mode 100644 index 0000000..aaad8d5 --- /dev/null +++ b/assembler/build_support.rs @@ -0,0 +1,137 @@ +// SPDX-License-Identifier: MPL-2.0 +// Internal Cargo artifact guard, shared only by the explicit assembler crates. +use std::{collections::BTreeMap, env, fs, io::Read, path::PathBuf}; + +const PIN: &str = "e0952ed65d07e14c6ed0aa64f3c9a5532dd7533b"; + +fn update(hash: u64, bytes: &[u8]) -> u64 { + bytes.iter().fold(hash, |h, byte| (h ^ u64::from(*byte)).wrapping_mul(0x100000001b3)) +} + +fn hash(bytes: &[u8]) -> String { + format!("{:016x}", update(0xcbf29ce484222325, bytes)) +} + +fn hash_file(path: &std::path::Path, maximum: Option) -> String { + let mut file = fs::File::open(path) + .unwrap_or_else(|_| panic!("missing Wave assembler artifact {}", path.display())); + let mut value = 0xcbf29ce484222325; + let mut seen = 0; + let mut buffer = [0; 16384]; + loop { + let count = file.read(&mut buffer).expect("cannot read Wave assembler artifact"); + if count == 0 { + return format!("{value:016x}"); + } + seen += count as u64; + if maximum.is_some_and(|limit| seen > limit) { + panic!("oversized Wave assembler artifact {}", path.display()); + } + value = update(value, &buffer[..count]); + } +} + +fn main() { + println!("cargo:rustc-check-cfg=cfg({CFG})"); + println!("cargo:rerun-if-env-changed={ENV}"); + let Some(directory) = env::var_os(ENV) else { return }; + if CFG == "whale_wave_amd64" { + assert!( + env::var_os("WHALE_WAVE_ASSEMBLER_DIR").is_some(), + "Wave AMD64 requires WHALE_WAVE_ASSEMBLER_DIR for shared assembler utilities" + ); + } + let directory = PathBuf::from(directory) + .canonicalize() + .expect("Wave assembler artifact directory must exist"); + let target = env::var("TARGET").expect("Cargo target required"); + let archive = directory.join(if target.contains("msvc") { + format!("{LIBRARY}.lib") + } else { + format!("lib{LIBRARY}.a") + }); + let metadata = directory.join(METADATA); + let provenance = directory.join("provenance.json"); + for path in [&archive, &metadata, &provenance] { + println!("cargo:rerun-if-changed={}", path.display()); + } + let mut text = String::new(); + fs::File::open(&metadata) + .expect("missing assembler metadata; build with tools/build_wave_assembler.py") + .take(4097) + .read_to_string(&mut text) + .expect("invalid Wave assembler metadata"); + assert!(text.len() <= 4096, "oversized Wave assembler metadata"); + let mut fields = BTreeMap::new(); + for line in text.lines() { + let (key, value) = line.split_once('=').expect("malformed Wave assembler metadata"); + assert!( + [ + "schema", + "target", + "wave_revision", + "opt_level", + "source_fnv64", + "abi_fnv64", + "archive_fnv64", + "provenance_fnv64" + ] + .contains(&key) + && fields.insert(key, value).is_none(), + "invalid Wave assembler metadata fields" + ); + } + assert_eq!(fields.len(), 8, "incomplete Wave assembler metadata"); + assert_eq!(fields.get("schema"), Some(&"1"), "unsupported Wave assembler metadata"); + assert_eq!(fields.get("target"), Some(&target.as_str()), "Wave assembler target mismatch"); + assert_eq!( + fields.get("wave_revision"), + Some(&PIN), + "Wave assembler compiler revision mismatch" + ); + assert!( + [Some(&"0"), Some(&"2")].contains(&fields.get("opt_level")), + "unsupported Wave assembler optimization level" + ); + let mut root = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap()); + for _ in 0..ROOT_UP { + assert!(root.pop(), "invalid assembler source root"); + } + let mut source = Vec::new(); + for (index, name) in SOURCES.iter().enumerate() { + let path = root.join(name); + println!("cargo:rerun-if-changed={}", path.display()); + if index != 0 { + source.push(b'\n'); + } + source.extend(fs::read(path).expect("missing Wave assembler source")); + } + assert_eq!( + fields.get("source_fnv64"), + Some(&hash(&source).as_str()), + "stale Wave assembler archive" + ); + let mut abi = Vec::new(); + for (index, name) in ABI_SOURCES.iter().enumerate() { + let path = root.join(name); + println!("cargo:rerun-if-changed={}", path.display()); + if index != 0 { + abi.push(b'\n'); + } + abi.extend(fs::read(path).expect("missing Wave assembler ABI source")); + } + assert_eq!(fields.get("abi_fnv64"), Some(&hash(&abi).as_str()), "stale Wave assembler ABI"); + assert_eq!( + fields.get("archive_fnv64"), + Some(&hash_file(&archive, None).as_str()), + "corrupt Wave assembler archive" + ); + assert_eq!( + fields.get("provenance_fnv64"), + Some(&hash_file(&provenance, Some(16 * 1024)).as_str()), + "corrupt Wave assembler provenance" + ); + println!("cargo:rustc-link-search=native={}", directory.display()); + println!("cargo:rustc-link-lib=static={LIBRARY}"); + println!("cargo:rustc-cfg={CFG}"); +} diff --git a/assembler/declarations.wave b/assembler/declarations.wave new file mode 100644 index 0000000..7eb8b0f --- /dev/null +++ b/assembler/declarations.wave @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: MPL-2.0 +// Internal link declarations for shared assembler source utilities. +extern(c) fun asm_span_valid(data: ptr, count: u64, width: u64) -> bool; +extern(c) fun asm_power_two(value: u64) -> bool; +extern(c) fun asm_align_up(size: u64, align: u64, output: ptr) -> bool; +extern(c) fun asm_number_add_checked(a: ptr, b: ptr, + output: ptr) -> bool; +extern(c) fun asm_number_neg_checked(value: ptr, output: ptr) -> bool; +extern(c) fun asm_number_sub_checked(a: ptr, b: ptr, + output: ptr) -> bool; +extern(c) fun asm_number_fits_signed(value: ptr, bits: u64) -> bool; +extern(c) fun asm_number_fits_unsigned(value: ptr, bits: u64) -> bool; +extern(c) fun asm_unicode_alphanumeric(cp: u64) -> bool; +extern(c) fun asm_output_grow(materialized: u64, section: u64, extra: u64, + limit: u64, logical: u64, output: ptr) -> i32; +extern(c) fun asm_output_align(materialized: u64, section: u64, alignment: u64, + limit: u64, logical: u64, output: ptr) -> i32; diff --git a/assembler/lexer.wave b/assembler/lexer.wave new file mode 100644 index 0000000..52eef86 --- /dev/null +++ b/assembler/lexer.wave @@ -0,0 +1,425 @@ +// SPDX-License-Identifier: MPL-2.0 +// Tokenization is native; allocation and public Rust enum construction are adapters. +fun asm_lex_error(c: ptr, status: u64, reason: u64, + start: u64, line: u64, column: u64, detail: u64) -> bool { + c.result.status = status; + c.result.reason = reason; + c.result.start = start; + c.result.end = c.at; + c.result.line = line; + c.result.column = column; + c.result.detail = detail; + c.result.work = c.work; + return false; +} + +fun asm_lex_charge(c: ptr) -> bool { + if (c.work >= c.max_work) { + return asm_lex_error(c, 4, 0, c.at, c.line, c.column, 0); + } + c.work += 1; + return true; +} + +fun asm_lex_peek(c: ptr, cp: ptr, width: ptr) -> bool { + if (c.at >= c.length) { + return false; + } + var first: u64 = c.source[c.at] as u64; + var count: u64 = 1; + var minimum: u64 = 0; + var value: u64 = first; + if (first >= 194 && first <= 223) { + count = 2; + minimum = 128; + value = first & 31; + } else if (first >= 224 && first <= 239) { + count = 3; + minimum = 2048; + value = first & 15; + } else if (first >= 240 && first <= 244) { + count = 4; + minimum = 65536; + value = first & 7; + } else if (first >= 128) { + return asm_lex_error(c, 5, 10, c.at, c.line, c.column, 0); + } + if (count > c.length - c.at) { + return asm_lex_error(c, 5, 10, c.at, c.line, c.column, 0); + } + var i: u64 = 1; + while (i < count) { + var octet: u64 = c.source[c.at + i] as u64; + if (octet < 128 || octet > 191) { + return asm_lex_error(c, 5, 10, c.at, c.line, c.column, 0); + } + value = (value << 6) | (octet & 63); + i += 1; + } + if (value < minimum || value > 1114111 || (value >= 55296 && value <= 57343)) { + return asm_lex_error(c, 5, 10, c.at, c.line, c.column, 0); + } + cp[0] = value; + width[0] = count; + return true; +} + +fun asm_lex_bump(c: ptr, cp: u64, width: u64) -> bool { + if (!asm_lex_charge(c)) { + return false; + } + c.at += width; + if (cp == 13) { + c.line += 1; + c.column = 1; + c.previous_cr = true; + } else if (cp == 10) { + if (!c.previous_cr) { + c.line += 1; + } + c.column = 1; + c.previous_cr = false; + } else { + c.column += 1; + c.previous_cr = false; + } + return true; +} + +fun asm_lex_identifier(cp: u64) -> bool { + return cp == 95 || cp == 46 || asm_unicode_alphanumeric(cp); +} + +fun asm_lex_digit(cp: u64, radix: u64) -> u64 { + if (cp >= 48 && cp <= 57 && cp - 48 < radix) { + return cp - 48; + } + if (radix == 16 && cp >= 65 && cp <= 70) { + return cp - 55; + } + if (radix == 16 && cp >= 97 && cp <= 102) { + return cp - 87; + } + return 18446744073709551615; +} + +fun asm_lex_decoded(c: ptr, octet: u8, mode: u64, + data: ptr, capacity: u64, maximum: u64) -> bool { + if (c.result.decoded >= maximum) { + return asm_lex_error(c, 3, 0, c.at, c.line, c.column, 0); + } + if (mode == 1) { + if (c.result.decoded >= capacity) { + return asm_lex_error(c, 5, 0, c.at, c.line, c.column, 0); + } + data[c.result.decoded] = octet; + } + c.result.decoded += 1; + return true; +} + +fun asm_lex_string(c: ptr, token: ptr, mode: u64, + decoded: ptr, capacity: u64, maximum: u64) -> bool { + if (!asm_lex_bump(c, 34, 1)) { + return false; + } + var cp: u64 = 0; + var width: u64 = 0; + var start: u64 = 0; + var line: u64 = 0; + var column: u64 = 0; + var octet: u64 = 0; + var i: u64 = 0; + var digit: u64 = 0; + var content: u64 = 0; + while (true) { + start = c.at; + line = c.line; + column = c.column; + if (!asm_lex_peek(c, &cp, &width)) { + if (c.result.status != 0) { + return false; + } + return asm_lex_error(c, 1, 2, token.start, token.line, token.column, 0); + } + content = c.at; + if (!asm_lex_bump(c, cp, width)) { + return false; + } + if (cp == 34) { + return true; + } + if (cp == 92) { + if (!asm_lex_peek(c, &cp, &width)) { + if (c.result.status != 0) { + return false; + } + return asm_lex_error(c, 1, 3, start, line, column, 0); + } + if (!asm_lex_bump(c, cp, width)) { + return false; + } + octet = cp; + if (cp == 110) { + octet = 10; + } else if (cp == 114) { + octet = 13; + } else if (cp == 116) { + octet = 9; + } else if (cp == 48) { + octet = 0; + } else if (cp == 120) { + octet = 0; + i = 0; + while (i < 2) { + if (!asm_lex_peek(c, &cp, &width)) { + if (c.result.status != 0) { + return false; + } + return asm_lex_error(c, 1, 4, start, line, column, 0); + } + if (!asm_lex_bump(c, cp, width)) { + return false; + } + digit = asm_lex_digit(cp, 16); + if (digit == 18446744073709551615) { + return asm_lex_error(c, 1, 5, start, line, column, 0); + } + octet = octet * 16 + digit; + i += 1; + } + } else if (cp != 34 && cp != 92) { + return asm_lex_error(c, 1, 6, start, line, column, 0); + } + if (!asm_lex_decoded(c, octet as u8, mode, decoded, capacity, maximum)) { + return false; + } + } else { + i = 0; + while (i < width) { + if (!asm_lex_decoded(c, c.source[content + i], mode, + decoded, capacity, maximum)) { + return false; + } + i += 1; + } + } + } + return true; +} + +export(c) fun whale_asm_lex(source: ptr, length: u64, max_tokens: u64, + max_decoded: u64, max_work: u64, mode: u64, + scratch_tokens: ptr, token_capacity: u64, + scratch_decoded: ptr, decoded_capacity: u64, + output_tokens: ptr, output_token_capacity: u64, + output_decoded: ptr, output_decoded_capacity: u64, + result: ptr) -> i32 { + if (result == null) { + return 5; + } + result.status = 0; + result.reason = 0; + result.start = 0; + result.end = 0; + result.line = 1; + result.column = 1; + result.detail = 0; + result.tokens = 0; + result.decoded = 0; + result.work = 0; + if (mode > 1 || !asm_span_valid(source, length, 1) + || (mode == 1 && (!asm_span_valid(scratch_tokens as ptr, token_capacity, 88) + || !asm_span_valid(output_tokens as ptr, output_token_capacity, 88) + || !asm_span_valid(scratch_decoded, decoded_capacity, 1) + || !asm_span_valid(output_decoded, output_decoded_capacity, 1)))) { + result.status = 5; + return 5; + } + if (length > 8388608) { + result.status = 6; + return 6; + } + var c: AsmLexCursor; + c.source = source; + c.length = length; + c.at = 0; + c.line = 1; + c.column = 1; + c.previous_cr = false; + c.work = 0; + c.max_work = max_work; + c.result = result; + var cp: u64 = 0; + var width: u64 = 0; + var kind: u64 = 0; + var radix: u64 = 0; + var digits: u64 = 0; + var digit: u64 = 0; + var number: u64 = 0; + var overflow: bool = false; + var token: AsmToken; + var i: u64 = 0; + while (c.at < length) { + if (!asm_lex_peek(&c, &cp, &width)) { + return result.status as i32; + } + token.start = c.at; + token.line = c.line; + token.column = c.column; + token.decoded_start = result.decoded; + token.decoded_len = 0; + token.low = 0; + token.high = 0; + if (cp == 59) { + while (c.at < length && cp != 10 && cp != 13) { + if (!asm_lex_bump(&c, cp, width)) { + return result.status as i32; + } + if (c.at < length && !asm_lex_peek(&c, &cp, &width)) { + return result.status as i32; + } + } + continue; + } + if (cp == 32 || cp == 9) { + if (!asm_lex_bump(&c, cp, width)) { + return result.status as i32; + } + continue; + } + if (cp == 34) { + kind = 2; + if (!asm_lex_string(&c, &token, mode, scratch_decoded, + decoded_capacity, max_decoded)) { + return result.status as i32; + } + token.decoded_len = result.decoded - token.decoded_start; + } else if (cp >= 48 && cp <= 57) { + kind = 1; + radix = 10; + if (cp == 48 && c.at + 1 < length) { + if (source[c.at + 1] == 120 || source[c.at + 1] == 88) { + radix = 16; + } else if (source[c.at + 1] == 98 || source[c.at + 1] == 66) { + radix = 2; + } + } + if (radix != 10) { + if (!asm_lex_bump(&c, cp, 1) + || !asm_lex_bump(&c, source[c.at] as u64, 1)) { + return result.status as i32; + } + } + digits = c.at; + number = 0; + overflow = false; + while (c.at < length) { + if (!asm_lex_peek(&c, &cp, &width)) { + return result.status as i32; + } + digit = asm_lex_digit(cp, radix); + if (digit == 18446744073709551615) { + break; + } + if (number > (18446744073709551615 - digit) / radix) { + overflow = true; + } else { + number = number * radix + digit; + } + if (!asm_lex_bump(&c, cp, width)) { + return result.status as i32; + } + } + if (digits == c.at) { + result.reason = 7; + if (radix == 2) { + result.reason = 8; + } + asm_lex_error(&c, 1, result.reason, token.start, token.line, token.column, 0); + return 1; + } + if (overflow) { + asm_lex_error(&c, 1, 9, token.start, token.line, token.column, 0); + return 1; + } + token.low = number; + } else if (asm_lex_identifier(cp)) { + kind = 0; + while (c.at < length && asm_lex_identifier(cp)) { + if (!asm_lex_bump(&c, cp, width)) { + return result.status as i32; + } + if (c.at < length && !asm_lex_peek(&c, &cp, &width)) { + return result.status as i32; + } + } + } else { + kind = 18446744073709551615; + if (cp == 44) { + kind = 3; + } else if (cp == 58) { + kind = 4; + } else if (cp == 91) { + kind = 5; + } else if (cp == 93) { + kind = 6; + } else if (cp == 43) { + kind = 7; + } else if (cp == 45) { + kind = 8; + } else if (cp == 42) { + kind = 9; + } else if (cp == 10 || cp == 13) { + kind = 11; + } + if (kind == 18446744073709551615) { + asm_lex_error(&c, 1, 1, c.at, c.line, c.column, cp); + result.end = c.at + width; + return 1; + } + if (!asm_lex_bump(&c, cp, width)) { + return result.status as i32; + } + if (cp == 13 && c.at < length && source[c.at] == 10) { + if (!asm_lex_bump(&c, 10, 1)) { + return result.status as i32; + } + } + } + token.kind = kind; + token.end = c.at; + token.end_line = c.line; + token.end_column = c.column; + if (result.tokens >= max_tokens) { + asm_lex_error(&c, 2, 0, token.start, token.line, token.column, 0); + return 2; + } + if (mode == 1) { + if (result.tokens >= token_capacity) { + asm_lex_error(&c, 5, 0, token.start, token.line, token.column, 0); + return 5; + } + scratch_tokens[result.tokens] = token; + } + result.tokens += 1; + } + result.work = c.work; + if (mode == 1) { + if (result.tokens > output_token_capacity || result.decoded > output_decoded_capacity) { + result.status = 5; + return 5; + } + i = 0; + while (i < result.tokens) { + output_tokens[i] = scratch_tokens[i]; + i += 1; + } + i = 0; + while (i < result.decoded) { + output_decoded[i] = scratch_decoded[i]; + i += 1; + } + } + return 0; +} diff --git a/assembler/meson.build b/assembler/meson.build new file mode 100644 index 0000000..d090166 --- /dev/null +++ b/assembler/meson.build @@ -0,0 +1,55 @@ +# SPDX-License-Identifier: MPL-2.0 +subdir('asmobj') +wave_assembler_all_dependencies = [] +wave_assembler_dependencies = [] +wave_assembler_directory = get_option('wave-assembler-dir') +if wave_assembler_directory == '' and wave_source != '' + wave_assembler_directory = meson.current_build_dir() + module_target = cargo_host_target + if module_target == '' + target_os = {'linux': 'unknown-linux-gnu', 'darwin': 'apple-darwin', 'windows': 'pc-windows-msvc'} + module_target = host_machine.cpu_family() + '-' + target_os[host_machine.system()] + endif + archive_name = module_target.contains('msvc') ? 'whale_wave_assembler.lib' : 'libwhale_wave_assembler.a' + arguments = ['--module', 'common', '--wave-source', wave_source, '--out-dir', '@OUTDIR@', + '--bootstrap-dir', wave_cache, '--target', module_target, + '--rust-toolchain', get_option('wave-rust-toolchain')] + if get_option('wave-allow-network') + arguments += ['--allow-network'] + endif + wave_assembler_module = custom_target('wave-assembler', + output: [archive_name, 'wave-assembler.meta', 'provenance.json'], + command: [python, files('../tools/build_wave_assembler.py'), arguments], + depend_files: files( + 'model.wave', + 'unicode.wave', + 'numeric.wave', + 'output.wave', + 'lexer.wave', + 'src/tokens.rs', + 'src/tokens_wave.rs', + '../tools/build_wave_assembler.py', + '../tools/wave_bootstrap.py', + 'build_support.rs', + ), + depends: wave_bootstrap, console: true) + wave_assembler_dependencies += [wave_assembler_module] +elif wave_assembler_directory != '' + if not fs.is_absolute(wave_assembler_directory) + error('-Dwave-assembler-dir must be absolute.') + endif + archive_name = host_machine.system() == 'windows' ? 'whale_wave_assembler.lib' : 'libwhale_wave_assembler.a' + foreach artifact : [archive_name, 'wave-assembler.meta', 'provenance.json'] + if not fs.is_file(wave_assembler_directory / artifact) + error('Missing Wave assembler artifact: ' + (wave_assembler_directory / artifact)) + endif + endforeach +endif +wave_assembler_all_dependencies += wave_assembler_dependencies +wave_amd64_directory = '' +if get_option('asm-amd64') + subdir('amd64') +endif +if wave_amd64_directory != '' and wave_assembler_directory == '' + error('The Wave AMD64 module requires -Dwave-assembler-dir or a Wave source build.') +endif diff --git a/assembler/model.wave b/assembler/model.wave new file mode 100644 index 0000000..dbe296e --- /dev/null +++ b/assembler/model.wave @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: MPL-2.0 +// Internal borrowed records shared by assembler source modules. +struct AsmWide { + low: u64; + high: u64; +} + +struct AsmToken { + kind: u64; + start: u64; + end: u64; + line: u64; + column: u64; + end_line: u64; + end_column: u64; + decoded_start: u64; + decoded_len: u64; + low: u64; + high: u64; +} + +struct AsmLexResult { + status: u64; + reason: u64; + start: u64; + end: u64; + line: u64; + column: u64; + detail: u64; + tokens: u64; + decoded: u64; + work: u64; +} + +struct AsmLexCursor { + source: ptr; + length: u64; + at: u64; + line: u64; + column: u64; + previous_cr: bool; + work: u64; + max_work: u64; + result: ptr; +} + + +struct AsmOutputGrowth { + materialized: u64; + section: u64; +} diff --git a/assembler/numeric.wave b/assembler/numeric.wave new file mode 100644 index 0000000..9cf0970 --- /dev/null +++ b/assembler/numeric.wave @@ -0,0 +1,105 @@ +// SPDX-License-Identifier: MPL-2.0 +// Exact checked signed arithmetic over two caller-owned words. +export(c) fun asm_span_valid(data: ptr, count: u64, width: u64) -> bool { + return width != 0 && count <= 9223372036854775807 / width + && (count == 0 || data != null) + && count * width <= 18446744073709551615 - (data as u64); +} + +export(c) fun asm_power_two(value: u64) -> bool { + return value != 0 && (value & (value - 1)) == 0; +} + +export(c) fun asm_align_up(size: u64, align: u64, output: ptr) -> bool { + if (!asm_power_two(align) || output == null || size > 18446744073709551615 - (align - 1)) { + return false; + } + output[0] = (size + align - 1) & ~(align - 1); + return true; +} + +export(c) fun asm_number_add_checked(a: ptr, b: ptr, + output: ptr) -> bool { + if (a == null || b == null || output == null) { + return false; + } + var low: u64 = a.low + b.low; + var carry: u64 = (low < a.low) as u64; + var high: u64 = a.high + b.high + carry; + var a_negative: bool = a.high >= 9223372036854775808; + var b_negative: bool = b.high >= 9223372036854775808; + var negative: bool = high >= 9223372036854775808; + if ((a_negative && b_negative && !negative) + || (!a_negative && !b_negative && negative)) { + return false; + } + output.low = low; + output.high = high; + return true; +} + +export(c) fun asm_number_neg_checked(value: ptr, output: ptr) -> bool { + if (value == null || output == null + || (value.low == 0 && value.high == 9223372036854775808)) { + return false; + } + var low: u64 = ~value.low + 1; + var high: u64 = ~value.high + (low == 0) as u64; + output.low = low; + output.high = high; + return true; +} + +export(c) fun asm_number_sub_checked(a: ptr, b: ptr, + output: ptr) -> bool { + if (a == null || b == null || output == null) { + return false; + } + var low: u64 = a.low - b.low; + var high: u64 = a.high - b.high - (a.low < b.low) as u64; + var a_negative: bool = a.high >= 9223372036854775808; + var b_negative: bool = b.high >= 9223372036854775808; + var negative: bool = high >= 9223372036854775808; + if ((a_negative && !b_negative && !negative) + || (!a_negative && b_negative && negative)) { + return false; + } + output.low = low; + output.high = high; + return true; +} + +export(c) fun asm_number_fits_signed(value: ptr, bits: u64) -> bool { + if (value == null || bits == 0 || bits > 128) { + return false; + } + if (bits == 128) { + return true; + } + var one: u64 = 1; + var all: u64 = 18446744073709551615; + if (bits <= 64) { + var top: u64 = one << (bits - 1); + return (value.high == 0 && value.low < top) + || (value.high == all && value.low >= all - top + 1); + } + var top: u64 = one << (bits - 65); + return value.high < top || value.high >= all - top + 1; +} + +export(c) fun asm_number_fits_unsigned(value: ptr, bits: u64) -> bool { + if (value == null || bits == 0 || bits > 128) { + return false; + } + if (bits == 128) { + return true; + } + var one: u64 = 1; + if (bits == 64) { + return value.high == 0; + } + if (bits < 64) { + return value.high == 0 && value.low < (one << bits); + } + return value.high < (one << (bits - 64)); +} diff --git a/assembler/output.wave b/assembler/output.wave new file mode 100644 index 0000000..a45f47d --- /dev/null +++ b/assembler/output.wave @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: MPL-2.0 +// Output accounting is independent of instruction syntax and relocation kinds. +// Logical growth reserves sparse storage without allocating materialized bytes. +export(c) fun asm_output_grow(materialized: u64, section: u64, extra: u64, + limit: u64, logical: u64, output: ptr) -> i32 { + if (output == null || logical > 1 || materialized > limit) { + return 3; + } + if (extra > 18446744073709551615 - section) { + return 1; + } + var total: u64 = materialized; + if (logical == 0) { + if (extra > 18446744073709551615 - total) { + return 1; + } + if (extra > limit - total) { + return 2; + } + total += extra; + } + output.materialized = total; + output.section = section + extra; + return 0; +} + +export(c) fun asm_output_align(materialized: u64, section: u64, alignment: u64, + limit: u64, logical: u64, output: ptr) -> i32 { + var padded: u64 = 0; + if (!asm_power_two(alignment)) { + return 3; + } + if (!asm_align_up(section, alignment, &padded)) { + return 1; + } + return asm_output_grow(materialized, section, padded - section, limit, logical, output); +} diff --git a/assembler/src/diagnostic.rs b/assembler/src/diagnostic.rs index 3e15909..63025ff 100644 --- a/assembler/src/diagnostic.rs +++ b/assembler/src/diagnostic.rs @@ -16,6 +16,7 @@ fn source(name: &str, span: SourceSpan) -> Context { impl ToDiagnostic for AsmError { fn diagnostic(&self) -> Diagnostic { let (phase, code) = match self { + Self::Backend(_) => ("backend", "assembler.backend"), Self::LexerError(_) => ("lex", "assembler.lex"), Self::ParserError(_) => ("parse", "assembler.parse"), Self::EncodeError(_) => ("encode", "assembler.encode"), diff --git a/assembler/src/error.rs b/assembler/src/error.rs index 12db44b..677988e 100644 --- a/assembler/src/error.rs +++ b/assembler/src/error.rs @@ -13,6 +13,8 @@ pub struct SourceSpan { #[derive(Debug, Clone)] pub enum AsmError { + /// A native module/transport failure, distinct from invalid assembly input. + Backend(&'static str), LexerError(String), ParserError(String), EncodeError(String), @@ -52,6 +54,7 @@ impl AsmError { impl fmt::Display for AsmError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { + AsmError::Backend(reason) => write!(f, "Assembler backend failure: {reason}"), AsmError::LexerError(s) => write!(f, "Lexer error: {}", s), AsmError::ParserError(s) => write!(f, "Parser error: {}", s), AsmError::EncodeError(s) => write!(f, "Encode error: {}", s), diff --git a/assembler/src/tokens.rs b/assembler/src/tokens.rs index 8d33e56..337d054 100644 --- a/assembler/src/tokens.rs +++ b/assembler/src/tokens.rs @@ -40,225 +40,91 @@ impl Token { } } -#[derive(Clone, Copy)] -struct Mark { - position: usize, - line: usize, - column: usize, -} +#[cfg(any(test, not(whale_wave_assembler)))] +#[path = "unicode_reference.rs"] +mod unicode; -struct Cursor<'a> { - source: &'a str, - position: usize, - line: usize, - column: usize, - previous_cr: bool, -} +#[cfg(any(test, not(whale_wave_assembler)))] +#[path = "tokens_reference.rs"] +mod reference; -impl<'a> Cursor<'a> { - fn mark(&self) -> Mark { - Mark { position: self.position, line: self.line, column: self.column } - } +#[cfg(whale_wave_assembler)] +#[path = "tokens_wave.rs"] +mod wave; - fn peek(&self) -> Option { - self.source[self.position..].chars().next() +pub fn tokenize(source: &str) -> Result, AsmError> { + #[cfg(whale_wave_assembler)] + { + wave::tokenize(source) } + #[cfg(not(whale_wave_assembler))] + { + reference::tokenize(source) + } +} - fn bump(&mut self) -> Option { - let ch = self.peek()?; - self.position += ch.len_utf8(); - match ch { - '\r' => { - self.line += 1; - self.column = 1; - self.previous_cr = true; - }, - '\n' => { - if !self.previous_cr { - self.line += 1; - } - self.column = 1; - self.previous_cr = false; +#[cfg(all(test, whale_wave_assembler))] +mod tests { + use super::*; + + fn compare(source: &str) { + let expected = reference::tokenize(source); + let actual = tokenize(source); + match (actual, expected) { + (Ok(actual), Ok(expected)) => { + assert_eq!(format!("{actual:?}"), format!("{expected:?}"), "{source:?}"); }, - _ => { - self.column += 1; - self.previous_cr = false; + (Err(actual), Err(expected)) => { + assert_eq!(actual.to_string(), expected.to_string(), "{source:?}"); }, + (actual, expected) => panic!("{source:?}: actual={actual:?}, expected={expected:?}"), } - Some(ch) } - fn token(&self, kind: TokenKind, start: Mark) -> Token { - Token { - kind, - position: start.position, - end_position: self.position, - line: start.line, - column: start.column, - end_line: self.line, - end_column: self.column, + #[test] + fn native_utf8_tokens_and_exact_malformed_diagnostics_match_reference() { + for source in [ + "", + "nop\r\nret", + "étiquette: db \"한\\xFF\"", + "0x", + "0b", + "18446744073709551615", + "18446744073709551616", + "0xfffffffffffffffff", + "\"\\", + "\"\\x", + "\"\\xA", + "\"\\x한\"", + "\"\\q\"", + "; 😀\r@", + "/", + "\"a\r\nb\"\r\nnop", + "\u{1e6c0}: nop", + ] { + compare(source); + } + let alphabet: Vec<_> = + "abcXYZ_.,:[]+-*; \t\r\n0123456789xAbB\"\\né한٣²😀\0\u{2003}".chars().collect(); + let mut state = 0x0057_4841_4c45_4153_u64; + for _ in 0..10_000 { + let mut source = String::new(); + for _ in 0..(state % 100) { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + source.push(alphabet[state as usize % alphabet.len()]); + } + compare(&source); + state = state.wrapping_add(1); } } - fn error(&self, msg: &str, start: Mark) -> AsmError { - let end = if self.position > start.position { - self.position - } else { - self.position + self.peek().map_or(0, char::len_utf8) - }; - AsmError::LexerError(msg.into()).at( - "", - SourceSpan { start: start.position, end, line: start.line, column: start.column }, - None, - ) - } -} - -pub fn tokenize(source: &str) -> Result, AsmError> { - let mut c = Cursor { source, position: 0, line: 1, column: 1, previous_cr: false }; - let mut tokens = Vec::new(); - while let Some(ch) = c.peek() { - let start = c.mark(); - let kind = match ch { - ';' => { - while c.peek().is_some_and(|ch| ch != '\n' && ch != '\r') { - c.bump(); - } - continue; - }, - ' ' | '\t' => { - c.bump(); - continue; - }, - '\n' | '\r' => { - c.bump(); - if ch == '\r' && c.peek() == Some('\n') { - c.bump(); - } - TokenKind::Newline - }, - ',' => { - c.bump(); - TokenKind::Comma - }, - ':' => { - c.bump(); - TokenKind::Colon - }, - '[' => { - c.bump(); - TokenKind::LBracket - }, - ']' => { - c.bump(); - TokenKind::RBracket - }, - '+' => { - c.bump(); - TokenKind::Plus - }, - '-' => { - c.bump(); - TokenKind::Minus - }, - '*' => { - c.bump(); - TokenKind::Multiply - }, - '"' => { - c.bump(); - let mut bytes = Vec::new(); - loop { - let at = c.mark(); - let ch = - c.bump().ok_or_else(|| c.error("Unterminated string literal", start))?; - match ch { - '"' => break, - '\\' => { - let escape = c.bump().ok_or_else(|| c.error("Truncated escape", at))?; - let byte = match escape { - '"' => b'"', - '\\' => b'\\', - 'n' => b'\n', - 'r' => b'\r', - 't' => b'\t', - '0' => 0, - 'x' => { - let mut value = 0; - for _ in 0..2 { - let digit = c.bump().ok_or_else(|| { - c.error( - "Truncated byte escape; expected two hex digits", - at, - ) - })?; - let digit = digit - .to_digit(16) - .filter(|_| digit.is_ascii_hexdigit()) - .ok_or_else(|| { - c.error( - "Invalid byte escape; expected two hex digits", - at, - ) - })?; - value = value * 16 + digit as u8; - } - value - }, - _ => return Err(c.error("Unknown string escape", at)), - }; - bytes.push(byte); - }, - _ => { - let mut utf8 = [0; 4]; - bytes.extend_from_slice(ch.encode_utf8(&mut utf8).as_bytes()); - }, - } - } - TokenKind::StringLiteral(bytes) - }, - ch if ch.is_ascii_digit() => { - let rest = &source[c.position..]; - let radix = if rest.starts_with("0x") || rest.starts_with("0X") { - 16 - } else if rest.starts_with("0b") || rest.starts_with("0B") { - 2 - } else { - 10 - }; - if radix != 10 { - c.bump(); - c.bump(); - } - let digits = c.position; - while c.peek().is_some_and(|ch| match radix { - 16 => ch.is_ascii_hexdigit(), - 2 => matches!(ch, '0' | '1'), - _ => ch.is_ascii_digit(), - }) { - c.bump(); - } - if c.position == digits { - return Err(c.error( - if radix == 16 { "Invalid hex number" } else { "Invalid binary number" }, - start, - )); - } - let number = i128::from_str_radix(&source[digits..c.position], radix) - .ok() - .filter(|n| *n <= u64::MAX as i128) - .ok_or_else(|| c.error("Number exceeds unsigned 64-bit range", start))?; - TokenKind::Number(number) - }, - ch if ch.is_alphanumeric() || ch == '_' || ch == '.' => { - while c.peek().is_some_and(|ch| ch.is_alphanumeric() || ch == '_' || ch == '.') { - c.bump(); - } - TokenKind::Identifier(source[start.position..c.position].into()) - }, - _ => return Err(c.error(&format!("Unexpected char '{ch}'"), start)), - }; - tokens.push(c.token(kind, start)); + #[test] + fn long_streams_do_not_accumulate_native_stack_or_change_coordinates() { + compare(&"nop\r\n".repeat(30_000)); + compare(&format!("db \"{}\"", "한\\xFF".repeat(10_000))); + let source = ";".repeat(8 * 1024 * 1024 + 1); + compare(&source); } - Ok(tokens) } diff --git a/assembler/src/tokens_reference.rs b/assembler/src/tokens_reference.rs new file mode 100644 index 0000000..8e46e71 --- /dev/null +++ b/assembler/src/tokens_reference.rs @@ -0,0 +1,237 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Explicit compatibility reference for the Wave assembler lexer. +use super::{Token, TokenKind}; + +use crate::{AsmError, SourceSpan}; + +#[derive(Clone, Copy)] +struct Mark { + position: usize, + line: usize, + column: usize, +} + +struct Cursor<'a> { + source: &'a str, + position: usize, + line: usize, + column: usize, + previous_cr: bool, +} + +impl<'a> Cursor<'a> { + fn mark(&self) -> Mark { + Mark { position: self.position, line: self.line, column: self.column } + } + + fn peek(&self) -> Option { + self.source[self.position..].chars().next() + } + + fn bump(&mut self) -> Option { + let ch = self.peek()?; + self.position += ch.len_utf8(); + match ch { + '\r' => { + self.line += 1; + self.column = 1; + self.previous_cr = true; + }, + '\n' => { + if !self.previous_cr { + self.line += 1; + } + self.column = 1; + self.previous_cr = false; + }, + _ => { + self.column += 1; + self.previous_cr = false; + }, + } + Some(ch) + } + + fn token(&self, kind: TokenKind, start: Mark) -> Token { + Token { + kind, + position: start.position, + end_position: self.position, + line: start.line, + column: start.column, + end_line: self.line, + end_column: self.column, + } + } + + fn error(&self, msg: &str, start: Mark) -> AsmError { + let end = if self.position > start.position { + self.position + } else { + self.position + self.peek().map_or(0, char::len_utf8) + }; + AsmError::LexerError(msg.into()).at( + "", + SourceSpan { start: start.position, end, line: start.line, column: start.column }, + None, + ) + } +} + +pub(super) fn tokenize(source: &str) -> Result, AsmError> { + if source.len() > 8 * 1024 * 1024 { + return Err(AsmError::LexerError("assembly input exceeds 8388608 bytes".into()).at( + "", + SourceSpan { start: 0, end: 0, line: 1, column: 1 }, + None, + )); + } + let mut c = Cursor { source, position: 0, line: 1, column: 1, previous_cr: false }; + let mut tokens = Vec::new(); + while let Some(ch) = c.peek() { + let start = c.mark(); + let kind = match ch { + ';' => { + while c.peek().is_some_and(|ch| ch != '\n' && ch != '\r') { + c.bump(); + } + continue; + }, + ' ' | '\t' => { + c.bump(); + continue; + }, + '\n' | '\r' => { + c.bump(); + if ch == '\r' && c.peek() == Some('\n') { + c.bump(); + } + TokenKind::Newline + }, + ',' => { + c.bump(); + TokenKind::Comma + }, + ':' => { + c.bump(); + TokenKind::Colon + }, + '[' => { + c.bump(); + TokenKind::LBracket + }, + ']' => { + c.bump(); + TokenKind::RBracket + }, + '+' => { + c.bump(); + TokenKind::Plus + }, + '-' => { + c.bump(); + TokenKind::Minus + }, + '*' => { + c.bump(); + TokenKind::Multiply + }, + '"' => { + c.bump(); + let mut bytes = Vec::new(); + loop { + let at = c.mark(); + let ch = + c.bump().ok_or_else(|| c.error("Unterminated string literal", start))?; + match ch { + '"' => break, + '\\' => { + let escape = c.bump().ok_or_else(|| c.error("Truncated escape", at))?; + let byte = match escape { + '"' => b'"', + '\\' => b'\\', + 'n' => b'\n', + 'r' => b'\r', + 't' => b'\t', + '0' => 0, + 'x' => { + let mut value = 0; + for _ in 0..2 { + let digit = c.bump().ok_or_else(|| { + c.error( + "Truncated byte escape; expected two hex digits", + at, + ) + })?; + let digit = digit + .to_digit(16) + .filter(|_| digit.is_ascii_hexdigit()) + .ok_or_else(|| { + c.error( + "Invalid byte escape; expected two hex digits", + at, + ) + })?; + value = value * 16 + digit as u8; + } + value + }, + _ => return Err(c.error("Unknown string escape", at)), + }; + bytes.push(byte); + }, + _ => { + let mut utf8 = [0; 4]; + bytes.extend_from_slice(ch.encode_utf8(&mut utf8).as_bytes()); + }, + } + } + TokenKind::StringLiteral(bytes) + }, + ch if ch.is_ascii_digit() => { + let rest = &source[c.position..]; + let radix = if rest.starts_with("0x") || rest.starts_with("0X") { + 16 + } else if rest.starts_with("0b") || rest.starts_with("0B") { + 2 + } else { + 10 + }; + if radix != 10 { + c.bump(); + c.bump(); + } + let digits = c.position; + while c.peek().is_some_and(|ch| match radix { + 16 => ch.is_ascii_hexdigit(), + 2 => matches!(ch, '0' | '1'), + _ => ch.is_ascii_digit(), + }) { + c.bump(); + } + if c.position == digits { + return Err(c.error( + if radix == 16 { "Invalid hex number" } else { "Invalid binary number" }, + start, + )); + } + let number = i128::from_str_radix(&source[digits..c.position], radix) + .ok() + .filter(|n| *n <= u64::MAX as i128) + .ok_or_else(|| c.error("Number exceeds unsigned 64-bit range", start))?; + TokenKind::Number(number) + }, + ch if crate::tokens::unicode::alphanumeric(ch) || ch == '_' || ch == '.' => { + while c.peek().is_some_and(|ch| { + crate::tokens::unicode::alphanumeric(ch) || ch == '_' || ch == '.' + }) { + c.bump(); + } + TokenKind::Identifier(source[start.position..c.position].into()) + }, + _ => return Err(c.error(&format!("Unexpected char '{ch}'"), start)), + }; + tokens.push(c.token(kind, start)); + } + Ok(tokens) +} diff --git a/assembler/src/tokens_wave.rs b/assembler/src/tokens_wave.rs new file mode 100644 index 0000000..fae4a5d --- /dev/null +++ b/assembler/src/tokens_wave.rs @@ -0,0 +1,229 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Allocation and typed transport for the native Wave source lexer. +use super::{Token, TokenKind}; + +use crate::{AsmError, SourceSpan}; + +const MAX_SOURCE: usize = 8 * 1024 * 1024; + +const BACKEND: &str = "assembler lexer transport"; + +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct RawToken { + kind: u64, + start: u64, + end: u64, + line: u64, + column: u64, + end_line: u64, + end_column: u64, + decoded_start: u64, + decoded_len: u64, + low: u64, + high: u64, +} + +#[repr(C)] +#[derive(Clone, Copy, Debug, Default)] +struct RawResult { + status: u64, + reason: u64, + start: u64, + end: u64, + line: u64, + column: u64, + detail: u64, + tokens: u64, + decoded: u64, + work: u64, +} + +unsafe extern "C" { + fn whale_asm_lex( + source: *const u8, + length: u64, + max_tokens: u64, + max_decoded: u64, + max_work: u64, + mode: u64, + scratch_tokens: *mut RawToken, + token_capacity: u64, + scratch_decoded: *mut u8, + decoded_capacity: u64, + output_tokens: *mut RawToken, + output_token_capacity: u64, + output_decoded: *mut u8, + output_decoded_capacity: u64, + result: *mut RawResult, + ) -> i32; +} + +fn backend() -> AsmError { + AsmError::Backend(BACKEND) +} + +fn initialized(count: usize) -> Result, AsmError> { + let mut values = Vec::new(); + values.try_reserve_exact(count).map_err(|_| AsmError::Backend("assembler lexer allocation"))?; + values.resize(count, T::default()); + Ok(values) +} + +fn copied(source: &[T]) -> Result, AsmError> { + let mut values = Vec::new(); + values + .try_reserve_exact(source.len()) + .map_err(|_| AsmError::Backend("assembler lexer allocation"))?; + values.extend_from_slice(source); + Ok(values) +} + +fn index(value: u64) -> Result { + usize::try_from(value).map_err(|_| backend()) +} + +fn failure(source: &str, result: &RawResult) -> AsmError { + if result.status == 5 { + return backend(); + } + let Ok(start) = index(result.start) else { return backend() }; + let Ok(end) = index(result.end) else { return backend() }; + let Ok(line) = index(result.line) else { return backend() }; + let Ok(column) = index(result.column) else { return backend() }; + if start > end || source.get(start..end).is_none() || line == 0 || column == 0 { + return backend(); + } + let message = match (result.status, result.reason) { + (1, 1) => match u32::try_from(result.detail).ok().and_then(char::from_u32) { + Some(ch) => format!("Unexpected char '{ch}'"), + None => return backend(), + }, + (1, 2) => "Unterminated string literal".into(), + (1, 3) => "Truncated escape".into(), + (1, 4) => "Truncated byte escape; expected two hex digits".into(), + (1, 5) => "Invalid byte escape; expected two hex digits".into(), + (1, 6) => "Unknown string escape".into(), + (1, 7) => "Invalid hex number".into(), + (1, 8) => "Invalid binary number".into(), + (1, 9) => "Number exceeds unsigned 64-bit range".into(), + (2, 0) => "assembly token limit exceeded".into(), + (3, 0) => "assembly decoded-byte limit exceeded".into(), + (4, 0) => "assembly lexer work limit exceeded".into(), + (6, 0) => "assembly input exceeds 8388608 bytes".into(), + _ => return backend(), + }; + AsmError::LexerError(message).at("", SourceSpan { start, end, line, column }, None) +} + +fn call( + source: &str, + mode: u64, + tokens: &mut [RawToken], + decoded: &mut [u8], +) -> Result { + let maximum = source.len() as u64; + let max_work = maximum.saturating_mul(2).saturating_add(1); + let mut result = RawResult::default(); + // Both aliases address a private initialized buffer. Native publication only + // copies scratch after complete validation; no public Token exists yet. + let status = unsafe { + whale_asm_lex( + source.as_ptr(), + maximum, + maximum, + maximum, + max_work, + mode, + tokens.as_mut_ptr(), + tokens.len() as u64, + decoded.as_mut_ptr(), + decoded.len() as u64, + tokens.as_mut_ptr(), + tokens.len() as u64, + decoded.as_mut_ptr(), + decoded.len() as u64, + &mut result, + ) + }; + if i32::try_from(result.status).ok() != Some(status) + || result.tokens > maximum + || result.decoded > maximum + || result.work > max_work + { + return Err(backend()); + } + if status != 0 { + return Err(failure(source, &result)); + } + if source.len() > MAX_SOURCE + || (mode == 1 + && (result.tokens > tokens.len() as u64 || result.decoded > decoded.len() as u64)) + { + return Err(backend()); + } + Ok(result) +} + +pub(super) fn tokenize(source: &str) -> Result, AsmError> { + let probe = call(source, 0, &mut [], &mut [])?; + let mut native = initialized::(index(probe.tokens)?)?; + let mut decoded = initialized::(index(probe.decoded)?)?; + let result = call(source, 1, &mut native, &mut decoded)?; + if result.tokens != probe.tokens || result.decoded != probe.decoded || result.work != probe.work + { + return Err(backend()); + } + let mut tokens = Vec::new(); + tokens + .try_reserve_exact(native.len()) + .map_err(|_| AsmError::Backend("assembler lexer allocation"))?; + let mut previous = 0; + for raw in native { + let start = index(raw.start)?; + let end = index(raw.end)?; + let text = source.get(start..end).ok_or_else(backend)?; + if start < previous + || start == end + || raw.high != 0 + || raw.line == 0 + || raw.column == 0 + || raw.end_line < raw.line + || raw.end_column == 0 + { + return Err(backend()); + } + previous = end; + let kind = match raw.kind { + 0 => TokenKind::Identifier( + String::from_utf8(copied(text.as_bytes())?).map_err(|_| backend())?, + ), + 1 => TokenKind::Number(i128::from(raw.low)), + 2 => { + let first = index(raw.decoded_start)?; + let end = first.checked_add(index(raw.decoded_len)?).ok_or_else(backend)?; + TokenKind::StringLiteral(copied(decoded.get(first..end).ok_or_else(backend)?)?) + }, + 3 => TokenKind::Comma, + 4 => TokenKind::Colon, + 5 => TokenKind::LBracket, + 6 => TokenKind::RBracket, + 7 => TokenKind::Plus, + 8 => TokenKind::Minus, + 9 => TokenKind::Multiply, + 10 => TokenKind::Divide, + 11 => TokenKind::Newline, + _ => return Err(backend()), + }; + tokens.push(Token { + kind, + position: start, + end_position: end, + line: index(raw.line)?, + column: index(raw.column)?, + end_line: index(raw.end_line)?, + end_column: index(raw.end_column)?, + }); + } + Ok(tokens) +} diff --git a/assembler/src/unicode_reference.rs b/assembler/src/unicode_reference.rs new file mode 100644 index 0000000..5f84f26 --- /dev/null +++ b/assembler/src/unicode_reference.rs @@ -0,0 +1,864 @@ +// SPDX-License-Identifier: MPL-2.0 +// Unicode 17.0 alphanumeric ranges, generated from Rust 1.96 char::is_alphanumeric. +// This is immutable character data; runtime classification executes in Wave. +pub(super) const ALPHANUMERIC: &[(u32, u32)] = &[ + (48, 57), + (65, 90), + (97, 122), + (170, 170), + (178, 179), + (181, 181), + (185, 186), + (188, 190), + (192, 214), + (216, 246), + (248, 705), + (710, 721), + (736, 740), + (748, 748), + (750, 750), + (837, 837), + (867, 884), + (886, 887), + (890, 893), + (895, 895), + (902, 902), + (904, 906), + (908, 908), + (910, 929), + (931, 1013), + (1015, 1153), + (1162, 1327), + (1329, 1366), + (1369, 1369), + (1376, 1416), + (1456, 1469), + (1471, 1471), + (1473, 1474), + (1476, 1477), + (1479, 1479), + (1488, 1514), + (1519, 1522), + (1552, 1562), + (1568, 1623), + (1625, 1641), + (1646, 1747), + (1749, 1756), + (1761, 1768), + (1773, 1788), + (1791, 1791), + (1808, 1855), + (1869, 1969), + (1984, 2026), + (2036, 2037), + (2042, 2042), + (2048, 2071), + (2074, 2092), + (2112, 2136), + (2144, 2154), + (2160, 2183), + (2185, 2191), + (2199, 2199), + (2208, 2249), + (2260, 2271), + (2275, 2281), + (2288, 2363), + (2365, 2380), + (2382, 2384), + (2389, 2403), + (2406, 2415), + (2417, 2435), + (2437, 2444), + (2447, 2448), + (2451, 2472), + (2474, 2480), + (2482, 2482), + (2486, 2489), + (2493, 2500), + (2503, 2504), + (2507, 2508), + (2510, 2510), + (2519, 2519), + (2524, 2525), + (2527, 2531), + (2534, 2545), + (2548, 2553), + (2556, 2556), + (2561, 2563), + (2565, 2570), + (2575, 2576), + (2579, 2600), + (2602, 2608), + (2610, 2611), + (2613, 2614), + (2616, 2617), + (2622, 2626), + (2631, 2632), + (2635, 2636), + (2641, 2641), + (2649, 2652), + (2654, 2654), + (2662, 2677), + (2689, 2691), + (2693, 2701), + (2703, 2705), + (2707, 2728), + (2730, 2736), + (2738, 2739), + (2741, 2745), + (2749, 2757), + (2759, 2761), + (2763, 2764), + (2768, 2768), + (2784, 2787), + (2790, 2799), + (2809, 2812), + (2817, 2819), + (2821, 2828), + (2831, 2832), + (2835, 2856), + (2858, 2864), + (2866, 2867), + (2869, 2873), + (2877, 2884), + (2887, 2888), + (2891, 2892), + (2902, 2903), + (2908, 2909), + (2911, 2915), + (2918, 2927), + (2929, 2935), + (2946, 2947), + (2949, 2954), + (2958, 2960), + (2962, 2965), + (2969, 2970), + (2972, 2972), + (2974, 2975), + (2979, 2980), + (2984, 2986), + (2990, 3001), + (3006, 3010), + (3014, 3016), + (3018, 3020), + (3024, 3024), + (3031, 3031), + (3046, 3058), + (3072, 3084), + (3086, 3088), + (3090, 3112), + (3114, 3129), + (3133, 3140), + (3142, 3144), + (3146, 3148), + (3157, 3158), + (3160, 3162), + (3164, 3165), + (3168, 3171), + (3174, 3183), + (3192, 3198), + (3200, 3203), + (3205, 3212), + (3214, 3216), + (3218, 3240), + (3242, 3251), + (3253, 3257), + (3261, 3268), + (3270, 3272), + (3274, 3276), + (3285, 3286), + (3292, 3294), + (3296, 3299), + (3302, 3311), + (3313, 3315), + (3328, 3340), + (3342, 3344), + (3346, 3386), + (3389, 3396), + (3398, 3400), + (3402, 3404), + (3406, 3406), + (3412, 3427), + (3430, 3448), + (3450, 3455), + (3457, 3459), + (3461, 3478), + (3482, 3505), + (3507, 3515), + (3517, 3517), + (3520, 3526), + (3535, 3540), + (3542, 3542), + (3544, 3551), + (3558, 3567), + (3570, 3571), + (3585, 3642), + (3648, 3654), + (3661, 3661), + (3664, 3673), + (3713, 3714), + (3716, 3716), + (3718, 3722), + (3724, 3747), + (3749, 3749), + (3751, 3769), + (3771, 3773), + (3776, 3780), + (3782, 3782), + (3789, 3789), + (3792, 3801), + (3804, 3807), + (3840, 3840), + (3872, 3891), + (3904, 3911), + (3913, 3948), + (3953, 3971), + (3976, 3991), + (3993, 4028), + (4096, 4150), + (4152, 4152), + (4155, 4169), + (4176, 4253), + (4256, 4293), + (4295, 4295), + (4301, 4301), + (4304, 4346), + (4348, 4680), + (4682, 4685), + (4688, 4694), + (4696, 4696), + (4698, 4701), + (4704, 4744), + (4746, 4749), + (4752, 4784), + (4786, 4789), + (4792, 4798), + (4800, 4800), + (4802, 4805), + (4808, 4822), + (4824, 4880), + (4882, 4885), + (4888, 4954), + (4969, 4988), + (4992, 5007), + (5024, 5109), + (5112, 5117), + (5121, 5740), + (5743, 5759), + (5761, 5786), + (5792, 5866), + (5870, 5880), + (5888, 5907), + (5919, 5939), + (5952, 5971), + (5984, 5996), + (5998, 6000), + (6002, 6003), + (6016, 6067), + (6070, 6088), + (6103, 6103), + (6108, 6108), + (6112, 6121), + (6128, 6137), + (6160, 6169), + (6176, 6264), + (6272, 6314), + (6320, 6389), + (6400, 6430), + (6432, 6443), + (6448, 6456), + (6470, 6509), + (6512, 6516), + (6528, 6571), + (6576, 6601), + (6608, 6618), + (6656, 6683), + (6688, 6750), + (6753, 6772), + (6784, 6793), + (6800, 6809), + (6823, 6823), + (6847, 6848), + (6860, 6862), + (6912, 6963), + (6965, 6979), + (6981, 6988), + (6992, 7001), + (7040, 7081), + (7084, 7141), + (7143, 7153), + (7168, 7222), + (7232, 7241), + (7245, 7293), + (7296, 7306), + (7312, 7354), + (7357, 7359), + (7401, 7404), + (7406, 7411), + (7413, 7414), + (7418, 7418), + (7424, 7615), + (7635, 7668), + (7680, 7957), + (7960, 7965), + (7968, 8005), + (8008, 8013), + (8016, 8023), + (8025, 8025), + (8027, 8027), + (8029, 8029), + (8031, 8061), + (8064, 8116), + (8118, 8124), + (8126, 8126), + (8130, 8132), + (8134, 8140), + (8144, 8147), + (8150, 8155), + (8160, 8172), + (8178, 8180), + (8182, 8188), + (8304, 8305), + (8308, 8313), + (8319, 8329), + (8336, 8348), + (8450, 8450), + (8455, 8455), + (8458, 8467), + (8469, 8469), + (8473, 8477), + (8484, 8484), + (8486, 8486), + (8488, 8488), + (8490, 8493), + (8495, 8505), + (8508, 8511), + (8517, 8521), + (8526, 8526), + (8528, 8585), + (9312, 9371), + (9398, 9471), + (10102, 10131), + (11264, 11492), + (11499, 11502), + (11506, 11507), + (11517, 11517), + (11520, 11557), + (11559, 11559), + (11565, 11565), + (11568, 11623), + (11631, 11631), + (11648, 11670), + (11680, 11686), + (11688, 11694), + (11696, 11702), + (11704, 11710), + (11712, 11718), + (11720, 11726), + (11728, 11734), + (11736, 11742), + (11744, 11775), + (11823, 11823), + (12293, 12295), + (12321, 12329), + (12337, 12341), + (12344, 12348), + (12353, 12438), + (12445, 12447), + (12449, 12538), + (12540, 12543), + (12549, 12591), + (12593, 12686), + (12690, 12693), + (12704, 12735), + (12784, 12799), + (12832, 12841), + (12872, 12879), + (12881, 12895), + (12928, 12937), + (12977, 12991), + (13312, 19903), + (19968, 42124), + (42192, 42237), + (42240, 42508), + (42512, 42539), + (42560, 42606), + (42612, 42619), + (42623, 42735), + (42775, 42783), + (42786, 42888), + (42891, 42972), + (42993, 43013), + (43015, 43047), + (43056, 43061), + (43072, 43123), + (43136, 43203), + (43205, 43205), + (43216, 43225), + (43250, 43255), + (43259, 43259), + (43261, 43306), + (43312, 43346), + (43360, 43388), + (43392, 43442), + (43444, 43455), + (43471, 43481), + (43488, 43518), + (43520, 43574), + (43584, 43597), + (43600, 43609), + (43616, 43638), + (43642, 43710), + (43712, 43712), + (43714, 43714), + (43739, 43741), + (43744, 43759), + (43762, 43765), + (43777, 43782), + (43785, 43790), + (43793, 43798), + (43808, 43814), + (43816, 43822), + (43824, 43866), + (43868, 43881), + (43888, 44010), + (44016, 44025), + (44032, 55203), + (55216, 55238), + (55243, 55291), + (63744, 64109), + (64112, 64217), + (64256, 64262), + (64275, 64279), + (64285, 64296), + (64298, 64310), + (64312, 64316), + (64318, 64318), + (64320, 64321), + (64323, 64324), + (64326, 64433), + (64467, 64829), + (64848, 64911), + (64914, 64967), + (65008, 65019), + (65136, 65140), + (65142, 65276), + (65296, 65305), + (65313, 65338), + (65345, 65370), + (65382, 65470), + (65474, 65479), + (65482, 65487), + (65490, 65495), + (65498, 65500), + (65536, 65547), + (65549, 65574), + (65576, 65594), + (65596, 65597), + (65599, 65613), + (65616, 65629), + (65664, 65786), + (65799, 65843), + (65856, 65912), + (65930, 65931), + (66176, 66204), + (66208, 66256), + (66273, 66299), + (66304, 66339), + (66349, 66378), + (66384, 66426), + (66432, 66461), + (66464, 66499), + (66504, 66511), + (66513, 66517), + (66560, 66717), + (66720, 66729), + (66736, 66771), + (66776, 66811), + (66816, 66855), + (66864, 66915), + (66928, 66938), + (66940, 66954), + (66956, 66962), + (66964, 66965), + (66967, 66977), + (66979, 66993), + (66995, 67001), + (67003, 67004), + (67008, 67059), + (67072, 67382), + (67392, 67413), + (67424, 67431), + (67456, 67461), + (67463, 67504), + (67506, 67514), + (67584, 67589), + (67592, 67592), + (67594, 67637), + (67639, 67640), + (67644, 67644), + (67647, 67669), + (67672, 67702), + (67705, 67742), + (67751, 67759), + (67808, 67826), + (67828, 67829), + (67835, 67867), + (67872, 67897), + (67904, 67929), + (67968, 68023), + (68028, 68047), + (68050, 68099), + (68101, 68102), + (68108, 68115), + (68117, 68119), + (68121, 68149), + (68160, 68168), + (68192, 68222), + (68224, 68255), + (68288, 68295), + (68297, 68324), + (68331, 68335), + (68352, 68405), + (68416, 68437), + (68440, 68466), + (68472, 68497), + (68521, 68527), + (68608, 68680), + (68736, 68786), + (68800, 68850), + (68858, 68903), + (68912, 68921), + (68928, 68965), + (68969, 68969), + (68975, 68997), + (69216, 69246), + (69248, 69289), + (69291, 69292), + (69296, 69297), + (69314, 69319), + (69370, 69372), + (69376, 69415), + (69424, 69445), + (69457, 69460), + (69488, 69505), + (69552, 69579), + (69600, 69622), + (69632, 69701), + (69714, 69743), + (69745, 69749), + (69760, 69816), + (69826, 69826), + (69840, 69864), + (69872, 69881), + (69888, 69938), + (69942, 69951), + (69956, 69959), + (69968, 70002), + (70006, 70006), + (70016, 70079), + (70081, 70084), + (70094, 70106), + (70108, 70108), + (70113, 70132), + (70144, 70161), + (70163, 70196), + (70199, 70199), + (70206, 70209), + (70272, 70278), + (70280, 70280), + (70282, 70285), + (70287, 70301), + (70303, 70312), + (70320, 70376), + (70384, 70393), + (70400, 70403), + (70405, 70412), + (70415, 70416), + (70419, 70440), + (70442, 70448), + (70450, 70451), + (70453, 70457), + (70461, 70468), + (70471, 70472), + (70475, 70476), + (70480, 70480), + (70487, 70487), + (70493, 70499), + (70528, 70537), + (70539, 70539), + (70542, 70542), + (70544, 70581), + (70583, 70592), + (70594, 70594), + (70597, 70597), + (70599, 70602), + (70604, 70605), + (70609, 70609), + (70611, 70611), + (70656, 70721), + (70723, 70725), + (70727, 70730), + (70736, 70745), + (70751, 70753), + (70784, 70849), + (70852, 70853), + (70855, 70855), + (70864, 70873), + (71040, 71093), + (71096, 71102), + (71128, 71133), + (71168, 71230), + (71232, 71232), + (71236, 71236), + (71248, 71257), + (71296, 71349), + (71352, 71352), + (71360, 71369), + (71376, 71395), + (71424, 71450), + (71453, 71466), + (71472, 71483), + (71488, 71494), + (71680, 71736), + (71840, 71922), + (71935, 71942), + (71945, 71945), + (71948, 71955), + (71957, 71958), + (71960, 71989), + (71991, 71992), + (71995, 71996), + (71999, 72002), + (72016, 72025), + (72096, 72103), + (72106, 72151), + (72154, 72159), + (72161, 72161), + (72163, 72164), + (72192, 72242), + (72245, 72254), + (72272, 72343), + (72349, 72349), + (72368, 72440), + (72544, 72551), + (72640, 72672), + (72688, 72697), + (72704, 72712), + (72714, 72758), + (72760, 72766), + (72768, 72768), + (72784, 72812), + (72818, 72847), + (72850, 72871), + (72873, 72886), + (72960, 72966), + (72968, 72969), + (72971, 73014), + (73018, 73018), + (73020, 73021), + (73023, 73025), + (73027, 73027), + (73030, 73031), + (73040, 73049), + (73056, 73061), + (73063, 73064), + (73066, 73102), + (73104, 73105), + (73107, 73110), + (73112, 73112), + (73120, 73129), + (73136, 73179), + (73184, 73193), + (73440, 73462), + (73472, 73488), + (73490, 73530), + (73534, 73536), + (73552, 73561), + (73648, 73648), + (73664, 73684), + (73728, 74649), + (74752, 74862), + (74880, 75075), + (77712, 77808), + (77824, 78895), + (78913, 78918), + (78944, 82938), + (82944, 83526), + (90368, 90414), + (90416, 90425), + (92160, 92728), + (92736, 92766), + (92768, 92777), + (92784, 92862), + (92864, 92873), + (92880, 92909), + (92928, 92975), + (92992, 92995), + (93008, 93017), + (93019, 93025), + (93027, 93047), + (93053, 93071), + (93504, 93548), + (93552, 93561), + (93760, 93846), + (93856, 93880), + (93883, 93907), + (93952, 94026), + (94031, 94087), + (94095, 94111), + (94176, 94177), + (94179, 94179), + (94192, 94198), + (94208, 101589), + (101631, 101662), + (101760, 101874), + (110576, 110579), + (110581, 110587), + (110589, 110590), + (110592, 110882), + (110898, 110898), + (110928, 110930), + (110933, 110933), + (110948, 110951), + (110960, 111355), + (113664, 113770), + (113776, 113788), + (113792, 113800), + (113808, 113817), + (113822, 113822), + (118000, 118009), + (119488, 119507), + (119520, 119539), + (119648, 119672), + (119808, 119892), + (119894, 119964), + (119966, 119967), + (119970, 119970), + (119973, 119974), + (119977, 119980), + (119982, 119993), + (119995, 119995), + (119997, 120003), + (120005, 120069), + (120071, 120074), + (120077, 120084), + (120086, 120092), + (120094, 120121), + (120123, 120126), + (120128, 120132), + (120134, 120134), + (120138, 120144), + (120146, 120485), + (120488, 120512), + (120514, 120538), + (120540, 120570), + (120572, 120596), + (120598, 120628), + (120630, 120654), + (120656, 120686), + (120688, 120712), + (120714, 120744), + (120746, 120770), + (120772, 120779), + (120782, 120831), + (122624, 122654), + (122661, 122666), + (122880, 122886), + (122888, 122904), + (122907, 122913), + (122915, 122916), + (122918, 122922), + (122928, 122989), + (123023, 123023), + (123136, 123180), + (123191, 123197), + (123200, 123209), + (123214, 123214), + (123536, 123565), + (123584, 123627), + (123632, 123641), + (124112, 124139), + (124144, 124153), + (124368, 124397), + (124400, 124410), + (124608, 124638), + (124640, 124661), + (124670, 124671), + (124896, 124902), + (124904, 124907), + (124909, 124910), + (124912, 124926), + (124928, 125124), + (125127, 125135), + (125184, 125251), + (125255, 125255), + (125259, 125259), + (125264, 125273), + (126065, 126123), + (126125, 126127), + (126129, 126132), + (126209, 126253), + (126255, 126269), + (126464, 126467), + (126469, 126495), + (126497, 126498), + (126500, 126500), + (126503, 126503), + (126505, 126514), + (126516, 126519), + (126521, 126521), + (126523, 126523), + (126530, 126530), + (126535, 126535), + (126537, 126537), + (126539, 126539), + (126541, 126543), + (126545, 126546), + (126548, 126548), + (126551, 126551), + (126553, 126553), + (126555, 126555), + (126557, 126557), + (126559, 126559), + (126561, 126562), + (126564, 126564), + (126567, 126570), + (126572, 126578), + (126580, 126583), + (126585, 126588), + (126590, 126590), + (126592, 126601), + (126603, 126619), + (126625, 126627), + (126629, 126633), + (126635, 126651), + (127232, 127244), + (127280, 127305), + (127312, 127337), + (127344, 127369), + (130032, 130041), + (131072, 173791), + (173824, 178205), + (178208, 183981), + (183984, 191456), + (191472, 192093), + (194560, 195101), + (196608, 201546), + (201552, 210041), +]; + +pub(super) fn alphanumeric(ch: char) -> bool { + let cp = u32::from(ch); + ALPHANUMERIC + .binary_search_by(|&(lo, hi)| { + if cp < lo { + std::cmp::Ordering::Greater + } else if cp > hi { + std::cmp::Ordering::Less + } else { + std::cmp::Ordering::Equal + } + }) + .is_ok() +} diff --git a/assembler/unicode.wave b/assembler/unicode.wave new file mode 100644 index 0000000..17965b9 --- /dev/null +++ b/assembler/unicode.wave @@ -0,0 +1,865 @@ +// SPDX-License-Identifier: MPL-2.0 +// Unicode 17.0 alphanumeric ranges, generated from Rust 1.96 char::is_alphanumeric. +// This is immutable character data; runtime classification executes in Wave. +const ASM_ALPHANUMERIC: array = [ + 48, 57, + 65, 90, + 97, 122, + 170, 170, + 178, 179, + 181, 181, + 185, 186, + 188, 190, + 192, 214, + 216, 246, + 248, 705, + 710, 721, + 736, 740, + 748, 748, + 750, 750, + 837, 837, + 867, 884, + 886, 887, + 890, 893, + 895, 895, + 902, 902, + 904, 906, + 908, 908, + 910, 929, + 931, 1013, + 1015, 1153, + 1162, 1327, + 1329, 1366, + 1369, 1369, + 1376, 1416, + 1456, 1469, + 1471, 1471, + 1473, 1474, + 1476, 1477, + 1479, 1479, + 1488, 1514, + 1519, 1522, + 1552, 1562, + 1568, 1623, + 1625, 1641, + 1646, 1747, + 1749, 1756, + 1761, 1768, + 1773, 1788, + 1791, 1791, + 1808, 1855, + 1869, 1969, + 1984, 2026, + 2036, 2037, + 2042, 2042, + 2048, 2071, + 2074, 2092, + 2112, 2136, + 2144, 2154, + 2160, 2183, + 2185, 2191, + 2199, 2199, + 2208, 2249, + 2260, 2271, + 2275, 2281, + 2288, 2363, + 2365, 2380, + 2382, 2384, + 2389, 2403, + 2406, 2415, + 2417, 2435, + 2437, 2444, + 2447, 2448, + 2451, 2472, + 2474, 2480, + 2482, 2482, + 2486, 2489, + 2493, 2500, + 2503, 2504, + 2507, 2508, + 2510, 2510, + 2519, 2519, + 2524, 2525, + 2527, 2531, + 2534, 2545, + 2548, 2553, + 2556, 2556, + 2561, 2563, + 2565, 2570, + 2575, 2576, + 2579, 2600, + 2602, 2608, + 2610, 2611, + 2613, 2614, + 2616, 2617, + 2622, 2626, + 2631, 2632, + 2635, 2636, + 2641, 2641, + 2649, 2652, + 2654, 2654, + 2662, 2677, + 2689, 2691, + 2693, 2701, + 2703, 2705, + 2707, 2728, + 2730, 2736, + 2738, 2739, + 2741, 2745, + 2749, 2757, + 2759, 2761, + 2763, 2764, + 2768, 2768, + 2784, 2787, + 2790, 2799, + 2809, 2812, + 2817, 2819, + 2821, 2828, + 2831, 2832, + 2835, 2856, + 2858, 2864, + 2866, 2867, + 2869, 2873, + 2877, 2884, + 2887, 2888, + 2891, 2892, + 2902, 2903, + 2908, 2909, + 2911, 2915, + 2918, 2927, + 2929, 2935, + 2946, 2947, + 2949, 2954, + 2958, 2960, + 2962, 2965, + 2969, 2970, + 2972, 2972, + 2974, 2975, + 2979, 2980, + 2984, 2986, + 2990, 3001, + 3006, 3010, + 3014, 3016, + 3018, 3020, + 3024, 3024, + 3031, 3031, + 3046, 3058, + 3072, 3084, + 3086, 3088, + 3090, 3112, + 3114, 3129, + 3133, 3140, + 3142, 3144, + 3146, 3148, + 3157, 3158, + 3160, 3162, + 3164, 3165, + 3168, 3171, + 3174, 3183, + 3192, 3198, + 3200, 3203, + 3205, 3212, + 3214, 3216, + 3218, 3240, + 3242, 3251, + 3253, 3257, + 3261, 3268, + 3270, 3272, + 3274, 3276, + 3285, 3286, + 3292, 3294, + 3296, 3299, + 3302, 3311, + 3313, 3315, + 3328, 3340, + 3342, 3344, + 3346, 3386, + 3389, 3396, + 3398, 3400, + 3402, 3404, + 3406, 3406, + 3412, 3427, + 3430, 3448, + 3450, 3455, + 3457, 3459, + 3461, 3478, + 3482, 3505, + 3507, 3515, + 3517, 3517, + 3520, 3526, + 3535, 3540, + 3542, 3542, + 3544, 3551, + 3558, 3567, + 3570, 3571, + 3585, 3642, + 3648, 3654, + 3661, 3661, + 3664, 3673, + 3713, 3714, + 3716, 3716, + 3718, 3722, + 3724, 3747, + 3749, 3749, + 3751, 3769, + 3771, 3773, + 3776, 3780, + 3782, 3782, + 3789, 3789, + 3792, 3801, + 3804, 3807, + 3840, 3840, + 3872, 3891, + 3904, 3911, + 3913, 3948, + 3953, 3971, + 3976, 3991, + 3993, 4028, + 4096, 4150, + 4152, 4152, + 4155, 4169, + 4176, 4253, + 4256, 4293, + 4295, 4295, + 4301, 4301, + 4304, 4346, + 4348, 4680, + 4682, 4685, + 4688, 4694, + 4696, 4696, + 4698, 4701, + 4704, 4744, + 4746, 4749, + 4752, 4784, + 4786, 4789, + 4792, 4798, + 4800, 4800, + 4802, 4805, + 4808, 4822, + 4824, 4880, + 4882, 4885, + 4888, 4954, + 4969, 4988, + 4992, 5007, + 5024, 5109, + 5112, 5117, + 5121, 5740, + 5743, 5759, + 5761, 5786, + 5792, 5866, + 5870, 5880, + 5888, 5907, + 5919, 5939, + 5952, 5971, + 5984, 5996, + 5998, 6000, + 6002, 6003, + 6016, 6067, + 6070, 6088, + 6103, 6103, + 6108, 6108, + 6112, 6121, + 6128, 6137, + 6160, 6169, + 6176, 6264, + 6272, 6314, + 6320, 6389, + 6400, 6430, + 6432, 6443, + 6448, 6456, + 6470, 6509, + 6512, 6516, + 6528, 6571, + 6576, 6601, + 6608, 6618, + 6656, 6683, + 6688, 6750, + 6753, 6772, + 6784, 6793, + 6800, 6809, + 6823, 6823, + 6847, 6848, + 6860, 6862, + 6912, 6963, + 6965, 6979, + 6981, 6988, + 6992, 7001, + 7040, 7081, + 7084, 7141, + 7143, 7153, + 7168, 7222, + 7232, 7241, + 7245, 7293, + 7296, 7306, + 7312, 7354, + 7357, 7359, + 7401, 7404, + 7406, 7411, + 7413, 7414, + 7418, 7418, + 7424, 7615, + 7635, 7668, + 7680, 7957, + 7960, 7965, + 7968, 8005, + 8008, 8013, + 8016, 8023, + 8025, 8025, + 8027, 8027, + 8029, 8029, + 8031, 8061, + 8064, 8116, + 8118, 8124, + 8126, 8126, + 8130, 8132, + 8134, 8140, + 8144, 8147, + 8150, 8155, + 8160, 8172, + 8178, 8180, + 8182, 8188, + 8304, 8305, + 8308, 8313, + 8319, 8329, + 8336, 8348, + 8450, 8450, + 8455, 8455, + 8458, 8467, + 8469, 8469, + 8473, 8477, + 8484, 8484, + 8486, 8486, + 8488, 8488, + 8490, 8493, + 8495, 8505, + 8508, 8511, + 8517, 8521, + 8526, 8526, + 8528, 8585, + 9312, 9371, + 9398, 9471, + 10102, 10131, + 11264, 11492, + 11499, 11502, + 11506, 11507, + 11517, 11517, + 11520, 11557, + 11559, 11559, + 11565, 11565, + 11568, 11623, + 11631, 11631, + 11648, 11670, + 11680, 11686, + 11688, 11694, + 11696, 11702, + 11704, 11710, + 11712, 11718, + 11720, 11726, + 11728, 11734, + 11736, 11742, + 11744, 11775, + 11823, 11823, + 12293, 12295, + 12321, 12329, + 12337, 12341, + 12344, 12348, + 12353, 12438, + 12445, 12447, + 12449, 12538, + 12540, 12543, + 12549, 12591, + 12593, 12686, + 12690, 12693, + 12704, 12735, + 12784, 12799, + 12832, 12841, + 12872, 12879, + 12881, 12895, + 12928, 12937, + 12977, 12991, + 13312, 19903, + 19968, 42124, + 42192, 42237, + 42240, 42508, + 42512, 42539, + 42560, 42606, + 42612, 42619, + 42623, 42735, + 42775, 42783, + 42786, 42888, + 42891, 42972, + 42993, 43013, + 43015, 43047, + 43056, 43061, + 43072, 43123, + 43136, 43203, + 43205, 43205, + 43216, 43225, + 43250, 43255, + 43259, 43259, + 43261, 43306, + 43312, 43346, + 43360, 43388, + 43392, 43442, + 43444, 43455, + 43471, 43481, + 43488, 43518, + 43520, 43574, + 43584, 43597, + 43600, 43609, + 43616, 43638, + 43642, 43710, + 43712, 43712, + 43714, 43714, + 43739, 43741, + 43744, 43759, + 43762, 43765, + 43777, 43782, + 43785, 43790, + 43793, 43798, + 43808, 43814, + 43816, 43822, + 43824, 43866, + 43868, 43881, + 43888, 44010, + 44016, 44025, + 44032, 55203, + 55216, 55238, + 55243, 55291, + 63744, 64109, + 64112, 64217, + 64256, 64262, + 64275, 64279, + 64285, 64296, + 64298, 64310, + 64312, 64316, + 64318, 64318, + 64320, 64321, + 64323, 64324, + 64326, 64433, + 64467, 64829, + 64848, 64911, + 64914, 64967, + 65008, 65019, + 65136, 65140, + 65142, 65276, + 65296, 65305, + 65313, 65338, + 65345, 65370, + 65382, 65470, + 65474, 65479, + 65482, 65487, + 65490, 65495, + 65498, 65500, + 65536, 65547, + 65549, 65574, + 65576, 65594, + 65596, 65597, + 65599, 65613, + 65616, 65629, + 65664, 65786, + 65799, 65843, + 65856, 65912, + 65930, 65931, + 66176, 66204, + 66208, 66256, + 66273, 66299, + 66304, 66339, + 66349, 66378, + 66384, 66426, + 66432, 66461, + 66464, 66499, + 66504, 66511, + 66513, 66517, + 66560, 66717, + 66720, 66729, + 66736, 66771, + 66776, 66811, + 66816, 66855, + 66864, 66915, + 66928, 66938, + 66940, 66954, + 66956, 66962, + 66964, 66965, + 66967, 66977, + 66979, 66993, + 66995, 67001, + 67003, 67004, + 67008, 67059, + 67072, 67382, + 67392, 67413, + 67424, 67431, + 67456, 67461, + 67463, 67504, + 67506, 67514, + 67584, 67589, + 67592, 67592, + 67594, 67637, + 67639, 67640, + 67644, 67644, + 67647, 67669, + 67672, 67702, + 67705, 67742, + 67751, 67759, + 67808, 67826, + 67828, 67829, + 67835, 67867, + 67872, 67897, + 67904, 67929, + 67968, 68023, + 68028, 68047, + 68050, 68099, + 68101, 68102, + 68108, 68115, + 68117, 68119, + 68121, 68149, + 68160, 68168, + 68192, 68222, + 68224, 68255, + 68288, 68295, + 68297, 68324, + 68331, 68335, + 68352, 68405, + 68416, 68437, + 68440, 68466, + 68472, 68497, + 68521, 68527, + 68608, 68680, + 68736, 68786, + 68800, 68850, + 68858, 68903, + 68912, 68921, + 68928, 68965, + 68969, 68969, + 68975, 68997, + 69216, 69246, + 69248, 69289, + 69291, 69292, + 69296, 69297, + 69314, 69319, + 69370, 69372, + 69376, 69415, + 69424, 69445, + 69457, 69460, + 69488, 69505, + 69552, 69579, + 69600, 69622, + 69632, 69701, + 69714, 69743, + 69745, 69749, + 69760, 69816, + 69826, 69826, + 69840, 69864, + 69872, 69881, + 69888, 69938, + 69942, 69951, + 69956, 69959, + 69968, 70002, + 70006, 70006, + 70016, 70079, + 70081, 70084, + 70094, 70106, + 70108, 70108, + 70113, 70132, + 70144, 70161, + 70163, 70196, + 70199, 70199, + 70206, 70209, + 70272, 70278, + 70280, 70280, + 70282, 70285, + 70287, 70301, + 70303, 70312, + 70320, 70376, + 70384, 70393, + 70400, 70403, + 70405, 70412, + 70415, 70416, + 70419, 70440, + 70442, 70448, + 70450, 70451, + 70453, 70457, + 70461, 70468, + 70471, 70472, + 70475, 70476, + 70480, 70480, + 70487, 70487, + 70493, 70499, + 70528, 70537, + 70539, 70539, + 70542, 70542, + 70544, 70581, + 70583, 70592, + 70594, 70594, + 70597, 70597, + 70599, 70602, + 70604, 70605, + 70609, 70609, + 70611, 70611, + 70656, 70721, + 70723, 70725, + 70727, 70730, + 70736, 70745, + 70751, 70753, + 70784, 70849, + 70852, 70853, + 70855, 70855, + 70864, 70873, + 71040, 71093, + 71096, 71102, + 71128, 71133, + 71168, 71230, + 71232, 71232, + 71236, 71236, + 71248, 71257, + 71296, 71349, + 71352, 71352, + 71360, 71369, + 71376, 71395, + 71424, 71450, + 71453, 71466, + 71472, 71483, + 71488, 71494, + 71680, 71736, + 71840, 71922, + 71935, 71942, + 71945, 71945, + 71948, 71955, + 71957, 71958, + 71960, 71989, + 71991, 71992, + 71995, 71996, + 71999, 72002, + 72016, 72025, + 72096, 72103, + 72106, 72151, + 72154, 72159, + 72161, 72161, + 72163, 72164, + 72192, 72242, + 72245, 72254, + 72272, 72343, + 72349, 72349, + 72368, 72440, + 72544, 72551, + 72640, 72672, + 72688, 72697, + 72704, 72712, + 72714, 72758, + 72760, 72766, + 72768, 72768, + 72784, 72812, + 72818, 72847, + 72850, 72871, + 72873, 72886, + 72960, 72966, + 72968, 72969, + 72971, 73014, + 73018, 73018, + 73020, 73021, + 73023, 73025, + 73027, 73027, + 73030, 73031, + 73040, 73049, + 73056, 73061, + 73063, 73064, + 73066, 73102, + 73104, 73105, + 73107, 73110, + 73112, 73112, + 73120, 73129, + 73136, 73179, + 73184, 73193, + 73440, 73462, + 73472, 73488, + 73490, 73530, + 73534, 73536, + 73552, 73561, + 73648, 73648, + 73664, 73684, + 73728, 74649, + 74752, 74862, + 74880, 75075, + 77712, 77808, + 77824, 78895, + 78913, 78918, + 78944, 82938, + 82944, 83526, + 90368, 90414, + 90416, 90425, + 92160, 92728, + 92736, 92766, + 92768, 92777, + 92784, 92862, + 92864, 92873, + 92880, 92909, + 92928, 92975, + 92992, 92995, + 93008, 93017, + 93019, 93025, + 93027, 93047, + 93053, 93071, + 93504, 93548, + 93552, 93561, + 93760, 93846, + 93856, 93880, + 93883, 93907, + 93952, 94026, + 94031, 94087, + 94095, 94111, + 94176, 94177, + 94179, 94179, + 94192, 94198, + 94208, 101589, + 101631, 101662, + 101760, 101874, + 110576, 110579, + 110581, 110587, + 110589, 110590, + 110592, 110882, + 110898, 110898, + 110928, 110930, + 110933, 110933, + 110948, 110951, + 110960, 111355, + 113664, 113770, + 113776, 113788, + 113792, 113800, + 113808, 113817, + 113822, 113822, + 118000, 118009, + 119488, 119507, + 119520, 119539, + 119648, 119672, + 119808, 119892, + 119894, 119964, + 119966, 119967, + 119970, 119970, + 119973, 119974, + 119977, 119980, + 119982, 119993, + 119995, 119995, + 119997, 120003, + 120005, 120069, + 120071, 120074, + 120077, 120084, + 120086, 120092, + 120094, 120121, + 120123, 120126, + 120128, 120132, + 120134, 120134, + 120138, 120144, + 120146, 120485, + 120488, 120512, + 120514, 120538, + 120540, 120570, + 120572, 120596, + 120598, 120628, + 120630, 120654, + 120656, 120686, + 120688, 120712, + 120714, 120744, + 120746, 120770, + 120772, 120779, + 120782, 120831, + 122624, 122654, + 122661, 122666, + 122880, 122886, + 122888, 122904, + 122907, 122913, + 122915, 122916, + 122918, 122922, + 122928, 122989, + 123023, 123023, + 123136, 123180, + 123191, 123197, + 123200, 123209, + 123214, 123214, + 123536, 123565, + 123584, 123627, + 123632, 123641, + 124112, 124139, + 124144, 124153, + 124368, 124397, + 124400, 124410, + 124608, 124638, + 124640, 124661, + 124670, 124671, + 124896, 124902, + 124904, 124907, + 124909, 124910, + 124912, 124926, + 124928, 125124, + 125127, 125135, + 125184, 125251, + 125255, 125255, + 125259, 125259, + 125264, 125273, + 126065, 126123, + 126125, 126127, + 126129, 126132, + 126209, 126253, + 126255, 126269, + 126464, 126467, + 126469, 126495, + 126497, 126498, + 126500, 126500, + 126503, 126503, + 126505, 126514, + 126516, 126519, + 126521, 126521, + 126523, 126523, + 126530, 126530, + 126535, 126535, + 126537, 126537, + 126539, 126539, + 126541, 126543, + 126545, 126546, + 126548, 126548, + 126551, 126551, + 126553, 126553, + 126555, 126555, + 126557, 126557, + 126559, 126559, + 126561, 126562, + 126564, 126564, + 126567, 126570, + 126572, 126578, + 126580, 126583, + 126585, 126588, + 126590, 126590, + 126592, 126601, + 126603, 126619, + 126625, 126627, + 126629, 126633, + 126635, 126651, + 127232, 127244, + 127280, 127305, + 127312, 127337, + 127344, 127369, + 130032, 130041, + 131072, 173791, + 173824, 178205, + 178208, 183981, + 183984, 191456, + 191472, 192093, + 194560, 195101, + 196608, 201546, + 201552, 210041 +]; + +export(c) fun asm_unicode_alphanumeric(cp: u64) -> bool { + var low: u64 = 0; + var high: u64 = 844; + while (low < high) { + var middle: u64 = low + (high - low) / 2; + if (cp < ASM_ALPHANUMERIC[middle * 2] as u64) { + high = middle; + } else if (cp > ASM_ALPHANUMERIC[middle * 2 + 1] as u64) { + low = middle + 1; + } else { + return true; + } + } + return false; +} diff --git a/meson.build b/meson.build index 7e08640..74a7467 100644 --- a/meson.build +++ b/meson.build @@ -37,7 +37,14 @@ elif not fs.is_absolute(wave_cache) endif asmobj_directory = get_option('asmobj-dir') wave_bootstrap = [] -if asmobj_directory == '' or (wave_source != '' and get_option('wave-ir-dir') == '') +needs_wave_bootstrap = asmobj_directory == '' +if wave_source != '' + needs_wave_bootstrap = needs_wave_bootstrap or get_option('wave-ir-dir') == '' or get_option('wave-assembler-dir') == '' + if get_option('asm-amd64') + needs_wave_bootstrap = needs_wave_bootstrap or get_option('wave-amd64-dir') == '' + endif +endif +if needs_wave_bootstrap if wave_source == '' or not fs.is_absolute(wave_source) or not fs.is_dir(wave_source) error('Supply -Dwave-source=/absolute/Wave or -Dasmobj-dir=/absolute/built/module.') endif @@ -53,7 +60,7 @@ if asmobj_directory == '' or (wave_source != '' and get_option('wave-ir-dir') == command: [python, bridge, bootstrap_arguments], depend_files: files('tools/wave_bootstrap.py', 'tools/meson_cargo.py'), console: true) endif -subdir('assembler/asmobj') +subdir('assembler') subdir('ir') profile = 'dev' @@ -89,6 +96,12 @@ build_arguments += ['--asmobj-dir', asmobj_directory] if wave_ir_directory != '' build_arguments += ['--wave-ir-dir', wave_ir_directory] endif +if wave_assembler_directory != '' + build_arguments += ['--wave-assembler-dir', wave_assembler_directory] +endif +if wave_amd64_directory != '' + build_arguments += ['--wave-amd64-dir', wave_amd64_directory] +endif foreach feature : selected_features build_arguments += ['--feature', feature] endforeach @@ -98,7 +111,7 @@ whale = custom_target('whale-cli', command: [python, bridge, build_arguments], depend_files: files('Cargo.toml', 'Cargo.lock', 'tools/meson_cargo.py'), depfile: 'whale-cargo.d', - depends: asmobj_dependencies + wave_ir_dependencies, + depends: asmobj_dependencies + wave_ir_dependencies + wave_assembler_all_dependencies, build_by_default: true, console: true, install: true, diff --git a/meson.options b/meson.options index f4b4f17..ff8149f 100644 --- a/meson.options +++ b/meson.options @@ -13,6 +13,10 @@ option('asmobj-dir', type: 'string', value: '', description: 'Absolute directory of the complete prebuilt Wave asmobj module for the executable host') option('wave-ir-dir', type: 'string', value: '', description: 'Absolute directory of a prebuilt internal Wave IR module; source builds use the pinned compiler') +option('wave-assembler-dir', type: 'string', value: '', + description: 'Absolute directory of the shared Wave assembler archive for the executable host') +option('wave-amd64-dir', type: 'string', value: '', + description: 'Absolute directory of the Wave AMD64 parser/encoder archive for the executable host') option('wave-source', type: 'string', value: '', description: 'Read-only Wave Git checkout containing the pinned bootstrap revision') option('wave-bootstrap-dir', type: 'string', value: '', diff --git a/tools/build_wave_assembler.py b/tools/build_wave_assembler.py new file mode 100644 index 0000000..f16ea14 --- /dev/null +++ b/tools/build_wave_assembler.py @@ -0,0 +1,193 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Build the explicit shared or AMD64 Wave assembler module with the pinned compiler, without editing Wave.""" + +import argparse +import hashlib +import json +import os +from pathlib import Path +import tempfile + +from wave_bootstrap import (DEFAULT_RUST_TOOLCHAIN, RUST_VERSION, WAVE_REVISION, + digest, ensure_bootstrap, run) + + +MODULES = { + 'common': { + 'sources': ( + 'assembler/model.wave', + 'assembler/unicode.wave', + 'assembler/numeric.wave', + 'assembler/output.wave', + 'assembler/lexer.wave', + ), + 'abi': ( + 'assembler/src/tokens.rs', + 'assembler/src/tokens_wave.rs', + ), + 'name': 'assembler', + }, + 'amd64': { + 'sources': ( + 'assembler/model.wave', + 'assembler/declarations.wave', + 'assembler/ast_model.wave', + 'assembler/amd64/parser_model.wave', + 'assembler/amd64/registers.wave', + 'assembler/amd64/expressions.wave', + 'assembler/amd64/operands.wave', + 'assembler/amd64/directives.wave', + 'assembler/amd64/parser.wave', + 'assembler/amd64/encoder_model.wave', + 'assembler/amd64/namespace.wave', + 'assembler/amd64/layout.wave', + 'assembler/amd64/address.wave', + 'assembler/amd64/emit.wave', + 'assembler/amd64/integer.wave', + 'assembler/amd64/sse.wave', + 'assembler/amd64/branch.wave', + 'assembler/amd64/directives_encode.wave', + 'assembler/amd64/encoder.wave', + ), + 'abi': ( + 'assembler/amd64/src/ast_model.rs', + 'assembler/amd64/src/parser_wave.rs', + 'assembler/amd64/src/encoder_wave.rs', + 'assembler/amd64/src/encoder_namespace_errors.rs', + 'assembler/amd64/src/tables.rs', + 'assembler/amd64/src/encoder.rs', + 'assembler/amd64/src/encoding/address.rs', + 'assembler/amd64/src/encoding/modrm.rs', + 'assembler/amd64/src/encoding/rex.rs', + 'assembler/amd64/src/encoding/sib.rs', + ), + 'name': 'amd64', + }, +} +TARGETS = ( + 'x86_64-unknown-linux-gnu', + 'aarch64-unknown-linux-gnu', + 'riscv64gc-unknown-linux-gnu', + 'x86_64-pc-windows-msvc', + 'aarch64-pc-windows-msvc', + 'x86_64-apple-darwin', + 'aarch64-apple-darwin', +) + + +def fnv64(data): + value = 0xcbf29ce484222325 + for octet in data: + value = ((value ^ octet) * 0x100000001b3) & 0xffffffffffffffff + return f"{value:016x}" + + +def source_bytes(root, module): + return b"\n".join((root / name).read_bytes() for name in MODULES[module]["sources"]) + + +def abi_bytes(root, module): + return b"\n".join((root / name).read_bytes() for name in MODULES[module]["abi"]) + + +def metadata(source, abi, archive, provenance, target, opt_level): + return (f"schema=1\ntarget={target}\nwave_revision={WAVE_REVISION}\n" + f"opt_level={opt_level}\nsource_fnv64={fnv64(source)}\n" + f"abi_fnv64={fnv64(abi)}\narchive_fnv64={fnv64(archive)}\n" + f"provenance_fnv64={fnv64(provenance)}\n") + + +def build(args): + root = Path(__file__).resolve().parents[1] + output = args.out_dir.resolve() + config = MODULES[args.module] + name = config["name"] + source = source_bytes(root, args.module) + abi = abi_bytes(root, args.module) + wave_source = args.wave_source.resolve() + if output == wave_source or output.is_relative_to(wave_source): + raise ValueError("Wave assembler output must be outside the read-only Wave checkout") + output.mkdir(parents=True, exist_ok=True) + bootstrap = ensure_bootstrap(wave_source, args.bootstrap_dir or output / "bootstrap-cache", + rust_toolchain=args.rust_toolchain, + allow_network=args.allow_network) + wave_target = args.target.replace("riscv64gc-", "riscv64-") + environment = os.environ.copy() + environment["WAVE_STD_REVISION"] = WAVE_REVISION + with tempfile.TemporaryDirectory(prefix=".wave-assembler-", dir=output) as temporary: + temporary = Path(temporary) + kernel = temporary / "assembler.wave" + kernel.write_bytes(source) + obj = temporary / "assembler.o" + run([bootstrap.compiler, "-O" + args.opt_level, "-C", "relocation-model=pic", + "--std-root", bootstrap.std_root, "--target=" + wave_target, "build", kernel, + "--freestanding", "--emit=obj", "-o", obj, "--target-dir", temporary / "build"], + cwd=temporary, env=environment) + archive_name = (f"whale_wave_{name}.lib" if "msvc" in args.target + else f"libwhale_wave_{name}.a") + archive = temporary / archive_name + archive_format = ("darwin" if "apple-darwin" in args.target else + "coff" if "msvc" in args.target else None) + archiver = [environment.get("AR", "ar")] + if archive_format: + archiver.append("--format=" + archive_format) + run([*archiver, "crsD", archive, obj]) + provenance = temporary / "provenance.json" + provenance.write_text(json.dumps({ + "wave_revision": WAVE_REVISION, "target": args.target, "module": args.module, + "opt_level": args.opt_level, + "source_sha256": hashlib.sha256(source).hexdigest(), + "abi_sha256": hashlib.sha256(abi).hexdigest(), + "archive_sha256": digest(archive), + "compiler_sha256": digest(bootstrap.compiler), + "std_sha256": bootstrap.metadata["std_sha256"], + "bootstrap_rust_version": RUST_VERSION, + "required_llvm_major": 21, + "bootstrap_provenance": str(bootstrap.provenance), + }, indent=2) + "\n") + fingerprint = temporary / f"wave-{name}.meta" + fingerprint.write_text(metadata(source, abi, archive.read_bytes(), + provenance.read_bytes(), args.target, args.opt_level)) + staged = (archive, provenance, fingerprint) + previous = {} + for path in staged: + destination = output / path.name + if destination.exists(): + backup = temporary / (path.name + ".previous") + os.link(destination, backup) + previous[destination] = backup + published = [] + try: + for path in staged: + destination = output / path.name + os.replace(path, destination) + published.append(destination) + except OSError: + for destination in reversed(published): + backup = previous.get(destination) + if backup is None: + destination.unlink() + else: + os.replace(backup, destination) + raise + return output + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--module", choices=tuple(MODULES), default="common") + parser.add_argument("--wave-source", type=Path, required=True) + parser.add_argument("--out-dir", type=Path, required=True) + parser.add_argument("--bootstrap-dir", type=Path) + parser.add_argument("--rust-toolchain", default=DEFAULT_RUST_TOOLCHAIN) + parser.add_argument("--target", choices=TARGETS, default=TARGETS[0]) + parser.add_argument("--opt-level", choices=("0", "2"), default="2") + parser.add_argument("--allow-network", action="store_true") + args = parser.parse_args() + name = MODULES[args.module]["name"].upper() + print(f"WHALE_WAVE_{name}_DIR={build(args)}") + + +if __name__ == "__main__": + main() diff --git a/tools/check_wave_amd64_cli.py b/tools/check_wave_amd64_cli.py new file mode 100644 index 0000000..19b1935 --- /dev/null +++ b/tools/check_wave_amd64_cli.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Compare AMD64 CLI encodings with NASM and execute static Linux fixtures.""" + +import argparse +import hashlib +import json +from pathlib import Path +import platform +import random +import shutil +import struct +import subprocess + + +def run(command, *, expected=0): + result = subprocess.run(list(map(str, command)), capture_output=True, timeout=30) + if result.returncode != expected: + raise ValueError(f"command failed: {command!r}: {result.stderr.decode(errors='replace')}") + return result + + +def text_section(path): + data = path.read_bytes() + if data[:6] != b"\x7fELF\x02\x01": + raise ValueError("oracle requires ELF64 little endian") + offset, = struct.unpack_from("= count or offset + width * count > len(data): + raise ValueError("invalid oracle section table") + sections = [struct.unpack_from(" len(data): + raise ValueError("truncated oracle text section") + return data[at:at + size] + raise ValueError("oracle has no text section") + + +def instructions(seed, count): + randomizer = random.Random(seed) + gprs = ("rax", "rcx", "rdx", "rbx", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", "rsp", "rbp") + for _ in range(count): + kind = randomizer.randrange(4) + base = randomizer.choice(gprs) + if kind == 0: + yield f"{randomizer.choice(('not', 'neg', 'div', 'idiv'))} {base}" + elif kind == 1: + index = randomizer.choice(tuple(reg for reg in gprs if reg != "rsp")) + scale = randomizer.choice((2, 4, 8)) + displacement = randomizer.choice((-129, -128, 1, 127, 128, 65536)) + yield f"lea {randomizer.choice(gprs)},[{base}+{index}*{scale}{displacement:+d}]" + elif kind == 2: + op = randomizer.choice(("movss", "movsd", "addss", "addsd", "subss", "subsd", + "mulss", "mulsd", "divss", "divsd")) + yield f"{op} xmm{randomizer.randrange(16)},xmm{randomizer.randrange(16)}" + else: + op = randomizer.choice(("movss", "movsd", "addss", "addsd", "subss", "subsd")) + yield f"{op} xmm{randomizer.randrange(16)},[{base}+16]" + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--binary", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--cases", type=int, default=2000) + parser.add_argument("--seed", type=int, default=0x357356) + parser.add_argument("--nasm", default="nasm") + args = parser.parse_args() + if not 1 <= args.cases <= 100000: + parser.error("--cases must be between 1 and 100000") + if platform.system() != "Linux" or platform.machine() != "x86_64": + parser.error("native static execution requires Linux x86_64") + nasm = shutil.which(args.nasm) + if nasm is None: + parser.error("NASM is required for the independent oracle") + binary = args.binary.resolve(strict=True) + output = args.output_dir.resolve() + output.mkdir(parents=True, exist_ok=True) + source = output / "vectors.asm" + source.write_text("section .text\n" + "\n".join(instructions(args.seed, args.cases)) + "\n") + whale_object, oracle_object = output / "whale.o", output / "nasm.o" + run([binary, "asm", "--amd64", source, "-o", whale_object]) + run([nasm, "-O0", "-f", "elf64", source, "-o", oracle_object]) + actual, expected = text_section(whale_object), text_section(oracle_object) + (output / "whale.text").write_bytes(actual) + (output / "nasm.text").write_bytes(expected) + if actual != expected: + first = next((i for i, pair in enumerate(zip(actual, expected)) if pair[0] != pair[1]), + min(len(actual), len(expected))) + raise ValueError(f"NASM encoding divergence at byte {first}; evidence retained in {output}") + + sources = { + "leaf": "section .text\nglobal _start\n_start: mov edi,42\nmov eax,60\nsyscall\n", + "start": ("section .text\nglobal _start\nextern helper\nextern payload\n" + "_start: lea rsi,[rel payload]\nmov eax,[rsi]\ncall helper\n" + "mov edi,eax\nmov eax,60\nsyscall\n"), + "helper": ("section .text\nglobal helper\nhelper: ret\nsection .data\n" + "global payload\npayload: dd 42\nsection .bss\nresb 64\n"), + } + objects = {} + for name, contents in sources.items(): + source = output / (name + ".asm") + source.write_text(contents) + objects[name] = output / (name + ".o") + run([binary, "asm", "--amd64", source, "-o", objects[name]]) + for name, inputs in (("leaf", [objects["leaf"]]), ("cross-object", [objects["start"], objects["helper"]])): + executable = output / name + run([binary, "link", *inputs, "-o", executable]) + run([executable], expected=42) + report = {"seed": args.seed, "instructions": args.cases, "bytes": len(actual), + "text_sha256": hashlib.sha256(actual).hexdigest(), + "binary_sha256": hashlib.sha256(binary.read_bytes()).hexdigest(), + "nasm": run([nasm, "-v"]).stdout.decode().strip(), + "leaf_exit": 42, "cross_object_exit": 42} + (output / "report.json").write_text(json.dumps(report, indent=2) + "\n") + print(f"NASM: {args.cases} AMD64 integer/address/SSE encodings; leaf/cross-object exit 42") + + +if __name__ == "__main__": + main() diff --git a/tools/check_wave_amd64_layout.py b/tools/check_wave_amd64_layout.py new file mode 100644 index 0000000..d9ffd3f --- /dev/null +++ b/tools/check_wave_amd64_layout.py @@ -0,0 +1,187 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Independent scoped constant, sparse layout and relaxation packet regressions.""" +import argparse +import ctypes as C +from pathlib import Path +import random +import re + +U = C.c_uint64 +NONE = (1 << 64) - 1 +ROOT = Path(__file__).resolve().parents[1] +TYPES = {'u64': U, 'i64': C.c_int64, 'u8': C.c_uint8, 'bool': C.c_bool} +for filename in ['assembler/model.wave', 'assembler/ast_model.wave', + 'assembler/amd64/encoder_model.wave']: + for name, body in re.findall(r'struct (\w+)\s*\{([^}]+)\}', (ROOT / filename).read_text()): + if name in TYPES: + continue + fields = [] + for field, kind in re.findall(r'(\w+):\s*([^;]+);', body): + pointer = re.fullmatch(r'ptr<(.+)>', kind) + fields.append((field, C.POINTER(TYPES[pointer[1]]) if pointer else TYPES[kind])) + TYPES[name] = type(name, (C.Structure,), {'_fields_': fields}) +Name, Expr, Item, Value, Operand, Input, Result = [TYPES[name] for name in + ['AsmName', 'AsmExpr', 'AsmItem', 'AsmDirectiveValue', 'AsmOperand', + 'AmdEncodeInput', 'AmdEncodeResult']] + + +class Packet: + def __init__(self): + self.names, self.items, self.values, self.operands, self.keep = [], [], [], [], [] + + def name(self, text): + encoded = text.encode() + data = (C.c_uint8 * len(encoded)).from_buffer_copy(encoded) + self.keep.append(data) + self.names.append(Name(data, len(encoded))) + return len(self.names) - 1 + + def number(self, value): + return Expr(kind=0, low=value & NONE, high=(value >> 64) & NONE) + + def symbol(self, name, addend=0): + return Expr(kind=1, name=self.name(name), low=addend & NONE, high=(addend >> 64) & NONE) + + def item(self, kind, name, **kwargs): + self.items.append(Item(kind=kind, name=self.name(name), **kwargs)) + + def const(self, name, value): + self.item(8, name, expression=value) + + def directive(self, name, values): + first = len(self.values) + self.values.extend(Value(kind=0, expression=value) for value in values) + self.item(2, name, first=first, count=len(values)) + + def instruction(self, name, label=None): + first = len(self.operands) + if label is not None: + self.operands.append(Operand(kind=2, name=self.name(label))) + self.item(0, name, first=first, count=len(self.operands)-first) + + def run(self, kernel, limit=1 << 20, iterations=1024): + capacity = len(self.names) + len(self.items) + len(self.operands) + len(self.values) + 1 + table_capacity = 1 << (capacity * 2 - 1).bit_length() + p = Input(max_output=limit, max_iterations=iterations, max_work=10000000) + arrays = {} + for field, kind, values in [ + ('names', Name, self.names), ('items', Item, self.items), + ('operands', Operand, self.operands), ('values', Value, self.values), + ('sections', TYPES['AmdSection'], [TYPES['AmdSection']() for _ in range(len(self.items)+1)]), + ('symbols', TYPES['AmdSymbol'], [TYPES['AmdSymbol']() for _ in range(capacity)]), + ('table', U, [0] * table_capacity), ('nodes', TYPES['AmdNode'], + [TYPES['AmdNode']() for _ in self.items]), + ('queue', U, [0] * capacity), ('relocations', TYPES['AmdRelocation'], + [TYPES['AmdRelocation']() for _ in range(len(self.items)+len(self.values)+1)]), + ]: + array = (kind * len(values))(*values) + arrays[field] = array + setattr(p, field, array) + p.name_count, p.item_count = len(self.names), len(self.items) + p.operand_count, p.value_count = len(self.operands), len(self.values) + p.section_capacity, p.symbol_capacity = len(arrays['sections']), capacity + p.table_capacity, p.relocation_capacity = table_capacity, len(arrays['relocations']) + result = Result() + code = kernel(C.byref(p), 0, C.byref(result)) + assert code == result.status and result.work <= p.max_work + if code: + return result, arrays, b'' + before = result.bytes + data = (C.c_uint8 * before)() + p.bytes, p.byte_capacity = data, before + code = kernel(C.byref(p), 1, C.byref(result)) + assert code == result.status == 0, (result.error, result.node, result.argument) + assert result.bytes == before and result.work <= p.max_work + return result, arrays, bytes(data) + + +def fixed(kernel): + p = Packet() + p.item(4, '.text') + p.instruction('nop') + r, a, data = p.run(kernel) + assert r.section_count == 1 and data == b'\x90' + p = Packet() + p.item(3, 'main') + p.item(3, '.again') + p.instruction('loop', '.again') + r, a, data = p.run(kernel) + assert data == b'\xe2\xfe' and r.relocation_count == 0 + p = Packet() + p.instruction('jmp', 'end') + p.directive('resb', [p.number(127)]) + p.item(3, 'end') + p.instruction('ret') + r, a, data = p.run(kernel) + assert data == b'\xeb\x7f' + b'\0' * 127 + b'\xc3', data[:8] + p = Packet() + p.item(4, '.bss') + p.directive('resb', [p.number(1 << 40)]) + p.directive('align', [p.number(1 << 41)]) + p.item(3, 'end') + r, a, data = p.run(kernel, limit=0) + assert data == b'' and a['sections'][1].zero_fill == 1 << 41 + for make, error in [ + (lambda p: (p.const('A', p.number(1)), p.const('A', p.number(2))), 101), + (lambda p: (p.const('A', p.symbol('B')), p.const('B', p.symbol('A'))), 105), + (lambda p: (p.const('A', p.number(1)), p.item(3, 'A')), 102), + (lambda p: p.item(3, '.orphan'), 100), + (lambda p: p.directive('db', [p.number(256)]), 167), + (lambda p: p.item(6, 'missing'), 113), + ]: + p = Packet() + make(p) + r, _, _ = p.run(kernel) + assert r.status and r.error == error, (error, r.status, r.error) + p = Packet() + p.item(7, 'external') + p.item(7, 'external') + r, a, _ = p.run(kernel) + assert r.output_symbols == 1 + output = [s for s in a['symbols'][:r.symbol_count] if s.flags & 6] + assert len(output) == 1 and output[0].flags & 1 and output[0].order == 0 + # These scale independently of native call-stack depth and exercise worklists. + p = Packet() + p.const('C0', p.number(1)) + for index in range(1, 5000): + p.const(f'C{index}', p.symbol(f'C{index-1}', 1)) + p.directive('dq', [p.symbol('C4999')]) + r, _, data = p.run(kernel) + assert data == (5000).to_bytes(8, 'little') + p = Packet() + for _ in range(65000): + p.instruction('nop') + r, _, data = p.run(kernel) + assert data == b'\x90' * 65000 + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--library', type=Path, required=True) + parser.add_argument('--cases', type=int, default=2000) + args = parser.parse_args() + kernel = C.CDLL(str(args.library.resolve())).whale_amd64_encode + kernel.argtypes = [C.POINTER(Input), U, C.POINTER(Result)] + fixed(kernel) + rng = random.Random(0x5748414C454C4159) + for _ in range(args.cases): + p = Packet() + expected = [] + parents = rng.randrange(1, 20) + for n in range(parents): + p.item(3, f'parent{n}') + p.const('.A', p.number(rng.randrange(128))) + p.const('.B', p.symbol('.A', 1)) + p.directive('db', [p.symbol('.B')]) + expected.append(p.items[-3].expression.low + 1) + p.item(3, '.end') + r, a, data = p.run(kernel) + assert data == bytes(expected) + assert r.output_symbols == parents * 2 + assert [s.order for s in a['symbols'][:r.symbol_count] if s.flags & 6] == list(range(parents*2)) + print(f'Wave AMD64 layout: {args.cases} independent scoped constant/section packets + branch relaxation, LOOP, sparse BSS, identity and failure regressions passed') + + +if __name__ == '__main__': + main() diff --git a/tools/check_wave_amd64_parser.py b/tools/check_wave_amd64_parser.py new file mode 100644 index 0000000..4530105 --- /dev/null +++ b/tools/check_wave_amd64_parser.py @@ -0,0 +1,191 @@ +#!/usr/bin/env python3 +"""Check the actual Wave AMD64 grammar ABI with independent bounded fixtures.""" +import argparse +import ctypes as c +import json +import random + +U = c.c_uint64 +P = c.c_void_p +MISSING = (1 << 64) - 1 +MIN128 = -(1 << 127) +MAX128 = (1 << 127) - 1 + + +class Name(c.Structure): + _fields_ = [("bytes", P), ("count", U)] + + +class Expr(c.Structure): + _fields_ = [(field, U) for field in ("kind", "name", "low", "high")] + + +class Operand(c.Structure): + _fields_ = [(field, U) for field in ( + "kind", "name", "low", "high", "mode", "width", "base", "index", "scale", "disp", "symbol")] + + +class Item(c.Structure): + _fields_ = [(field, U) for field in ("kind", "name", "aux", "flags")] + _fields_ += [("expression", Expr), ("first", U), ("count", U)] + + +class Directive(c.Structure): + _fields_ = [("kind", U), ("expression", Expr), ("bytes", P), ("count", U)] + + +class Token(c.Structure): + _fields_ = [("kind", U), ("position", U), ("end", U), ("text", Name), ("low", U), ("high", U)] + + +class Span(c.Structure): + _fields_ = [("start", U), ("end", U)] + + +class Input(c.Structure): + _fields_ = [("tokens", P), ("count", U), ("mode", U), ("max_work", U)] + + +class Output(c.Structure): + _fields_ = [(field, ty) for name in ("item", "span", "operand", "value", "name", "byte") + for field, ty in ((name + "s", P), (name + "_capacity", U))] + + +class Result(c.Structure): + _fields_ = [(field, U) for field in ( + "status", "error", "index", "detail", "items", "operands", "values", "names", "bytes", "work")] + + +PUNCTUATION = {",": 3, ":": 4, "[": 5, "]": 6, "+": 7, "-": 8, "*": 9, "/": 10, "\n": 11} + + +def signed(low, high): + value = low | (high << 64) + return value - (1 << 128) if high >> 63 else value + + +class Packet: + def __init__(self, library, atoms): + self.buffers = [] + self.tokens = (Token * len(atoms))() + position = 0 + payload = 0 + for token, atom in zip(self.tokens, atoms): + token.position = position + spelling = str(atom).encode("utf-8") + position += len(spelling) + token.end = position + position += 1 + if isinstance(atom, int): + token.kind = 1 + bits = atom & ((1 << 128) - 1) + token.low = bits & MISSING + token.high = bits >> 64 + elif atom in PUNCTUATION: + token.kind = PUNCTUATION[atom] + else: + token.kind = 0 + buffer = c.create_string_buffer(spelling) + self.buffers.append(buffer) + token.text = Name(c.addressof(buffer), len(spelling)) + payload += len(spelling) + self.input = Input(c.addressof(self.tokens), len(atoms), 0, 16 * (len(atoms) + payload + 1)) + self.result = Result() + empty = Output() + status = library.whale_amd64_parse(c.byref(self.input), c.byref(empty), c.byref(self.result)) + assert status == self.result.status, (status, self.result.status) + assert self.result.work <= self.input.max_work + if status: + assert status == 1, (status, atoms) + return + assert max(self.result.items, self.result.operands, self.result.values, self.result.names) <= len(atoms) + assert self.result.bytes <= payload + self.items = (Item * self.result.items)() + self.spans = (Span * self.result.items)() + self.operands = (Operand * self.result.operands)() + self.values = (Directive * self.result.values)() + self.names = (Name * self.result.names)() + self.bytes = (c.c_ubyte * self.result.bytes)() + output = Output( + c.addressof(self.items), len(self.items), c.addressof(self.spans), len(self.spans), + c.addressof(self.operands), len(self.operands), c.addressof(self.values), len(self.values), + c.addressof(self.names), len(self.names), c.addressof(self.bytes), len(self.bytes)) + published = Result() + self.input.mode = 1 + status = library.whale_amd64_parse(c.byref(self.input), c.byref(output), c.byref(published)) + assert status == 0 and tuple(getattr(published, field) for field, _ in Result._fields_) == tuple( + getattr(self.result, field) for field, _ in Result._fields_) + + def name(self, index): + name = self.names[index] + return c.string_at(name.bytes, name.count).decode("utf-8") + + +def check(library, cases): + library.whale_amd64_parse.argtypes = [c.POINTER(Input), c.POINTER(Output), c.POINTER(Result)] + library.whale_amd64_parse.restype = c.c_int + assert [c.sizeof(record) for record in (Name, Expr, Operand, Item, Directive, Token, Span, Input, Output, Result)] == [16, 32, 88, 80, 56, 56, 16, 32, 96, 80] + randomizer = random.Random(0x357_128) + integers = [MIN128, MIN128 + 1, -(1 << 63), -1, 0, 1, (1 << 64) - 1, MAX128] + for iteration in range(cases): + if iteration < 64: + a, b = randomizer.choice(integers), randomizer.choice(integers) + elif iteration % 3 == 0: + a, b = (randomizer.randrange(MIN128, MAX128 + 1) for _ in range(2)) + elif iteration % 3 == 1: + a, b = (randomizer.randrange(-(1 << 63), 1 << 64) for _ in range(2)) + else: + a = randomizer.randrange(MIN128 + (1 << 64), MAX128 - (1 << 64)) + b = -a + randomizer.randrange(-(1 << 63), 1 << 64) + packet = Packet(library, ["mov", a, "+", b]) + total = a + b + if not MIN128 <= total <= MAX128: + assert (packet.result.status, packet.result.error, packet.result.index) == (1, 28, 3) + elif not -(1 << 63) <= total <= (1 << 64) - 1: + assert (packet.result.status, packet.result.error, packet.result.index) == (1, 34, 3) + else: + assert packet.result.status == 0 and len(packet.items) == 1 + operand = packet.operands[0] + assert operand.kind == 1 and signed(operand.low, operand.high) == total + symbolic = Packet(library, ["mov", "Target", "+", a, "+", b]) + if MIN128 <= total <= MAX128: + assert symbolic.result.status == 0 + operand = symbolic.operands[0] + assert operand.kind == (2 if total == 0 else 3) + assert symbolic.name(operand.name) == "Target" + assert signed(operand.low, operand.high) == total + else: + assert (symbolic.result.status, symbolic.result.error, symbolic.result.index) == (1, 35, 5) + registers = ["rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi"] + [f"r{index}" for index in range(8, 16)] + memory_cases = 0 + for base in registers: + for index in registers: + for scale in (1, 2, 4, 8): + packet = Packet(library, ["MOV", "qword", "[", base.upper(), "+", index, "*", scale, "+", "Data", "-", 7, "]"]) + assert packet.result.status == 0 + memory = packet.operands[0] + assert memory.kind == 4 and memory.mode == 0 and memory.width == 64 + assert packet.name(memory.base) == base and packet.name(memory.index) == index + assert packet.name(memory.symbol) == "Data" and memory.scale == scale + assert memory.disp == (1 << 64) - 7 + memory_cases += 1 + malformed = Input(None, MISSING, 0, 1) + result = Result() + output = Output() + assert library.whale_amd64_parse(c.byref(malformed), c.byref(output), c.byref(result)) == 2 + assert result.status == 2 and result.error == 0 + return {"numeric_cases": cases * 2, "memory_cases": memory_cases, "malformed_spans": 1} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", required=True) + parser.add_argument("--cases", type=int, default=10000) + args = parser.parse_args() + if not 1 <= args.cases <= 100000: + parser.error("--cases must be between 1 and 100000") + print(json.dumps(check(c.CDLL(args.library), args.cases), sort_keys=True)) + + +if __name__ == "__main__": + main() diff --git a/tools/check_wave_assembler.py b/tools/check_wave_assembler.py new file mode 100644 index 0000000..17c3859 --- /dev/null +++ b/tools/check_wave_assembler.py @@ -0,0 +1,284 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Independent UTF-8 lexer and checked-number checks for native Wave assembly.""" +import argparse +import bisect +import ctypes as C +from pathlib import Path +import random +import re + +U = C.c_uint64 +MASK = (1 << 64) - 1 +MIN, MAX = -(1 << 127), (1 << 127) - 1 + + +class Token(C.Structure): + _fields_ = [(name, U) for name in + "kind start end line column end_line end_column decoded_start decoded_len low high".split()] + + +class Result(C.Structure): + _fields_ = [(name, U) for name in + "status reason start end line column detail tokens decoded work".split()] + + +class Wide(C.Structure): + _fields_ = [("low", U), ("high", U)] + + +def wide(value): + return Wide(value & MASK, (value >> 64) & MASK) + + +def integer(value): + bits = value.low | value.high << 64 + return bits - (1 << 128) if bits >> 127 else bits + + +text = (Path(__file__).resolve().parents[1] / "assembler/src/unicode_reference.rs").read_text() +RANGES = [(int(lo), int(hi)) for lo, hi in re.findall(r"\((\d+), (\d+)\)", text)] +STARTS = [lo for lo, _ in RANGES] + + +def alphanumeric(ch): + cp = ord(ch) + at = bisect.bisect_right(STARTS, cp) - 1 + return at >= 0 and cp <= RANGES[at][1] + + +class Syntax(Exception): + def __init__(self, reason, start, end, line, column, detail=0): + self.expected = (1, reason, start, end, line, column, detail) + + +def reference(source): + at, byte, line, column, cr = 0, 0, 1, 1, False + tokens, decoded = [], bytearray() + + def bump(): + nonlocal at, byte, line, column, cr + ch = source[at] + at += 1 + byte += len(ch.encode()) + if ch == '\r': + line, column, cr = line + 1, 1, True + elif ch == '\n': + line, column, cr = line + int(not cr), 1, False + else: + column, cr = column + 1, False + return ch + + def fail(reason, mark, detail=0, unconsumed=False): + start, ln, col = mark + end = byte if byte > start else byte + (len(source[at].encode()) if at < len(source) else 0) + if unconsumed: + end = byte + len(source[at].encode()) + raise Syntax(reason, start, end, ln, col, detail) + + while at < len(source): + ch = source[at] + mark = (byte, line, column) + if ch == ';': + while at < len(source) and source[at] not in '\r\n': + bump() + continue + if ch in ' \t': + bump() + continue + decoded_start = len(decoded) + number = 0 + if ch == '"': + kind = 2 + bump() + while True: + escape_mark = (byte, line, column) + if at == len(source): + fail(2, mark) + ch = bump() + if ch == '"': + break + if ch != '\\': + decoded.extend(ch.encode()) + continue + if at == len(source): + fail(3, escape_mark) + ch = bump() + if ch in {'"', '\\', 'n', 'r', 't', '0'}: + decoded.append({'"': 34, '\\': 92, 'n': 10, 'r': 13, 't': 9, '0': 0}[ch]) + elif ch == 'x': + value = 0 + for _ in range(2): + if at == len(source): + fail(4, escape_mark) + ch = bump() + if ch not in '0123456789abcdefABCDEF': + fail(5, escape_mark) + value = value * 16 + int(ch, 16) + decoded.append(value) + else: + fail(6, escape_mark) + elif ch in '0123456789': + kind, radix = 1, 10 + if source[at:at+2].lower() in ('0x', '0b'): + radix = 16 if source[at+1].lower() == 'x' else 2 + bump() + bump() + digits = at + alphabet = '0123456789abcdef'[:radix] if radix != 10 else '0123456789' + while at < len(source) and source[at].lower() in alphabet: + bump() + if at == digits: + fail(7 if radix == 16 else 8, mark) + number = int(source[digits:at], radix) + if number > MASK: + fail(9, mark) + elif ch in '_.' or alphanumeric(ch): + kind = 0 + while at < len(source) and (source[at] in '_.' or alphanumeric(source[at])): + bump() + else: + punctuation = {',': 3, ':': 4, '[': 5, ']': 6, '+': 7, '-': 8, '*': 9, + '\n': 11, '\r': 11} + if ch not in punctuation: + fail(1, mark, ord(ch), unconsumed=True) + kind = punctuation[ch] + bump() + if ch == '\r' and at < len(source) and source[at] == '\n': + bump() + tokens.append((kind, mark[0], byte, mark[1], mark[2], line, column, + decoded_start, len(decoded) - decoded_start, number, 0)) + return tokens, bytes(decoded) + + +def check(lex, source): + encoded = source.encode() + raw = (C.c_uint8 * len(encoded)).from_buffer_copy(encoded) + try: + expected = reference(source) + except Syntax as error: + expected = error.expected + probe = Result() + code = lex(raw, len(raw), len(raw), len(raw), len(raw) * 2 + 1, 0, + None, 0, None, 0, None, 0, None, 0, C.byref(probe)) + assert code == probe.status + if probe.status: + actual = tuple(getattr(probe, name) for name in + 'status reason start end line column detail'.split()) + assert actual == expected, (source, actual, expected) + return + tokens, decoded = expected + assert probe.tokens == len(tokens) and probe.decoded == len(decoded), source + scratch, output = (Token * len(tokens))(), (Token * len(tokens))() + text, published = (C.c_uint8 * len(decoded))(), (C.c_uint8 * len(decoded))() + result = Result() + code = lex(raw, len(raw), len(raw), len(raw), len(raw) * 2 + 1, 1, + scratch, len(scratch), text, len(text), output, len(output), + published, len(published), C.byref(result)) + assert code == result.status == 0 + actual = [tuple(getattr(token, name) for name, _ in Token._fields_) for token in output] + assert actual == tokens and bytes(published) == decoded, (source, actual, tokens) + assert result.work == probe.work <= len(raw) + # A failed publication must preserve the caller's output byte-for-byte. + sentinel = (Token * 1)() + C.memset(sentinel, 0xA5, C.sizeof(sentinel)) + before = bytes(sentinel) + result = Result() + code = lex(raw, len(raw), 0, 0, 0, 1, scratch, len(scratch), text, len(text), + sentinel, 1, published, len(published), C.byref(result)) + if encoded: + assert code in (2, 3, 4) and bytes(sentinel) == before + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--library', type=Path, required=True) + parser.add_argument('--cases', type=int, default=10000) + args = parser.parse_args() + library = C.CDLL(str(args.library.resolve())) + lex = library.whale_asm_lex + lex.argtypes = [C.POINTER(C.c_uint8), U, U, U, U, U, C.POINTER(Token), U, + C.POINTER(C.c_uint8), U, C.POINTER(Token), U, + C.POINTER(C.c_uint8), U, C.POINTER(Result)] + alphabet = 'abcXYZ_.,:[]+-*; \t\r\n0123456789xAbB"\\né한٣²😀\x00\u2003' + rng = random.Random(0x5748414C4541534D) + for source in ['', 'nop\r\nret', 'étiquette: db "한\\xFF"', '0x', '0b', + '18446744073709551615', '18446744073709551616', '0xfffffffffffffffff', + '"\\', '"\\x', '"\\xA', '"\\x한"', '"\\q"', '; 😀\r@', '/']: + check(lex, source) + for _ in range(args.cases): + check(lex, ''.join(rng.choice(alphabet) for _ in range(rng.randrange(100)))) + add, neg, sub = (library.asm_number_add_checked, library.asm_number_neg_checked, + library.asm_number_sub_checked) + for fn in (add, sub): + fn.argtypes = [C.POINTER(Wide), C.POINTER(Wide), C.POINTER(Wide)] + fn.restype = C.c_bool + neg.argtypes = [C.POINTER(Wide), C.POINTER(Wide)] + neg.restype = C.c_bool + pairs = [(a, b) for a in [MIN, MIN+1, -1, 0, 1, MAX-1, MAX] + for b in [MIN, MIN+1, -1, 0, 1, MAX-1, MAX]] + pairs += [(rng.randrange(MIN, MAX+1), rng.randrange(MIN, MAX+1)) + for _ in range(args.cases)] + for a, b in pairs: + for fn, expected in ((add, a+b), (sub, a-b)): + output = wide(99) + valid = fn(C.byref(wide(a)), C.byref(wide(b)), C.byref(output)) + assert valid == (MIN <= expected <= MAX) + assert integer(output) == (expected if valid else 99) + output = wide(99) + valid = neg(C.byref(wide(a)), C.byref(output)) + assert valid == (a != MIN) and integer(output) == (-a if valid else 99) + class Growth(C.Structure): + _fields_ = [('materialized', U), ('section', U)] + grow = library.asm_output_grow + grow.argtypes = [U, U, U, U, U, C.POINTER(Growth)] + align = library.asm_output_align + align.argtypes = [U, U, U, U, U, C.POINTER(Growth)] + for _ in range(args.cases): + materialized, section, extra, limit = [rng.getrandbits(64) for _ in range(4)] + logical = rng.randrange(2) + output = Growth(77, 99) + expected = 0 + if materialized > limit: + expected = 3 + elif section + extra > MASK or (not logical and materialized + extra > MASK): + expected = 1 + elif not logical and materialized + extra > limit: + expected = 2 + code = grow(materialized, section, extra, limit, logical, C.byref(output)) + assert code == expected + assert (output.materialized, output.section) == ( + (materialized + (0 if logical else extra), section + extra) if not code else (77, 99)) + output = Growth(77, 99) + alignment = 1 << rng.randrange(64) + padded = (section + alignment - 1) & -alignment + expected = 1 if padded > MASK else (3 if materialized > limit else 0) + total = materialized + (0 if logical else padded - section) + if not expected and total > MASK: + expected = 1 + if not expected and total > limit: + expected = 2 + code = align(materialized, section, alignment, limit, logical, C.byref(output)) + assert code == expected + assert (output.materialized, output.section) == ((total, padded) if not code else (77, 99)) + output = Growth() + assert grow(0, 0, 1 << 40, 1, 1, C.byref(output)) == 0 + assert (output.materialized, output.section) == (0, 1 << 40) + for encoded in [b'\xc0\x80', b'\xed\xa0\x80', b'\xf4\x90\x80\x80', b'\xe2']: + raw = (C.c_uint8 * len(encoded)).from_buffer_copy(encoded) + scratch, published = (Token * 1)(), (Token * 1)() + C.memset(published, 0xA5, C.sizeof(published)) + before = bytes(published) + result = Result() + code = lex(raw, len(raw), 1, 1, 100, 1, scratch, 1, None, 0, + published, 1, None, 0, C.byref(result)) + assert code == result.status == 5 and bytes(published) == before + classifier = library.asm_unicode_alphanumeric + classifier.argtypes, classifier.restype = [U], C.c_bool + for cp in range(0x110000): + assert classifier(cp) == alphanumeric(chr(cp)), cp + print(f'Wave assembler: {args.cases} independent lexer streams + {args.cases} signed128 + neutral output vectors, all Unicode17 scalar classifications, exact malformed diagnostics and transactional limits passed') + + +if __name__ == '__main__': + main() diff --git a/tools/meson_cargo.py b/tools/meson_cargo.py index 5e6b9c6..ff8a956 100644 --- a/tools/meson_cargo.py +++ b/tools/meson_cargo.py @@ -36,10 +36,13 @@ def validate_features(features): def cargo_environment(target_dir, asmobj_directory, profile, optimization, debug_info, - wave_ir_directory=None): + wave_ir_directory=None, wave_assembler_directory=None, + wave_amd64_directory=None): environment = os.environ.copy() environment.pop("WHALE_ASMOBJ_DIR", None) environment.pop("WHALE_WAVE_IR_DIR", None) + environment.pop("WHALE_WAVE_ASSEMBLER_DIR", None) + environment.pop("WHALE_WAVE_AMD64_DIR", None) environment.pop("CARGO_BUILD_TARGET", None) environment["CARGO_TARGET_DIR"] = str(target_dir) environment["CARGO_INCREMENTAL"] = "0" @@ -50,6 +53,10 @@ def cargo_environment(target_dir, asmobj_directory, profile, optimization, debug environment["WHALE_ASMOBJ_DIR"] = str(asmobj_directory) if wave_ir_directory: environment["WHALE_WAVE_IR_DIR"] = str(wave_ir_directory) + if wave_assembler_directory: + environment["WHALE_WAVE_ASSEMBLER_DIR"] = str(wave_assembler_directory) + if wave_amd64_directory: + environment["WHALE_WAVE_AMD64_DIR"] = str(wave_amd64_directory) return environment @@ -158,6 +165,12 @@ def source_dependencies(source, features): dependencies.add(source / "assembler/asmobj") dependencies.update((source / "assembler/asmobj").glob("*.wave")) dependencies.update((source / "ir").glob("*.wave")) + dependencies.update((source / "assembler").glob("*.wave")) + if (source / "assembler/build_support.rs").is_file(): + dependencies.add(source / "assembler/build_support.rs") + for arch in ASSEMBLERS: + if "asm-" + arch in features: + dependencies.update((source / "assembler" / arch).glob("*.wave")) return dependencies @@ -185,11 +198,19 @@ def build(arguments): asmobj_directory = arguments.asmobj_dir.resolve() if arguments.asmobj_dir else None wave_ir_directory = arguments.wave_ir_dir.resolve() if arguments.wave_ir_dir else None features = validate_features(arguments.feature) + shared_path = getattr(arguments, "wave_assembler_dir", None) + amd64_path = getattr(arguments, "wave_amd64_dir", None) + wave_assembler_directory = shared_path.resolve() if shared_path else None + wave_amd64_directory = amd64_path.resolve() if amd64_path else None + if wave_amd64_directory and "asm-amd64" not in features: + raise BuildError("a Wave AMD64 archive requires the AMD64 product output") + if wave_amd64_directory and not wave_assembler_directory: + raise BuildError("the Wave AMD64 archive requires the shared Wave assembler archive") if target_dir in [source, source / "target"]: raise BuildError("Meson requires its own private Cargo target directory") environment = cargo_environment(target_dir, asmobj_directory, arguments.profile, arguments.opt_level, arguments.debug_info, - wave_ir_directory) + wave_ir_directory, wave_assembler_directory, wave_amd64_directory) target = arguments.host_target or native_target(arguments.cargo, source, environment) if not TRIPLE.fullmatch(target): raise BuildError("cargo host target must be a Rust target triple") @@ -210,6 +231,11 @@ def build(arguments): if wave_ir_directory: archive = "whale_wave_ir.lib" if "msvc" in target else "libwhale_wave_ir.a" dependencies.update(wave_ir_directory / name for name in [archive, "wave-ir.meta", "provenance.json"]) + for name, directory in [("assembler", wave_assembler_directory), ("amd64", wave_amd64_directory)]: + if directory: + archive = f"whale_wave_{name}.lib" if "msvc" in target else f"libwhale_wave_{name}.a" + dependencies.update(directory / file for file in + [archive, f"wave-{name}.meta", "provenance.json"]) contents = make_escape(output) + ": " + " ".join(make_escape(path) for path in sorted(dependencies)) + "\n" candidate = None candidate_depfile = None @@ -314,6 +340,8 @@ def main(argv=None): compile_parser.add_argument("--feature", action="append", default=[]) compile_parser.add_argument("--asmobj-dir", type=Path) compile_parser.add_argument("--wave-ir-dir", type=Path) + compile_parser.add_argument("--wave-assembler-dir", type=Path) + compile_parser.add_argument("--wave-amd64-dir", type=Path) smoke_parser = commands.add_parser("smoke") smoke_parser.add_argument("--binary", type=Path, required=True) smoke_parser.add_argument("--feature", action="append", default=[]) diff --git a/tools/test_build_wave_assembler.py b/tools/test_build_wave_assembler.py new file mode 100644 index 0000000..2a17c40 --- /dev/null +++ b/tools/test_build_wave_assembler.py @@ -0,0 +1,162 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Assembler archive publication, selection and source/ABI guard regressions.""" + +import argparse +import hashlib +import os +from pathlib import Path +import subprocess +import tempfile +import unittest +from unittest.mock import patch + +import build_wave_assembler as helper +from wave_bootstrap import Bootstrap + + +ROOT = Path(__file__).resolve().parents[1] +NATIVE = "x86_64-unknown-linux-gnu" + + +class PublicationTests(unittest.TestCase): + def test_all_owned_wave_roles_are_in_the_explicit_build_lists(self): + owned = {path.relative_to(ROOT).as_posix() + for directory in (ROOT / "assembler", ROOT / "assembler/amd64") + for path in directory.glob("*.wave")} + configured = {file for config in helper.MODULES.values() for file in config["sources"]} + self.assertEqual(owned, configured) + + def test_compilation_archiving_and_partial_publication_preserve_last_good_set(self): + for module, config in helper.MODULES.items(): + name = config["name"] + names = (f"libwhale_wave_{name}.a", "provenance.json", f"wave-{name}.meta") + failures = ("compile", "archive", *names) + for failure in failures: + with self.subTest(module=module, failure=failure), tempfile.TemporaryDirectory() as tmp: + root = Path(tmp).resolve() + wave = root / "Wave" + wave.mkdir() + marker = wave / "unrelated.wave" + marker.write_bytes(b"owned elsewhere") + output = root / "output" + output.mkdir() + for file in names: + (output / file).write_bytes(b"previous " + file.encode()) + compiler = root / "compiler" + compiler.write_bytes(b"pinned compiler") + bootstrap = Bootstrap(compiler, root / "std", root / "bootstrap.json", + {"std_sha256": "1" * 64}, True) + args = argparse.Namespace(module=module, wave_source=wave, out_dir=output, + bootstrap_dir=root / "cache", rust_toolchain="1.89", target=NATIVE, + opt_level="2", allow_network=False) + original_replace = os.replace + injected = False + + def replace(source, destination): + nonlocal injected + if not injected and Path(destination) == output / failure: + injected = True + raise OSError("injected publication failure") + return original_replace(source, destination) + + def run(command, **kwargs): + command = list(map(str, command)) + if "-o" in command: + kernel = Path(command[command.index("build") + 1]) + self.assertEqual(kernel.read_bytes(), b"kernel") + Path(command[command.index("-o") + 1]).write_bytes(b"object") + if failure == "compile": + raise subprocess.CalledProcessError(1, command) + else: + Path(command[-2]).write_bytes(b"new archive") + if failure == "archive": + raise subprocess.CalledProcessError(1, command) + + with patch.object(helper, "ensure_bootstrap", return_value=bootstrap), \ + patch.object(helper, "source_bytes", return_value=b"kernel"), \ + patch.object(helper, "abi_bytes", return_value=b"ABI"), \ + patch.object(helper, "run", side_effect=run), \ + patch.object(helper.os, "replace", side_effect=replace): + with self.assertRaises((OSError, subprocess.CalledProcessError)): + helper.build(args) + for file in names: + self.assertEqual((output / file).read_bytes(), b"previous " + file.encode()) + self.assertEqual(marker.read_bytes(), b"owned elsewhere") + self.assertEqual({p.name for p in output.iterdir()}, set(names)) + + +class GuardTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.temporary = tempfile.TemporaryDirectory() + cls.directory = Path(cls.temporary.name).resolve() + cls.guards = {} + for module in helper.MODULES: + source = ROOT / "assembler" / ("build.rs" if module == "common" else module + "/build.rs") + binary = cls.directory / module + subprocess.run(["rustc", "--edition=2021", "-Dwarnings", str(source), "-o", str(binary)], + check=True, capture_output=True) + cls.guards[module] = binary + + @classmethod + def tearDownClass(cls): + cls.temporary.cleanup() + + def test_plain_cargo_is_available_and_all_stale_or_corrupt_inputs_are_rejected(self): + for module, config in helper.MODULES.items(): + with self.subTest(module=module), tempfile.TemporaryDirectory() as tmp: + root = Path(tmp).resolve() + for file in (*config["sources"], *config["abi"]): + path = root / file + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(file.encode()) + source = root / "assembler" + if module != "common": + source /= module + output = root / "archive" + output.mkdir() + name = config["name"] + archive = output / f"libwhale_wave_{name}.a" + provenance = output / "provenance.json" + metadata = output / f"wave-{name}.meta" + archive.write_bytes(b"archive") + provenance.write_bytes(b"pinned provenance") + original = helper.metadata(helper.source_bytes(root, module), + helper.abi_bytes(root, module), archive.read_bytes(), provenance.read_bytes(), NATIVE, "2") + metadata.write_text(original) + env = os.environ.copy() + for variable in ("WHALE_WAVE_ASSEMBLER_DIR", "WHALE_WAVE_AMD64_DIR"): + env.pop(variable, None) + env.update(CARGO_MANIFEST_DIR=str(source), TARGET=NATIVE) + plain = subprocess.run([str(self.guards[module])], env=env, capture_output=True) + self.assertEqual(plain.returncode, 0, plain.stderr) + self.assertNotIn(b"rustc-link-lib", plain.stdout) + env["WHALE_WAVE_ASSEMBLER_DIR"] = str(output) + env[f"WHALE_WAVE_{name.upper()}_DIR"] = str(output) + + def check(path, replacement, accepted=False): + previous = path.read_bytes() + path.write_bytes(replacement) + try: + result = subprocess.run([str(self.guards[module])], env=env, capture_output=True) + self.assertEqual(result.returncode == 0, accepted, result.stderr) + finally: + path.write_bytes(previous) + + check(metadata, original.encode(), True) + for file in (*config["sources"], *config["abi"]): + check(root / file, b"changed source or boundary") + check(archive, b"corrupt archive") + check(provenance, b"corrupt provenance") + check(metadata, original.replace("schema=1", "schema=2").encode()) + check(metadata, original.replace("opt_level=2", "opt_level=1").encode()) + check(metadata, (original + "schema=1\n").encode()) + check(metadata, original.replace(NATIVE, "aarch64-unknown-linux-gnu").encode()) + check(metadata, b"x" * 4097) + check(provenance, b"x" * (16 * 1024 + 1)) + self.assertEqual(hashlib.sha256(archive.read_bytes()).hexdigest(), + hashlib.sha256(b"archive").hexdigest()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_meson_build.py b/tools/test_meson_build.py index c2e14bd..b281b0f 100644 --- a/tools/test_meson_build.py +++ b/tools/test_meson_build.py @@ -33,10 +33,14 @@ def test_no_isa_product_has_no_implicit_default_features(self): def test_ambient_wave_and_cargo_target_cannot_change_selection(self): with patch.dict(os.environ, {"WHALE_ASMOBJ_DIR": "old", "WHALE_WAVE_IR_DIR": "old", + "WHALE_WAVE_ASSEMBLER_DIR": "old", + "WHALE_WAVE_AMD64_DIR": "old", "CARGO_BUILD_TARGET": "old"}): environment = cargo_environment("private", None, "dev", "2", "2") self.assertNotIn("WHALE_ASMOBJ_DIR", environment) self.assertNotIn("WHALE_WAVE_IR_DIR", environment) + self.assertNotIn("WHALE_WAVE_ASSEMBLER_DIR", environment) + self.assertNotIn("WHALE_WAVE_AMD64_DIR", environment) self.assertNotIn("CARGO_BUILD_TARGET", environment) self.assertEqual(environment["CARGO_TARGET_DIR"], "private") self.assertEqual(environment["CARGO_PROFILE_DEV_OPT_LEVEL"], "2") @@ -44,6 +48,9 @@ def test_ambient_wave_and_cargo_target_cannot_change_selection(self): selected = cargo_environment("private", "asmobj", "dev", "2", "2", "wave-ir") self.assertEqual(selected["WHALE_ASMOBJ_DIR"], "asmobj") self.assertEqual(selected["WHALE_WAVE_IR_DIR"], "wave-ir") + selected = cargo_environment("private", "asmobj", "dev", "2", "2", "ir", "common", "amd64") + self.assertEqual(selected["WHALE_WAVE_ASSEMBLER_DIR"], "common") + self.assertEqual(selected["WHALE_WAVE_AMD64_DIR"], "amd64") def test_wave_is_explicit_and_unknown_features_fail(self): self.assertEqual(validate_features(["asm-amd64", "asm-amd64"]), ["asm-amd64"]) @@ -120,11 +127,19 @@ def test_source_dirs_and_manifests_track_additions_without_disabled_isas(self): (source / "ir/model.wave").write_text("// type graph") (source / "toolchain/src/assembly_object.rs").write_text("// ffi boundary") (source / "Cargo.toml").write_text("manifest") + (source / "assembler/model.wave").write_text("shared model") + (source / "assembler/build_support.rs").write_text("guard") + (source / "assembler/amd64/encoder.wave").write_text("disabled") + (source / "assembler/aarch64/encoder.wave").write_text("selected") dependencies = source_dependencies(source, ["asm-aarch64"]) self.assertNotIn(source, dependencies) self.assertIn(source / "assembler/aarch64/src", dependencies) self.assertIn(source / "assembler/aarch64/src/lib.rs", dependencies) self.assertNotIn(source / "assembler/amd64/src/lib.rs", dependencies) + self.assertNotIn(source / "assembler/amd64/encoder.wave", dependencies) + self.assertIn(source / "assembler/aarch64/encoder.wave", dependencies) + self.assertIn(source / "assembler/model.wave", dependencies) + self.assertIn(source / "assembler/build_support.rs", dependencies) self.assertIn(source / "Cargo.toml", dependencies) self.assertIn(source / "toolchain/src/assembly_object.rs", dependencies) self.assertIn(source / "ir/model.wave", dependencies) From 12150a9d1a09ab84eaf89e17d2fdc320fdb2d64e Mon Sep 17 00:00:00 2001 From: LunaStev Date: Sat, 31 Oct 2026 14:04:10 +0900 Subject: [PATCH 6/8] assembler: move fixed-width ISAs and object translation into Wave roles Implement the supported AArch64, RV64I and LoongArch64 assemblers in role-specific Wave sources with a shared bounded source/section/symbol driver. Keep instruction selection in each ISA, including direct helper compatibility, and retain independent Rust migration references. Split asmobj ELF/COFF/Mach-O relocation policy into explicitly dispatched architecture files. Add selected archive provenance guards and Meson paths. Preserve sparse BSS, target profiles, exact diagnostics and failure order. Verify official native O0/O2 archives, independent LLVM/math/source vectors, whole workspace default/all-feature tests, Clippy, Rust 1.86 and Meson source products. Foreign instruction words and objects are not native host claims. Refs #358, #359, #360, #361. Signed-off-by: LunaStev --- .github/workflows/asmobj.yml | 22 +- BUILDING.md | 8 +- assembler/aarch64/build.rs | 31 + assembler/aarch64/encoder.wave | 416 ++++++ assembler/aarch64/encoding.wave | 288 ++++ assembler/aarch64/entry.wave | 43 + assembler/aarch64/meson.build | 53 + assembler/aarch64/operands.wave | 101 ++ assembler/aarch64/parser.wave | 39 + assembler/aarch64/registers.wave | 103 ++ assembler/aarch64/src/encoder.rs | 14 +- assembler/aarch64/src/encoding/arithmetic.rs | 3 +- assembler/aarch64/src/encoding/branch.rs | 2 +- assembler/aarch64/src/encoding/memory.rs | 3 +- assembler/aarch64/src/lib.rs | 37 +- assembler/aarch64/src/parser.rs | 2 +- assembler/aarch64/src/wave.rs | 383 ++++++ assembler/asmobj/README.md | 5 +- assembler/asmobj/meson.build | 5 +- assembler/asmobj/relocations.wave | 41 +- assembler/asmobj/relocations/aarch64.wave | 29 + assembler/asmobj/relocations/amd64.wave | 12 + assembler/asmobj/relocations/loongarch64.wave | 10 + assembler/asmobj/relocations/riscv64.wave | 10 + assembler/build.rs | 16 +- assembler/build_support.rs | 4 +- assembler/fixed_declarations.wave | 47 + assembler/fixed_driver.wave | 443 +++++++ assembler/fixed_model.wave | 139 ++ assembler/fixed_namespace.wave | 433 ++++++ assembler/fixed_numbers.wave | 228 ++++ assembler/fixed_operands.wave | 146 +++ assembler/fixed_relative.wave | 137 ++ assembler/fixed_scalar.wave | 45 + assembler/fixed_source.wave | 288 ++++ assembler/fixed_text.wave | 175 +++ assembler/loongarch64/branch.wave | 13 + assembler/loongarch64/build.rs | 33 + assembler/loongarch64/encoder.wave | 149 +++ assembler/loongarch64/entry.wave | 28 + assembler/loongarch64/formats.wave | 13 + assembler/loongarch64/meson.build | 55 + assembler/loongarch64/model.wave | 8 + assembler/loongarch64/operands.wave | 26 + assembler/loongarch64/registers.wave | 166 +++ assembler/loongarch64/src/encoder.rs | 18 +- assembler/loongarch64/src/encoding/branch.rs | 2 +- assembler/loongarch64/src/lib.rs | 151 ++- assembler/loongarch64/src/wave.rs | 44 + assembler/loongarch64/tables.wave | 432 ++++++ assembler/meson.build | 27 +- assembler/riscv64/build.rs | 31 + assembler/riscv64/encoder.wave | 750 +++++++++++ assembler/riscv64/encoding.wave | 31 + assembler/riscv64/entry.wave | 64 + assembler/riscv64/meson.build | 53 + assembler/riscv64/operands.wave | 90 ++ assembler/riscv64/parser.wave | 55 + assembler/riscv64/registers.wave | 203 +++ assembler/riscv64/src/encoder.rs | 141 +- assembler/riscv64/src/encoder_reference.rs | 139 ++ assembler/riscv64/src/encoding/branch.rs | 30 +- .../riscv64/src/encoding/branch_reference.rs | 27 + assembler/riscv64/src/encoding/mod.rs | 6 +- assembler/riscv64/src/encoding_reference.rs | 6 + assembler/riscv64/src/lib.rs | 130 +- assembler/riscv64/src/parser.rs | 68 +- assembler/riscv64/src/parser_reference.rs | 54 + assembler/riscv64/src/wave.rs | 119 ++ assembler/riscv64/tests/standard_sections.rs | 23 + assembler/src/fixed.rs | 513 +------- assembler/src/fixed_reference.rs | 492 +++++++ assembler/src/fixed_wave.rs | 1156 +++++++++++++++++ meson.build | 17 +- meson.options | 6 + toolchain/build.rs | 17 +- tools/build_asmobj.py | 7 +- tools/build_wave_assembler.py | 78 +- tools/check_asmobj.py | 2 +- tools/check_wave_fixed.py | 226 ++++ tools/check_wave_loongarch64.py | 211 +++ tools/check_wave_riscv64.py | 383 ++++++ tools/meson_cargo.py | 42 +- tools/test_build_asmobj.py | 23 +- tools/test_build_wave_assembler.py | 3 +- tools/test_meson_build.py | 6 + 86 files changed, 9398 insertions(+), 730 deletions(-) create mode 100644 assembler/aarch64/build.rs create mode 100644 assembler/aarch64/encoder.wave create mode 100644 assembler/aarch64/encoding.wave create mode 100644 assembler/aarch64/entry.wave create mode 100644 assembler/aarch64/meson.build create mode 100644 assembler/aarch64/operands.wave create mode 100644 assembler/aarch64/parser.wave create mode 100644 assembler/aarch64/registers.wave create mode 100644 assembler/aarch64/src/wave.rs create mode 100644 assembler/asmobj/relocations/aarch64.wave create mode 100644 assembler/asmobj/relocations/amd64.wave create mode 100644 assembler/asmobj/relocations/loongarch64.wave create mode 100644 assembler/asmobj/relocations/riscv64.wave create mode 100644 assembler/fixed_declarations.wave create mode 100644 assembler/fixed_driver.wave create mode 100644 assembler/fixed_model.wave create mode 100644 assembler/fixed_namespace.wave create mode 100644 assembler/fixed_numbers.wave create mode 100644 assembler/fixed_operands.wave create mode 100644 assembler/fixed_relative.wave create mode 100644 assembler/fixed_scalar.wave create mode 100644 assembler/fixed_source.wave create mode 100644 assembler/fixed_text.wave create mode 100644 assembler/loongarch64/branch.wave create mode 100644 assembler/loongarch64/build.rs create mode 100644 assembler/loongarch64/encoder.wave create mode 100644 assembler/loongarch64/entry.wave create mode 100644 assembler/loongarch64/formats.wave create mode 100644 assembler/loongarch64/meson.build create mode 100644 assembler/loongarch64/model.wave create mode 100644 assembler/loongarch64/operands.wave create mode 100644 assembler/loongarch64/registers.wave create mode 100644 assembler/loongarch64/src/wave.rs create mode 100644 assembler/loongarch64/tables.wave create mode 100644 assembler/riscv64/build.rs create mode 100644 assembler/riscv64/encoder.wave create mode 100644 assembler/riscv64/encoding.wave create mode 100644 assembler/riscv64/entry.wave create mode 100644 assembler/riscv64/meson.build create mode 100644 assembler/riscv64/operands.wave create mode 100644 assembler/riscv64/parser.wave create mode 100644 assembler/riscv64/registers.wave create mode 100644 assembler/riscv64/src/encoder_reference.rs create mode 100644 assembler/riscv64/src/encoding/branch_reference.rs create mode 100644 assembler/riscv64/src/encoding_reference.rs create mode 100644 assembler/riscv64/src/parser_reference.rs create mode 100644 assembler/riscv64/src/wave.rs create mode 100644 assembler/riscv64/tests/standard_sections.rs create mode 100644 assembler/src/fixed_reference.rs create mode 100644 assembler/src/fixed_wave.rs create mode 100644 tools/check_wave_fixed.py create mode 100644 tools/check_wave_loongarch64.py create mode 100755 tools/check_wave_riscv64.py diff --git a/.github/workflows/asmobj.yml b/.github/workflows/asmobj.yml index 2e2c2ae..19698f9 100644 --- a/.github/workflows/asmobj.yml +++ b/.github/workflows/asmobj.yml @@ -109,10 +109,10 @@ jobs: WHALE_WAVE_IR_DIR="$RUNNER_TEMP/wave-ir-o$optimization" \ cargo test -p ir --all-features --locked --offline done - - name: Run shared and AMD64 Wave assemblers at O0 and O2 + - name: Run all Wave assemblers at O0 and O2 run: | for optimization in 0 2; do - for module in common amd64; do + for module in common amd64 aarch64 riscv64 loongarch64; do python3 tools/build_wave_assembler.py --module "$module" \ --wave-source .asmobj-bootstrap-source \ --bootstrap-dir "$RUNNER_TEMP/asmobj-bootstrap" --rust-toolchain 1.89.0 \ @@ -121,6 +121,9 @@ jobs: done export WHALE_WAVE_ASSEMBLER_DIR="$RUNNER_TEMP/assembler-common-o$optimization" export WHALE_WAVE_AMD64_DIR="$RUNNER_TEMP/assembler-amd64-o$optimization" + export WHALE_WAVE_AARCH64_DIR="$RUNNER_TEMP/assembler-aarch64-o$optimization" + export WHALE_WAVE_RISCV64_DIR="$RUNNER_TEMP/assembler-riscv64-o$optimization" + export WHALE_WAVE_LOONGARCH64_DIR="$RUNNER_TEMP/assembler-loongarch64-o$optimization" export WHALE_ASMOBJ_DIR="$GITHUB_WORKSPACE/.ci-asmobj/x86_64-unknown-linux-gnu" export WHALE_WAVE_IR_DIR="$RUNNER_TEMP/wave-ir-o2" cc -shared -Wl,--whole-archive "$WHALE_WAVE_ASSEMBLER_DIR/libwhale_wave_assembler.a" \ @@ -138,7 +141,20 @@ jobs: timeout 180s python3 tools/fuzz_limits.py --memory-mib 512 -- "$assembler_python" \ tools/check_wave_amd64_layout.py \ --library "$RUNNER_TEMP/assembler-amd64-o$optimization.so" --cases 2000 - cargo test -p assembler -p amd64 --locked --offline + timeout 180s python3 tools/fuzz_limits.py --memory-mib 512 -- "$assembler_python" \ + tools/check_wave_fixed.py \ + --library "$RUNNER_TEMP/assembler-common-o$optimization.so" --cases 10000 + for module in riscv64 loongarch64; do + cc -shared -Wl,--whole-archive \ + "$RUNNER_TEMP/assembler-$module-o$optimization/libwhale_wave_$module.a" \ + "$WHALE_WAVE_ASSEMBLER_DIR/libwhale_wave_assembler.a" \ + -Wl,--no-whole-archive -o "$RUNNER_TEMP/assembler-$module-o$optimization.so" + timeout 180s python3 tools/fuzz_limits.py --memory-mib 512 -- "$assembler_python" \ + "tools/check_wave_$module.py" \ + --library "$RUNNER_TEMP/assembler-$module-o$optimization.so" --cases 50000 + done + cargo test -p assembler -p amd64 -p aarch64 -p riscv64 -p loongarch64 --locked --offline + cargo test -p whale --all-features --locked --offline cargo build -p whale --all-features --locked --offline timeout 180s python3 tools/fuzz_limits.py --memory-mib 512 -- "$assembler_python" \ tools/check_wave_amd64_cli.py --binary target/debug/whale \ diff --git a/BUILDING.md b/BUILDING.md index 6bef8e7..56cafce 100644 --- a/BUILDING.md +++ b/BUILDING.md @@ -78,12 +78,12 @@ to use them. Ordinary Cargo keeps the Rust reference during the IR migration. The Wave numeric core uses two 64-bit words for 128-bit integers and exact IEEE rounding; it does not depend on host floating-point arithmetic. -Source builds also compile the shared Wave assembler and selected AMD64 module. +Source builds also compile the shared Wave assembler and selected ISA modules. Prebuilt builds select them with `-Dwave-assembler-dir=...` and -`-Dwave-amd64-dir=...`; unselected ISA archives are not linked. -For focused Cargo tests, `tools/build_wave_assembler.py --module common|amd64` +`-Dwave-ARCH-dir=...` for each selected ISA; unselected archives are not linked. +For focused Cargo tests, `tools/build_wave_assembler.py --module common|amd64|aarch64|riscv64|loongarch64` produces the corresponding archive. Set `WHALE_WAVE_ASSEMBLER_DIR` and -`WHALE_WAVE_AMD64_DIR` explicitly; Cargo does not invoke Wave. +the corresponding `WHALE_WAVE_ARCH_DIR` explicitly; Cargo does not invoke Wave. For work confined to Rust components, ordinary Cargo builds remain available: diff --git a/assembler/aarch64/build.rs b/assembler/aarch64/build.rs new file mode 100644 index 0000000..40043f7 --- /dev/null +++ b/assembler/aarch64/build.rs @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: MPL-2.0 +const CFG: &str = "whale_wave_aarch64"; + +const ENV: &str = "WHALE_WAVE_AARCH64_DIR"; + +const LIBRARY: &str = "whale_wave_aarch64"; + +const METADATA: &str = "wave-aarch64.meta"; + +const ROOT_UP: usize = 2; + +const SOURCES: &[&str] = &[ + "assembler/model.wave", + "assembler/declarations.wave", + "assembler/fixed_model.wave", + "assembler/fixed_declarations.wave", + "assembler/aarch64/registers.wave", + "assembler/aarch64/parser.wave", + "assembler/aarch64/operands.wave", + "assembler/aarch64/encoding.wave", + "assembler/aarch64/encoder.wave", + "assembler/aarch64/entry.wave", +]; + +const ABI_SOURCES: &[&str] = &[ + "assembler/aarch64/src/wave.rs", + "assembler/aarch64/src/lib.rs", + "assembler/aarch64/src/encoder.rs", + "assembler/aarch64/src/parser.rs", +]; +include!("../build_support.rs"); diff --git a/assembler/aarch64/encoder.wave b/assembler/aarch64/encoder.wave new file mode 100644 index 0000000..59ffc3e --- /dev/null +++ b/assembler/aarch64/encoder.wave @@ -0,0 +1,416 @@ +// SPDX-License-Identifier: MPL-2.0 +// A64 instruction selection; all operand decisions and bit encodings are native. +fun a64_condition(instruction: ptr, output: ptr) -> bool { + var name: FixedText = instruction.mnemonic; + name.data = &name.data[2]; + name.count -= 2; + if (asm_fixed_word(name, 29029, 2, instruction.fold)) { // eq + output[0] = 0; + } else if (asm_fixed_word(name, 25966, 2, instruction.fold)) { // ne + output[0] = 1; + } else if (asm_fixed_word(name, 29539, 2, instruction.fold) + || asm_fixed_word(name, 29544, 2, instruction.fold)) { // cs/hs + output[0] = 2; + } else if (asm_fixed_word(name, 25443, 2, instruction.fold) + || asm_fixed_word(name, 28524, 2, instruction.fold)) { // cc/lo + output[0] = 3; + } else if (asm_fixed_word(name, 26989, 2, instruction.fold)) { // mi + output[0] = 4; + } else if (asm_fixed_word(name, 27760, 2, instruction.fold)) { // pl + output[0] = 5; + } else if (asm_fixed_word(name, 29558, 2, instruction.fold)) { // vs + output[0] = 6; + } else if (asm_fixed_word(name, 25462, 2, instruction.fold)) { // vc + output[0] = 7; + } else if (asm_fixed_word(name, 26984, 2, instruction.fold)) { // hi + output[0] = 8; + } else if (asm_fixed_word(name, 29548, 2, instruction.fold)) { // ls + output[0] = 9; + } else if (asm_fixed_word(name, 25959, 2, instruction.fold)) { // ge + output[0] = 10; + } else if (asm_fixed_word(name, 29804, 2, instruction.fold)) { // lt + output[0] = 11; + } else if (asm_fixed_word(name, 29799, 2, instruction.fold)) { // gt + output[0] = 12; + } else if (asm_fixed_word(name, 25964, 2, instruction.fold)) { // le + output[0] = 13; + } else if (asm_fixed_word(name, 27745, 2, instruction.fold)) { // al + output[0] = 14; + } else if (asm_fixed_word(name, 30318, 2, instruction.fold)) { // nv + output[0] = 15; + } else { + return false; + } + return true; +} + +fun a64_opcode(instruction: ptr) -> u64 { + if (a64_mnemonic(instruction, 7368558, 3)) { // nop + return 0; + } + if (a64_mnemonic(instruction, 7628146, 3)) { // ret + return 1; + } + if (a64_mnemonic(instruction, 29282, 2)) { // br + return 2; + } + if (a64_mnemonic(instruction, 7498850, 3)) { // blr + return 3; + } + if (a64_mnemonic(instruction, 6518387, 3)) { // svc + return 4; + } + if (a64_mnemonic(instruction, 7041634, 3)) { // brk + return 5; + } + if (a64_mnemonic(instruction, 7761773, 3)) { // mov + return 6; + } + if (a64_mnemonic(instruction, 2054582125, 4)) { // movz + return 7; + } + if (a64_mnemonic(instruction, 1853255533, 4)) { // movn + return 8; + } + if (a64_mnemonic(instruction, 1802923885, 4)) { // movk + return 9; + } + if (a64_mnemonic(instruction, 6579297, 3)) { // add + return 10; + } + if (a64_mnemonic(instruction, 1935959137, 4)) { // adds + return 11; + } + if (a64_mnemonic(instruction, 6452595, 3)) { // sub + return 12; + } + if (a64_mnemonic(instruction, 1935832435, 4)) { // subs + return 13; + } + if (a64_mnemonic(instruction, 7368035, 3)) { // cmp + return 14; + } + if (a64_mnemonic(instruction, 7236963, 3)) { // cmn + return 15; + } + if (a64_mnemonic(instruction, 6581857, 3)) { // and + return 16; + } + if (a64_mnemonic(instruction, 1935961697, 4)) { // ands + return 17; + } + if (a64_mnemonic(instruction, 7500399, 3)) { // orr + return 18; + } + if (a64_mnemonic(instruction, 7499621, 3)) { // eor + return 19; + } + if (a64_mnemonic(instruction, 7107436, 3)) { // lsl + return 20; + } + if (a64_mnemonic(instruction, 7500652, 3)) { // lsr + return 21; + } + if (a64_mnemonic(instruction, 7500641, 3)) { // asr + return 22; + } + if (a64_mnemonic(instruction, 7496812, 3)) { // ldr + return 23; + } + if (a64_mnemonic(instruction, 7500915, 3)) { // str + return 24; + } + if (a64_mnemonic(instruction, 1651663980, 4)) { // ldrb + return 25; + } + if (a64_mnemonic(instruction, 1651668083, 4)) { // strb + return 26; + } + if (a64_mnemonic(instruction, 1752327276, 4)) { // ldrh + return 27; + } + if (a64_mnemonic(instruction, 1752331379, 4)) { // strh + return 28; + } + if (a64_mnemonic(instruction, 513037984876, 5)) { // ldrsw + return 29; + } + if (a64_mnemonic(instruction, 1920296044, 4)) { // ldur + return 30; + } + if (a64_mnemonic(instruction, 1920300147, 4)) { // stur + return 31; + } + if (a64_mnemonic(instruction, 98, 1)) { // b + return 32; + } + if (a64_mnemonic(instruction, 27746, 2)) { // bl + return 33; + } + if (a64_mnemonic(instruction, 8020579, 3)) { // cbz + return 34; + } + if (a64_mnemonic(instruction, 2054054499, 4)) { // cbnz + return 35; + } + if (a64_mnemonic(instruction, 7496801, 3)) { // adr + return 36; + } + var prefix: FixedText = instruction.mnemonic; + if (prefix.count >= 2) { + prefix.count = 2; + if (asm_fixed_word(prefix, 11874, 2, instruction.fold)) { // b. + return 37; + } + } + return 18446744073709551615; +} + +fun a64_encode(instruction: ptr, context: ptr, + result: ptr) -> bool { + if (!asm_fixed_charge(result, instruction.mnemonic.count + 1)) { + return false; + } + var operation: u64 = a64_opcode(instruction); + if (operation == 0) { // NOP + if (!asm_fixed_count(instruction, 0, result)) { + return false; + } + result.word = 3573751839; + return true; + } + if (operation >= 1 && operation <= 3) { // RET/BR/BLR + var target: A64Register; + target.index = 30; + target.width = 64; + target.sp = 0; + target.zero = 0; + if (operation != 1 || instruction.count != 0) { + if (!asm_fixed_count(instruction, 1, result) + || !a64_register(instruction.operands[0], &target, result)) { + return false; + } + } + if (target.width != 64 || target.index == 31) { + return a64_fail(result, 1008); + } + var base: u64 = 3596550144; // RET + if (operation == 2) { + base = 3592355840; // BR + } else if (operation == 3) { + base = 3594452992; // BLR + } + result.word = base | (target.index << 5); + return true; + } + if (operation == 4 || operation == 5) { // SVC/BRK + if (!asm_fixed_count(instruction, 1, result)) { + return false; + } + var immediate: u64 = 0; + if (!asm_fixed_unsigned(instruction.operands[0], 16, &immediate, result)) { + return false; + } + var base: u64 = 3556769793; // SVC + if (operation == 5) { + base = 3558866944; // BRK + } + result.word = base | (immediate << 5); + return true; + } + if (operation == 6) { // MOV + if (!asm_fixed_count(instruction, 2, result)) { + return false; + } + var rd: A64Register; + if (!a64_register(instruction.operands[0], &rd, result)) { + return false; + } + var value: AsmWide; + if (asm_fixed_try_integer(instruction.operands[1], &value, result)) { + if (!a64_no_sp(&rd, result)) { + return false; + } + return a64_mov_immediate(&rd, &value, result); + } + if (result.status != 0) { + return false; + } + var rn: A64Register; + if (!a64_register(instruction.operands[1], &rn, result) + || !a64_same(&rd, &rn, result)) { + return false; + } + if (rd.sp != 0 || rn.sp != 0) { + if (rd.zero != 0 || rn.zero != 0) { + return a64_fail(result, 1009); + } + result.word = 285212672 | a64_sf(&rd) | (rn.index << 5) | rd.index; + } else { + result.word = 704644064 | a64_sf(&rd) | (rn.index << 16) | rd.index; + } + return true; + } + if (operation >= 7 && operation <= 9) { // MOVZ/MOVN/MOVK + if (instruction.count < 2 || instruction.count > 3) { + return a64_fail(result, 1010); + } + var rd: A64Register; + var immediate: u64 = 0; + if (!a64_register(instruction.operands[0], &rd, result) || !a64_no_sp(&rd, result) + || !asm_fixed_unsigned(instruction.operands[1], 16, &immediate, result)) { + return false; + } + var lane: u64 = 0; + if (instruction.count == 3) { + var modifier: A64Shift; + if (!a64_shift(instruction.operands[2], 64, &modifier, result)) { + return false; + } + if (modifier.kind != 0 || modifier.amount % 16 != 0 || modifier.amount >= rd.width) { + return a64_fail(result, 1011); + } + lane = modifier.amount / 16; + } + result.word = a64_wide_word(&rd, operation - 7, lane, immediate); + return true; + } + if (operation >= 10 && operation <= 15) { // ADD/ADDS/SUB/SUBS/CMP/CMN + var compare: bool = operation >= 14; + var sub: bool = operation == 12 || operation == 13 || operation == 14; + var flags: bool = compare || operation == 11 || operation == 13; + return a64_arithmetic(instruction, compare, sub, flags, result); + } + if (operation >= 16 && operation <= 19) { // AND/ANDS/ORR/EOR + var code: u64 = 0; + if (operation == 17) { + code = 3; + } else if (operation == 18) { + code = 1; + } else if (operation == 19) { + code = 2; + } + return a64_logical(instruction, code, result); + } + if (operation >= 20 && operation <= 22) { // LSL/LSR/ASR + return a64_shift_encoding(instruction, operation - 20, result); + } + if (operation >= 23 && operation <= 31) { // Load/store families. + var load: bool = operation == 23 || operation == 25 || operation == 27 + || operation == 29 || operation == 30; + var size: u64 = 2; + if (operation == 25 || operation == 26) { + size = 0; + } else if (operation == 27 || operation == 28) { + size = 1; + } + return a64_memory_encoding(instruction, load, size, operation >= 30, + operation == 29, result); + } + if (operation == 32 || operation == 33) { // B/BL + if (!asm_fixed_count(instruction, 1, result)) { + return false; + } + var code: u64 = 282; + if (operation == 33) { + code = 283; + } + var offset: i64 = 0; + var immediate: u64 = 0; + if (!asm_fixed_pc_relative(context, instruction.operands[0], code, &offset, result) + || !asm_fixed_displacement(offset, 26, 4, &immediate, result)) { + return false; + } + result.word = a64_direct_word(operation == 33, immediate); + return true; + } + if (operation == 34 || operation == 35) { // CBZ/CBNZ + if (!asm_fixed_count(instruction, 2, result)) { + return false; + } + var rt: A64Register; + var offset: i64 = 0; + var immediate: u64 = 0; + if (!a64_register(instruction.operands[0], &rt, result) || !a64_no_sp(&rt, result) + || !asm_fixed_pc_relative(context, instruction.operands[1], 280, &offset, result) + || !asm_fixed_displacement(offset, 19, 4, &immediate, result)) { + return false; + } + result.word = a64_compare_word(operation == 35, rt.width == 64, rt.index, immediate); + return true; + } + if (operation == 36) { // ADR + if (!asm_fixed_count(instruction, 2, result)) { + return false; + } + var rd: A64Register; + var offset: i64 = 0; + var immediate: u64 = 0; + if (!a64_register(instruction.operands[0], &rd, result) || !a64_no_sp(&rd, result)) { + return false; + } + if (rd.width != 64) { + return a64_fail(result, 1013); + } + if (!asm_fixed_pc_relative(context, instruction.operands[1], 274, &offset, result) + || !asm_fixed_displacement(offset, 21, 1, &immediate, result)) { + return false; + } + result.word = a64_address_word(rd.index, immediate); + return true; + } + if (operation == 37) { // B.cond + var condition: u64 = 0; + if (!a64_condition(instruction, &condition)) { + return a64_fail(result, 1014); + } + if (!asm_fixed_count(instruction, 1, result)) { + return false; + } + var offset: i64 = 0; + var immediate: u64 = 0; + if (!asm_fixed_pc_relative(context, instruction.operands[0], 280, &offset, result) + || !asm_fixed_displacement(offset, 19, 4, &immediate, result)) { + return false; + } + result.word = a64_conditional_word(condition, immediate); + return true; + } + asm_fixed_fail(result, 1015, instruction.mnemonic, 0); + result.display = instruction.fold; + return false; +} + +export(c) fun whale_aarch64_encode(instruction: ptr, + context: ptr, result: ptr) -> i32 { + if (result == null) { + return 2; + } + if (instruction == null || context == null || instruction.fold > 1 + || !asm_span_valid(instruction.mnemonic.data, instruction.mnemonic.count, 1) + || !asm_span_valid(instruction.operands as ptr, instruction.count, 16)) { + result.status = 2; + result.word = 0; + return 2; + } + var at: u64 = 0; + while (at < instruction.count) { + if (!asm_fixed_charge(result, 1)) { + return result.status as i32; + } + if (!asm_span_valid(instruction.operands[at].data, instruction.operands[at].count, 1)) { + result.status = 2; + result.word = 0; + return 2; + } + at += 1; + } + if (!a64_encode(instruction, context, result)) { + if (result.status == 0) { + result.status = 2; + result.word = 0; + } + return result.status as i32; + } + return 0; +} diff --git a/assembler/aarch64/encoding.wave b/assembler/aarch64/encoding.wave new file mode 100644 index 0000000..1d09970 --- /dev/null +++ b/assembler/aarch64/encoding.wave @@ -0,0 +1,288 @@ +// SPDX-License-Identifier: MPL-2.0 +// Bit-field placement for validated A64 operands. +fun a64_direct_word(link: bool, immediate: u64) -> u64 { + if (link) { + return 2483027968 | immediate; // BL + } + return 335544320 | immediate; // B +} + +fun a64_conditional_word(condition: u64, immediate: u64) -> u64 { + return 1409286144 | (immediate << 5) | condition; // B.cond +} + +fun a64_compare_word(nonzero: bool, wide: bool, register: u64, immediate: u64) -> u64 { + var word: u64 = 872415232 | (immediate << 5) | register; // CBZ + if (nonzero) { + word = word | 16777216; + } + if (wide) { + word = word | 2147483648; + } + return word; +} + +fun a64_address_word(register: u64, immediate: u64) -> u64 { + return 268435456 | ((immediate & 3) << 29) | ((immediate >> 2) << 5) | register; // ADR +} + +fun a64_wide_base(operation: u64) -> u64 { + if (operation == 1) { + return 310378496; // MOVN + } + if (operation == 2) { + return 1920991232; // MOVK + } + return 1384120320; // MOVZ +} + +fun a64_wide_word(register: ptr, operation: u64, lane: u64, immediate: u64) -> u64 { + return a64_wide_base(operation) | a64_sf(register) | (lane << 21) + | (immediate << 5) | register.index; +} + +fun a64_mov_immediate(register: ptr, value: ptr, + result: ptr) -> bool { + if (!asm_number_fits_signed(value, register.width) + && !asm_number_fits_unsigned(value, register.width)) { + return a64_fail(result, 1016); + } + var mask: u64 = 18446744073709551615; + if (register.width == 32) { + mask = 4294967295; + } + // Preserve the established MOVN spelling for -65536..-1. + if (value.high == 18446744073709551615 && value.low >= 18446744073709486080) { + result.word = a64_wide_word(register, 1, 0, (~value.low) & 65535); + return true; + } + var lane_mask: u64 = 65535; + var operation: u64 = 0; + while (operation < 2) { + var pattern: u64 = value.low & mask; + if (operation == 1) { + pattern = ~pattern & mask; + } + var lane: u64 = 0; + while (lane < register.width / 16) { + var shift: u64 = lane * 16; + if ((pattern & ~(lane_mask << shift)) == 0) { + result.word = a64_wide_word(register, operation, lane, + (pattern >> shift) & lane_mask); + return true; + } + lane += 1; + } + operation += 1; + } + return a64_fail(result, 1017); // Multi-instruction constants require MOVZ/MOVK. +} + +fun a64_arithmetic(instruction: ptr, compare: bool, sub: bool, + flags: bool, result: ptr) -> bool { + var rd: A64Register; + var rn: A64Register; + var rm_position: u64 = 2; + var shift_position: u64 = 3; + var count: u64 = instruction.count; + if (compare) { + if (count == 0) { + return a64_fail(result, 1018); + } + // Comparison aliases inspect the first register before checking arity. + if (!a64_register(instruction.operands[0], &rn, result)) { + return false; + } + count += 1; + rm_position = 1; + shift_position = 2; + rd.index = 31; + rd.width = rn.width; + rd.sp = 0; + rd.zero = 1; + } + if (count < 3 || count > 4) { + return a64_fail(result, 1019); + } + if (!compare) { + if (!a64_register(instruction.operands[0], &rd, result) + || !a64_register(instruction.operands[1], &rn, result)) { + return false; + } + } + if (!a64_same(&rd, &rn, result)) { + return false; + } + var operation: u64 = 0; + if (sub) { + operation = operation | 1073741824; + } + if (flags) { + operation = operation | 536870912; + } + var immediate_value: AsmWide; + if (asm_fixed_try_integer(instruction.operands[rm_position], &immediate_value, result)) { + if (rn.zero != 0 || (flags && rd.sp != 0) || (!flags && rd.zero != 0)) { + return a64_fail(result, 1020); + } + var immediate: u64 = 0; + if (!asm_fixed_unsigned(instruction.operands[rm_position], 12, &immediate, result)) { + return false; + } + var shift: u64 = 0; + if (count == 4) { + var modifier: A64Shift; + if (!a64_shift(instruction.operands[shift_position], 64, &modifier, result)) { + return false; + } + if (modifier.kind != 0 || (modifier.amount != 0 && modifier.amount != 12)) { + return a64_fail(result, 1021); + } + if (modifier.amount == 12) { + shift = 1; + } + } + result.word = 285212672 | a64_sf(&rd) | operation | (shift << 22) + | (immediate << 10) | (rn.index << 5) | rd.index; + return true; + } + if (result.status != 0 || !a64_no_sp(&rd, result) || !a64_no_sp(&rn, result)) { + return false; + } + var rm: A64Register; + if (!a64_register(instruction.operands[rm_position], &rm, result) + || !a64_no_sp(&rm, result) || !a64_same(&rd, &rm, result)) { + return false; + } + var modifier: A64Shift; + modifier.kind = 0; + modifier.amount = 0; + if (count == 4 + && !a64_shift(instruction.operands[shift_position], rd.width, &modifier, result)) { + return false; + } + if (modifier.kind == 3) { + return a64_fail(result, 1022); + } + result.word = 184549376 | a64_sf(&rd) | operation | (modifier.kind << 22) + | (rm.index << 16) | (modifier.amount << 10) | (rn.index << 5) | rd.index; + return true; +} + +fun a64_logical(instruction: ptr, operation: u64, + result: ptr) -> bool { + if (instruction.count < 3 || instruction.count > 4) { + return a64_fail(result, 1012); + } + var rd: A64Register; + var rn: A64Register; + var rm: A64Register; + if (!a64_register(instruction.operands[0], &rd, result) || !a64_no_sp(&rd, result) + || !a64_register(instruction.operands[1], &rn, result) || !a64_no_sp(&rn, result) + || !a64_register(instruction.operands[2], &rm, result) || !a64_no_sp(&rm, result) + || !a64_same(&rd, &rn, result) || !a64_same(&rd, &rm, result)) { + return false; + } + var modifier: A64Shift; + modifier.kind = 0; + modifier.amount = 0; + if (instruction.count == 4 + && !a64_shift(instruction.operands[3], rd.width, &modifier, result)) { + return false; + } + var base: u64 = 167772160 | (operation << 29); // AND/ORR/EOR/ANDS. + result.word = base | a64_sf(&rd) | (modifier.kind << 22) | (rm.index << 16) + | (modifier.amount << 10) | (rn.index << 5) | rd.index; + return true; +} + +fun a64_shift_encoding(instruction: ptr, operation: u64, + result: ptr) -> bool { + if (!asm_fixed_count(instruction, 3, result)) { + return false; + } + var rd: A64Register; + var rn: A64Register; + if (!a64_register(instruction.operands[0], &rd, result) || !a64_no_sp(&rd, result) + || !a64_register(instruction.operands[1], &rn, result) || !a64_no_sp(&rn, result) + || !a64_same(&rd, &rn, result)) { + return false; + } + var bits: u64 = 5; + if (rd.width == 64) { + bits = 6; + } + var amount: u64 = 0; + if (!asm_fixed_unsigned(instruction.operands[2], bits, &amount, result)) { + return false; + } + var immr: u64 = amount; + var imms: u64 = rd.width - 1; + if (operation == 0) { + immr = (rd.width - amount) % rd.width; + imms -= amount; + } + var base: u64 = 1392508928; // UBFM for LSL/LSR. + if (operation == 2) { + base = 318767104; // SBFM for ASR. + } + var n: u64 = 0; + if (rd.width == 64) { + n = 4194304; + } + result.word = base | a64_sf(&rd) | n | (immr << 16) | (imms << 10) + | (rn.index << 5) | rd.index; + return true; +} + +fun a64_memory_encoding(instruction: ptr, load: bool, + size_kind: u64, unscaled: bool, sign_extend: bool, result: ptr) -> bool { + if (!asm_fixed_count(instruction, 2, result)) { + return false; + } + var rt: A64Register; + var memory: A64Memory; + if (!a64_register(instruction.operands[0], &rt, result) || !a64_no_sp(&rt, result) + || !a64_memory(instruction.operands[1], &memory, result)) { + return false; + } + var size: u64 = size_kind; + if (size_kind == 2 && rt.width == 64) { + size = 3; + } + if (size < 2 && rt.width != 32) { + return a64_fail(result, 1023); + } + if (sign_extend && rt.width != 64) { + return a64_fail(result, 1024); + } + var load_bit: u64 = 0; + if (load) { + load_bit = 4194304; + } + var opcode: u64 = 0; + var immediate: u64 = 0; + if (unscaled) { + if (!asm_number_fits_signed(&memory.offset, 9)) { + return a64_fail(result, 1026); + } + opcode = 939524096 | (size << 30) | load_bit; + immediate = (memory.offset.low & 511) << 12; + } else { + if (sign_extend) { + size = 2; + } + var scale: u64 = 1 << size; + if (memory.offset.high != 0 || memory.offset.low % scale != 0 + || memory.offset.low / scale > 4095) { + return a64_fail(result, 1025); + } + opcode = 956301312 | (size << 30) | load_bit; + if (sign_extend) { + opcode = 3112173568; + } + immediate = (memory.offset.low / scale) << 10; + } + result.word = opcode | immediate | (memory.base.index << 5) | rt.index; + return true; +} diff --git a/assembler/aarch64/entry.wave b/assembler/aarch64/entry.wave new file mode 100644 index 0000000..0cd09c1 --- /dev/null +++ b/assembler/aarch64/entry.wave @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: MPL-2.0 +// Source preparation, instruction selection and publication stay in native code. +export(c) fun whale_aarch64_assemble(packet: ptr, result: ptr) -> i32 { + if (result == null) { + return 2; + } + if (packet == null) { + result.status = 2; + result.word = 0; + return 2; + } + var state: FixedState; + if (!asm_fixed_prepare(packet, &state, result)) { + if (result.status == 0) { + result.status = 2; + result.word = 0; + } + return result.status as i32; + } + while (true) { + var instruction: FixedInstruction; + var next: i32 = asm_fixed_next(&state, &instruction, result); + if (next == 0) { + return result.status as i32; + } + if (next != 1) { + if (result.status == 0) { + result.status = 2; + result.word = 0; + } + return result.status as i32; + } + if (!a64_encode(&instruction, &state.context, result) + || !asm_fixed_commit(&state, result.word, result)) { + if (result.status == 0) { + result.status = 2; + result.word = 0; + } + return result.status as i32; + } + } + return 0; +} diff --git a/assembler/aarch64/meson.build b/assembler/aarch64/meson.build new file mode 100644 index 0000000..8011949 --- /dev/null +++ b/assembler/aarch64/meson.build @@ -0,0 +1,53 @@ +# SPDX-License-Identifier: MPL-2.0 +wave_aarch64_dependencies = [] +wave_aarch64_directory = get_option('wave-aarch64-dir') +if wave_aarch64_directory == '' and wave_source != '' + wave_aarch64_directory = meson.current_build_dir() + module_target = cargo_host_target + if module_target == '' + target_os = {'linux': 'unknown-linux-gnu', 'darwin': 'apple-darwin', 'windows': 'pc-windows-msvc'} + module_target = host_machine.cpu_family() + '-' + target_os[host_machine.system()] + endif + archive_name = module_target.contains('msvc') ? 'whale_wave_aarch64.lib' : 'libwhale_wave_aarch64.a' + arguments = ['--module', 'aarch64', '--wave-source', wave_source, '--out-dir', '@OUTDIR@', + '--bootstrap-dir', wave_cache, '--target', module_target, + '--rust-toolchain', get_option('wave-rust-toolchain')] + if get_option('wave-allow-network') + arguments += ['--allow-network'] + endif + wave_aarch64_module = custom_target('wave-aarch64', + output: [archive_name, 'wave-aarch64.meta', 'provenance.json'], + command: [python, files('../../tools/build_wave_assembler.py'), arguments], + depend_files: files( + '../model.wave', + '../declarations.wave', + '../fixed_model.wave', + '../fixed_declarations.wave', + 'registers.wave', + 'parser.wave', + 'operands.wave', + 'encoding.wave', + 'encoder.wave', + 'entry.wave', + 'src/wave.rs', + 'src/lib.rs', + 'src/encoder.rs', + 'src/parser.rs', + '../../tools/build_wave_assembler.py', + '../../tools/wave_bootstrap.py', + '../build_support.rs', + ), + depends: wave_bootstrap, console: true) + wave_aarch64_dependencies += [wave_aarch64_module] +elif wave_aarch64_directory != '' + if not fs.is_absolute(wave_aarch64_directory) + error('-Dwave-aarch64-dir must be absolute.') + endif + archive_name = host_machine.system() == 'windows' ? 'whale_wave_aarch64.lib' : 'libwhale_wave_aarch64.a' + foreach artifact : [archive_name, 'wave-aarch64.meta', 'provenance.json'] + if not fs.is_file(wave_aarch64_directory / artifact) + error('Missing Wave aarch64 artifact: ' + (wave_aarch64_directory / artifact)) + endif + endforeach +endif +wave_assembler_all_dependencies += wave_aarch64_dependencies diff --git a/assembler/aarch64/operands.wave b/assembler/aarch64/operands.wave new file mode 100644 index 0000000..3c1f7ed --- /dev/null +++ b/assembler/aarch64/operands.wave @@ -0,0 +1,101 @@ +// SPDX-License-Identifier: MPL-2.0 +// Shift modifiers and base-plus-offset addresses are parsed without allocation. +struct A64Shift { + kind: u64; + amount: u64; +} + +struct A64Memory { + base: A64Register; + offset: AsmWide; +} + +fun a64_shift(text: FixedText, width: u64, output: ptr, + result: ptr) -> bool { + if (!asm_fixed_charge(result, text.count)) { + return false; + } + var trimmed: FixedText = asm_fixed_trim(text); + var start: u64 = 0; + var at: u64 = 0; + var count: u64 = 0; + var words: array; + while (at < trimmed.count) { + if (!asm_fixed_charge(result, 1)) { + return false; + } + var space: u64 = asm_fixed_space(trimmed, at); + if (space != 0) { + if (at > start) { + if (count >= 2) { + return a64_fail(result, 1003); + } + words[count].data = &trimmed.data[start]; + words[count].count = at - start; + count += 1; + } + at += space; + start = at; + } else { + at += 1; + } + } + if (at > start) { + if (count >= 2) { + return a64_fail(result, 1003); + } + words[count].data = &trimmed.data[start]; + words[count].count = at - start; + count += 1; + } + if (count != 2) { + return a64_fail(result, 1003); // Shift requires kind and amount. + } + output.kind = 0; + if (asm_fixed_word(words[0], 7107436, 3, 1)) { // lsl + output.kind = 0; + } else if (asm_fixed_word(words[0], 7500652, 3, 1)) { // lsr + output.kind = 1; + } else if (asm_fixed_word(words[0], 7500641, 3, 1)) { // asr + output.kind = 2; + } else if (asm_fixed_word(words[0], 7499634, 3, 1)) { // ror + output.kind = 3; + } else { + return a64_fail(result, 1004); // Unsupported shift kind. + } + var bits: u64 = 5; + if (width == 64) { + bits = 6; + } + return asm_fixed_unsigned(words[1], bits, &output.amount, result); +} + +fun a64_memory(text: FixedText, output: ptr, result: ptr) -> bool { + if (text.count < 2 || text.data[0] != 91 || text.data[text.count - 1] != 93) { + return a64_fail(result, 1005); // Writeback and non-bracketed memory are unsupported. + } + var inside: FixedText; + inside.data = &text.data[1]; + inside.count = text.count - 2; + var count: u64 = 0; + if (!asm_fixed_operands(inside, null, 0, &count, result)) { + return false; + } + if (count == 0 || count > 2) { + return a64_fail(result, 1006); + } + var parts: array; + if (!asm_fixed_operands(inside, &parts[0], 2, &count, result) + || !a64_register(parts[0], &output.base, result)) { + return false; + } + if (output.base.width != 64 || output.base.zero != 0) { + return a64_fail(result, 1007); // Base requires X0..X30 or SP. + } + output.offset.low = 0; + output.offset.high = 0; + if (count == 2) { + return asm_fixed_integer(parts[1], &output.offset, result); + } + return true; +} diff --git a/assembler/aarch64/parser.wave b/assembler/aarch64/parser.wave new file mode 100644 index 0000000..ffcea54 --- /dev/null +++ b/assembler/aarch64/parser.wave @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: MPL-2.0 +// Typed register parsing and diagnostic selection stay in the A64 module. +fun a64_fail(result: ptr, code: u64) -> bool { + var empty: FixedText; + empty.data = null; + empty.count = 0; + return asm_fixed_fail(result, code, empty, 0); +} + +fun a64_register(text: FixedText, output: ptr, result: ptr) -> bool { + if (!asm_fixed_charge(result, text.count)) { + return false; + } + var trimmed: FixedText = asm_fixed_trim(text); + if (!a64_register_bytes(trimmed.data, trimmed.count, output)) { + asm_fixed_fail(result, 1000, trimmed, 0); + result.display = 1; + return false; + } + return true; +} + +fun a64_same(left: ptr, right: ptr, result: ptr) -> bool { + if (left.width != right.width) { + return a64_fail(result, 1001); // Register widths must match. + } + return true; +} + +fun a64_no_sp(register: ptr, result: ptr) -> bool { + if (register.sp != 0) { + return a64_fail(result, 1002); // SP is not valid in this operand. + } + return true; +} + +fun a64_mnemonic(instruction: ptr, key: u64, length: u64) -> bool { + return asm_fixed_word(instruction.mnemonic, key, length, instruction.fold); +} diff --git a/assembler/aarch64/registers.wave b/assembler/aarch64/registers.wave new file mode 100644 index 0000000..ecddec2 --- /dev/null +++ b/assembler/aarch64/registers.wave @@ -0,0 +1,103 @@ +// SPDX-License-Identifier: MPL-2.0 +// Register 31 retains its distinct stack-pointer and zero-register roles. +struct A64Register { + index: u64; + width: u64; + sp: u64; + zero: u64; +} + +fun a64_lower(value: u8) -> u8 { + if (value >= 65 && value <= 90) { + return value + 32; + } + return value; +} + +fun a64_keyword(bytes: ptr, count: u64, key: u64, length: u64, fold: bool) -> bool { + if (count != length) { + return false; + } + var index: u64 = 0; + while (index < count) { + var value: u8 = bytes[index]; + if (fold) { + value = a64_lower(value); + } + if (value != ((key >> (index * 8)) & 255) as u8) { + return false; + } + index += 1; + } + return true; +} + +fun a64_register_bytes(bytes: ptr, count: u64, output: ptr) -> bool { + output.index = 0; + output.width = 64; + output.sp = 0; + output.zero = 0; + // sp, wsp, xzr, wzr + if (a64_keyword(bytes, count, 28787, 2, true) + || a64_keyword(bytes, count, 7369591, 3, true)) { + output.index = 31; + output.sp = 1; + if (count == 3) { + output.width = 32; + } + return true; + } + if (a64_keyword(bytes, count, 7502456, 3, true) + || a64_keyword(bytes, count, 7502455, 3, true)) { + output.index = 31; + output.zero = 1; + if (a64_lower(bytes[0]) == 119) { + output.width = 32; + } + return true; + } + // fp, lr + if (a64_keyword(bytes, count, 28774, 2, true)) { + output.index = 29; + return true; + } + if (a64_keyword(bytes, count, 29292, 2, true)) { + output.index = 30; + return true; + } + if (count < 2 || count > 3) { + return false; + } + var prefix: u8 = a64_lower(bytes[0]); + if (prefix != 120 && prefix != 119) { + return false; + } + if (prefix == 119) { + output.width = 32; + } + if (count == 3 && bytes[1] == 48) { + return false; + } + var index: u64 = 1; + var number: u64 = 0; + while (index < count) { + var digit: u8 = bytes[index]; + if (digit < 48 || digit > 57) { + return false; + } + number = number * 10 + (digit - 48) as u64; + index += 1; + } + if (number > 30) { + return false; + } + output.index = number; + return true; +} + +fun a64_sf(register: ptr) -> u64 { + if (register.width == 64) { + return 2147483648; + } + return 0; +} diff --git a/assembler/aarch64/src/encoder.rs b/assembler/aarch64/src/encoder.rs index 2f0c6aa..8280fd6 100644 --- a/assembler/aarch64/src/encoder.rs +++ b/assembler/aarch64/src/encoder.rs @@ -7,7 +7,8 @@ use crate::{ }; use assembler::{ - fixed::{self, count, error, unsigned, Context, Instruction}, + fixed::reference::{self as fixed, count, error, unsigned}, + fixed::{Context, Instruction}, AsmError, }; @@ -119,7 +120,7 @@ pub(crate) fn encode(inst: &Instruction, cx: &mut Context<'_>) -> Result { let a = count(inst, 2)?; @@ -128,7 +129,7 @@ pub(crate) fn encode(inst: &Instruction, cx: &mut Context<'_>) -> Result { @@ -137,13 +138,16 @@ pub(crate) fn encode(inst: &Instruction, cx: &mut Context<'_>) -> Result { let condition = tables::condition(&m[2..]).ok_or_else(|| error("invalid A64 branch condition"))?; let a = count(inst, 1)?; - branch::conditional(condition, cx.pc_relative(&a[0], tables::CONDBR19_RELOCATION)?) + branch::conditional( + condition, + cx.pc_relative_reference(&a[0], tables::CONDBR19_RELOCATION)?, + ) }, _ => Err(error(format!("unsupported A64 instruction {m:?}"))), } diff --git a/assembler/aarch64/src/encoding/arithmetic.rs b/assembler/aarch64/src/encoding/arithmetic.rs index 51acf59..a16e9c9 100644 --- a/assembler/aarch64/src/encoding/arithmetic.rs +++ b/assembler/aarch64/src/encoding/arithmetic.rs @@ -5,7 +5,8 @@ use super::sf; use crate::parser::{no_sp, reg, same, shift}; use assembler::{ - fixed::{self, error, unsigned, Instruction}, + fixed::reference::{self as fixed, error, unsigned}, + fixed::Instruction, AsmError, }; diff --git a/assembler/aarch64/src/encoding/branch.rs b/assembler/aarch64/src/encoding/branch.rs index 8484947..f43cbd9 100644 --- a/assembler/aarch64/src/encoding/branch.rs +++ b/assembler/aarch64/src/encoding/branch.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MPL-2.0 //! A64 branch ranges, scaled immediates and split ADR immediate fields. -use assembler::{fixed::displacement, AsmError}; +use assembler::{fixed::reference::displacement, AsmError}; pub(crate) fn direct(link: bool, offset: i64) -> Result { Ok(if link { 0x94000000 } else { 0x14000000 } | displacement(offset, 26, 4)?) diff --git a/assembler/aarch64/src/encoding/memory.rs b/assembler/aarch64/src/encoding/memory.rs index 3568344..d59a663 100644 --- a/assembler/aarch64/src/encoding/memory.rs +++ b/assembler/aarch64/src/encoding/memory.rs @@ -3,7 +3,8 @@ use crate::parser::{no_sp, reg}; use assembler::{ - fixed::{count, error, Instruction}, + fixed::reference::{count, error}, + fixed::Instruction, AsmError, }; diff --git a/assembler/aarch64/src/lib.rs b/assembler/aarch64/src/lib.rs index e4f2ae7..076e035 100644 --- a/assembler/aarch64/src/lib.rs +++ b/assembler/aarch64/src/lib.rs @@ -1,18 +1,25 @@ // SPDX-License-Identifier: MPL-2.0 //! AArch64 assembler entry point; instruction handling lives in the ISA modules. use assembler::{ - fixed::{self, Context, FixedIsa, Instruction}, + fixed::{Context, FixedIsa, Instruction}, AsmError, AssemblerOutput, AssemblyLimits, }; +#[cfg(any(not(whale_wave_aarch64), test))] mod encoder; +#[cfg(any(not(whale_wave_aarch64), test))] mod encoding; +#[cfg(any(not(whale_wave_aarch64), test))] mod parser; +#[cfg(any(not(whale_wave_aarch64), test))] mod tables; +#[cfg(whale_wave_aarch64)] +mod wave; + pub struct AArch64; impl assembler::extension::Assembler for AArch64 { @@ -30,7 +37,14 @@ impl assembler::extension::Assembler for AArch64 { source: &str, limits: &AssemblyLimits, ) -> Result { - fixed::assemble(self, name, source, limits) + #[cfg(whale_wave_aarch64)] + { + wave::assemble(name, source, limits) + } + #[cfg(not(whale_wave_aarch64))] + { + assembler::fixed::reference::assemble(self, name, source, limits) + } } } @@ -43,11 +57,28 @@ impl FixedIsa for AArch64 { false } + #[cfg(whale_wave_aarch64)] + fn native_assemble( + &self, + name: &str, + source: &str, + limits: &AssemblyLimits, + ) -> Option> { + Some(wave::assemble(name, source, limits)) + } + fn encode( &self, instruction: &Instruction, context: &mut Context<'_>, ) -> Result { - encoder::encode(instruction, context) + #[cfg(whale_wave_aarch64)] + { + wave::encode(instruction, context) + } + #[cfg(not(whale_wave_aarch64))] + { + encoder::encode(instruction, context) + } } } diff --git a/assembler/aarch64/src/parser.rs b/assembler/aarch64/src/parser.rs index e12898f..d905681 100644 --- a/assembler/aarch64/src/parser.rs +++ b/assembler/aarch64/src/parser.rs @@ -3,7 +3,7 @@ use crate::tables; use assembler::{ - fixed::{self, error, unsigned}, + fixed::reference::{self as fixed, error, unsigned}, AsmError, }; diff --git a/assembler/aarch64/src/wave.rs b/assembler/aarch64/src/wave.rs new file mode 100644 index 0000000..0562143 --- /dev/null +++ b/assembler/aarch64/src/wave.rs @@ -0,0 +1,383 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Typed buffers and diagnostic text for the native A64 module. +use assembler::fixed::{native, Context, Instruction}; + +use assembler::{AsmError, AssemblerOutput, AssemblyLimits}; + +use native::{FixedContext, FixedInput, FixedInstruction, FixedResult}; + +unsafe extern "C" { + fn whale_aarch64_assemble(packet: *const FixedInput, result: *mut FixedResult) -> i32; + + fn whale_aarch64_encode( + instruction: *const FixedInstruction, + context: *mut FixedContext, + result: *mut FixedResult, + ) -> i32; +} + +fn render(code: u64, text: &str, _detail: u64) -> AsmError { + let message = match code { + 1000 => return assembler::fixed::error(format!("invalid A64 register {text:?}")), + 1001 => "register widths must match", + 1002 => "SP is not valid in this operand", + 1003 => "shift requires kind and amount", + 1004 => "unsupported shift kind", + 1005 => "memory operand requires [base, #offset]; writeback is unsupported", + 1006 => "memory operand accepts a base and immediate offset", + 1007 => "memory base requires X0..X30 or SP", + 1008 => "indirect control flow requires X0..X30", + 1009 => "mov cannot mix SP and ZR", + 1010 => "wide move requires register, imm16 and optional lsl", + 1011 => "wide move shift must be 0/16 for W, or 0/16/32/48 for X", + 1012 => "logical register operation requires three operands and optional shift", + 1013 => "adr requires an X register", + 1014 => "invalid A64 branch condition", + 1015 => return assembler::fixed::error(format!("unsupported A64 instruction {text:?}")), + 1016 => "mov immediate does not fit the destination register width", + 1017 => "mov immediate requires a single 16-bit MOVZ/MOVN; use movz/movk for larger values", + 1018 => "comparison requires operands", + 1019 => "arithmetic requires three operands and optional shift", + 1020 => "immediate arithmetic uses SP for register 31, except the flag-setting destination", + 1021 => "immediate add/sub accepts only lsl #0 or #12", + 1022 => "add/sub does not support ror", + 1023 => "byte/halfword transfer requires a W register", + 1024 => "ldrsw requires an X register", + 1025 => "unsigned load/store offset must be scaled, nonnegative and fit 12 bits", + 1026 => "unscaled load/store offset must fit signed 9 bits", + _ => return AsmError::Backend("A64 diagnostic transport"), + }; + assembler::fixed::error(message) +} + +pub(super) fn assemble( + name: &str, + source: &str, + limits: &AssemblyLimits, +) -> Result { + native::assemble(name, source, limits, "aarch64", false, whale_aarch64_assemble, render) +} + +pub(super) fn encode( + instruction: &Instruction, + context: &mut Context<'_>, +) -> Result { + native::encode(instruction, context, whale_aarch64_encode, render) +} + +#[cfg(test)] +mod tests { + use super::*; + + use assembler::fixed::FixedIsa; + + struct ReferenceA64; + + impl FixedIsa for ReferenceA64 { + fn id(&self) -> &'static str { + "aarch64" + } + + fn hash_comments(&self) -> bool { + false + } + + fn encode( + &self, + instruction: &Instruction, + context: &mut Context<'_>, + ) -> Result { + crate::encoder::encode(instruction, context) + } + } + + fn snapshot(output: &AssemblerOutput) -> String { + let sections: Vec<_> = output + .sections + .iter() + .map(|section| { + let relocations: Vec<_> = section + .relocs + .iter() + .map(|relocation| { + ( + relocation.offset, + &relocation.symbol, + format!("{:?}", relocation.kind), + relocation.addend, + ) + }) + .collect(); + ( + §ion.name, + section.kind, + section.align, + §ion.data, + section.zero_fill, + relocations, + ) + }) + .collect(); + let symbols: Vec<_> = output + .symbols + .iter() + .map(|symbol| { + ( + &symbol.name, + symbol.kind, + symbol.size, + symbol.visibility, + symbol.section_index, + symbol.offset, + symbol.is_global, + ) + }) + .collect(); + format!("{sections:?}/{symbols:?}") + } + + fn compare_result( + actual: Result, + expected: Result, + source: &str, + ) { + match (actual, expected) { + (Ok(actual), Ok(expected)) => { + assert_eq!(snapshot(&actual), snapshot(&expected), "{source}") + }, + (Err(actual), Err(expected)) => { + assert_eq!(actual.to_string(), expected.to_string(), "{source}") + }, + (actual, expected) => { + panic!("A64 divergence {source:?}: {:?}/{:?}", actual.err(), expected.err()) + }, + } + } + + fn compare(source: &str) { + compare_result( + assemble("oracle.s", source, &AssemblyLimits::default()), + assembler::fixed::reference::assemble( + &ReferenceA64, + "oracle.s", + source, + &AssemblyLimits::default(), + ), + source, + ); + } + + #[test] + fn native_a64_matches_retained_independent_instruction_and_error_policy() { + for source in [ + "nop", + "ret", + "RET X9", + "mov x0,sp", + "mov sp,x0", + "mov wzr,#0", + "mov x0,#-65536", + "mov w1,#-2147483648", + "mov x2,#0xffff000000000000", + "movz w0,#3,LSL\u{2003}#16", + "b.eq #-4", + "b.hs #4", + "b.lo #0", + "b.nv #8", + "adr x0,#-1", + "cbnz xzr,#4", + "ldr x0,[sp,#32760]", + "ldur xzr,[x30,#-256]", + "ldr w0,[x1]", + "strh wzr,[sp,#2]", + "mov x31,#1", + "mov X01,x0", + "mov x0,w1", + "mov sp,xzr", + "mov xzr,sp", + "add sp,x0,x1", + "adds sp,sp,#1", + "add xzr,x0,#1", + "add x0,xzr,#1", + "cmp xzr,#1", + "cmp", + "cmp BAD", + "cmp x0", + "cmp bad,x0,x1,x2", + "add x0,x1,x2,ror #1", + "add x0,x1,#1,lsl #1", + "mov x0,#0x12345678", + "mov w0,#4294967296", + "mov x0,#-9223372036854775809", + "mov x0,#0x+1", + "mov x0,#0b+1", + "mov x0,#0x-1", + "mov x0,#-0x-1", + "mov x0,#0x_+_1_", + "mov x0,#0x-80000000000000000000000000000000", + "mov x0,#-0x-80000000000000000000000000000000", + "svc #0x+1", + "mov x0,#-170141183460469231731687303715884105728", + "mov x0,#170141183460469231731687303715884105728", + "movk w0,#1,lsl #32", + "movz x0,#65536", + "movz sp,#1", + "movz x0,#1,lsr #16", + "lsl w0,w1,#32", + "asr x0,x1,#64", + "and x0,x1,x2,rotate #1", + "orr x0,x1,x2,lsl #1 #2", + "ldr x0,[w1]", + "ldr x0,[xzr]", + "ldr x0,[]", + "ldr x0,[x1,#1,#2]", + "ldr x0,[x1,,#2]", + "ldr x0,[x1,#1]", + "ldr x0,[x1] !", + "ldur x0,[sp,#256]", + "ldrsw w0,[x1]", + "ldrb x0,[x1]", + "br sp", + "ret xzr", + "ret w0", + "svc #-1", + "svc #65536", + "b.eq #2", + "b #134217728", + "adr w0,#0", + "b.what #0", + "b.eq", + "unsupported", + "mov bad,#1\nfoo:\nfoo:\n", + ".word missing\n.invalid\n", + "mov bad,#1\n.bss\nnop\n", + ] { + compare(source); + } + } + + #[test] + fn native_a64_matches_sections_symbols_relocations_and_legacy_source_order() { + for source in [ + ".global entry\n.extern external\nentry: bl external+4\nb local\nlocal: adr x0,entry\nret\n", + ".text\nstart: b datum\n.data\ndatum: .quad start+8\n.word start-4\n.bss\n.zero 4096\n.align 12\n", + ".section .custom\n.byte 1,2,-1\n.hword 65535\n.short -32768\n.long 4294967295\n.balign 16\n", + "\u{2003}MAIN:\u{00a0}MOV\u{2003}X0,#1\r\nret // preserved comment\n", + ".global missing\nnop\n", ".extern x\nx: nop\n", "x: nop\n.extern x\n", + ".bss\n.word 0\n", ".text\n.byte 1\nnop\n", ".word undefined\n", ".byte undefined\n", + ] { compare(source); } + } + + #[test] + fn generated_native_a64_fields_match_independent_reference_words() { + let mut random = 0x0358_6400_0001_u64; + for _ in 0..5000 { + random ^= random << 13; + random ^= random >> 7; + random ^= random << 17; + let wide = random & 1 != 0; + let prefix = if wide { "x" } else { "w" }; + let rd = random % 31; + let rn = (random >> 7) % 31; + let rm = (random >> 13) % 31; + let shift = (random >> 19) % if wide { 64 } else { 32 }; + let immediate = (random >> 25) & 4095; + let source = match (random >> 37) % 8 { + 0 => format!("add {prefix}{rd},{prefix}{rn},{prefix}{rm},lsl #{shift}"), + 1 => format!("subs {prefix}{rd},{prefix}{rn},#{immediate},lsl #12"), + 2 => format!("orr {prefix}{rd},{prefix}{rn},{prefix}{rm},ror #{shift}"), + 3 => format!("asr {prefix}{rd},{prefix}{rn},#{shift}"), + 4 => format!( + "movk {prefix}{rd},#{},lsl #{}", + random & 65535, + ((random >> 48) % if wide { 4 } else { 2 }) * 16 + ), + 5 => format!("ldr {prefix}{rd},[x{rn},#{}]", immediate * if wide { 8 } else { 4 }), + 6 => format!("stur {prefix}{rd},[x{rn},#{}]", ((random >> 45) & 511) as i64 - 256), + _ => format!( + "cbnz {prefix}{rd},#{}", + (((random >> 21) & 0x7ffff) as i64 - 0x40000) * 4 + ), + }; + compare(&source); + } + } + + struct Manual<'a> { + instruction: &'a Instruction, + native: bool, + } + + impl FixedIsa for Manual<'_> { + fn id(&self) -> &'static str { + "aarch64" + } + + fn encode( + &self, + _instruction: &Instruction, + context: &mut Context<'_>, + ) -> Result { + if self.native { + encode(self.instruction, context) + } else { + crate::encoder::encode(self.instruction, context) + } + } + } + + #[test] + fn direct_leaf_keeps_manual_spelling_and_context_authority() { + for (mnemonic, operands) in [ + ("MOV", vec!["x0", "#1"]), + ("mov", vec!["\u{2003}X0\u{00a0}", "#1"]), + ("ldr", vec!["x0", " [x1]"]), + ("ldr", vec!["x0", "[x1] "]), + ("add", vec!["x0", "x1", "x2", "lsl\u{2003}#1"]), + ("bl", vec!["Target+4"]), + ("adr", vec!["x0", "Target-8"]), + ] { + let instruction = Instruction { + mnemonic: mnemonic.into(), + operands: operands.into_iter().map(str::to_owned).collect(), + }; + let source = ".extern Target\nnop\n"; + compare_result( + assembler::fixed::reference::assemble( + &Manual { instruction: &instruction, native: true }, + "manual.s", + source, + &AssemblyLimits::default(), + ), + assembler::fixed::reference::assemble( + &Manual { instruction: &instruction, native: false }, + "manual.s", + source, + &AssemblyLimits::default(), + ), + mnemonic, + ); + } + } + + #[test] + fn malformed_native_records_do_not_fabricate_instruction_words() { + let mut result = FixedResult { word: u64::MAX, ..FixedResult::default() }; + assert_eq!(unsafe { whale_aarch64_assemble(std::ptr::null(), &mut result) }, 2); + assert_eq!((result.status, result.word), (2, 0)); + result = FixedResult { word: u64::MAX, ..FixedResult::default() }; + assert_eq!( + unsafe { whale_aarch64_encode(std::ptr::null(), std::ptr::null_mut(), &mut result) }, + 2 + ); + assert_eq!((result.status, result.word), (2, 0)); + let instruction = FixedInstruction { + mnemonic: native::FixedText { data: std::ptr::null(), count: u64::MAX }, + ..FixedInstruction::default() + }; + let mut context = FixedContext::default(); + result = FixedResult::default(); + assert_eq!(unsafe { whale_aarch64_encode(&instruction, &mut context, &mut result) }, 2); + assert_eq!((result.status, result.word), (2, 0)); + } +} diff --git a/assembler/asmobj/README.md b/assembler/asmobj/README.md index 3b49581..a686b52 100644 --- a/assembler/asmobj/README.md +++ b/assembler/asmobj/README.md @@ -8,7 +8,8 @@ implementation, or language-specific `wave/` subdirectory. | `model.wave` | Private borrowed input/output records and resource checks | | `sections.wave` | Section role and sparse-storage mapping | | `symbols.wave` | Symbol mapping, name lookup and undefined-symbol creation | -| `relocations.wave` | ELF, COFF and Mach-O relocation translation by ISA | +| `relocations.wave` | Bounded namespace/target dispatch and relocation records | +| `relocations/*.wave` | ISA-owned ELF, COFF and Mach-O translation rules | | `entry.wave` | Validate the complete conversion before publishing output | Meson builds these explicit sources as one module. The calling Rust code in @@ -17,7 +18,7 @@ Meson builds these explicit sources as one module. The calling Rust code in copy of asmobj's mapping rules. An executable built without this module reports that assembly-to-object conversion is unavailable. -New architectures extend the relocation source and its tests, together with +New architectures add a relocation role file and its tests, together with ordinary target/build-list edits elsewhere in Whale. The borrowed records are private implementation details. diff --git a/assembler/asmobj/meson.build b/assembler/asmobj/meson.build index 4078573..9fc8988 100644 --- a/assembler/asmobj/meson.build +++ b/assembler/asmobj/meson.build @@ -20,7 +20,10 @@ if asmobj_directory == '' asmobj_module = custom_target('asmobj', output: [archive_name, 'asmobj.meta', 'provenance.json'], command: [python, files('../../tools/build_asmobj.py'), arguments], - depend_files: files('model.wave', 'sections.wave', 'symbols.wave', 'relocations.wave', 'entry.wave', + depend_files: files('model.wave', 'sections.wave', 'symbols.wave', + 'relocations/amd64.wave', 'relocations/aarch64.wave', + 'relocations/riscv64.wave', 'relocations/loongarch64.wave', + 'relocations.wave', 'entry.wave', '../../toolchain/src/assembly_object.rs', '../../tools/build_asmobj.py', '../../tools/wave_bootstrap.py'), depends: wave_bootstrap, console: true) diff --git a/assembler/asmobj/relocations.wave b/assembler/asmobj/relocations.wave index 657fc46..17c83b1 100644 --- a/assembler/asmobj/relocations.wave +++ b/assembler/asmobj/relocations.wave @@ -11,15 +11,11 @@ fun asmobj_relocation_kind(state: ptr, target: ptr, kind[0] = relocation.kind; code[0] = 0; if (relocation.kind == 4) { - if (target.format == 2) { - kind[0] = 8; - code[0] = 2; - } else if (undefined == 0) { - kind[0] = 3; - } + return asmobj_amd64_control(target, undefined, kind, code); + } + if (relocation.kind != 6) { return 0; } - if (relocation.kind != 6) { return 0; } var machine: u64 = 18446744073709551615; if (asmobj_literal_equal(state, relocation.namespace, relocation.namespace_len, "aarch64" as ptr, 7)) { @@ -31,27 +27,22 @@ fun asmobj_relocation_kind(state: ptr, target: ptr, "loongarch64" as ptr, 11)) { machine = 3; } - if (state.status != 0) { return state.status; } - if (machine == 18446744073709551615) { return 3; } - if (machine != target.machine) { return 4; } - if (target.format == 0) { - code[0] = relocation.code; - return 0; + if (state.status != 0) { + return state.status; } - if (target.format == 2 && machine == 1 && (relocation.code == 282 || relocation.code == 283)) { - kind[0] = 8; - code[0] = 2; - return 0; + if (machine == 18446744073709551615) { + return 3; } - if (target.format == 1 && machine == 1) { - kind[0] = 7; - if (relocation.code == 274) { code[0] = 5; } - else if (relocation.code == 280) { code[0] = 15; } - else if (relocation.code == 282 || relocation.code == 283) { code[0] = 3; } - else { return 5; } - return 0; + if (machine != target.machine) { + return 4; + } + if (machine == 1) { + return asmobj_aarch64_relocation(target, relocation, kind, code); + } + if (machine == 2) { + return asmobj_riscv64_relocation(target, relocation, code); } - return 6; + return asmobj_loongarch64_relocation(target, relocation, code); } fun asmobj_relocation_valid(relocation: ptr, section_count: u64) -> bool { diff --git a/assembler/asmobj/relocations/aarch64.wave b/assembler/asmobj/relocations/aarch64.wave new file mode 100644 index 0000000..33f2eda --- /dev/null +++ b/assembler/asmobj/relocations/aarch64.wave @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: MPL-2.0 +// AArch64 ELF IDs and the supported COFF/Mach-O translations. +fun asmobj_aarch64_relocation(target: ptr, relocation: ptr, + kind: ptr, code: ptr) -> i32 { + if (target.format == 0) { + code[0] = relocation.code; + return 0; + } + // Mach-O ARM64_RELOC_BRANCH26. + if (target.format == 2 && (relocation.code == 282 || relocation.code == 283)) { + kind[0] = 8; + code[0] = 2; + return 0; + } + if (target.format == 1) { + kind[0] = 7; + if (relocation.code == 274) { // ADR_PREL_LO21 -> REL21. + code[0] = 5; + } else if (relocation.code == 280) { // CONDBR19 -> BRANCH19. + code[0] = 15; + } else if (relocation.code == 282 || relocation.code == 283) { // JUMP26/CALL26. + code[0] = 3; + } else { + return 5; + } + return 0; + } + return 6; +} diff --git a/assembler/asmobj/relocations/amd64.wave b/assembler/asmobj/relocations/amd64.wave new file mode 100644 index 0000000..64e9cb7 --- /dev/null +++ b/assembler/asmobj/relocations/amd64.wave @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: MPL-2.0 +// Legacy near-control transfers select PC-relative or Mach-O branch forms. +fun asmobj_amd64_control(target: ptr, undefined: u64, + kind: ptr, code: ptr) -> i32 { + if (target.format == 2) { + kind[0] = 8; + code[0] = 2; + } else if (undefined == 0) { + kind[0] = 3; + } + return 0; +} diff --git a/assembler/asmobj/relocations/loongarch64.wave b/assembler/asmobj/relocations/loongarch64.wave new file mode 100644 index 0000000..2b118e2 --- /dev/null +++ b/assembler/asmobj/relocations/loongarch64.wave @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: MPL-2.0 +// LoongArch relocation numbers are preserved for ELF only. +fun asmobj_loongarch64_relocation(target: ptr, relocation: ptr, + code: ptr) -> i32 { + if (target.format != 0) { + return 6; + } + code[0] = relocation.code; + return 0; +} diff --git a/assembler/asmobj/relocations/riscv64.wave b/assembler/asmobj/relocations/riscv64.wave new file mode 100644 index 0000000..9900de1 --- /dev/null +++ b/assembler/asmobj/relocations/riscv64.wave @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: MPL-2.0 +// RISC-V relocation numbers are preserved for ELF; other formats are unsupported. +fun asmobj_riscv64_relocation(target: ptr, relocation: ptr, + code: ptr) -> i32 { + if (target.format != 0) { + return 6; + } + code[0] = relocation.code; + return 0; +} diff --git a/assembler/build.rs b/assembler/build.rs index af6eb65..90fa289 100644 --- a/assembler/build.rs +++ b/assembler/build.rs @@ -15,7 +15,21 @@ const SOURCES: &[&str] = &[ "assembler/numeric.wave", "assembler/output.wave", "assembler/lexer.wave", + "assembler/fixed_model.wave", + "assembler/fixed_text.wave", + "assembler/fixed_numbers.wave", + "assembler/fixed_operands.wave", + "assembler/fixed_namespace.wave", + "assembler/fixed_relative.wave", + "assembler/fixed_scalar.wave", + "assembler/fixed_source.wave", + "assembler/fixed_driver.wave", ]; -const ABI_SOURCES: &[&str] = &["assembler/src/tokens.rs", "assembler/src/tokens_wave.rs"]; +const ABI_SOURCES: &[&str] = &[ + "assembler/src/tokens.rs", + "assembler/src/tokens_wave.rs", + "assembler/src/fixed.rs", + "assembler/src/fixed_wave.rs", +]; include!("build_support.rs"); diff --git a/assembler/build_support.rs b/assembler/build_support.rs index aaad8d5..1ea1241 100644 --- a/assembler/build_support.rs +++ b/assembler/build_support.rs @@ -35,10 +35,10 @@ fn main() { println!("cargo:rustc-check-cfg=cfg({CFG})"); println!("cargo:rerun-if-env-changed={ENV}"); let Some(directory) = env::var_os(ENV) else { return }; - if CFG == "whale_wave_amd64" { + if CFG != "whale_wave_assembler" { assert!( env::var_os("WHALE_WAVE_ASSEMBLER_DIR").is_some(), - "Wave AMD64 requires WHALE_WAVE_ASSEMBLER_DIR for shared assembler utilities" + "Wave ISA modules require WHALE_WAVE_ASSEMBLER_DIR for shared assembler utilities" ); } let directory = PathBuf::from(directory) diff --git a/assembler/fixed_declarations.wave b/assembler/fixed_declarations.wave new file mode 100644 index 0000000..374d95a --- /dev/null +++ b/assembler/fixed_declarations.wave @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: MPL-2.0 +// Ordinary internal links to the shared fixed-width source helpers. +extern(c) fun asm_fixed_trim(text: FixedText) -> FixedText; +extern(c) fun asm_fixed_word(text: FixedText, word: u64, count: u64, fold: u64) -> bool; +extern(c) fun asm_fixed_equal(left: FixedText, right: FixedText, fold: u64) -> bool; +extern(c) fun asm_fixed_fail(result: ptr, code: u64, + text: FixedText, detail: u64) -> bool; +extern(c) fun asm_fixed_count(instruction: ptr, count: u64, + result: ptr) -> bool; +extern(c) fun asm_fixed_integer(text: FixedText, output: ptr, + result: ptr) -> bool; +extern(c) fun asm_fixed_try_integer(text: FixedText, output: ptr, + result: ptr) -> bool; +extern(c) fun asm_fixed_signed(text: FixedText, bits: u64, output: ptr, + result: ptr) -> bool; +extern(c) fun asm_fixed_unsigned(text: FixedText, bits: u64, output: ptr, + result: ptr) -> bool; +extern(c) fun asm_fixed_i64(text: FixedText, output: ptr, + result: ptr) -> bool; +extern(c) fun asm_fixed_displacement(value: i64, bits: u64, alignment: i64, + output: ptr, result: ptr) -> bool; +extern(c) fun asm_fixed_pc_relative(context: ptr, text: FixedText, + code: u64, output: ptr, result: ptr) -> bool; +extern(c) fun asm_fixed_operands(text: FixedText, output: ptr, capacity: u64, + count: ptr, result: ptr) -> bool; +extern(c) fun asm_fixed_result_init(result: ptr, max_work: u64); +extern(c) fun asm_fixed_charge(result: ptr, units: u64) -> bool; +extern(c) fun asm_fixed_space(text: FixedText, at: u64) -> u64; +extern(c) fun asm_fixed_prepare(packet: ptr, state: ptr, + result: ptr) -> bool; +// next: 1 requests one instruction, 0 completes, -1 reports failure. +extern(c) fun asm_fixed_next(state: ptr, instruction: ptr, + result: ptr) -> i32; +extern(c) fun asm_fixed_commit(state: ptr, word: u64, + result: ptr) -> bool; +extern(c) fun asm_fixed_identifier(text: FixedText, result: ptr) -> bool; +extern(c) fun asm_fixed_symbol(state: ptr, name: FixedText, kind: u64, + result: ptr) -> u64; +extern(c) fun asm_fixed_section(state: ptr, name: FixedText, + result: ptr) -> bool; +extern(c) fun asm_fixed_record(state: ptr, record: ptr, + result: ptr) -> bool; +extern(c) fun asm_fixed_finish(state: ptr, result: ptr) -> bool; +extern(c) fun asm_fixed_lookup(context: ptr, name: FixedText, + result: ptr) -> u64; +extern(c) fun asm_fixed_expression(context: ptr, text: FixedText, + number: ptr, symbol: ptr, addend: ptr, result: ptr) -> bool; diff --git a/assembler/fixed_driver.wave b/assembler/fixed_driver.wave new file mode 100644 index 0000000..863ba64 --- /dev/null +++ b/assembler/fixed_driver.wave @@ -0,0 +1,443 @@ +// SPDX-License-Identifier: MPL-2.0 +// Shared native preparation and publication; the owning ISA supplies each word. +fun asm_fixed_packet_valid(packet: ptr, result: ptr) -> bool { + if (packet == null || packet.mode > 1 || packet.hash_comments > 1 + || packet.section_capacity == 0 || packet.global_capacity < packet.symbol_capacity + || packet.order_capacity < packet.symbol_capacity + || !asm_power_two(packet.table_capacity) || packet.table_capacity < 2 + || packet.symbol_capacity > packet.table_capacity / 2 + || !asm_span_valid(packet.source.data, packet.source.count, 1) + || !asm_span_valid(packet.namespace.data, packet.namespace.count, 1) + || !asm_span_valid(packet.sections as ptr, packet.section_capacity, 48) + || !asm_span_valid(packet.symbols as ptr, packet.symbol_capacity, 64) + || !asm_span_valid(packet.table as ptr, packet.table_capacity, 8) + || !asm_span_valid(packet.globals as ptr, packet.global_capacity, 24) + || !asm_span_valid(packet.records as ptr, packet.record_capacity, 96) + || !asm_span_valid(packet.operands as ptr, packet.operand_capacity, 16) + || !asm_span_valid(packet.order as ptr, packet.order_capacity, 8) + || !asm_span_valid(packet.relocations as ptr, packet.relocation_capacity, 40) + || !asm_span_valid(packet.bytes, packet.byte_capacity, 1)) { + return asm_fixed_fail(result, 94, result.text, 0); + } + if (packet.source.count > 8388608) { + return asm_fixed_fail(result, 41, packet.source, 0); + } + if (packet.max_passes == 0) { + return asm_fixed_fail(result, 42, packet.source, 0); + } + return true; +} + +export(c) fun asm_fixed_prepare(packet: ptr, state: ptr, + result: ptr) -> bool { + if (result == null || packet == null || state == null) { + return false; + } + asm_fixed_result_init(result, packet.max_work); + if (!asm_fixed_packet_valid(packet, result)) { + return false; + } + state.packet = packet; + state.context.source = packet.source; + state.context.namespace = packet.namespace; + state.context.symbols = packet.symbols; + state.context.symbol_count = 0; + state.context.table = packet.table; + state.context.table_capacity = packet.table_capacity; + state.context.section = 0; + state.context.offset = 0; + state.context.relocations = packet.relocations; + state.context.relocation_count = 0; + state.context.relocation_capacity = packet.relocation_capacity; + state.section_count = 1; + state.symbol_count = 0; + state.definition_count = 0; + state.global_count = 0; + state.record_count = 0; + state.operand_count = 0; + state.selected = 0; + state.materialized = 0; + state.next = 0; + state.pending = 0; + packet.sections[0].name.data = null; + packet.sections[0].name.count = 0; + packet.sections[0].kind = 0; + packet.sections[0].align = 4; + packet.sections[0].size = 0; + packet.sections[0].first = 0; + var at: u64 = 0; + while (at < packet.table_capacity) { + if (!asm_fixed_charge(result, 1)) { + return false; + } + packet.table[at] = 18446744073709551615; + at += 1; + } + if (!asm_fixed_source(state, result) || !asm_fixed_finish(state, result)) { + return false; + } + state.context.symbol_count = state.symbol_count; + if (packet.mode == 1 && state.materialized > packet.byte_capacity) { + return asm_fixed_fail(result, 94, packet.source, 0); + } + return true; +} + +fun asm_fixed_publish(state: ptr, section: u64, offset: u64, + value: u64, width: u64, result: ptr) -> bool { + var at: u64 = 0; + if (section >= state.section_count || width > 8 + || offset > state.packet.sections[section].size + || width > state.packet.sections[section].size - offset) { + return asm_fixed_fail(result, 94, result.text, 0); + } + if (state.packet.mode == 1) { + var first: u64 = state.packet.sections[section].first; + if (first > state.packet.byte_capacity || offset > state.packet.byte_capacity - first + || width > state.packet.byte_capacity - first - offset) { + return asm_fixed_fail(result, 94, result.text, 0); + } + while (at < width) { + state.packet.bytes[first + offset + at] = (value >> (at * 8)) as u8; + at += 1; + } + } + return true; +} + +fun asm_fixed_data(state: ptr, record: ptr, + result: ptr) -> bool { + var at: u64 = 0; + var number: AsmWide; + var symbol: u64 = 0; + var addend: i64 = 0; + var location: u64 = record.offset; + var code: u64 = 18446744073709551615; + var relocation: ptr; + if (record.unit != 1 && record.unit != 2 && record.unit != 4 && record.unit != 8) { + return asm_fixed_fail(result, 94, record.mnemonic, 0); + } + while (at < record.count) { + if (!asm_fixed_charge(result, 1) + || !asm_fixed_expression(&state.context, + state.packet.operands[record.first + at], &number, &symbol, &addend, result)) { + return false; + } + if (symbol == 18446744073709551615) { + if (!asm_number_fits_signed(&number, record.unit * 8) + && !asm_number_fits_unsigned(&number, record.unit * 8)) { + return asm_fixed_fail(result, 79, record.mnemonic, 0); + } + } else { + if (symbol >= state.context.symbol_count) { + return asm_fixed_fail(result, 13, result.text, 0); + } + if (record.unit != 4 && record.unit != 8) { + return asm_fixed_fail(result, 80, record.mnemonic, 0); + } + if (state.context.relocation_count >= state.context.relocation_capacity) { + return asm_fixed_fail(result, 94, record.mnemonic, 0); + } + code = 18446744073709551615; + if (record.unit == 8) { + code = 18446744073709551614; + } + relocation = &state.context.relocations[state.context.relocation_count]; + relocation.section = record.section; + relocation.offset = location; + relocation.symbol = symbol; + relocation.code = code; + relocation.addend = addend; + state.context.relocation_count += 1; + number.low = 0; + number.high = 0; + } + if (!asm_fixed_publish(state, record.section, location, number.low, record.unit, result)) { + return false; + } + location += record.unit; + at += 1; + } + return true; +} + +export(c) fun asm_fixed_next(state: ptr, instruction: ptr, + result: ptr) -> i32 { + if (state == null || instruction == null || result == null || state.packet == null) { + return -1; + } + if (result.status != 0 || state.pending != 0) { + if (result.status == 0) { + asm_fixed_fail(result, 94, result.text, 0); + } + return -1; + } + var record: ptr; + var section: ptr; + var at: u64 = 0; + while (state.next < state.record_count) { + if (!asm_fixed_charge(result, 1)) { + return -1; + } + record = &state.packet.records[state.next]; + result.start = record.start; + result.end = record.end; + result.line = record.line; + result.previous_line = 0; + result.previous_start = 0; + result.previous_end = 0; + result.text = record.mnemonic; + if (record.section >= state.section_count + || record.first > state.operand_count + || record.count > state.operand_count - record.first) { + asm_fixed_fail(result, 94, record.mnemonic, 0); + return -1; + } + section = &state.packet.sections[record.section]; + state.context.section = record.section; + state.context.offset = record.offset; + if (section.kind == 3) { + state.next += 1; + continue; + } + if (record.kind == 0) { + instruction.mnemonic = record.mnemonic; + instruction.operands = state.packet.operands; + if (record.count != 0) { + instruction.operands = &state.packet.operands[record.first]; + } + instruction.count = record.count; + instruction.fold = 1; + state.pending = 1; + return 1; + } + if (record.kind == 1) { + if (!asm_fixed_data(state, record, result)) { + return -1; + } + } else if (record.kind == 2 || record.kind == 3) { + if (state.packet.mode == 1) { + at = 0; + if (record.offset > section.size || record.size > section.size - record.offset + || section.first > state.packet.byte_capacity + || record.offset > state.packet.byte_capacity - section.first + || record.size > state.packet.byte_capacity - section.first - record.offset) { + asm_fixed_fail(result, 94, record.mnemonic, 0); + return -1; + } + while (at < record.size) { + if (!asm_fixed_charge(result, 1)) { + return -1; + } + state.packet.bytes[section.first + record.offset + at] = 0; + at += 1; + } + } + } else { + asm_fixed_fail(result, 94, record.mnemonic, 0); + return -1; + } + state.next += 1; + } + result.relocations = state.context.relocation_count; + return 0; +} + +export(c) fun asm_fixed_commit(state: ptr, word: u64, + result: ptr) -> bool { + if (state == null || result == null || state.packet == null) { + return false; + } + if (result.status != 0) { + return false; + } + if (state.pending != 1 || state.next >= state.record_count || word > 4294967295) { + return asm_fixed_fail(result, 94, result.text, 0); + } + var record: ptr = &state.packet.records[state.next]; + if (record.kind != 0 + || !asm_fixed_publish(state, record.section, record.offset, word, 4, result)) { + return false; + } + state.pending = 0; + state.next += 1; + return true; +} + +fun asm_fixed_probe_bound(value: u64, extra: u64, maximum: u64) -> u64 { + if (value >= maximum || extra >= maximum - value) { + return maximum; + } + return value + extra; +} + +fun asm_fixed_probe_data(text: FixedText, result: ptr) -> bool { + var start: u64 = 0; + var at: u64 = 0; + var first: u64 = 0; + var part: FixedText; + while (at <= text.count) { + if (!asm_fixed_charge(result, 1)) { + return false; + } + if (at == text.count || text.data[at] == 44) { + part = asm_fixed_trim(asm_fixed_slice(text, start, at)); + if (part.count != 0) { + first = part.data[0] as u64; + if ((first >= 65 && first <= 90) || (first >= 97 && first <= 122) + || first == 95 || first == 46 || first == 36) { + result.relocations += 1; + } + } + start = at + 1; + } + at += 1; + } + return true; +} + +fun asm_fixed_probe_line(text: FixedText, definitions: ptr, globals: ptr, + result: ptr) -> bool { + var at: u64 = 0; + var colon: u64 = 0; + var word_end: u64 = 0; + var count: u64 = 0; + var mnemonic: FixedText; + var tail: FixedText; + text = asm_fixed_trim(text); + while (text.count != 0) { + colon = 0; + while (colon < text.count && text.data[colon] != 58) { + if (!asm_fixed_charge(result, 1)) { + return false; + } + colon += 1; + } + if (colon == text.count) { + break; + } + definitions[0] = asm_fixed_probe_bound(definitions[0], 1, 65537); + text = asm_fixed_trim(asm_fixed_slice(text, colon + 1, text.count)); + } + if (text.count == 0) { + return true; + } + while (word_end < text.count && asm_fixed_space(text, word_end) == 0) { + if (!asm_fixed_charge(result, 1)) { + return false; + } + word_end += 1; + } + mnemonic = asm_fixed_slice(text, 0, word_end); + tail = asm_fixed_trim(asm_fixed_slice(text, word_end, text.count)); + if (asm_fixed_word(mnemonic, 500236121134, 5, 1) + || asm_fixed_word(mnemonic, 418564367406, 5, 1) + || asm_fixed_word(mnemonic, 27431034386608686, 7, 1) + || asm_fixed_word(mnemonic, 1936941614, 4, 1) + || asm_fixed_word(mnemonic, 7957695015191671598, 8, 1)) { + result.sections = asm_fixed_probe_bound(result.sections, 1, 4097); + return true; + } + if (tail.count != 0) { + count = 1; + while (at < tail.count) { + if (!asm_fixed_charge(result, 1)) { + return false; + } + if (tail.data[at] == 44) { + count += 1; + } + at += 1; + } + } + if (asm_fixed_word(mnemonic, 30506372888815406, 7, 1) + || asm_fixed_word(mnemonic, 119170031970094, 6, 1) + || asm_fixed_word(mnemonic, 31088027509482798, 7, 1)) { + globals[0] = asm_fixed_probe_bound(globals[0], count, 65537); + if (asm_fixed_word(mnemonic, 31088027509482798, 7, 1)) { + definitions[0] = asm_fixed_probe_bound(definitions[0], count, 65537); + } + result.operands += count; + return true; + } + // Source stops at the first record beyond its hard limit. Later records + // cannot require buffers and must not amplify a short-record input. + if (result.records >= 262145) { + return true; + } + result.records += 1; + if (asm_fixed_word(mnemonic, 478660622894, 5, 1) + || asm_fixed_word(mnemonic, 111477510927150, 6, 1) + || asm_fixed_word(mnemonic, 31075949925720622, 7, 1) + || asm_fixed_word(mnemonic, 7955443180981350446, 8, 1) + || asm_fixed_word(mnemonic, 121390429397294, 6, 1)) { + return true; + } + result.operands += count; + if (asm_fixed_word(mnemonic, 435745808942, 5, 1) + || asm_fixed_word(mnemonic, 110442659145774, 6, 1) + || asm_fixed_word(mnemonic, 128034844209966, 6, 1) + || asm_fixed_word(mnemonic, 431416637230, 5, 1) + || asm_fixed_word(mnemonic, 444234427438, 5, 1) + || asm_fixed_word(mnemonic, 431131816238, 5, 1)) { + return asm_fixed_probe_data(tail, result); + } + result.relocations += 1; + return true; +} + +export(c) fun whale_fixed_probe(source: ptr, hash_comments: u64, + result: ptr) -> i32 { + if (result == null || source == null) { + return 2; + } + var max_work: u64 = result.max_work; + asm_fixed_result_init(result, max_work); + if (hash_comments > 1 || !asm_span_valid(source.data, source.count, 1)) { + asm_fixed_fail(result, 94, source[0], 0); + return result.status as i32; + } + if (source.count > 8388608) { + asm_fixed_fail(result, 41, source[0], 0); + return result.status as i32; + } + result.sections = 1; + var definitions: u64 = 0; + var globals: u64 = 0; + var line_start: u64 = 0; + var line_end: u64 = 0; + var comment: u64 = 0; + var at: u64 = 0; + while (line_start < source.count) { + line_end = line_start; + while (line_end < source.count && source.data[line_end] != 10) { + if (!asm_fixed_charge(result, 1)) { + return result.status as i32; + } + line_end += 1; + } + comment = line_end; + at = line_start; + while (at < line_end) { + if (!asm_fixed_charge(result, 1)) { + return result.status as i32; + } + if (source.data[at] == 59 || (hash_comments != 0 && source.data[at] == 35) + || (source.data[at] == 47 && at + 1 < line_end && source.data[at + 1] == 47)) { + comment = at; + break; + } + at += 1; + } + if (!asm_fixed_probe_line(asm_fixed_slice(source[0], line_start, comment), + &definitions, &globals, result)) { + return result.status as i32; + } + line_start = line_end; + if (line_start < source.count) { + line_start += 1; + } + } + result.symbols = definitions + globals; + return 0; +} diff --git a/assembler/fixed_model.wave b/assembler/fixed_model.wave new file mode 100644 index 0000000..b34c09a --- /dev/null +++ b/assembler/fixed_model.wave @@ -0,0 +1,139 @@ +// SPDX-License-Identifier: MPL-2.0 +// Borrowed fixed-width source records. Only the owning ISA selects opcodes. +struct FixedText { + data: ptr; + count: u64; +} + +struct FixedInstruction { + mnemonic: FixedText; + operands: ptr; + count: u64; + fold: u64; +} + +struct FixedSymbol { + name: FixedText; + section: u64; + offset: u64; + start: u64; + end: u64; + line: u64; + flags: u64; +} + +struct FixedRelocation { + section: u64; + offset: u64; + symbol: u64; + code: u64; + addend: i64; +} + +struct FixedContext { + source: FixedText; + namespace: FixedText; + symbols: ptr; + symbol_count: u64; + table: ptr; + table_capacity: u64; + section: u64; + offset: u64; + relocations: ptr; + relocation_count: u64; + relocation_capacity: u64; +} + +struct FixedResult { + status: u64; + error: u64; + start: u64; + end: u64; + line: u64; + previous_start: u64; + previous_end: u64; + previous_line: u64; + text: FixedText; + detail: u64; + display: u64; + word: u64; + sections: u64; + symbols: u64; + relocations: u64; + records: u64; + operands: u64; + bytes: u64; + work: u64; + max_work: u64; +} + +struct FixedSection { + name: FixedText; + kind: u64; + align: u64; + size: u64; + first: u64; +} + +struct FixedRecord { + section: u64; + offset: u64; + start: u64; + end: u64; + line: u64; + kind: u64; + unit: u64; + first: u64; + count: u64; + size: u64; + mnemonic: FixedText; +} + +struct FixedGlobal { + start: u64; + end: u64; + line: u64; +} + +struct FixedInput { + source: FixedText; + namespace: FixedText; + hash_comments: u64; + mode: u64; + max_output: u64; + max_passes: u64; + max_work: u64; + sections: ptr; + section_capacity: u64; + symbols: ptr; + symbol_capacity: u64; + table: ptr; + table_capacity: u64; + globals: ptr; + global_capacity: u64; + records: ptr; + record_capacity: u64; + operands: ptr; + operand_capacity: u64; + order: ptr; + order_capacity: u64; + relocations: ptr; + relocation_capacity: u64; + bytes: ptr; + byte_capacity: u64; +} + +struct FixedState { + packet: ptr; + context: FixedContext; + section_count: u64; + symbol_count: u64; + definition_count: u64; + global_count: u64; + record_count: u64; + operand_count: u64; + selected: u64; + materialized: u64; + next: u64; + pending: u64; +} diff --git a/assembler/fixed_namespace.wave b/assembler/fixed_namespace.wave new file mode 100644 index 0000000..5e1f043 --- /dev/null +++ b/assembler/fixed_namespace.wave @@ -0,0 +1,433 @@ +// SPDX-License-Identifier: MPL-2.0 +// Indexed ASCII symbols; no concrete ISA or opcode is referenced here. +fun asm_fixed_hash(text: FixedText, result: ptr) -> u64 { + var hash: u64 = 14695981039346656037; + var at: u64 = 0; + while (at < text.count) { + if (!asm_fixed_charge(result, 1)) { + return 0; + } + hash = (hash ^ (text.data[at] as u64)) * 1099511628211; + at += 1; + } + return hash; +} + +fun asm_fixed_slot(context: ptr, name: FixedText, + result: ptr) -> u64 { + var slot: u64 = 0; + var index: u64 = 0; + var attempts: u64 = 0; + if (context.table_capacity < 2 || !asm_power_two(context.table_capacity) + || !asm_span_valid(context.table as ptr, context.table_capacity, 8)) { + result.status = 2; + return context.table_capacity; + } + slot = asm_fixed_hash(name, result) & (context.table_capacity - 1); + while (result.status == 0 && attempts < context.table_capacity) { + if (!asm_fixed_charge(result, 1)) { + return context.table_capacity; + } + index = context.table[slot]; + if (index == 18446744073709551615) { + return slot; + } + if (index >= context.symbol_count) { + result.status = 2; + return context.table_capacity; + } + if (!asm_fixed_charge(result, name.count + context.symbols[index].name.count)) { + return context.table_capacity; + } + if (asm_fixed_equal(name, context.symbols[index].name, 0)) { + return slot; + } + slot = (slot + 1) & (context.table_capacity - 1); + attempts += 1; + } + if (result.status == 0) { + result.status = 2; + } + return context.table_capacity; +} + +export(c) fun asm_fixed_lookup(context: ptr, name: FixedText, + result: ptr) -> u64 { + var slot: u64 = 0; + if (context.symbol_count == 0) { + return 0; + } + slot = asm_fixed_slot(context, name, result); + if (slot >= context.table_capacity) { + return context.symbol_count; + } + if (context.table[slot] == 18446744073709551615) { + return context.symbol_count; + } + return context.table[slot]; +} + +export(c) fun whale_fixed_context_index(context: ptr, + result: ptr) -> i32 { + var at: u64 = 0; + var slot: u64 = 0; + var count: u64 = 0; + if (context == null || result == null) { + return 2; + } + count = context.symbol_count; + if (!asm_span_valid(context.symbols as ptr, count, 64) + || context.table_capacity < 2 || !asm_power_two(context.table_capacity) + || count > context.table_capacity / 2 + || !asm_span_valid(context.table as ptr, context.table_capacity, 8)) { + result.status = 2; + return 2; + } + while (at < context.table_capacity) { + if (!asm_fixed_charge(result, 1)) { + return result.status as i32; + } + context.table[at] = 18446744073709551615; + at += 1; + } + context.symbol_count = 0; + at = 0; + while (at < count) { + if (!asm_fixed_identifier(context.symbols[at].name, result)) { + return result.status as i32; + } + slot = asm_fixed_slot(context, context.symbols[at].name, result); + if (result.status != 0) { + return result.status as i32; + } + if (context.table[slot] != 18446744073709551615) { + result.status = 2; + return 2; + } + context.table[slot] = at; + context.symbol_count += 1; + at += 1; + } + return result.status as i32; +} + +export(c) fun asm_fixed_symbol(state: ptr, name: FixedText, kind: u64, + result: ptr) -> u64 { + var slot: u64 = 0; + var index: u64 = 0; + var symbol: ptr; + var span: ptr; + if (!asm_fixed_identifier(name, result)) { + return state.packet.symbol_capacity; + } + if (kind == 1 && state.definition_count >= 65536) { + asm_fixed_fail(result, 70, name, 0); + return state.packet.symbol_capacity; + } + if ((kind == 2 || kind == 3) && state.global_count >= 65536) { + asm_fixed_fail(result, 72, name, 0); + return state.packet.symbol_capacity; + } + slot = asm_fixed_slot(&state.context, name, result); + if (result.status != 0) { + return state.packet.symbol_capacity; + } + index = state.context.table[slot]; + if (index == 18446744073709551615) { + if (kind == 0) { + return state.symbol_count; + } + if (state.symbol_count >= state.packet.symbol_capacity + || state.symbol_count >= state.packet.global_capacity) { + result.status = 2; + return state.packet.symbol_capacity; + } + index = state.symbol_count; + symbol = &state.packet.symbols[index]; + symbol.name = name; + symbol.section = 18446744073709551615; + symbol.offset = 0; + symbol.start = result.start; + symbol.end = result.end; + symbol.line = result.line; + symbol.flags = 0; + state.packet.globals[index].line = 0; + state.context.table[slot] = index; + state.symbol_count += 1; + state.context.symbol_count = state.symbol_count; + } + symbol = &state.packet.symbols[index]; + if (kind == 1) { + if ((symbol.flags & 6) != 0) { + result.previous_start = symbol.start; + result.previous_end = symbol.end; + result.previous_line = symbol.line; + asm_fixed_fail(result, 71, name, 0); + return state.packet.symbol_capacity; + } + symbol.flags = symbol.flags | 2; + symbol.section = state.selected; + symbol.offset = state.packet.sections[state.selected].size; + symbol.start = result.start; + symbol.end = result.end; + symbol.line = result.line; + state.definition_count += 1; + } else if (kind == 2 || kind == 3) { + if ((symbol.flags & 1) == 0) { + state.global_count += 1; + symbol.flags = symbol.flags | 1; + } + span = &state.packet.globals[index]; + span.start = result.start; + span.end = result.end; + span.line = result.line; + if (kind == 3) { + if ((symbol.flags & 2) != 0) { + asm_fixed_fail(result, 73, name, 0); + return state.packet.symbol_capacity; + } + if ((symbol.flags & 4) == 0) { + if (state.definition_count >= 65536) { + asm_fixed_fail(result, 70, name, 0); + return state.packet.symbol_capacity; + } + state.definition_count += 1; + symbol.start = result.start; + symbol.end = result.end; + symbol.line = result.line; + symbol.flags = symbol.flags | 4; + } + } + } else if (kind != 0) { + result.status = 2; + return state.packet.symbol_capacity; + } + return index; +} + +fun asm_fixed_standard(name: FixedText, kind: u64) -> bool { + if (name.data == null) { + return name.count == kind; + } + // .text, .data, .rodata, .bss: exact section names, not mnemonic aliases. + if (kind == 0) { + return asm_fixed_word(name, 500236121134, 5, 0); + } + if (kind == 1) { + return asm_fixed_word(name, 418564367406, 5, 0); + } + if (kind == 2) { + return asm_fixed_word(name, 27431034386608686, 7, 0); + } + return kind == 3 && asm_fixed_word(name, 1936941614, 4, 0); +} + +fun asm_fixed_section_equal(left: FixedText, right: FixedText) -> bool { + if (left.data == null) { + return asm_fixed_standard(right, left.count); + } + if (right.data == null) { + return asm_fixed_standard(left, right.count); + } + return asm_fixed_equal(left, right, 0); +} + +export(c) fun asm_fixed_section(state: ptr, name: FixedText, + result: ptr) -> bool { + var index: u64 = 0; + var kind: u64 = 1; + var section: ptr; + if (name.data == null) { + if (name.count > 3) { + result.status = 2; + return false; + } + } else if (!asm_fixed_identifier(name, result)) { + return false; + } + while (index < state.section_count) { + if (!asm_fixed_charge(result, name.count + state.packet.sections[index].name.count + 1)) { + return false; + } + if (asm_fixed_section_equal(name, state.packet.sections[index].name)) { + state.selected = index; + return true; + } + index += 1; + } + if (index >= 4096) { + return asm_fixed_fail(result, 75, name, 0); + } + if (index >= state.packet.section_capacity) { + result.status = 2; + return false; + } + if (asm_fixed_standard(name, 0)) { + kind = 0; + } else if (asm_fixed_standard(name, 2)) { + kind = 2; + } else if (asm_fixed_standard(name, 3)) { + kind = 3; + } + section = &state.packet.sections[index]; + section.name = name; + section.kind = kind; + section.align = 1; + if (kind == 0) { + section.align = 4; + } + section.size = 0; + section.first = 0; + state.selected = index; + state.section_count += 1; + return true; +} + +export(c) fun asm_fixed_record(state: ptr, record: ptr, + result: ptr) -> bool { + var section: ptr = &state.packet.sections[state.selected]; + var growth: AsmOutputGrowth; + var limit: u64 = state.packet.max_output; + var status: i32 = 0; + if (limit > 268435456) { + limit = 268435456; + } + record.section = state.selected; + record.offset = section.size; + status = asm_output_grow(state.materialized, section.size, record.size, + limit, (section.kind == 3) as u64, &growth); + if (status != 0) { + if (status == 1) { + return asm_fixed_fail(result, 76, record.mnemonic, 0); + } + if (status == 2) { + return asm_fixed_fail(result, 77, record.mnemonic, 0); + } + result.status = 2; + return false; + } + section.size = growth.section; + state.materialized = growth.materialized; + if (state.record_count >= 262144) { + return asm_fixed_fail(result, 78, record.mnemonic, 0); + } + if (state.record_count >= state.packet.record_capacity) { + result.status = 2; + return false; + } + state.packet.records[state.record_count] = record[0]; + state.record_count += 1; + return true; +} + +fun asm_fixed_symbol_less(state: ptr, left: u64, right: u64, + result: ptr) -> bool { + var a: FixedText = state.packet.symbols[left].name; + var b: FixedText = state.packet.symbols[right].name; + var at: u64 = 0; + while (at < a.count && at < b.count) { + if (!asm_fixed_charge(result, 1)) { + return false; + } + if (a.data[at] < b.data[at]) { + return true; + } + if (a.data[at] > b.data[at]) { + return false; + } + at += 1; + } + return a.count < b.count; +} + +fun asm_fixed_sift(state: ptr, start: u64, end: u64, + result: ptr) { + var root: u64 = start; + var child: u64 = 0; + var swap: u64 = 0; + var temporary: u64 = 0; + while (root < end / 2) { + child = root * 2 + 1; + swap = root; + if (asm_fixed_symbol_less(state, state.packet.order[swap], state.packet.order[child], result)) { + swap = child; + } + if (child + 1 < end + && asm_fixed_symbol_less(state, state.packet.order[swap], state.packet.order[child + 1], result)) { + swap = child + 1; + } + if (result.status != 0 || swap == root) { + return; + } + temporary = state.packet.order[root]; + state.packet.order[root] = state.packet.order[swap]; + state.packet.order[swap] = temporary; + root = swap; + } +} + +export(c) fun asm_fixed_finish(state: ptr, result: ptr) -> bool { + var at: u64 = 0; + var end: u64 = state.symbol_count; + var temporary: u64 = 0; + var index: u64 = 0; + var first: u64 = 0; + var symbol: ptr; + var span: ptr; + if (state.symbol_count > state.packet.order_capacity) { + result.status = 2; + return false; + } + while (at < state.symbol_count) { + state.packet.order[at] = at; + at += 1; + } + at = state.symbol_count / 2; + while (at != 0) { + at -= 1; + asm_fixed_sift(state, at, end, result); + if (result.status != 0) { + return false; + } + } + while (end > 1) { + end -= 1; + temporary = state.packet.order[0]; + state.packet.order[0] = state.packet.order[end]; + state.packet.order[end] = temporary; + asm_fixed_sift(state, 0, end, result); + if (result.status != 0) { + return false; + } + } + at = 0; + while (at < state.symbol_count) { + if (!asm_fixed_charge(result, 1)) { + return false; + } + index = state.packet.order[at]; + symbol = &state.packet.symbols[index]; + if ((symbol.flags & 1) != 0 && (symbol.flags & 6) == 0) { + span = &state.packet.globals[index]; + result.start = span.start; + result.end = span.end; + result.line = span.line; + return asm_fixed_fail(result, 74, symbol.name, 0); + } + at += 1; + } + at = 0; + while (at < state.section_count) { + state.packet.sections[at].first = first; + if (state.packet.sections[at].kind != 3) { + first += state.packet.sections[at].size; + } + at += 1; + } + result.sections = state.section_count; + result.symbols = state.symbol_count; + result.records = state.record_count; + result.operands = state.operand_count; + result.bytes = state.materialized; + return result.status == 0; +} diff --git a/assembler/fixed_numbers.wave b/assembler/fixed_numbers.wave new file mode 100644 index 0000000..79873b1 --- /dev/null +++ b/assembler/fixed_numbers.wave @@ -0,0 +1,228 @@ +// SPDX-License-Identifier: MPL-2.0 +// Preserve the fixed-width assembly grammar's checked signed-i128 literals. +export(c) fun asm_fixed_integer(text: FixedText, output: ptr, + result: ptr) -> bool { + var value: FixedText = text; + var negative: bool = false; + var inner_negative: bool = false; + var maximum_high: u64 = 9223372036854775807; + var radix: u64 = 10; + var at: u64 = 0; + var next: u64 = 0; + var digit: u64 = 0; + var octet: u64 = 0; + var low: u64 = 0; + var high: u64 = 0; + var lower: u64 = 0; + var upper: u64 = 0; + var digits: u64 = 0; + var parsed: AsmWide; + if (result.status != 0) { + return false; + } + if (output == null || !asm_span_valid(text.data, text.count, 1)) { + result.status = 2; + return false; + } + if (!asm_fixed_charge(result, text.count + 1)) { + return false; + } + value = asm_fixed_trim(text); + if (value.count != 0 && value.data[0] == 35) { + value = asm_fixed_trim(asm_fixed_slice(value, 1, value.count)); + } + if (value.count != 0 && (value.data[0] == 43 || value.data[0] == 45)) { + negative = value.data[0] == 45; + value = asm_fixed_trim(asm_fixed_slice(value, 1, value.count)); + } + if (value.count == 0 || value.data[0] < 48 || value.data[0] > 57) { + return asm_fixed_fail(result, 2, value, 0); + } + if (value.data[0] == 48) { + next = 1; + while (next < value.count && value.data[next] == 95) { + next += 1; + } + if (next < value.count && (value.data[next] == 120 || value.data[next] == 88)) { + radix = 16; + at = next + 1; + } else if (next < value.count && (value.data[next] == 98 || value.data[next] == 66)) { + radix = 2; + at = next + 1; + } + } + // from_str_radix accepts a sign after a radix prefix, including MIN. + // The outer assembly sign is applied afterwards with checked negation. + if (radix != 10) { + while (at < value.count && value.data[at] == 95) { + at += 1; + } + if (at < value.count && (value.data[at] == 43 || value.data[at] == 45)) { + inner_negative = value.data[at] == 45; + at += 1; + } + if (inner_negative) { + maximum_high = 9223372036854775808; + } + } + while (at < value.count) { + octet = value.data[at] as u64; + at += 1; + if (octet != 95) { + digit = asm_lex_digit(octet, radix); + if (digit >= radix) { + return asm_fixed_fail(result, 2, value, 0); + } + // Split multiplication avoids host-width arithmetic and unchecked carry. + lower = (low & 4294967295) * radix + digit; + upper = (low >> 32) * radix + (lower >> 32); + if (high > (maximum_high - (upper >> 32)) / radix) { + return asm_fixed_fail(result, 2, value, 0); + } + high = high * radix + (upper >> 32); + low = (upper << 32) | (lower & 4294967295); + digits += 1; + } + } + if (digits == 0 || (high == 9223372036854775808 && low != 0)) { + return asm_fixed_fail(result, 2, value, 0); + } + parsed.low = low; + parsed.high = high; + if (inner_negative) { + parsed.low = ~low + 1; + parsed.high = ~high + (parsed.low == 0) as u64; + } + if (negative && !asm_number_neg_checked(&parsed, &parsed)) { + return asm_fixed_fail(result, 3, value, 0); + } + output[0] = parsed; + return true; +} + +export(c) fun asm_fixed_try_integer(text: FixedText, output: ptr, + result: ptr) -> bool { + var old_text: FixedText = result.text; + var detail: u64 = result.detail; + var display: u64 = result.display; + if (result.status != 0) { + return false; + } + if (asm_fixed_integer(text, output, result)) { + return true; + } + if (result.status == 1 && (result.error == 2 || result.error == 3)) { + result.status = 0; + result.error = 0; + result.text = old_text; + result.detail = detail; + result.display = display; + } + return false; +} + +export(c) fun asm_fixed_signed(text: FixedText, bits: u64, output: ptr, + result: ptr) -> bool { + var value: AsmWide; + var one: u64 = 1; + if (output == null) { + result.status = 2; + return false; + } + if (bits == 0 || bits > 32) { + return asm_fixed_fail(result, 4, text, 0); + } + if (!asm_fixed_integer(text, &value, result)) { + return false; + } + if (!asm_number_fits_signed(&value, bits)) { + return asm_fixed_fail(result, 5, text, bits); + } + output[0] = value.low & ((one << bits) - 1); + return true; +} + +export(c) fun asm_fixed_unsigned(text: FixedText, bits: u64, output: ptr, + result: ptr) -> bool { + var value: AsmWide; + if (output == null) { + result.status = 2; + return false; + } + if (bits == 0 || bits > 32) { + return asm_fixed_fail(result, 4, text, 0); + } + if (!asm_fixed_integer(text, &value, result)) { + return false; + } + if (!asm_number_fits_unsigned(&value, bits)) { + return asm_fixed_fail(result, 6, text, bits); + } + output[0] = value.low; + return true; +} + +export(c) fun asm_fixed_i64(text: FixedText, output: ptr, + result: ptr) -> bool { + var value: AsmWide; + if (output == null) { + result.status = 2; + return false; + } + if (!asm_fixed_integer(text, &value, result)) { + return false; + } + if (!asm_number_fits_signed(&value, 64)) { + return asm_fixed_fail(result, 14, text, 0); + } + output[0] = value.low as i64; + return true; +} + +export(c) fun asm_fixed_displacement(value: i64, bits: u64, alignment: i64, + output: ptr, result: ptr) -> bool { + var scaled: i64 = 0; + var one: u64 = 1; + if (output == null) { + result.status = 2; + return false; + } + if (bits == 0 || bits > 32 || alignment <= 0) { + return asm_fixed_fail(result, 7, result.text, 0); + } + if (value % alignment != 0) { + return asm_fixed_fail(result, 8, result.text, alignment as u64); + } + scaled = value / alignment; + if (scaled < -((one << (bits - 1)) as i64) + || scaled >= (one << (bits - 1)) as i64) { + return asm_fixed_fail(result, 9, result.text, bits); + } + output[0] = (scaled as u64) & ((one << bits) - 1); + return true; +} + +export(c) fun asm_fixed_identifier(text: FixedText, result: ptr) -> bool { + var at: u64 = 0; + var octet: u64 = 0; + if (!asm_span_valid(text.data, text.count, 1)) { + result.status = 2; + return false; + } + if (!asm_fixed_charge(result, text.count + 1)) { + return false; + } + if (text.count == 0) { + return asm_fixed_fail(result, 11, text, 0); + } + while (at < text.count) { + octet = text.data[at] as u64; + if (!((octet >= 65 && octet <= 90) || (octet >= 97 && octet <= 122) + || octet == 95 || octet == 46 || octet == 36 + || (at != 0 && octet >= 48 && octet <= 57))) { + return asm_fixed_fail(result, 11, text, 0); + } + at += 1; + } + return true; +} diff --git a/assembler/fixed_operands.wave b/assembler/fixed_operands.wave new file mode 100644 index 0000000..4b4cdf4 --- /dev/null +++ b/assembler/fixed_operands.wave @@ -0,0 +1,146 @@ +// SPDX-License-Identifier: MPL-2.0 +// Balanced operand splitting uses a small fast stack and bounded rescans only +// beyond 64 nesting levels. A count probe never needs an allocation callback. +fun asm_fixed_operands_inner(text: FixedText, output: ptr, capacity: u64, + count: ptr, result: ptr) -> bool { + var value: FixedText = text; + var at: u64 = 0; + var start: u64 = 0; + var depth: u64 = 0; + var stack: u64 = 0; + var octet: u64 = 0; + var expected: u64 = 0; + var found: u64 = 0; + var back: u64 = 0; + var pending: u64 = 0; + var total: u64 = 0; + var empty: bool = false; + var part: FixedText; + var one: u64 = 1; + if (result.status != 0) { + return false; + } + if (count == null || !asm_span_valid(value.data, value.count, 1) + || (output == null && capacity != 0) + || !asm_span_valid(output as ptr, capacity, 16)) { + result.status = 2; + return false; + } + if (!asm_fixed_charge(result, text.count + 1)) { + return false; + } + value = asm_fixed_trim(text); + count[0] = 0; + if (value.count == 0) { + return true; + } + while (at < value.count) { + if (!asm_fixed_charge(result, 1)) { + return false; + } + octet = value.data[at] as u64; + if (octet == 91 || octet == 40) { + if (depth < 64) { + stack = stack & ~(one << depth); + if (octet == 91) { + stack = stack | (one << depth); + } + } + depth += 1; + } else if (octet == 93 || octet == 41) { + if (depth == 0) { + return asm_fixed_fail(result, 15, value, 0); + } + expected = 40; + if (octet == 93) { + expected = 91; + } + if (depth <= 64) { + found = 40; + if ((stack & (one << (depth - 1))) != 0) { + found = 91; + } + } else { + back = at; + pending = 1; + found = 0; + while (back != 0 && pending != 0) { + if (!asm_fixed_charge(result, 1)) { + return false; + } + back -= 1; + if (value.data[back] == 93 || value.data[back] == 41) { + pending += 1; + } else if (value.data[back] == 91 || value.data[back] == 40) { + pending -= 1; + if (pending == 0) { + found = value.data[back] as u64; + } + } + } + } + if (found != expected) { + return asm_fixed_fail(result, 15, value, 0); + } + depth -= 1; + } else if (octet == 44 && depth == 0) { + if (total >= 65536) { + return asm_fixed_fail(result, 17, value, 0); + } + part = asm_fixed_trim(asm_fixed_slice(value, start, at)); + empty = empty || part.count == 0; + if (output != null) { + if (total >= capacity) { + result.status = 2; + return false; + } + output[total] = part; + } + total += 1; + start = at + 1; + } + at += 1; + } + if (depth != 0) { + return asm_fixed_fail(result, 16, value, 0); + } + if (total >= 65536) { + return asm_fixed_fail(result, 17, value, 0); + } + part = asm_fixed_trim(asm_fixed_slice(value, start, value.count)); + empty = empty || part.count == 0; + if (output != null) { + if (total >= capacity) { + result.status = 2; + return false; + } + output[total] = part; + } + total += 1; + if (empty) { + return asm_fixed_fail(result, 18, value, 0); + } + count[0] = total; + return true; +} + +export(c) fun asm_fixed_operands(text: FixedText, output: ptr, capacity: u64, + count: ptr, result: ptr) -> bool { + var needed: u64 = 0; + if (count == null || (output == null && capacity != 0)) { + result.status = 2; + return false; + } + if (!asm_fixed_operands_inner(text, null, 0, &needed, result)) { + return false; + } + if (output == null) { + count[0] = needed; + return true; + } + if (needed > capacity || !asm_span_valid(output as ptr, capacity, 16)) { + result.status = 2; + return false; + } + return asm_fixed_operands_inner(text, output, capacity, count, result); +} diff --git a/assembler/fixed_relative.wave b/assembler/fixed_relative.wave new file mode 100644 index 0000000..55f51d6 --- /dev/null +++ b/assembler/fixed_relative.wave @@ -0,0 +1,137 @@ +// SPDX-License-Identifier: MPL-2.0 +// Resolve one optional symbol/addend, retaining opaque ISA relocation codes. +export(c) fun asm_fixed_expression(context: ptr, text: FixedText, + number: ptr, symbol: ptr, addend: ptr, result: ptr) -> bool { + var value: FixedText = text; + var name: FixedText; + var suffix: FixedText; + var at: u64 = 1; + var split: u64 = value.count; + var extra: AsmWide; + if (number == null || symbol == null || addend == null) { + result.status = 2; + return false; + } + if (!asm_span_valid(text.data, text.count, 1)) { + result.status = 2; + return false; + } + if (!asm_fixed_charge(result, text.count + 1)) { + return false; + } + value = asm_fixed_trim(text); + symbol[0] = 18446744073709551615; + addend[0] = 0; + if (asm_fixed_try_integer(text, number, result)) { + return true; + } + if (result.status != 0) { + return false; + } + while (at < value.count) { + if (!asm_fixed_charge(result, 1)) { + return false; + } + if (value.data[at] == 43 || value.data[at] == 45) { + split = at; + break; + } + at += 1; + } + name = asm_fixed_trim(asm_fixed_slice(value, 0, split)); + if (split != value.count) { + suffix = asm_fixed_slice(value, split, value.count); + if (!asm_fixed_integer(suffix, &extra, result)) { + return false; + } + if (!asm_number_fits_signed(&extra, 64)) { + return asm_fixed_fail(result, 10, suffix, 0); + } + addend[0] = extra.low as i64; + } + if (!asm_fixed_identifier(name, result)) { + return false; + } + symbol[0] = asm_fixed_lookup(context, name, result); + result.text = name; + number.low = 0; + number.high = 0; + return result.status == 0; +} + +export(c) fun asm_fixed_pc_relative(context: ptr, text: FixedText, + code: u64, output: ptr, result: ptr) -> bool { + var number: AsmWide; + var addition: AsmWide; + var origin: AsmWide; + var target: u64 = 0; + var extra: i64 = 0; + var symbol: ptr; + var relocation: ptr; + if (context == null || output == null + || !asm_span_valid(context.symbols as ptr, context.symbol_count, 64) + || !asm_span_valid(context.relocations as ptr, context.relocation_capacity, 40) + || context.relocation_count > context.relocation_capacity) { + result.status = 2; + return false; + } + if (!asm_fixed_expression(context, text, &number, &target, &extra, result)) { + return false; + } + if (target == 18446744073709551615) { + if (!asm_number_fits_signed(&number, 64)) { + return asm_fixed_fail(result, 14, text, 0); + } + output[0] = number.low as i64; + return true; + } + if (target >= context.symbol_count) { + return asm_fixed_fail(result, 12, result.text, 0); + } + symbol = &context.symbols[target]; + if (symbol.section == context.section) { + number.low = symbol.offset; + number.high = 0; + addition.low = extra as u64; + addition.high = 0; + if (extra < 0) { + addition.high = 18446744073709551615; + } + origin.low = context.offset; + origin.high = 0; + if (!asm_number_add_checked(&number, &addition, &number) + || !asm_number_sub_checked(&number, &origin, &number) + || !asm_number_fits_signed(&number, 64)) { + return asm_fixed_fail(result, 14, text, 0); + } + output[0] = number.low as i64; + return true; + } + if (context.relocation_count >= context.relocation_capacity || code > 4294967295) { + result.status = 2; + return false; + } + relocation = &context.relocations[context.relocation_count]; + relocation.section = context.section; + relocation.offset = context.offset; + relocation.symbol = target; + relocation.code = code; + relocation.addend = extra; + context.relocation_count += 1; + output[0] = 0; + return true; +} + +export(c) fun whale_fixed_relative(context: ptr, text: ptr, + code: u64, result: ptr) -> i32 { + var value: i64 = 0; + if (result == null || context == null || text == null) { + return 2; + } + if (asm_fixed_pc_relative(context, text[0], code, &value, result)) { + result.word = value as u64; + } else if (result.status == 0) { + result.status = 2; + } + return result.status as i32; +} diff --git a/assembler/fixed_scalar.wave b/assembler/fixed_scalar.wave new file mode 100644 index 0000000..1d9c663 --- /dev/null +++ b/assembler/fixed_scalar.wave @@ -0,0 +1,45 @@ +// SPDX-License-Identifier: MPL-2.0 +// Pointer-only C wrappers keep host transport independent of struct ABI lowering. +export(c) fun whale_fixed_scalar(mode: u64, text: ptr, bits: u64, + value: i64, alignment: i64, result: ptr) -> i32 { + var number: AsmWide; + var word: u64 = 0; + var ok: bool = false; + if (result == null || text == null) { + return 2; + } + if (mode == 0) { + ok = asm_fixed_integer(text[0], &number, result); + if (ok) { + result.word = number.low; + result.detail = number.high; + } + } else if (mode == 1) { + ok = asm_fixed_signed(text[0], bits, &word, result); + } else if (mode == 2) { + ok = asm_fixed_unsigned(text[0], bits, &word, result); + } else if (mode == 3) { + ok = asm_fixed_displacement(value, bits, alignment, &word, result); + } else { + result.status = 2; + return 2; + } + if (ok && mode != 0) { + result.word = word; + } + if (!ok && result.status == 0) { + result.status = 2; + } + return result.status as i32; +} + +export(c) fun whale_fixed_operands(text: ptr, output: ptr, + capacity: u64, count: ptr, result: ptr) -> i32 { + if (result == null || text == null) { + return 2; + } + if (!asm_fixed_operands(text[0], output, capacity, count, result) && result.status == 0) { + result.status = 2; + } + return result.status as i32; +} diff --git a/assembler/fixed_source.wave b/assembler/fixed_source.wave new file mode 100644 index 0000000..3f9e6cd --- /dev/null +++ b/assembler/fixed_source.wave @@ -0,0 +1,288 @@ +// SPDX-License-Identifier: MPL-2.0 +// First-pass fixed-width source grammar, shared by each owning ISA module. +fun asm_fixed_source_operands(state: ptr, text: FixedText, + first: ptr, count: ptr, result: ptr) -> bool { + var length: u64 = 0; + if (!asm_fixed_operands(text, null, 0, &length, result)) { + return false; + } + if (state.operand_count > state.packet.operand_capacity + || length > state.packet.operand_capacity - state.operand_count) { + return asm_fixed_fail(result, 94, text, 0); + } + first[0] = state.operand_count; + count[0] = length; + if (length != 0) { + var written: u64 = 0; + if (!asm_fixed_operands(text, &state.packet.operands[state.operand_count], + state.packet.operand_capacity - state.operand_count, &written, result)) { + return false; + } + if (written != length) { + return asm_fixed_fail(result, 94, text, 0); + } + } + state.operand_count += length; + return true; +} + +fun asm_fixed_source_record(state: ptr, mnemonic: FixedText, + tail: FixedText, result: ptr) -> bool { + var record: FixedRecord; + record.section = state.selected; + record.offset = state.packet.sections[state.selected].size; + record.start = result.start; + record.end = result.end; + record.line = result.line; + record.kind = 0; + record.unit = 0; + record.first = 0; + record.count = 0; + record.size = 4; + record.mnemonic = mnemonic; + var number: AsmWide; + var alignment: u64 = 0; + if (asm_fixed_word(mnemonic, 435745808942, 5, 1) + || asm_fixed_word(mnemonic, 110442659145774, 6, 1) + || asm_fixed_word(mnemonic, 128034844209966, 6, 1) + || asm_fixed_word(mnemonic, 431416637230, 5, 1) + || asm_fixed_word(mnemonic, 444234427438, 5, 1) + || asm_fixed_word(mnemonic, 431131816238, 5, 1)) { + record.kind = 1; + record.unit = 4; + if (asm_fixed_word(mnemonic, 435745808942, 5, 1)) { + record.unit = 1; + } else if (asm_fixed_word(mnemonic, 110442659145774, 6, 1) + || asm_fixed_word(mnemonic, 128034844209966, 6, 1)) { + record.unit = 2; + } else if (asm_fixed_word(mnemonic, 431131816238, 5, 1)) { + record.unit = 8; + } + if (!asm_fixed_source_operands(state, tail, &record.first, &record.count, result)) { + return false; + } + if (record.count == 0) { + return asm_fixed_fail(result, 32, mnemonic, 0); + } + if (record.count > 18446744073709551615 / record.unit) { + return asm_fixed_fail(result, 40, mnemonic, 0); + } + record.size = record.count * record.unit; + } else if (asm_fixed_word(mnemonic, 478660622894, 5, 1) + || asm_fixed_word(mnemonic, 111477510927150, 6, 1)) { + record.kind = 2; + record.unit = 1; + if (!asm_fixed_integer(tail, &number, result)) { + return false; + } + if (!asm_number_fits_unsigned(&number, 64)) { + return asm_fixed_fail(result, 33, tail, 0); + } + record.size = number.low; + } else if (asm_fixed_word(mnemonic, 31075949925720622, 7, 1) + || asm_fixed_word(mnemonic, 7955443180981350446, 8, 1) + || asm_fixed_word(mnemonic, 121390429397294, 6, 1)) { + record.kind = 3; + if (!asm_fixed_integer(tail, &number, result)) { + return false; + } + if (!asm_number_fits_unsigned(&number, 64)) { + return asm_fixed_fail(result, 36, tail, 0); + } + alignment = number.low; + if (!asm_fixed_word(mnemonic, 31075949925720622, 7, 1)) { + if (alignment >= 64) { + return asm_fixed_fail(result, 37, tail, 0); + } + var one: u64 = 1; + alignment = one << alignment; + } + if (!asm_power_two(alignment)) { + return asm_fixed_fail(result, 38, tail, 0); + } + if (alignment > state.packet.sections[state.selected].align) { + state.packet.sections[state.selected].align = alignment; + } + record.unit = alignment; + record.size = (alignment - record.offset % alignment) % alignment; + } else { + if (mnemonic.count != 0 && mnemonic.data[0] == 46) { + asm_fixed_fail(result, 39, mnemonic, 0); + result.display = 1; + return false; + } + if (!asm_fixed_source_operands(state, tail, &record.first, &record.count, result)) { + return false; + } + } + var section_kind: u64 = state.packet.sections[state.selected].kind; + if (section_kind == 3 && record.kind != 2 && record.kind != 3) { + return asm_fixed_fail(result, 34, mnemonic, 0); + } + if (record.kind == 0 && (section_kind != 0 || record.offset % 4 != 0)) { + return asm_fixed_fail(result, 35, mnemonic, 0); + } + return asm_fixed_record(state, &record, result); +} + +fun asm_fixed_source_statement(state: ptr, text: FixedText, + result: ptr) -> bool { + var colon: u64 = 0; + var label: FixedText; + var symbol: u64 = 0; + var word_end: u64 = 0; + var mnemonic: FixedText; + var tail: FixedText; + var section: FixedText; + var kind: u64 = 0; + var first: u64 = 0; + var count: u64 = 0; + var index: u64 = 0; + text = asm_fixed_trim(text); + while (text.count != 0) { + colon = 0; + while (colon < text.count && text.data[colon] != 58) { + if (!asm_fixed_charge(result, 1)) { + return false; + } + colon += 1; + } + if (colon == text.count) { + break; + } + label = asm_fixed_trim(asm_fixed_slice(text, 0, colon)); + if (!asm_fixed_identifier(label, result)) { + return false; + } + symbol = asm_fixed_symbol(state, label, 1, result); + if (result.status != 0) { + return false; + } + text = asm_fixed_trim(asm_fixed_slice(text, colon + 1, text.count)); + } + if (text.count == 0) { + return true; + } + while (word_end < text.count && asm_fixed_space(text, word_end) == 0) { + if (!asm_fixed_charge(result, 1)) { + return false; + } + word_end += 1; + } + mnemonic = asm_fixed_slice(text, 0, word_end); + tail = asm_fixed_trim(asm_fixed_slice(text, word_end, text.count)); + if (asm_fixed_word(mnemonic, 500236121134, 5, 1) + || asm_fixed_word(mnemonic, 418564367406, 5, 1) + || asm_fixed_word(mnemonic, 27431034386608686, 7, 1) + || asm_fixed_word(mnemonic, 1936941614, 4, 1) + || asm_fixed_word(mnemonic, 7957695015191671598, 8, 1)) { + if (asm_fixed_word(mnemonic, 7957695015191671598, 8, 1)) { + if (!asm_fixed_identifier(tail, result)) { + return false; + } + section = tail; + } else { + if (tail.count != 0) { + return asm_fixed_fail(result, 30, mnemonic, 0); + } + kind = 1; + if (asm_fixed_word(mnemonic, 500236121134, 5, 1)) { + kind = 0; + } else if (asm_fixed_word(mnemonic, 27431034386608686, 7, 1)) { + kind = 2; + } else if (asm_fixed_word(mnemonic, 1936941614, 4, 1)) { + kind = 3; + } + section.data = null; + section.count = kind; + } + return asm_fixed_section(state, section, result); + } + if (asm_fixed_word(mnemonic, 30506372888815406, 7, 1) + || asm_fixed_word(mnemonic, 119170031970094, 6, 1) + || asm_fixed_word(mnemonic, 31088027509482798, 7, 1)) { + if (!asm_fixed_source_operands(state, tail, &first, &count, result)) { + return false; + } + if (count == 0) { + return asm_fixed_fail(result, 31, mnemonic, 0); + } + kind = 2; + if (asm_fixed_word(mnemonic, 31088027509482798, 7, 1)) { + kind = 3; + } + while (index < count) { + if (!asm_fixed_charge(result, 1)) { + return false; + } + label = state.packet.operands[first + index]; + if (!asm_fixed_identifier(label, result)) { + return false; + } + symbol = asm_fixed_symbol(state, label, kind, result); + if (result.status != 0) { + return false; + } + index += 1; + } + return true; + } + return asm_fixed_source_record(state, mnemonic, tail, result); +} + +fun asm_fixed_source(state: ptr, result: ptr) -> bool { + var source: FixedText = state.packet.source; + var line_start: u64 = 0; + var line_end: u64 = 0; + var span_end: u64 = 0; + var end: u64 = 0; + var at: u64 = 0; + var comment: u64 = 0; + var line: u64 = 1; + var text: FixedText; + while (line_start < source.count) { + line_end = line_start; + while (line_end < source.count && source.data[line_end] != 10) { + if (!asm_fixed_charge(result, 1)) { + return false; + } + line_end += 1; + } + end = line_end; + if (line_end < source.count) { + line_end += 1; + } + span_end = line_end; + while (span_end > line_start + && (source.data[span_end - 1] == 10 || source.data[span_end - 1] == 13)) { + span_end -= 1; + } + result.start = line_start; + result.end = span_end; + result.line = line; + result.previous_start = 0; + result.previous_end = 0; + result.previous_line = 0; + at = line_start; + comment = end; + while (at < end) { + if (!asm_fixed_charge(result, 1)) { + return false; + } + if (source.data[at] == 59 + || (state.packet.hash_comments != 0 && source.data[at] == 35) + || (source.data[at] == 47 && at + 1 < end && source.data[at + 1] == 47)) { + comment = at; + break; + } + at += 1; + } + text = asm_fixed_slice(source, line_start, comment); + if (!asm_fixed_source_statement(state, text, result)) { + return false; + } + line_start = line_end; + line += 1; + } + return true; +} diff --git a/assembler/fixed_text.wave b/assembler/fixed_text.wave new file mode 100644 index 0000000..0767a0f --- /dev/null +++ b/assembler/fixed_text.wave @@ -0,0 +1,175 @@ +// SPDX-License-Identifier: MPL-2.0 +// Unicode White_Space is the property used by Rust str::trim/split_whitespace. +export(c) fun asm_fixed_space(text: FixedText, at: u64) -> u64 { + if (at >= text.count) { + return 0; + } + var a: u64 = text.data[at] as u64; + if ((a >= 9 && a <= 13) || a == 32) { + return 1; + } + if (text.count - at >= 2 && a == 194 + && (text.data[at + 1] == 133 || text.data[at + 1] == 160)) { + return 2; + } + if (text.count - at < 3) { + return 0; + } + var b: u64 = text.data[at + 1] as u64; + var c: u64 = text.data[at + 2] as u64; + if ((a == 225 && b == 154 && c == 128) + || (a == 226 && b == 128 && ((c >= 128 && c <= 138) || c == 168 || c == 169 || c == 175)) + || (a == 226 && b == 129 && c == 159) + || (a == 227 && b == 128 && c == 128)) { + return 3; + } + return 0; +} + +fun asm_fixed_slice(text: FixedText, start: u64, end: u64) -> FixedText { + var output: FixedText; + output.data = text.data; + output.count = 0; + if (start <= end && end <= text.count) { + output.data = &text.data[start]; + output.count = end - start; + } + return output; +} + +export(c) fun asm_fixed_trim(text: FixedText) -> FixedText { + var start: u64 = 0; + var end: u64 = text.count; + var width: u64 = 0; + if (!asm_span_valid(text.data, text.count, 1)) { + return text; + } + while (start < end) { + width = asm_fixed_space(text, start); + if (width == 0) { + break; + } + start += width; + } + while (end > start) { + width = 0; + if (asm_fixed_space(text, end - 1) == 1) { + width = 1; + } else if (end - start >= 2 && asm_fixed_space(text, end - 2) == 2) { + width = 2; + } else if (end - start >= 3 && asm_fixed_space(text, end - 3) == 3) { + width = 3; + } + if (width == 0) { + break; + } + end -= width; + } + return asm_fixed_slice(text, start, end); +} + +export(c) fun asm_fixed_word(text: FixedText, word: u64, count: u64, fold: u64) -> bool { + if (text.count != count || count > 8 || fold > 1 + || !asm_span_valid(text.data, text.count, 1)) { + return false; + } + var at: u64 = 0; + var octet: u64 = 0; + while (at < count) { + octet = text.data[at] as u64; + if (fold != 0 && octet >= 65 && octet <= 90) { + octet += 32; + } + if (octet != ((word >> (at * 8)) & 255)) { + return false; + } + at += 1; + } + return true; +} + +export(c) fun asm_fixed_equal(left: FixedText, right: FixedText, fold: u64) -> bool { + if (left.count != right.count || fold > 1 + || !asm_span_valid(left.data, left.count, 1) + || !asm_span_valid(right.data, right.count, 1)) { + return false; + } + var at: u64 = 0; + var a: u64 = 0; + var b: u64 = 0; + while (at < left.count) { + a = left.data[at] as u64; + b = right.data[at] as u64; + if (fold != 0) { + if (a >= 65 && a <= 90) { + a += 32; + } + if (b >= 65 && b <= 90) { + b += 32; + } + } + if (a != b) { + return false; + } + at += 1; + } + return true; +} + +export(c) fun asm_fixed_result_init(result: ptr, max_work: u64) { + result.status = 0; + result.error = 0; + result.start = 0; + result.end = 0; + result.line = 0; + result.previous_start = 0; + result.previous_end = 0; + result.previous_line = 0; + result.text.data = null; + result.text.count = 0; + result.detail = 0; + result.display = 0; + result.word = 0; + result.sections = 0; + result.symbols = 0; + result.relocations = 0; + result.records = 0; + result.operands = 0; + result.bytes = 0; + result.work = 0; + result.max_work = max_work; +} + +export(c) fun asm_fixed_fail(result: ptr, code: u64, + text: FixedText, detail: u64) -> bool { + if (result.status == 0) { + result.status = 1; + result.error = code; + result.text = text; + result.detail = detail; + } + return false; +} + +export(c) fun asm_fixed_charge(result: ptr, units: u64) -> bool { + if (result.status != 0) { + return false; + } + if (result.work > result.max_work || units > result.max_work - result.work) { + return asm_fixed_fail(result, 93, result.text, 0); + } + result.work += units; + return true; +} + +export(c) fun asm_fixed_count(instruction: ptr, count: u64, + result: ptr) -> bool { + if (result.status != 0) { + return false; + } + if (instruction.count != count) { + result.display = instruction.fold; + return asm_fixed_fail(result, 1, instruction.mnemonic, count); + } + return true; +} diff --git a/assembler/loongarch64/branch.wave b/assembler/loongarch64/branch.wave new file mode 100644 index 0000000..21d5c9e --- /dev/null +++ b/assembler/loongarch64/branch.wave @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: MPL-2.0 +// Scaled B16/B21/B26 immediate packing. Callers validate byte displacements first. +fun loong_b26(opcode: u64, immediate: u64) -> u64 { + return opcode | ((immediate & 65535) << 10) | (immediate >> 16); +} + +fun loong_b21(opcode: u64, rj: u64, immediate: u64) -> u64 { + return opcode | (rj << 5) | ((immediate & 65535) << 10) | (immediate >> 16); +} + +fun loong_b16(opcode: u64, rj: u64, rd: u64, immediate: u64) -> u64 { + return opcode | rd | (rj << 5) | (immediate << 10); +} diff --git a/assembler/loongarch64/build.rs b/assembler/loongarch64/build.rs new file mode 100644 index 0000000..55bda5a --- /dev/null +++ b/assembler/loongarch64/build.rs @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: MPL-2.0 +const CFG: &str = "whale_wave_loongarch64"; + +const ENV: &str = "WHALE_WAVE_LOONGARCH64_DIR"; + +const LIBRARY: &str = "whale_wave_loongarch64"; + +const METADATA: &str = "wave-loongarch64.meta"; + +const ROOT_UP: usize = 2; + +const SOURCES: &[&str] = &[ + "assembler/model.wave", + "assembler/declarations.wave", + "assembler/fixed_model.wave", + "assembler/fixed_declarations.wave", + "assembler/loongarch64/model.wave", + "assembler/loongarch64/registers.wave", + "assembler/loongarch64/tables.wave", + "assembler/loongarch64/operands.wave", + "assembler/loongarch64/formats.wave", + "assembler/loongarch64/branch.wave", + "assembler/loongarch64/encoder.wave", + "assembler/loongarch64/entry.wave", +]; + +const ABI_SOURCES: &[&str] = &[ + "assembler/loongarch64/src/wave.rs", + "assembler/loongarch64/src/lib.rs", + "assembler/loongarch64/src/encoder.rs", + "assembler/loongarch64/src/parser.rs", +]; +include!("../build_support.rs"); diff --git a/assembler/loongarch64/encoder.wave b/assembler/loongarch64/encoder.wave new file mode 100644 index 0000000..3537096 --- /dev/null +++ b/assembler/loongarch64/encoder.wave @@ -0,0 +1,149 @@ +// SPDX-License-Identifier: MPL-2.0 +// Complete current LP64S integer subset. Every register and field decision is native. +fun loong_encode(instruction: ptr, context: ptr, + result: ptr) -> bool { + var operation: LoongOpcode; + if (!loong_lookup(instruction.mnemonic, instruction.fold, &operation)) { + asm_fixed_fail(result, 3003, instruction.mnemonic, 0); + result.display = instruction.fold; + return false; + } + if (!asm_fixed_count(instruction, operation.count, result)) { + return false; + } + var index: u64 = 0; + while (index < operation.count) { + if (!asm_span_valid(instruction.operands[index].data, + instruction.operands[index].count, 1)) { + return asm_fixed_fail(result, 3004, instruction.mnemonic, 0); + } + if (!asm_fixed_charge(result, instruction.operands[index].count + 1)) { + return false; + } + index += 1; + } + var rd: u64 = 0; + var rj: u64 = 0; + var rk: u64 = 0; + var immediate: u64 = 0; + var offset: i64 = 0; + var a: FixedText; + var b: FixedText; + var c: FixedText; + if (operation.count > 0) { + a = instruction.operands[0]; + } + if (operation.count > 1) { + b = instruction.operands[1]; + } + if (operation.count > 2) { + c = instruction.operands[2]; + } + if (operation.form == 0) { + if (!loong_register(a, &rd, result) || !loong_register(b, &rj, result) + || !loong_register(c, &rk, result)) { + return false; + } + result.word = loong_three(operation.opcode, rd, rj, rk); + } else if (operation.form == 1 || operation.form == 2) { + // The legacy immediate forms validate the field before both registers. + if (operation.form == 1) { + if (!asm_fixed_signed(c, 12, &immediate, result)) { + return false; + } + } else if (!asm_fixed_unsigned(c, 12, &immediate, result)) { + return false; + } + if (!loong_register(a, &rd, result) || !loong_register(b, &rj, result)) { + return false; + } + result.word = loong_immediate(operation.opcode, rd, rj, immediate); + } else if (operation.form == 3 || operation.form == 4) { + if (!loong_register(a, &rd, result) || !loong_register(b, &rj, result)) { + return false; + } + if (operation.form == 3) { + if (!asm_fixed_unsigned(c, operation.bits, &immediate, result)) { + return false; + } + } else if (!asm_fixed_signed(c, 12, &immediate, result)) { + return false; + } + result.word = loong_immediate(operation.opcode, rd, rj, immediate); + } else if (operation.form == 5) { + if (!loong_register(a, &rj, result) || !loong_register(b, &rd, result) + || !asm_fixed_pc_relative(context, c, 64, &offset, result) + || !asm_fixed_displacement(offset, 16, 4, &immediate, result)) { + return false; + } + result.word = loong_b16(operation.opcode, rj, rd, immediate); + } else if (operation.form == 6) { + result.word = operation.opcode; + } else if (operation.form == 7) { + if (!loong_register(a, &rd, result) || !loong_register(b, &rj, result)) { + return false; + } + result.word = operation.opcode | rd | (rj << 5); + } else if (operation.form == 8) { + if (!loong_register(a, &rd, result) + || !asm_fixed_signed(b, 12, &immediate, result)) { + return false; + } + result.word = operation.opcode | rd | (immediate << 10); + } else if (operation.form == 9) { + if (!loong_upper_immediate(b, &immediate, result) + || !loong_register(a, &rd, result)) { + return false; + } + result.word = loong_upper(operation.opcode, rd, immediate); + } else if (operation.form == 10) { + if (!asm_fixed_pc_relative(context, a, 66, &offset, result) + || !asm_fixed_displacement(offset, 26, 4, &immediate, result)) { + return false; + } + result.word = loong_b26(operation.opcode, immediate); + } else if (operation.form == 11) { + if (!loong_register(a, &rj, result) + || !asm_fixed_pc_relative(context, b, 65, &offset, result) + || !asm_fixed_displacement(offset, 21, 4, &immediate, result)) { + return false; + } + result.word = loong_b21(operation.opcode, rj, immediate); + } else if (operation.form == 12) { + if (!loong_jirl_offset(c, &offset, result) + || !loong_register(a, &rd, result) || !loong_register(b, &rj, result) + || !asm_fixed_displacement(offset, 16, 4, &immediate, result)) { + return false; + } + result.word = loong_b16(operation.opcode, rj, rd, immediate); + } else if (operation.form == 13) { + if (!asm_fixed_unsigned(a, 15, &immediate, result)) { + return false; + } + result.word = operation.opcode | immediate; + } else { + return asm_fixed_fail(result, 3004, instruction.mnemonic, 0); + } + return true; +} + +export(c) fun whale_loongarch64_encode(instruction: ptr, + context: ptr, result: ptr) -> i32 { + if (instruction == null || context == null || result == null) { + return 2; + } + result.status = 0; + result.error = 0; + result.word = 0; + if (!asm_span_valid(instruction.mnemonic.data, instruction.mnemonic.count, 1) + || !asm_span_valid(instruction.operands as ptr, instruction.count, 16) + || instruction.fold > 1) { + asm_fixed_fail(result, 3004, instruction.mnemonic, 0); + return result.status as i32; + } + if (!asm_fixed_charge(result, instruction.mnemonic.count + 1) + || !loong_encode(instruction, context, result)) { + return result.status as i32; + } + return 0; +} diff --git a/assembler/loongarch64/entry.wave b/assembler/loongarch64/entry.wave new file mode 100644 index 0000000..410fbce --- /dev/null +++ b/assembler/loongarch64/entry.wave @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: MPL-2.0 +// Native source execution stays in Wave across the shared driver and ISA kernel. +export(c) fun whale_loongarch64_assemble(packet: ptr, + result: ptr) -> i32 { + if (packet == null || result == null) { + return 2; + } + var state: FixedState; + var instruction: FixedInstruction; + var next: i32 = 0; + if (!asm_fixed_prepare(packet, &state, result)) { + return result.status as i32; + } + while (true) { + next = asm_fixed_next(&state, &instruction, result); + if (next == 0) { + return 0; + } + if (next != 1) { + return result.status as i32; + } + if (whale_loongarch64_encode(&instruction, &state.context, result) != 0 + || !asm_fixed_commit(&state, result.word, result)) { + return result.status as i32; + } + } + return 0; +} diff --git a/assembler/loongarch64/formats.wave b/assembler/loongarch64/formats.wave new file mode 100644 index 0000000..6e1d377 --- /dev/null +++ b/assembler/loongarch64/formats.wave @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: MPL-2.0 +// Fixed-width little-endian integer instruction fields. +fun loong_three(opcode: u64, rd: u64, rj: u64, rk: u64) -> u64 { + return opcode | rd | (rj << 5) | (rk << 10); +} + +fun loong_immediate(opcode: u64, rd: u64, rj: u64, immediate: u64) -> u64 { + return opcode | rd | (rj << 5) | (immediate << 10); +} + +fun loong_upper(opcode: u64, rd: u64, immediate: u64) -> u64 { + return opcode | rd | ((immediate & 1048575) << 5); +} diff --git a/assembler/loongarch64/meson.build b/assembler/loongarch64/meson.build new file mode 100644 index 0000000..43c8113 --- /dev/null +++ b/assembler/loongarch64/meson.build @@ -0,0 +1,55 @@ +# SPDX-License-Identifier: MPL-2.0 +wave_loongarch64_dependencies = [] +wave_loongarch64_directory = get_option('wave-loongarch64-dir') +if wave_loongarch64_directory == '' and wave_source != '' + wave_loongarch64_directory = meson.current_build_dir() + module_target = cargo_host_target + if module_target == '' + target_os = {'linux': 'unknown-linux-gnu', 'darwin': 'apple-darwin', 'windows': 'pc-windows-msvc'} + module_target = host_machine.cpu_family() + '-' + target_os[host_machine.system()] + endif + archive_name = module_target.contains('msvc') ? 'whale_wave_loongarch64.lib' : 'libwhale_wave_loongarch64.a' + arguments = ['--module', 'loongarch64', '--wave-source', wave_source, '--out-dir', '@OUTDIR@', + '--bootstrap-dir', wave_cache, '--target', module_target, + '--rust-toolchain', get_option('wave-rust-toolchain')] + if get_option('wave-allow-network') + arguments += ['--allow-network'] + endif + wave_loongarch64_module = custom_target('wave-loongarch64', + output: [archive_name, 'wave-loongarch64.meta', 'provenance.json'], + command: [python, files('../../tools/build_wave_assembler.py'), arguments], + depend_files: files( + '../model.wave', + '../declarations.wave', + '../fixed_model.wave', + '../fixed_declarations.wave', + 'model.wave', + 'registers.wave', + 'tables.wave', + 'operands.wave', + 'formats.wave', + 'branch.wave', + 'encoder.wave', + 'entry.wave', + 'src/wave.rs', + 'src/lib.rs', + 'src/encoder.rs', + 'src/parser.rs', + '../../tools/build_wave_assembler.py', + '../../tools/wave_bootstrap.py', + '../build_support.rs', + ), + depends: wave_bootstrap, console: true) + wave_loongarch64_dependencies += [wave_loongarch64_module] +elif wave_loongarch64_directory != '' + if not fs.is_absolute(wave_loongarch64_directory) + error('-Dwave-loongarch64-dir must be absolute.') + endif + archive_name = host_machine.system() == 'windows' ? 'whale_wave_loongarch64.lib' : 'libwhale_wave_loongarch64.a' + foreach artifact : [archive_name, 'wave-loongarch64.meta', 'provenance.json'] + if not fs.is_file(wave_loongarch64_directory / artifact) + error('Missing Wave loongarch64 artifact: ' + (wave_loongarch64_directory / artifact)) + endif + endforeach +endif +wave_assembler_all_dependencies += wave_loongarch64_dependencies diff --git a/assembler/loongarch64/model.wave b/assembler/loongarch64/model.wave new file mode 100644 index 0000000..4b60b60 --- /dev/null +++ b/assembler/loongarch64/model.wave @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: MPL-2.0 +// LoongArch64 instruction classification; integer fields contain no host addresses. +struct LoongOpcode { + form: u64; + opcode: u64; + bits: u64; + count: u64; +} diff --git a/assembler/loongarch64/operands.wave b/assembler/loongarch64/operands.wave new file mode 100644 index 0000000..57c621a --- /dev/null +++ b/assembler/loongarch64/operands.wave @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: MPL-2.0 +// LoongArch-specific immediate diagnostics preserve source evaluation order. +fun loong_upper_immediate(text: FixedText, output: ptr, + result: ptr) -> bool { + var number: AsmWide; + if (!asm_fixed_integer(text, &number, result)) { + return false; + } + if (!asm_number_fits_signed(&number, 20)) { + return asm_fixed_fail(result, 3001, text, 0); + } + output[0] = number.low & 1048575; + return true; +} + +fun loong_jirl_offset(text: FixedText, output: ptr, result: ptr) -> bool { + var number: AsmWide; + if (!asm_fixed_integer(text, &number, result)) { + return false; + } + if (!asm_number_fits_signed(&number, 64)) { + return asm_fixed_fail(result, 3002, text, 0); + } + output[0] = number.low as i64; + return true; +} diff --git a/assembler/loongarch64/registers.wave b/assembler/loongarch64/registers.wave new file mode 100644 index 0000000..aeb5ed9 --- /dev/null +++ b/assembler/loongarch64/registers.wave @@ -0,0 +1,166 @@ +// SPDX-License-Identifier: MPL-2.0 +// ABI aliases and canonical numeric registers; dollar prefixes are optional. +fun loong_register_error(text: FixedText, result: ptr) -> bool { + asm_fixed_fail(result, 3000, text, 0); + result.display = 1; + return false; +} + +fun loong_register(raw: FixedText, output: ptr, result: ptr) -> bool { + var text: FixedText = asm_fixed_trim(raw); + if (text.count != 0 && text.data[0] == 36) { + text.data = &text.data[1]; + text.count -= 1; + } + if (asm_fixed_word(text, 1869768058, 4, 1)) { // zero + output[0] = 0; + return true; + } + if (asm_fixed_word(text, 24946, 2, 1)) { // ra + output[0] = 1; + return true; + } + if (asm_fixed_word(text, 28788, 2, 1)) { // tp + output[0] = 2; + return true; + } + if (asm_fixed_word(text, 28787, 2, 1)) { // sp + output[0] = 3; + return true; + } + if (asm_fixed_word(text, 12385, 2, 1)) { // a0 + output[0] = 4; + return true; + } + if (asm_fixed_word(text, 12641, 2, 1)) { // a1 + output[0] = 5; + return true; + } + if (asm_fixed_word(text, 12897, 2, 1)) { // a2 + output[0] = 6; + return true; + } + if (asm_fixed_word(text, 13153, 2, 1)) { // a3 + output[0] = 7; + return true; + } + if (asm_fixed_word(text, 13409, 2, 1)) { // a4 + output[0] = 8; + return true; + } + if (asm_fixed_word(text, 13665, 2, 1)) { // a5 + output[0] = 9; + return true; + } + if (asm_fixed_word(text, 13921, 2, 1)) { // a6 + output[0] = 10; + return true; + } + if (asm_fixed_word(text, 14177, 2, 1)) { // a7 + output[0] = 11; + return true; + } + if (asm_fixed_word(text, 12404, 2, 1)) { // t0 + output[0] = 12; + return true; + } + if (asm_fixed_word(text, 12660, 2, 1)) { // t1 + output[0] = 13; + return true; + } + if (asm_fixed_word(text, 12916, 2, 1)) { // t2 + output[0] = 14; + return true; + } + if (asm_fixed_word(text, 13172, 2, 1)) { // t3 + output[0] = 15; + return true; + } + if (asm_fixed_word(text, 13428, 2, 1)) { // t4 + output[0] = 16; + return true; + } + if (asm_fixed_word(text, 13684, 2, 1)) { // t5 + output[0] = 17; + return true; + } + if (asm_fixed_word(text, 13940, 2, 1)) { // t6 + output[0] = 18; + return true; + } + if (asm_fixed_word(text, 14196, 2, 1)) { // t7 + output[0] = 19; + return true; + } + if (asm_fixed_word(text, 14452, 2, 1)) { // t8 + output[0] = 20; + return true; + } + if (asm_fixed_word(text, 12405, 2, 1)) { // u0 + output[0] = 21; + return true; + } + if (asm_fixed_word(text, 28774, 2, 1)) { // fp + output[0] = 22; + return true; + } + if (asm_fixed_word(text, 12403, 2, 1)) { // s0 + output[0] = 23; + return true; + } + if (asm_fixed_word(text, 12659, 2, 1)) { // s1 + output[0] = 24; + return true; + } + if (asm_fixed_word(text, 12915, 2, 1)) { // s2 + output[0] = 25; + return true; + } + if (asm_fixed_word(text, 13171, 2, 1)) { // s3 + output[0] = 26; + return true; + } + if (asm_fixed_word(text, 13427, 2, 1)) { // s4 + output[0] = 27; + return true; + } + if (asm_fixed_word(text, 13683, 2, 1)) { // s5 + output[0] = 28; + return true; + } + if (asm_fixed_word(text, 13939, 2, 1)) { // s6 + output[0] = 29; + return true; + } + if (asm_fixed_word(text, 14195, 2, 1)) { // s7 + output[0] = 30; + return true; + } + if (asm_fixed_word(text, 14451, 2, 1)) { // s8 + output[0] = 31; + return true; + } + if (text.count < 2 || text.count > 3 + || (text.data[0] != 114 && text.data[0] != 82)) { + return loong_register_error(text, result); + } + if (text.count > 2 && text.data[1] == 48) { + return loong_register_error(text, result); + } + var number: u64 = 0; + var at: u64 = 1; + var octet: u64 = 0; + while (at < text.count) { + octet = text.data[at] as u64; + if (octet < 48 || octet > 57) { + return loong_register_error(text, result); + } + number = number * 10 + octet - 48; + at += 1; + } + if (number >= 32) { + return loong_register_error(text, result); + } + output[0] = number; + return true; +} diff --git a/assembler/loongarch64/src/encoder.rs b/assembler/loongarch64/src/encoder.rs index 13665aa..5190a35 100644 --- a/assembler/loongarch64/src/encoder.rs +++ b/assembler/loongarch64/src/encoder.rs @@ -6,8 +6,10 @@ use crate::{ tables, }; +use assembler::fixed::reference::{count, signed, unsigned}; + use assembler::{ - fixed::{self, count, error, signed, unsigned, Context, Instruction}, + fixed::{self, error, Context, Instruction}, AsmError, }; @@ -36,7 +38,7 @@ pub(crate) fn encode(inst: &Instruction, cx: &mut Context<'_>) -> Result) -> Result { let a = count(inst, 2)?; - let n = fixed::integer(&a[1])?; + let n = fixed::reference::integer(&a[1])?; if !(-(1 << 19)..(1 << 19)).contains(&n) { return Err(error("upper immediate must fit signed 20 bits")); } @@ -68,15 +70,19 @@ pub(crate) fn encode(inst: &Instruction, cx: &mut Context<'_>) -> Result { let a = count(inst, 1)?; - branch::direct(m == "bl", cx.pc_relative(&a[0], tables::B26_RELOCATION)?) + branch::direct(m == "bl", cx.pc_relative_reference(&a[0], tables::B26_RELOCATION)?) }, "beqz" | "bnez" => { let a = count(inst, 2)?; - branch::zero(m == "bnez", reg(&a[0])?, cx.pc_relative(&a[1], tables::B21_RELOCATION)?) + branch::zero( + m == "bnez", + reg(&a[0])?, + cx.pc_relative_reference(&a[1], tables::B21_RELOCATION)?, + ) }, "jirl" => { let a = count(inst, 3)?; - let value = i64::try_from(fixed::integer(&a[2])?) + let value = i64::try_from(fixed::reference::integer(&a[2])?) .map_err(|_| error("jirl displacement exceeds i64"))?; branch::indirect(reg(&a[0])?, reg(&a[1])?, value) }, diff --git a/assembler/loongarch64/src/encoding/branch.rs b/assembler/loongarch64/src/encoding/branch.rs index a149b1e..5c9890d 100644 --- a/assembler/loongarch64/src/encoding/branch.rs +++ b/assembler/loongarch64/src/encoding/branch.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MPL-2.0 //! LoongArch B16/B21/B26 scaled offsets, split fields and JIRL encoding. -use assembler::{fixed::displacement, AsmError}; +use assembler::{fixed::reference::displacement, AsmError}; pub(crate) fn direct(link: bool, offset: i64) -> Result { let imm = displacement(offset, 26, 4)?; diff --git a/assembler/loongarch64/src/lib.rs b/assembler/loongarch64/src/lib.rs index 5e77b33..89c5801 100644 --- a/assembler/loongarch64/src/lib.rs +++ b/assembler/loongarch64/src/lib.rs @@ -1,16 +1,30 @@ // SPDX-License-Identifier: MPL-2.0 //! LoongArch64 assembler entry point; instruction handling lives in the ISA modules. use assembler::{ - fixed::{self, Context, FixedIsa, Instruction}, + fixed::{Context, FixedIsa, Instruction}, AsmError, AssemblerOutput, AssemblyLimits, }; +#[cfg(not(whale_wave_loongarch64))] mod encoder; +#[cfg(all(test, whale_wave_loongarch64))] +#[path = "encoder.rs"] +mod reference_encoder; + +#[cfg(whale_wave_loongarch64)] +mod wave; + +#[cfg(not(whale_wave_loongarch64))] +use assembler::fixed; + +#[cfg(any(test, not(whale_wave_loongarch64)))] mod encoding; +#[cfg(any(test, not(whale_wave_loongarch64)))] mod parser; +#[cfg(any(test, not(whale_wave_loongarch64)))] mod tables; pub struct LoongArch64; @@ -30,7 +44,14 @@ impl assembler::extension::Assembler for LoongArch64 { source: &str, limits: &AssemblyLimits, ) -> Result { - fixed::assemble(self, name, source, limits) + #[cfg(whale_wave_loongarch64)] + { + wave::assemble(name, source, limits) + } + #[cfg(not(whale_wave_loongarch64))] + { + fixed::assemble(self, name, source, limits) + } } } @@ -39,11 +60,135 @@ impl FixedIsa for LoongArch64 { "loongarch64" } + #[cfg(whale_wave_loongarch64)] + fn native_assemble( + &self, + name: &str, + source: &str, + limits: &AssemblyLimits, + ) -> Option> { + Some(wave::assemble(name, source, limits)) + } + fn encode( &self, instruction: &Instruction, context: &mut Context<'_>, ) -> Result { - encoder::encode(instruction, context) + #[cfg(whale_wave_loongarch64)] + { + wave::encode(instruction, context) + } + #[cfg(not(whale_wave_loongarch64))] + { + encoder::encode(instruction, context) + } + } +} + +#[cfg(all(test, whale_wave_loongarch64))] +mod wave_tests { + use super::*; + + struct Reference; + + impl FixedIsa for Reference { + fn id(&self) -> &'static str { + "loongarch64" + } + + fn encode( + &self, + instruction: &Instruction, + context: &mut Context<'_>, + ) -> Result { + reference_encoder::encode(instruction, context) + } + } + + fn compare(source: &str, limits: AssemblyLimits) { + let expected = + assembler::fixed::reference::assemble(&Reference, "한/source.s", source, &limits); + let actual = wave::assemble("한/source.s", source, &limits); + match (actual, expected) { + (Ok(actual), Ok(expected)) => { + assert_eq!(actual.sections.len(), expected.sections.len(), "{source}"); + for (actual, expected) in actual.sections.iter().zip(&expected.sections) { + assert_eq!(actual.name, expected.name, "{source}"); + assert_eq!(actual.kind, expected.kind, "{source}"); + assert_eq!(actual.align, expected.align, "{source}"); + assert_eq!(actual.data, expected.data, "{source}"); + assert_eq!(actual.zero_fill, expected.zero_fill, "{source}"); + assert_eq!( + format!("{:?}", actual.relocs), + format!("{:?}", expected.relocs), + "{source}" + ); + } + assert_eq!(actual.symbols.len(), expected.symbols.len(), "{source}"); + for (actual, expected) in actual.symbols.iter().zip(&expected.symbols) { + assert_eq!(actual.name, expected.name, "{source}"); + assert_eq!(actual.section_index, expected.section_index, "{source}"); + assert_eq!(actual.offset, expected.offset, "{source}"); + assert_eq!(actual.is_global, expected.is_global, "{source}"); + } + }, + (Err(actual), Err(expected)) => { + assert_eq!(actual.to_string(), expected.to_string(), "{source}"); + }, + (actual, expected) => panic!( + "{source}: result classes differ: actual={}, expected={}", + actual.is_ok(), + expected.is_ok() + ), + } + } + + #[test] + fn native_complete_inventory_and_validation_precedence_match_reference() { + for line in include_str!("../tests/fixtures/encodings.tsv").lines() { + if !line.is_empty() && !line.starts_with('#') { + compare(line.split_once('\t').unwrap().1, AssemblyLimits::default()); + } + } + for source in [ + "", "ADD.D $R0,$R1,$R2", "move $FP, $S0", "move r01,r0", + "ld.d BAD,$r0,99999", "addi.d BAD,$r0,99999", "slli.d BAD,$r0,99999", + "lu12i.w BAD,524288", "jirl BAD,BAD,18446744073709551616", "li.d BAD,99999", + "add.d $r0,$r0", "nop $r0", "beqz $r1,2", "b 134217728", + "move $$sp,r0", "move r1,r0", ".global missing\nBAD\n", + "here: here: nop", ".extern foo\nfoo: nop", "foo: nop\n.extern foo", + ".text\n.byte 0\nnop", ".data\nnop", ".bss\n.word 0", + ".balign 0", ".align 64", ".zero -1", ".quad missing", ".byte here\nhere: nop", + ".section .TEXT\n.byte 1", ".data\n.byte 1,2,255,-128\n.hword 65535,-32768\n.long 4294967295\n.quad -1", + ".global start\nstart: beq $r1,$r2,done\nnop\ndone: bl external+8\n.extern external\n.data\n.quad start+4", + ".bss\n.zero 1099511627776\n.balign 4096\nstorage:\n.text\nret\n.global storage", + "; 한글\r\n add.d $bad,$r0,$r0 ; ignored\r\n", "nop\rret", + ] { + compare(source, AssemblyLimits::default()); + } + for limits in [ + AssemblyLimits { max_output_bytes: 0, ..Default::default() }, + AssemblyLimits { max_output_bytes: 3, ..Default::default() }, + AssemblyLimits { max_relax_iterations: 0, ..Default::default() }, + ] { + compare("nop", limits); + } + } + + #[test] + fn native_generated_integer_and_branch_sources_match_explicit_reference() { + let mut state = 0x0057_4841_4c45_4c41_u64; + for _ in 0..2000 { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + let rd = state % 32; + let rj = (state >> 5) % 32; + let rk = (state >> 10) % 32; + let immediate = ((state >> 16) % 4096) as i64 - 2048; + let offset = (((state >> 28) % 65536) as i64 - 32768) * 4; + compare(&format!("add.d $r{rd},$r{rj},$r{rk}\naddi.d $r{rd},$r{rj},{immediate}\nbeq $r{rj},$r{rd},{offset}"), AssemblyLimits::default()); + } } } diff --git a/assembler/loongarch64/src/wave.rs b/assembler/loongarch64/src/wave.rs new file mode 100644 index 0000000..57c593c --- /dev/null +++ b/assembler/loongarch64/src/wave.rs @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Typed transport and diagnostics for the complete native Wave LoongArch64 module. +use assembler::{ + fixed::{native, Context, Instruction}, + AsmError, AssemblerOutput, AssemblyLimits, +}; + +unsafe extern "C" { + fn whale_loongarch64_assemble( + packet: *const native::FixedInput, + result: *mut native::FixedResult, + ) -> i32; + + fn whale_loongarch64_encode( + instruction: *const native::FixedInstruction, + context: *mut native::FixedContext, + result: *mut native::FixedResult, + ) -> i32; +} + +fn render(code: u64, text: &str, _detail: u64) -> AsmError { + match code { + 3000 => AsmError::EncodeError(format!("invalid LoongArch64 register {text:?}")), + 3001 => AsmError::EncodeError("upper immediate must fit signed 20 bits".into()), + 3002 => AsmError::EncodeError("jirl displacement exceeds i64".into()), + 3003 => AsmError::EncodeError(format!("unsupported LoongArch64 instruction {text:?}")), + _ => AsmError::Backend("LoongArch64 native transport"), + } +} + +pub(super) fn assemble( + name: &str, + source: &str, + limits: &AssemblyLimits, +) -> Result { + native::assemble(name, source, limits, "loongarch64", true, whale_loongarch64_assemble, render) +} + +pub(super) fn encode( + instruction: &Instruction, + context: &mut Context<'_>, +) -> Result { + native::encode(instruction, context, whale_loongarch64_encode, render) +} diff --git a/assembler/loongarch64/tables.wave b/assembler/loongarch64/tables.wave new file mode 100644 index 0000000..7c488ff --- /dev/null +++ b/assembler/loongarch64/tables.wave @@ -0,0 +1,432 @@ +// SPDX-License-Identifier: MPL-2.0 +// Complete current integer opcode inventory and operand forms. +fun loong_lookup(text: FixedText, fold: u64, output: ptr) -> bool { + if (asm_fixed_word(text, 511879439457, 5, fold)) { // add.w + output.form = 0; + output.opcode = 1048576; + output.bits = 0; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 430275060833, 5, fold)) { // add.d + output.form = 0; + output.opcode = 1081344; + output.bits = 0; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 511879312755, 5, fold)) { // sub.w + output.form = 0; + output.opcode = 1114112; + output.bits = 0; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 430274934131, 5, fold)) { // sub.d + output.form = 0; + output.opcode = 1146880; + output.bits = 0; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 7629939, 3, fold)) { // slt + output.form = 0; + output.opcode = 1179648; + output.bits = 0; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 1970564211, 4, fold)) { // sltu + output.form = 0; + output.opcode = 1212416; + output.bits = 0; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 7499630, 3, fold)) { // nor + output.form = 0; + output.opcode = 1310720; + output.bits = 0; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 6581857, 3, fold)) { // and + output.form = 0; + output.opcode = 1343488; + output.bits = 0; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 29295, 2, fold)) { // or + output.form = 0; + output.opcode = 1376256; + output.bits = 0; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 7499640, 3, fold)) { // xor + output.form = 0; + output.opcode = 1409024; + output.bits = 0; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 511879965811, 5, fold)) { // sll.w + output.form = 0; + output.opcode = 1507328; + output.bits = 0; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 511879967347, 5, fold)) { // srl.w + output.form = 0; + output.opcode = 1540096; + output.bits = 0; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 511879246451, 5, fold)) { // sra.w + output.form = 0; + output.opcode = 1572864; + output.bits = 0; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 430275587187, 5, fold)) { // sll.d + output.form = 0; + output.opcode = 1605632; + output.bits = 0; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 430275588723, 5, fold)) { // srl.d + output.form = 0; + output.opcode = 1638400; + output.bits = 0; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 430274867827, 5, fold)) { // sra.d + output.form = 0; + output.opcode = 1671168; + output.bits = 0; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 1769237619, 4, fold)) { // slti + output.form = 1; + output.opcode = 33554432; + output.bits = 12; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 452942130291, 5, fold)) { // sltui + output.form = 1; + output.opcode = 37748736; + output.bits = 12; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 131041220387937, 6, fold)) { // addi.w + output.form = 1; + output.opcode = 41943040; + output.bits = 12; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 110150499460193, 6, fold)) { // addi.d + output.form = 1; + output.opcode = 46137344; + output.bits = 12; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 28198527019873644, 7, fold)) { // lu52i.d + output.form = 1; + output.opcode = 50331648; + output.bits = 12; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 1768189537, 4, fold)) { // andi + output.form = 2; + output.opcode = 54525952; + output.bits = 12; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 6910575, 3, fold)) { // ori + output.form = 2; + output.opcode = 58720256; + output.bits = 12; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 1769107320, 4, fold)) { // xori + output.form = 2; + output.opcode = 62914560; + output.bits = 12; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 131041220914291, 6, fold)) { // slli.w + output.form = 3; + output.opcode = 4227072; + output.bits = 5; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 131041220915827, 6, fold)) { // srli.w + output.form = 3; + output.opcode = 4489216; + output.bits = 5; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 131041220194931, 6, fold)) { // srai.w + output.form = 3; + output.opcode = 4751360; + output.bits = 5; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 110150499986547, 6, fold)) { // slli.d + output.form = 3; + output.opcode = 4259840; + output.bits = 6; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 110150499988083, 6, fold)) { // srli.d + output.form = 3; + output.opcode = 4521984; + output.bits = 6; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 110150499267187, 6, fold)) { // srai.d + output.form = 3; + output.opcode = 4784128; + output.bits = 6; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 1647207532, 4, fold)) { // ld.b + output.form = 4; + output.opcode = 671088640; + output.bits = 12; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 1747870828, 4, fold)) { // ld.h + output.form = 4; + output.opcode = 675282944; + output.bits = 12; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 1999529068, 4, fold)) { // ld.w + output.form = 4; + output.opcode = 679477248; + output.bits = 12; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 1680761964, 4, fold)) { // ld.d + output.form = 4; + output.opcode = 683671552; + output.bits = 12; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 1647211635, 4, fold)) { // st.b + output.form = 4; + output.opcode = 687865856; + output.bits = 12; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 1747874931, 4, fold)) { // st.h + output.form = 4; + output.opcode = 692060160; + output.bits = 12; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 1999533171, 4, fold)) { // st.w + output.form = 4; + output.opcode = 696254464; + output.bits = 12; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 1680766067, 4, fold)) { // st.d + output.form = 4; + output.opcode = 700448768; + output.bits = 12; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 504158381164, 5, fold)) { // ld.bu + output.form = 4; + output.opcode = 704643072; + output.bits = 12; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 504259044460, 5, fold)) { // ld.hu + output.form = 4; + output.opcode = 708837376; + output.bits = 12; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 504510702700, 5, fold)) { // ld.wu + output.form = 4; + output.opcode = 713031680; + output.bits = 12; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 7431522, 3, fold)) { // beq + output.form = 5; + output.opcode = 1476395008; + output.bits = 16; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 6647394, 3, fold)) { // bne + output.form = 5; + output.opcode = 1543503872; + output.bits = 16; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 7629922, 3, fold)) { // blt + output.form = 5; + output.opcode = 1610612736; + output.bits = 16; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 6645602, 3, fold)) { // bge + output.form = 5; + output.opcode = 1677721600; + output.bits = 16; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 1970564194, 4, fold)) { // bltu + output.form = 5; + output.opcode = 1744830464; + output.bits = 16; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 1969579874, 4, fold)) { // bgeu + output.form = 5; + output.opcode = 1811939328; + output.bits = 16; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 7368558, 3, fold)) { // nop + output.form = 6; + output.opcode = 54525952; + output.bits = 0; + output.count = 0; + return true; + } + else if (asm_fixed_word(text, 7628146, 3, fold)) { // ret + output.form = 6; + output.opcode = 1275068448; + output.bits = 0; + output.count = 0; + return true; + } + else if (asm_fixed_word(text, 1702260589, 4, fold)) { // move + output.form = 7; + output.opcode = 1376256; + output.bits = 0; + output.count = 2; + return true; + } + else if (asm_fixed_word(text, 1680763244, 4, fold)) { // li.d + output.form = 8; + output.opcode = 46137344; + output.bits = 12; + output.count = 2; + return true; + } + else if (asm_fixed_word(text, 1999530348, 4, fold)) { // li.w + output.form = 8; + output.opcode = 41943040; + output.bits = 12; + output.count = 2; + return true; + } + else if (asm_fixed_word(text, 33546551577113964, 7, fold)) { // lu12i.w + output.form = 9; + output.opcode = 335544320; + output.bits = 20; + output.count = 2; + return true; + } + else if (asm_fixed_word(text, 28198527019742572, 7, fold)) { // lu32i.d + output.form = 9; + output.opcode = 369098752; + output.bits = 20; + output.count = 2; + return true; + } + else if (asm_fixed_word(text, 98, 1, fold)) { // b + output.form = 10; + output.opcode = 1342177280; + output.bits = 26; + output.count = 1; + return true; + } + else if (asm_fixed_word(text, 27746, 2, fold)) { // bl + output.form = 10; + output.opcode = 1409286144; + output.bits = 26; + output.count = 1; + return true; + } + else if (asm_fixed_word(text, 2054251874, 4, fold)) { // beqz + output.form = 11; + output.opcode = 1073741824; + output.bits = 21; + output.count = 2; + return true; + } + else if (asm_fixed_word(text, 2053467746, 4, fold)) { // bnez + output.form = 11; + output.opcode = 1140850688; + output.bits = 21; + output.count = 2; + return true; + } + else if (asm_fixed_word(text, 1819437418, 4, fold)) { // jirl + output.form = 12; + output.opcode = 1275068416; + output.bits = 16; + output.count = 3; + return true; + } + else if (asm_fixed_word(text, 30518463020890483, 7, fold)) { // syscall + output.form = 13; + output.opcode = 2818048; + output.bits = 15; + output.count = 1; + return true; + } + else if (asm_fixed_word(text, 461195539042, 5, fold)) { // break + output.form = 13; + output.opcode = 2752512; + output.bits = 15; + output.count = 1; + return true; + } + return false; +} diff --git a/assembler/meson.build b/assembler/meson.build index d090166..9aa4670 100644 --- a/assembler/meson.build +++ b/assembler/meson.build @@ -26,8 +26,19 @@ if wave_assembler_directory == '' and wave_source != '' 'numeric.wave', 'output.wave', 'lexer.wave', + 'fixed_model.wave', + 'fixed_text.wave', + 'fixed_numbers.wave', + 'fixed_operands.wave', + 'fixed_namespace.wave', + 'fixed_relative.wave', + 'fixed_scalar.wave', + 'fixed_source.wave', + 'fixed_driver.wave', 'src/tokens.rs', 'src/tokens_wave.rs', + 'src/fixed.rs', + 'src/fixed_wave.rs', '../tools/build_wave_assembler.py', '../tools/wave_bootstrap.py', 'build_support.rs', @@ -50,6 +61,18 @@ wave_amd64_directory = '' if get_option('asm-amd64') subdir('amd64') endif -if wave_amd64_directory != '' and wave_assembler_directory == '' - error('The Wave AMD64 module requires -Dwave-assembler-dir or a Wave source build.') +wave_aarch64_directory = '' +if get_option('asm-aarch64') + subdir('aarch64') +endif +wave_riscv64_directory = '' +if get_option('asm-riscv64') + subdir('riscv64') +endif +wave_loongarch64_directory = '' +if get_option('asm-loongarch64') + subdir('loongarch64') +endif +if wave_assembler_directory == '' and (wave_amd64_directory != '' or wave_aarch64_directory != '' or wave_riscv64_directory != '' or wave_loongarch64_directory != '') + error('Wave ISA modules require -Dwave-assembler-dir or a Wave source build.') endif diff --git a/assembler/riscv64/build.rs b/assembler/riscv64/build.rs new file mode 100644 index 0000000..d8053fc --- /dev/null +++ b/assembler/riscv64/build.rs @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: MPL-2.0 +const CFG: &str = "whale_wave_riscv64"; + +const ENV: &str = "WHALE_WAVE_RISCV64_DIR"; + +const LIBRARY: &str = "whale_wave_riscv64"; + +const METADATA: &str = "wave-riscv64.meta"; + +const ROOT_UP: usize = 2; + +const SOURCES: &[&str] = &[ + "assembler/model.wave", + "assembler/declarations.wave", + "assembler/fixed_model.wave", + "assembler/fixed_declarations.wave", + "assembler/riscv64/registers.wave", + "assembler/riscv64/operands.wave", + "assembler/riscv64/encoding.wave", + "assembler/riscv64/encoder.wave", + "assembler/riscv64/parser.wave", + "assembler/riscv64/entry.wave", +]; + +const ABI_SOURCES: &[&str] = &[ + "assembler/riscv64/src/wave.rs", + "assembler/riscv64/src/lib.rs", + "assembler/riscv64/src/encoder.rs", + "assembler/riscv64/src/parser.rs", +]; +include!("../build_support.rs"); diff --git a/assembler/riscv64/encoder.wave b/assembler/riscv64/encoder.wave new file mode 100644 index 0000000..9468a83 --- /dev/null +++ b/assembler/riscv64/encoder.wave @@ -0,0 +1,750 @@ +// SPDX-License-Identifier: MPL-2.0 +// The supported RV64I instruction inventory; no extension is inferred. +struct RvOpcode { + form: u64; + opcode: u64; + f3: u64; + f7: u64; +} + +fun rv_lookup(text: FixedText, fold: u64, output: ptr) -> bool { + // add + if (asm_fixed_word(text, 6579297, 3, fold)) { + output.form = 0; + output.opcode = 51; + output.f3 = 0; + output.f7 = 0; + return true; + } + // addw + if (asm_fixed_word(text, 2003068001, 4, fold)) { + output.form = 0; + output.opcode = 59; + output.f3 = 0; + output.f7 = 0; + return true; + } + // sub + if (asm_fixed_word(text, 6452595, 3, fold)) { + output.form = 0; + output.opcode = 51; + output.f3 = 0; + output.f7 = 32; + return true; + } + // subw + if (asm_fixed_word(text, 2002941299, 4, fold)) { + output.form = 0; + output.opcode = 59; + output.f3 = 0; + output.f7 = 32; + return true; + } + // sll + if (asm_fixed_word(text, 7105651, 3, fold)) { + output.form = 0; + output.opcode = 51; + output.f3 = 1; + output.f7 = 0; + return true; + } + // sllw + if (asm_fixed_word(text, 2003594355, 4, fold)) { + output.form = 0; + output.opcode = 59; + output.f3 = 1; + output.f7 = 0; + return true; + } + // slt + if (asm_fixed_word(text, 7629939, 3, fold)) { + output.form = 0; + output.opcode = 51; + output.f3 = 2; + output.f7 = 0; + return true; + } + // sltu + if (asm_fixed_word(text, 1970564211, 4, fold)) { + output.form = 0; + output.opcode = 51; + output.f3 = 3; + output.f7 = 0; + return true; + } + // xor + if (asm_fixed_word(text, 7499640, 3, fold)) { + output.form = 0; + output.opcode = 51; + output.f3 = 4; + output.f7 = 0; + return true; + } + // srl + if (asm_fixed_word(text, 7107187, 3, fold)) { + output.form = 0; + output.opcode = 51; + output.f3 = 5; + output.f7 = 0; + return true; + } + // srlw + if (asm_fixed_word(text, 2003595891, 4, fold)) { + output.form = 0; + output.opcode = 59; + output.f3 = 5; + output.f7 = 0; + return true; + } + // sra + if (asm_fixed_word(text, 6386291, 3, fold)) { + output.form = 0; + output.opcode = 51; + output.f3 = 5; + output.f7 = 32; + return true; + } + // sraw + if (asm_fixed_word(text, 2002874995, 4, fold)) { + output.form = 0; + output.opcode = 59; + output.f3 = 5; + output.f7 = 32; + return true; + } + // or + if (asm_fixed_word(text, 29295, 2, fold)) { + output.form = 0; + output.opcode = 51; + output.f3 = 6; + output.f7 = 0; + return true; + } + // and + if (asm_fixed_word(text, 6581857, 3, fold)) { + output.form = 0; + output.opcode = 51; + output.f3 = 7; + output.f7 = 0; + return true; + } + // addi + if (asm_fixed_word(text, 1768186977, 4, fold)) { + output.form = 1; + output.opcode = 19; + output.f3 = 0; + output.f7 = 0; + return true; + } + // slti + if (asm_fixed_word(text, 1769237619, 4, fold)) { + output.form = 1; + output.opcode = 19; + output.f3 = 2; + output.f7 = 0; + return true; + } + // sltiu + if (asm_fixed_word(text, 504280411251, 5, fold)) { + output.form = 1; + output.opcode = 19; + output.f3 = 3; + output.f7 = 0; + return true; + } + // xori + if (asm_fixed_word(text, 1769107320, 4, fold)) { + output.form = 1; + output.opcode = 19; + output.f3 = 4; + output.f7 = 0; + return true; + } + // ori + if (asm_fixed_word(text, 6910575, 3, fold)) { + output.form = 1; + output.opcode = 19; + output.f3 = 6; + output.f7 = 0; + return true; + } + // andi + if (asm_fixed_word(text, 1768189537, 4, fold)) { + output.form = 1; + output.opcode = 19; + output.f3 = 7; + output.f7 = 0; + return true; + } + // addiw + if (asm_fixed_word(text, 512869295201, 5, fold)) { + output.form = 1; + output.opcode = 27; + output.f3 = 0; + output.f7 = 0; + return true; + } + // beq + if (asm_fixed_word(text, 7431522, 3, fold)) { + output.form = 2; + output.opcode = 0; + output.f3 = 0; + output.f7 = 0; + return true; + } + // bne + if (asm_fixed_word(text, 6647394, 3, fold)) { + output.form = 2; + output.opcode = 0; + output.f3 = 1; + output.f7 = 0; + return true; + } + // blt + if (asm_fixed_word(text, 7629922, 3, fold)) { + output.form = 2; + output.opcode = 0; + output.f3 = 4; + output.f7 = 0; + return true; + } + // bge + if (asm_fixed_word(text, 6645602, 3, fold)) { + output.form = 2; + output.opcode = 0; + output.f3 = 5; + output.f7 = 0; + return true; + } + // bltu + if (asm_fixed_word(text, 1970564194, 4, fold)) { + output.form = 2; + output.opcode = 0; + output.f3 = 6; + output.f7 = 0; + return true; + } + // bgeu + if (asm_fixed_word(text, 1969579874, 4, fold)) { + output.form = 2; + output.opcode = 0; + output.f3 = 7; + output.f7 = 0; + return true; + } + // lb + if (asm_fixed_word(text, 25196, 2, fold)) { + output.form = 3; + output.opcode = 0; + output.f3 = 0; + output.f7 = 0; + return true; + } + // lh + if (asm_fixed_word(text, 26732, 2, fold)) { + output.form = 3; + output.opcode = 0; + output.f3 = 1; + output.f7 = 0; + return true; + } + // lw + if (asm_fixed_word(text, 30572, 2, fold)) { + output.form = 3; + output.opcode = 0; + output.f3 = 2; + output.f7 = 0; + return true; + } + // ld + if (asm_fixed_word(text, 25708, 2, fold)) { + output.form = 3; + output.opcode = 0; + output.f3 = 3; + output.f7 = 0; + return true; + } + // lbu + if (asm_fixed_word(text, 7692908, 3, fold)) { + output.form = 3; + output.opcode = 0; + output.f3 = 4; + output.f7 = 0; + return true; + } + // lhu + if (asm_fixed_word(text, 7694444, 3, fold)) { + output.form = 3; + output.opcode = 0; + output.f3 = 5; + output.f7 = 0; + return true; + } + // lwu + if (asm_fixed_word(text, 7698284, 3, fold)) { + output.form = 3; + output.opcode = 0; + output.f3 = 6; + output.f7 = 0; + return true; + } + // sb + if (asm_fixed_word(text, 25203, 2, fold)) { + output.form = 4; + output.opcode = 0; + output.f3 = 0; + output.f7 = 0; + return true; + } + // sh + if (asm_fixed_word(text, 26739, 2, fold)) { + output.form = 4; + output.opcode = 0; + output.f3 = 1; + output.f7 = 0; + return true; + } + // sw + if (asm_fixed_word(text, 30579, 2, fold)) { + output.form = 4; + output.opcode = 0; + output.f3 = 2; + output.f7 = 0; + return true; + } + // sd + if (asm_fixed_word(text, 25715, 2, fold)) { + output.form = 4; + output.opcode = 0; + output.f3 = 3; + output.f7 = 0; + return true; + } + // nop + if (asm_fixed_word(text, 7368558, 3, fold)) { + output.form = 5; + output.opcode = 0; + output.f3 = 0; + output.f7 = 0; + return true; + } + // ret + if (asm_fixed_word(text, 7628146, 3, fold)) { + output.form = 5; + output.opcode = 1; + output.f3 = 0; + output.f7 = 0; + return true; + } + // ecall + if (asm_fixed_word(text, 465674789733, 5, fold)) { + output.form = 5; + output.opcode = 2; + output.f3 = 0; + output.f7 = 0; + return true; + } + // ebreak + if (asm_fixed_word(text, 118066057994853, 6, fold)) { + output.form = 5; + output.opcode = 3; + output.f3 = 0; + output.f7 = 0; + return true; + } + // mv + if (asm_fixed_word(text, 30317, 2, fold)) { + output.form = 5; + output.opcode = 4; + output.f3 = 0; + output.f7 = 0; + return true; + } + // not + if (asm_fixed_word(text, 7630702, 3, fold)) { + output.form = 5; + output.opcode = 5; + output.f3 = 0; + output.f7 = 0; + return true; + } + // neg + if (asm_fixed_word(text, 6776174, 3, fold)) { + output.form = 5; + output.opcode = 6; + output.f3 = 0; + output.f7 = 0; + return true; + } + // negw + if (asm_fixed_word(text, 2003264878, 4, fold)) { + output.form = 5; + output.opcode = 7; + output.f3 = 0; + output.f7 = 0; + return true; + } + // li + if (asm_fixed_word(text, 26988, 2, fold)) { + output.form = 5; + output.opcode = 8; + output.f3 = 0; + output.f7 = 0; + return true; + } + // jr + if (asm_fixed_word(text, 29290, 2, fold)) { + output.form = 5; + output.opcode = 9; + output.f3 = 0; + output.f7 = 0; + return true; + } + // j + if (asm_fixed_word(text, 106, 1, fold)) { + output.form = 5; + output.opcode = 10; + output.f3 = 0; + output.f7 = 0; + return true; + } + // jal + if (asm_fixed_word(text, 7102826, 3, fold)) { + output.form = 5; + output.opcode = 11; + output.f3 = 0; + output.f7 = 0; + return true; + } + // jalr + if (asm_fixed_word(text, 1919705450, 4, fold)) { + output.form = 5; + output.opcode = 12; + output.f3 = 0; + output.f7 = 0; + return true; + } + // beqz + if (asm_fixed_word(text, 2054251874, 4, fold)) { + output.form = 5; + output.opcode = 13; + output.f3 = 0; + output.f7 = 0; + return true; + } + // bnez + if (asm_fixed_word(text, 2053467746, 4, fold)) { + output.form = 5; + output.opcode = 14; + output.f3 = 0; + output.f7 = 0; + return true; + } + // lui + if (asm_fixed_word(text, 6911340, 3, fold)) { + output.form = 5; + output.opcode = 15; + output.f3 = 0; + output.f7 = 0; + return true; + } + // auipc + if (asm_fixed_word(text, 427087721825, 5, fold)) { + output.form = 5; + output.opcode = 16; + output.f3 = 0; + output.f7 = 0; + return true; + } + // slli + if (asm_fixed_word(text, 1768713331, 4, fold)) { + output.form = 5; + output.opcode = 17; + output.f3 = 0; + output.f7 = 0; + return true; + } + // srli + if (asm_fixed_word(text, 1768714867, 4, fold)) { + output.form = 5; + output.opcode = 18; + output.f3 = 0; + output.f7 = 0; + return true; + } + // srai + if (asm_fixed_word(text, 1767993971, 4, fold)) { + output.form = 5; + output.opcode = 19; + output.f3 = 0; + output.f7 = 0; + return true; + } + // slliw + if (asm_fixed_word(text, 512869821555, 5, fold)) { + output.form = 5; + output.opcode = 20; + output.f3 = 0; + output.f7 = 0; + return true; + } + // srliw + if (asm_fixed_word(text, 512869823091, 5, fold)) { + output.form = 5; + output.opcode = 21; + output.f3 = 0; + output.f7 = 0; + return true; + } + // sraiw + if (asm_fixed_word(text, 512869102195, 5, fold)) { + output.form = 5; + output.opcode = 22; + output.f3 = 0; + output.f7 = 0; + return true; + } + // fence + if (asm_fixed_word(text, 435459876198, 5, fold)) { + output.form = 5; + output.opcode = 23; + output.f3 = 0; + output.f7 = 0; + return true; + } + return false; +} + +fun rv_jump(context: ptr, text: FixedText, rd: u64, + result: ptr) -> bool { + var displacement: i64 = 0; + var scaled: u64 = 0; + if (!asm_fixed_pc_relative(context, text, 17, &displacement, result) + || !asm_fixed_displacement(displacement, 20, 2, &scaled, result)) { + return false; + } + result.word = rv_jump_bits(rd, displacement as u64); + return true; +} + +fun rv_branch(context: ptr, text: FixedText, f3: u64, rs1: u64, + rs2: u64, result: ptr) -> bool { + var displacement: i64 = 0; + var scaled: u64 = 0; + if (!asm_fixed_pc_relative(context, text, 16, &displacement, result) + || !asm_fixed_displacement(displacement, 12, 2, &scaled, result)) { + return false; + } + result.word = rv_branch_bits(f3, rs1, rs2, displacement as u64); + return true; +} + +fun rv_encode(instruction: ptr, context: ptr, + result: ptr) -> bool { + var operation: RvOpcode; + if (!asm_fixed_charge(result, instruction.mnemonic.count)) { + return false; + } + if (!rv_lookup(instruction.mnemonic, instruction.fold, &operation)) { + asm_fixed_fail(result, 2006, instruction.mnemonic, 0); + result.display = instruction.fold; + return false; + } + var count: u64 = 3; + var rd: u64 = 0; + var rs1: u64 = 0; + var rs2: u64 = 0; + var immediate: u64 = 0; + var second: u64 = 0; + var word: u64 = 0; + if (operation.form == 3 || operation.form == 4) { + count = 2; + } else if (operation.form == 5) { + count = 2; + if (operation.opcode <= 3) { + count = 0; + } else if (operation.opcode == 9 || operation.opcode == 10) { + count = 1; + } else if (operation.opcode == 11) { + if (instruction.count == 1) { + count = 1; + } + } else if (operation.opcode == 12) { + count = 3; + if (instruction.count == 1 || instruction.count == 2) { + count = instruction.count; + } + } else if (operation.opcode >= 17 && operation.opcode <= 22) { + count = 3; + } else if (operation.opcode == 23 && instruction.count == 0) { + count = 0; + } + } + if (!asm_fixed_count(instruction, count, result)) { + return false; + } + if (operation.form == 0) { + if (!rv_reg(instruction.operands[0], &rd, result) + || !rv_reg(instruction.operands[1], &rs1, result) + || !rv_reg(instruction.operands[2], &rs2, result)) { + return false; + } + result.word = rv_r(operation.opcode, operation.f3, operation.f7, rd, rs1, rs2); + return true; + } + if (operation.form == 1) { + if (!rv_reg(instruction.operands[0], &rd, result) + || !rv_reg(instruction.operands[1], &rs1, result) + || !asm_fixed_signed(instruction.operands[2], 12, &immediate, result)) { + return false; + } + result.word = rv_i(operation.opcode, operation.f3, rd, rs1, immediate); + return true; + } + if (operation.form == 2) { + return rv_reg(instruction.operands[0], &rs1, result) + && rv_reg(instruction.operands[1], &rs2, result) + && rv_branch(context, instruction.operands[2], operation.f3, rs1, rs2, result); + } + if (operation.form == 3 || operation.form == 4) { + // Match the established diagnostic order: memory is validated before rd. + if (!rv_memory(instruction.operands[1], &rs1, &immediate, result) + || !rv_reg(instruction.operands[0], &rd, result)) { + return false; + } + if (operation.form == 3) { + result.word = rv_i(3, operation.f3, rd, rs1, immediate); + } else { + result.word = rv_store(operation.f3, rs1, rd, immediate); + } + return true; + } + var alias: u64 = operation.opcode; + if (alias <= 3) { + word = 19; + if (alias == 1) { + word = 32871; + } else if (alias == 2) { + word = 115; + } else if (alias == 3) { + word = 1048691; + } + result.word = word; + return true; + } + if (alias >= 4 && alias <= 7) { + if (!rv_reg(instruction.operands[0], &rd, result) + || !rv_reg(instruction.operands[1], &rs1, result)) { + return false; + } + word = rv_i(19, 0, rd, rs1, 0); + if (alias == 5) { + word = rv_i(19, 4, rd, rs1, 4095); + } else if (alias == 6) { + word = rv_r(51, 0, 32, rd, 0, rs1); + } else if (alias == 7) { + word = rv_r(59, 0, 32, rd, 0, rs1); + } + result.word = word; + return true; + } + if (alias == 8) { + if (!rv_reg(instruction.operands[0], &rd, result) + || !asm_fixed_signed(instruction.operands[1], 12, &immediate, result)) { + return false; + } + result.word = rv_i(19, 0, rd, 0, immediate); + return true; + } + if (alias == 9) { + if (!rv_reg(instruction.operands[0], &rs1, result)) { + return false; + } + result.word = rv_i(103, 0, 0, rs1, 0); + return true; + } + if (alias == 10) { + return rv_jump(context, instruction.operands[0], 0, result); + } + if (alias == 11) { + if (count == 1) { + return rv_jump(context, instruction.operands[0], 1, result); + } + return rv_reg(instruction.operands[0], &rd, result) + && rv_jump(context, instruction.operands[1], rd, result); + } + if (alias == 12) { + if (count == 1) { + if (!rv_reg(instruction.operands[0], &rs1, result)) { + return false; + } + result.word = rv_i(103, 0, 1, rs1, 0); + return true; + } + if (count == 2) { + if (!rv_memory(instruction.operands[1], &rs1, &immediate, result) + || !rv_reg(instruction.operands[0], &rd, result)) { + return false; + } + } else if (!rv_reg(instruction.operands[0], &rd, result) + || !rv_reg(instruction.operands[1], &rs1, result) + || !asm_fixed_signed(instruction.operands[2], 12, &immediate, result)) { + return false; + } + result.word = rv_i(103, 0, rd, rs1, immediate); + return true; + } + if (alias == 13 || alias == 14) { + return rv_reg(instruction.operands[0], &rs1, result) + && rv_branch(context, instruction.operands[1], alias - 13, rs1, 0, result); + } + if (alias == 15 || alias == 16) { + // The original contract validates the upper immediate before rd. + if (!asm_fixed_unsigned(instruction.operands[1], 20, &immediate, result) + || !rv_reg(instruction.operands[0], &rd, result)) { + return false; + } + word = 55; + if (alias == 16) { + word = 23; + } + result.word = rv_upper(word, rd, immediate); + return true; + } + if (alias >= 17 && alias <= 22) { + word = 19; + count = 6; + if (alias >= 20) { + word = 27; + count = 5; + } + // Shift validation precedes register validation in the original encoder. + if (!asm_fixed_unsigned(instruction.operands[2], count, &immediate, result) + || !rv_reg(instruction.operands[0], &rd, result) + || !rv_reg(instruction.operands[1], &rs1, result)) { + return false; + } + second = 5; + if (alias == 17 || alias == 20) { + second = 1; + } + if (alias == 19 || alias == 22) { + immediate = immediate | 1024; + } + result.word = rv_i(word, second, rd, rs1, immediate); + return true; + } + if (alias == 23) { + if (count == 0) { + result.word = 267386895; + return true; + } + if (!rv_fence(instruction.operands[0], &immediate, result) + || !rv_fence(instruction.operands[1], &second, result)) { + return false; + } + result.word = 15 | (immediate << 24) | (second << 20); + return true; + } + return asm_fixed_fail(result, 2006, instruction.mnemonic, 0); +} diff --git a/assembler/riscv64/encoding.wave b/assembler/riscv64/encoding.wave new file mode 100644 index 0000000..56a8574 --- /dev/null +++ b/assembler/riscv64/encoding.wave @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: MPL-2.0 +// RV64I field packing after operand validation; results are exactly 32 bits. +fun rv_r(opcode: u64, f3: u64, f7: u64, rd: u64, rs1: u64, rs2: u64) -> u64 { + return (opcode | (rd << 7) | (f3 << 12) | (rs1 << 15) | (rs2 << 20) | (f7 << 25)) + & 4294967295; +} + +fun rv_i(opcode: u64, f3: u64, rd: u64, rs1: u64, immediate: u64) -> u64 { + return (opcode | (rd << 7) | (f3 << 12) | (rs1 << 15) | (immediate << 20)) & 4294967295; +} + +fun rv_store(f3: u64, rs1: u64, rs2: u64, immediate: u64) -> u64 { + return (35 | ((immediate & 31) << 7) | (f3 << 12) | (rs1 << 15) | (rs2 << 20) + | ((immediate >> 5) << 25)) & 4294967295; +} + +fun rv_upper(opcode: u64, rd: u64, immediate: u64) -> u64 { + return (opcode | (rd << 7) | ((immediate & 1048575) << 12)) & 4294967295; +} + +fun rv_jump_bits(rd: u64, displacement: u64) -> u64 { + return (111 | (rd << 7) | (((displacement >> 20) & 1) << 31) + | (((displacement >> 1) & 1023) << 21) | (((displacement >> 11) & 1) << 20) + | (((displacement >> 12) & 255) << 12)) & 4294967295; +} + +fun rv_branch_bits(f3: u64, rs1: u64, rs2: u64, displacement: u64) -> u64 { + return (99 | (((displacement >> 11) & 1) << 7) | (((displacement >> 1) & 15) << 8) + | (f3 << 12) | (rs1 << 15) | (rs2 << 20) | (((displacement >> 5) & 63) << 25) + | (((displacement >> 12) & 1) << 31)) & 4294967295; +} diff --git a/assembler/riscv64/entry.wave b/assembler/riscv64/entry.wave new file mode 100644 index 0000000..8c300b2 --- /dev/null +++ b/assembler/riscv64/entry.wave @@ -0,0 +1,64 @@ +// SPDX-License-Identifier: MPL-2.0 +// The source driver is appended once its shared prepare/next/commit ABI is ready. +export(c) fun whale_riscv64_instruction(instruction: ptr, + context: ptr, result: ptr) -> i32 { + if (result == null) { + return 2; + } + if (instruction == null || context == null || instruction.fold > 1 + || !asm_span_valid(instruction.mnemonic.data, instruction.mnemonic.count, 1) + || !asm_span_valid(instruction.operands as ptr, instruction.count, 16)) { + result.status = 2; + return 2; + } + var index: u64 = 0; + while (index < instruction.count) { + if (!asm_fixed_charge(result, 1)) { + return result.status as i32; + } + if (!asm_span_valid(instruction.operands[index].data, instruction.operands[index].count, 1)) { + result.status = 2; + return 2; + } + index += 1; + } + if (!rv_encode(instruction, context, result)) { + return result.status as i32; + } + return 0; +} + +export(c) fun whale_riscv64_entry(packet: ptr, result: ptr) -> i32 { + if (packet == null || result == null) { + return 2; + } + var state: FixedState; + var instruction: FixedInstruction; + var step: i32 = 0; + if (!asm_fixed_prepare(packet, &state, result)) { + if (result.status == 0) { + result.status = 2; + } + return result.status as i32; + } + while (true) { + step = asm_fixed_next(&state, &instruction, result); + if (step == 0) { + return result.status as i32; + } + if (step != 1) { + if (result.status == 0) { + result.status = 2; + } + return result.status as i32; + } + if (whale_riscv64_instruction(&instruction, &state.context, result) != 0 + || !asm_fixed_commit(&state, result.word, result)) { + if (result.status == 0) { + result.status = 2; + } + return result.status as i32; + } + } + return 2; +} diff --git a/assembler/riscv64/meson.build b/assembler/riscv64/meson.build new file mode 100644 index 0000000..b9bca78 --- /dev/null +++ b/assembler/riscv64/meson.build @@ -0,0 +1,53 @@ +# SPDX-License-Identifier: MPL-2.0 +wave_riscv64_dependencies = [] +wave_riscv64_directory = get_option('wave-riscv64-dir') +if wave_riscv64_directory == '' and wave_source != '' + wave_riscv64_directory = meson.current_build_dir() + module_target = cargo_host_target + if module_target == '' + target_os = {'linux': 'unknown-linux-gnu', 'darwin': 'apple-darwin', 'windows': 'pc-windows-msvc'} + module_target = host_machine.cpu_family() + '-' + target_os[host_machine.system()] + endif + archive_name = module_target.contains('msvc') ? 'whale_wave_riscv64.lib' : 'libwhale_wave_riscv64.a' + arguments = ['--module', 'riscv64', '--wave-source', wave_source, '--out-dir', '@OUTDIR@', + '--bootstrap-dir', wave_cache, '--target', module_target, + '--rust-toolchain', get_option('wave-rust-toolchain')] + if get_option('wave-allow-network') + arguments += ['--allow-network'] + endif + wave_riscv64_module = custom_target('wave-riscv64', + output: [archive_name, 'wave-riscv64.meta', 'provenance.json'], + command: [python, files('../../tools/build_wave_assembler.py'), arguments], + depend_files: files( + '../model.wave', + '../declarations.wave', + '../fixed_model.wave', + '../fixed_declarations.wave', + 'registers.wave', + 'operands.wave', + 'encoding.wave', + 'encoder.wave', + 'parser.wave', + 'entry.wave', + 'src/wave.rs', + 'src/lib.rs', + 'src/encoder.rs', + 'src/parser.rs', + '../../tools/build_wave_assembler.py', + '../../tools/wave_bootstrap.py', + '../build_support.rs', + ), + depends: wave_bootstrap, console: true) + wave_riscv64_dependencies += [wave_riscv64_module] +elif wave_riscv64_directory != '' + if not fs.is_absolute(wave_riscv64_directory) + error('-Dwave-riscv64-dir must be absolute.') + endif + archive_name = host_machine.system() == 'windows' ? 'whale_wave_riscv64.lib' : 'libwhale_wave_riscv64.a' + foreach artifact : [archive_name, 'wave-riscv64.meta', 'provenance.json'] + if not fs.is_file(wave_riscv64_directory / artifact) + error('Missing Wave riscv64 artifact: ' + (wave_riscv64_directory / artifact)) + endif + endforeach +endif +wave_assembler_all_dependencies += wave_riscv64_dependencies diff --git a/assembler/riscv64/operands.wave b/assembler/riscv64/operands.wave new file mode 100644 index 0000000..c405361 --- /dev/null +++ b/assembler/riscv64/operands.wave @@ -0,0 +1,90 @@ +// SPDX-License-Identifier: MPL-2.0 +// Register, offset(base), and FENCE operands. Numeric policy is shared source. +fun rv_reg(text: FixedText, output: ptr, result: ptr) -> bool { + if (!asm_fixed_charge(result, text.count)) { + return false; + } + var trimmed: FixedText = asm_fixed_trim(text); + if (!rv_register(trimmed.data, trimmed.count, output)) { + asm_fixed_fail(result, 2000, trimmed, 0); + result.display = 1; + return false; + } + return true; +} + +fun rv_memory(text: FixedText, base: ptr, immediate: ptr, + result: ptr) -> bool { + var opening: u64 = 0; + while (opening < text.count && text.data[opening] != 40) { + if (!asm_fixed_charge(result, 1)) { + return false; + } + opening += 1; + } + if (opening == text.count) { + return asm_fixed_fail(result, 2001, text, 0); + } + if (text.count < opening + 2 || text.data[text.count - 1] != 41) { + return asm_fixed_fail(result, 2002, text, 0); + } + var at: u64 = opening + 1; + while (at + 1 < text.count) { + if (!asm_fixed_charge(result, 1)) { + return false; + } + if (text.data[at] == 40 || text.data[at] == 41) { + return asm_fixed_fail(result, 2002, text, 0); + } + at += 1; + } + var register: FixedText; + register.data = &text.data[opening + 1]; + register.count = text.count - opening - 2; + if (!rv_reg(register, base, result)) { + return false; + } + var offset: FixedText; + offset.data = text.data; + offset.count = opening; + offset = asm_fixed_trim(offset); + if (offset.count == 0) { + immediate[0] = 0; + return true; + } + return asm_fixed_signed(offset, 12, immediate, result); +} + +fun rv_fence(text: FixedText, output: ptr, result: ptr) -> bool { + output[0] = 0; + if (rv_name(text.data, text.count, 48, 1, false)) { + return true; + } + var at: u64 = 0; + var flag: u64 = 0; + var mask: u64 = 0; + while (at < text.count) { + if (!asm_fixed_charge(result, 1)) { + return false; + } + flag = 0; + if (text.data[at] == 105) { + flag = 8; + } else if (text.data[at] == 111) { + flag = 4; + } else if (text.data[at] == 114) { + flag = 2; + } else if (text.data[at] == 119) { + flag = 1; + } else { + return asm_fixed_fail(result, 2003, text, 0); + } + if ((mask & flag) != 0) { + return asm_fixed_fail(result, 2004, text, 0); + } + mask = mask | flag; + at += 1; + } + output[0] = mask; + return true; +} diff --git a/assembler/riscv64/parser.wave b/assembler/riscv64/parser.wave new file mode 100644 index 0000000..67383c0 --- /dev/null +++ b/assembler/riscv64/parser.wave @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: MPL-2.0 +// Direct operand/branch boundaries keep native tests independent of source layout. +export(c) fun whale_riscv64_operand(mode: u64, text: ptr, + result: ptr) -> i32 { + if (result == null) { + return 2; + } + asm_fixed_result_init(result, 16777216); + if (text == null || !asm_span_valid(text.data, text.count, 1) || mode > 2) { + result.status = 2; + return 2; + } + var value: u64 = 0; + var second: u64 = 0; + var success: bool = false; + if (mode == 0) { + success = rv_reg(text[0], &value, result); + } else if (mode == 1) { + success = rv_memory(text[0], &value, &second, result); + } else { + success = rv_fence(text[0], &value, result); + } + if (!success) { + return result.status as i32; + } + result.word = value; + result.detail = second; + return 0; +} + +export(c) fun whale_riscv64_branch(jump: u64, f3: u64, rs1: u64, rs2: u64, + value: i64, result: ptr) -> i32 { + if (result == null) { + return 2; + } + asm_fixed_result_init(result, 16777216); + if (jump > 1 || f3 > 7 || rs1 > 31 || rs2 > 31) { + result.status = 2; + return 2; + } + var scaled: u64 = 0; + var bits: u64 = 12; + if (jump == 1) { + bits = 20; + } + if (!asm_fixed_displacement(value, bits, 2, &scaled, result)) { + return result.status as i32; + } + if (jump == 1) { + result.word = rv_jump_bits(rs1, value as u64); + } else { + result.word = rv_branch_bits(f3, rs1, rs2, value as u64); + } + return 0; +} diff --git a/assembler/riscv64/registers.wave b/assembler/riscv64/registers.wave new file mode 100644 index 0000000..9054f1c --- /dev/null +++ b/assembler/riscv64/registers.wave @@ -0,0 +1,203 @@ +// SPDX-License-Identifier: MPL-2.0 +// Exact ASCII register spellings after shared Unicode whitespace trimming. +fun rv_name(data: ptr, count: u64, word: u64, length: u64, fold: bool) -> bool { + if (count != length) { + return false; + } + var at: u64 = 0; + while (at < length) { + var value: u8 = data[at]; + if (fold && value >= 65 && value <= 90) { + value += 32; + } + if (value != ((word >> (at * 8)) & 255) as u8) { + return false; + } + at += 1; + } + return true; +} + +fun rv_register(data: ptr, count: u64, output: ptr) -> bool { + // zero + if (rv_name(data, count, 1869768058, 4, true)) { + output[0] = 0; + return true; + } + // ra + if (rv_name(data, count, 24946, 2, true)) { + output[0] = 1; + return true; + } + // sp + if (rv_name(data, count, 28787, 2, true)) { + output[0] = 2; + return true; + } + // gp + if (rv_name(data, count, 28775, 2, true)) { + output[0] = 3; + return true; + } + // tp + if (rv_name(data, count, 28788, 2, true)) { + output[0] = 4; + return true; + } + // t0 + if (rv_name(data, count, 12404, 2, true)) { + output[0] = 5; + return true; + } + // t1 + if (rv_name(data, count, 12660, 2, true)) { + output[0] = 6; + return true; + } + // t2 + if (rv_name(data, count, 12916, 2, true)) { + output[0] = 7; + return true; + } + // s0 + if (rv_name(data, count, 12403, 2, true)) { + output[0] = 8; + return true; + } + // s1 + if (rv_name(data, count, 12659, 2, true)) { + output[0] = 9; + return true; + } + // a0 + if (rv_name(data, count, 12385, 2, true)) { + output[0] = 10; + return true; + } + // a1 + if (rv_name(data, count, 12641, 2, true)) { + output[0] = 11; + return true; + } + // a2 + if (rv_name(data, count, 12897, 2, true)) { + output[0] = 12; + return true; + } + // a3 + if (rv_name(data, count, 13153, 2, true)) { + output[0] = 13; + return true; + } + // a4 + if (rv_name(data, count, 13409, 2, true)) { + output[0] = 14; + return true; + } + // a5 + if (rv_name(data, count, 13665, 2, true)) { + output[0] = 15; + return true; + } + // a6 + if (rv_name(data, count, 13921, 2, true)) { + output[0] = 16; + return true; + } + // a7 + if (rv_name(data, count, 14177, 2, true)) { + output[0] = 17; + return true; + } + // s2 + if (rv_name(data, count, 12915, 2, true)) { + output[0] = 18; + return true; + } + // s3 + if (rv_name(data, count, 13171, 2, true)) { + output[0] = 19; + return true; + } + // s4 + if (rv_name(data, count, 13427, 2, true)) { + output[0] = 20; + return true; + } + // s5 + if (rv_name(data, count, 13683, 2, true)) { + output[0] = 21; + return true; + } + // s6 + if (rv_name(data, count, 13939, 2, true)) { + output[0] = 22; + return true; + } + // s7 + if (rv_name(data, count, 14195, 2, true)) { + output[0] = 23; + return true; + } + // s8 + if (rv_name(data, count, 14451, 2, true)) { + output[0] = 24; + return true; + } + // s9 + if (rv_name(data, count, 14707, 2, true)) { + output[0] = 25; + return true; + } + // s10 + if (rv_name(data, count, 3158387, 3, true)) { + output[0] = 26; + return true; + } + // s11 + if (rv_name(data, count, 3223923, 3, true)) { + output[0] = 27; + return true; + } + // t3 + if (rv_name(data, count, 13172, 2, true)) { + output[0] = 28; + return true; + } + // t4 + if (rv_name(data, count, 13428, 2, true)) { + output[0] = 29; + return true; + } + // t5 + if (rv_name(data, count, 13684, 2, true)) { + output[0] = 30; + return true; + } + // t6 + if (rv_name(data, count, 13940, 2, true)) { + output[0] = 31; + return true; + } + // fp is the ABI alias for s0/x8. + if (rv_name(data, count, 28774, 2, true)) { + output[0] = 8; + return true; + } + if ((count != 2 && count != 3) || (data[0] != 120 && data[0] != 88) + || data[1] < 48 || data[1] > 57) { + return false; + } + var number: u64 = (data[1] - 48) as u64; + if (count == 3) { + if (number == 0 || data[2] < 48 || data[2] > 57) { + return false; + } + number = number * 10 + ((data[2] - 48) as u64); + } + if (number >= 32) { + return false; + } + output[0] = number; + return true; +} diff --git a/assembler/riscv64/src/encoder.rs b/assembler/riscv64/src/encoder.rs index 2a54be4..34a3fdd 100644 --- a/assembler/riscv64/src/encoder.rs +++ b/assembler/riscv64/src/encoder.rs @@ -1,133 +1,20 @@ // SPDX-License-Identifier: MPL-2.0 -//! RV64I instruction selection, single-instruction aliases and relocation resolution. -use crate::{ - encoding::{ - branch::{branch, jump}, - formats::{self, i, r}, - }, - parser::{fence_mask, memory, reg}, - tables, -}; - +//! RV64I instruction transport; product instruction policy is Wave source. use assembler::{ - fixed::{count, error, signed, unsigned, Context, Instruction}, + fixed::{Context, Instruction}, AsmError, }; -pub(crate) fn encode(inst: &Instruction, cx: &mut Context<'_>) -> Result { - let m = inst.mnemonic.as_str(); - if let Some((opcode, f3, f7)) = tables::register(m) { - let a = count(inst, 3)?; - return Ok(r(opcode, f3, f7, reg(&a[0])?, reg(&a[1])?, reg(&a[2])?)); - } - if let Some((opcode, f3)) = tables::immediate(m) { - let a = count(inst, 3)?; - return Ok(i(opcode, f3, reg(&a[0])?, reg(&a[1])?, signed(&a[2], 12)?)); - } - if let Some(f3) = tables::branch(m) { - let a = count(inst, 3)?; - return branch( - f3, - reg(&a[0])?, - reg(&a[1])?, - cx.pc_relative(&a[2], tables::BRANCH_RELOCATION)?, - ); - } - if let Some(f3) = tables::load(m) { - let a = count(inst, 2)?; - let (base, imm) = memory(&a[1])?; - return Ok(i(3, f3, reg(&a[0])?, base, imm)); - } - if let Some(f3) = tables::store(m) { - let a = count(inst, 2)?; - let (base, imm) = memory(&a[1])?; - return Ok(formats::store(f3, base, reg(&a[0])?, imm)); - } - match m { - "nop" | "ret" | "ecall" | "ebreak" => { - count(inst, 0)?; - Ok(match m { - "nop" => 0x13, - "ret" => 0x8067, - "ecall" => 0x73, - _ => 0x100073, - }) - }, - "mv" | "not" | "neg" | "negw" => { - let a = count(inst, 2)?; - let rd = reg(&a[0])?; - let rs = reg(&a[1])?; - Ok(match m { - "mv" => i(0x13, 0, rd, rs, 0), - "not" => i(0x13, 4, rd, rs, 0xfff), - "neg" => r(0x33, 0, 0x20, rd, 0, rs), - _ => r(0x3b, 0, 0x20, rd, 0, rs), - }) - }, - "li" => { - let a = count(inst, 2)?; - Ok(i(0x13, 0, reg(&a[0])?, 0, signed(&a[1], 12)?)) - }, - "jr" => { - let a = count(inst, 1)?; - Ok(i(0x67, 0, 0, reg(&a[0])?, 0)) - }, - "j" => { - let a = count(inst, 1)?; - jump(0, cx.pc_relative(&a[0], tables::JAL_RELOCATION)?) - }, - "jal" => { - if inst.operands.len() == 1 { - return jump(1, cx.pc_relative(&inst.operands[0], tables::JAL_RELOCATION)?); - } - let a = count(inst, 2)?; - jump(reg(&a[0])?, cx.pc_relative(&a[1], tables::JAL_RELOCATION)?) - }, - "jalr" => { - if inst.operands.len() == 1 { - return Ok(i(0x67, 0, 1, reg(&inst.operands[0])?, 0)); - } - if inst.operands.len() == 2 { - let a = count(inst, 2)?; - let (base, imm) = memory(&a[1])?; - return Ok(i(0x67, 0, reg(&a[0])?, base, imm)); - } - let a = count(inst, 3)?; - Ok(i(0x67, 0, reg(&a[0])?, reg(&a[1])?, signed(&a[2], 12)?)) - }, - "beqz" | "bnez" => { - let a = count(inst, 2)?; - branch( - u32::from(m == "bnez"), - reg(&a[0])?, - 0, - cx.pc_relative(&a[1], tables::BRANCH_RELOCATION)?, - ) - }, - "lui" | "auipc" => { - let a = count(inst, 2)?; - let value = unsigned(&a[1], 20)?; - Ok(formats::upper(if m == "lui" { 0x37 } else { 0x17 }, reg(&a[0])?, value)) - }, - "slli" | "srli" | "srai" | "slliw" | "srliw" | "sraiw" => { - let a = count(inst, 3)?; - let word = m.ends_with('w'); - let shift = unsigned(&a[2], if word { 5 } else { 6 })?; - Ok(i( - if word { 0x1b } else { 0x13 }, - if m.starts_with("sll") { 1 } else { 5 }, - reg(&a[0])?, - reg(&a[1])?, - shift | if m.starts_with("sra") { 0x400 } else { 0 }, - )) - }, - "fence" => { - if inst.operands.is_empty() { - return Ok(0x0ff0000f); - } - let a = count(inst, 2)?; - Ok(0x0f | fence_mask(&a[0])? << 24 | fence_mask(&a[1])? << 20) - }, - _ => Err(error(format!("unsupported RV64I instruction {m:?}"))), - } +#[cfg(any(test, not(whale_wave_riscv64)))] +#[path = "encoder_reference.rs"] +pub(crate) mod reference; + +pub(crate) fn encode( + instruction: &Instruction, + context: &mut Context<'_>, +) -> Result { + #[cfg(whale_wave_riscv64)] + return crate::wave::encode(instruction, context); + #[cfg(not(whale_wave_riscv64))] + reference::encode(instruction, context) } diff --git a/assembler/riscv64/src/encoder_reference.rs b/assembler/riscv64/src/encoder_reference.rs new file mode 100644 index 0000000..9dac1e6 --- /dev/null +++ b/assembler/riscv64/src/encoder_reference.rs @@ -0,0 +1,139 @@ +// SPDX-License-Identifier: MPL-2.0 +//! RV64I instruction selection, single-instruction aliases and relocation resolution. +use crate::{ + encoding::reference::{ + branch::{branch, jump}, + formats::{self, i, r}, + }, + parser::reference::{fence_mask, memory, reg}, + tables, +}; + +use assembler::{ + fixed::{ + reference::{count, error, signed, unsigned}, + Context, Instruction, + }, + AsmError, +}; + +pub(crate) fn encode(inst: &Instruction, cx: &mut Context<'_>) -> Result { + let m = inst.mnemonic.as_str(); + if let Some((opcode, f3, f7)) = tables::register(m) { + let a = count(inst, 3)?; + return Ok(r(opcode, f3, f7, reg(&a[0])?, reg(&a[1])?, reg(&a[2])?)); + } + if let Some((opcode, f3)) = tables::immediate(m) { + let a = count(inst, 3)?; + return Ok(i(opcode, f3, reg(&a[0])?, reg(&a[1])?, signed(&a[2], 12)?)); + } + if let Some(f3) = tables::branch(m) { + let a = count(inst, 3)?; + return branch( + f3, + reg(&a[0])?, + reg(&a[1])?, + cx.pc_relative_reference(&a[2], tables::BRANCH_RELOCATION)?, + ); + } + if let Some(f3) = tables::load(m) { + let a = count(inst, 2)?; + let (base, imm) = memory(&a[1])?; + return Ok(i(3, f3, reg(&a[0])?, base, imm)); + } + if let Some(f3) = tables::store(m) { + let a = count(inst, 2)?; + let (base, imm) = memory(&a[1])?; + return Ok(formats::store(f3, base, reg(&a[0])?, imm)); + } + match m { + "nop" | "ret" | "ecall" | "ebreak" => { + count(inst, 0)?; + Ok(match m { + "nop" => 0x13, + "ret" => 0x8067, + "ecall" => 0x73, + _ => 0x100073, + }) + }, + "mv" | "not" | "neg" | "negw" => { + let a = count(inst, 2)?; + let rd = reg(&a[0])?; + let rs = reg(&a[1])?; + Ok(match m { + "mv" => i(0x13, 0, rd, rs, 0), + "not" => i(0x13, 4, rd, rs, 0xfff), + "neg" => r(0x33, 0, 0x20, rd, 0, rs), + _ => r(0x3b, 0, 0x20, rd, 0, rs), + }) + }, + "li" => { + let a = count(inst, 2)?; + Ok(i(0x13, 0, reg(&a[0])?, 0, signed(&a[1], 12)?)) + }, + "jr" => { + let a = count(inst, 1)?; + Ok(i(0x67, 0, 0, reg(&a[0])?, 0)) + }, + "j" => { + let a = count(inst, 1)?; + jump(0, cx.pc_relative_reference(&a[0], tables::JAL_RELOCATION)?) + }, + "jal" => { + if inst.operands.len() == 1 { + return jump( + 1, + cx.pc_relative_reference(&inst.operands[0], tables::JAL_RELOCATION)?, + ); + } + let a = count(inst, 2)?; + jump(reg(&a[0])?, cx.pc_relative_reference(&a[1], tables::JAL_RELOCATION)?) + }, + "jalr" => { + if inst.operands.len() == 1 { + return Ok(i(0x67, 0, 1, reg(&inst.operands[0])?, 0)); + } + if inst.operands.len() == 2 { + let a = count(inst, 2)?; + let (base, imm) = memory(&a[1])?; + return Ok(i(0x67, 0, reg(&a[0])?, base, imm)); + } + let a = count(inst, 3)?; + Ok(i(0x67, 0, reg(&a[0])?, reg(&a[1])?, signed(&a[2], 12)?)) + }, + "beqz" | "bnez" => { + let a = count(inst, 2)?; + branch( + u32::from(m == "bnez"), + reg(&a[0])?, + 0, + cx.pc_relative_reference(&a[1], tables::BRANCH_RELOCATION)?, + ) + }, + "lui" | "auipc" => { + let a = count(inst, 2)?; + let value = unsigned(&a[1], 20)?; + Ok(formats::upper(if m == "lui" { 0x37 } else { 0x17 }, reg(&a[0])?, value)) + }, + "slli" | "srli" | "srai" | "slliw" | "srliw" | "sraiw" => { + let a = count(inst, 3)?; + let word = m.ends_with('w'); + let shift = unsigned(&a[2], if word { 5 } else { 6 })?; + Ok(i( + if word { 0x1b } else { 0x13 }, + if m.starts_with("sll") { 1 } else { 5 }, + reg(&a[0])?, + reg(&a[1])?, + shift | if m.starts_with("sra") { 0x400 } else { 0 }, + )) + }, + "fence" => { + if inst.operands.is_empty() { + return Ok(0x0ff0000f); + } + let a = count(inst, 2)?; + Ok(0x0f | fence_mask(&a[0])? << 24 | fence_mask(&a[1])? << 20) + }, + _ => Err(error(format!("unsupported RV64I instruction {m:?}"))), + } +} diff --git a/assembler/riscv64/src/encoding/branch.rs b/assembler/riscv64/src/encoding/branch.rs index 8849cac..c9e49d8 100644 --- a/assembler/riscv64/src/encoding/branch.rs +++ b/assembler/riscv64/src/encoding/branch.rs @@ -1,29 +1,19 @@ // SPDX-License-Identifier: MPL-2.0 -//! Checked J/B displacements and noncontiguous immediate field packing. -use assembler::{fixed, AsmError}; +//! Direct native branch validation and field packing regression boundary. +use assembler::AsmError; pub(crate) fn jump(rd: u32, displacement: i64) -> Result { - fixed::displacement(displacement, 20, 2)?; - let imm = displacement as u32; - Ok(0x6f - | rd << 7 - | ((imm >> 20) & 1) << 31 - | ((imm >> 1) & 0x3ff) << 21 - | ((imm >> 11) & 1) << 20 - | ((imm >> 12) & 0xff) << 12) + #[cfg(whale_wave_riscv64)] + return crate::wave::branch(true, 0, rd, 0, displacement); + #[cfg(not(whale_wave_riscv64))] + super::reference::branch::jump(rd, displacement) } pub(crate) fn branch(f3: u32, rs1: u32, rs2: u32, displacement: i64) -> Result { - fixed::displacement(displacement, 12, 2)?; - let imm = displacement as u32; - Ok(0x63 - | ((imm >> 11) & 1) << 7 - | ((imm >> 1) & 15) << 8 - | f3 << 12 - | rs1 << 15 - | rs2 << 20 - | ((imm >> 5) & 63) << 25 - | ((imm >> 12) & 1) << 31) + #[cfg(whale_wave_riscv64)] + return crate::wave::branch(false, f3, rs1, rs2, displacement); + #[cfg(not(whale_wave_riscv64))] + super::reference::branch::branch(f3, rs1, rs2, displacement) } #[cfg(test)] diff --git a/assembler/riscv64/src/encoding/branch_reference.rs b/assembler/riscv64/src/encoding/branch_reference.rs new file mode 100644 index 0000000..06b5a51 --- /dev/null +++ b/assembler/riscv64/src/encoding/branch_reference.rs @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Checked J/B displacements and noncontiguous immediate field packing. +use assembler::{fixed, AsmError}; + +pub(crate) fn jump(rd: u32, displacement: i64) -> Result { + fixed::reference::displacement(displacement, 20, 2)?; + let imm = displacement as u32; + Ok(0x6f + | rd << 7 + | ((imm >> 20) & 1) << 31 + | ((imm >> 1) & 0x3ff) << 21 + | ((imm >> 11) & 1) << 20 + | ((imm >> 12) & 0xff) << 12) +} + +pub(crate) fn branch(f3: u32, rs1: u32, rs2: u32, displacement: i64) -> Result { + fixed::reference::displacement(displacement, 12, 2)?; + let imm = displacement as u32; + Ok(0x63 + | ((imm >> 11) & 1) << 7 + | ((imm >> 1) & 15) << 8 + | f3 << 12 + | rs1 << 15 + | rs2 << 20 + | ((imm >> 5) & 63) << 25 + | ((imm >> 12) & 1) << 31) +} diff --git a/assembler/riscv64/src/encoding/mod.rs b/assembler/riscv64/src/encoding/mod.rs index b43e7cf..78a0dd4 100644 --- a/assembler/riscv64/src/encoding/mod.rs +++ b/assembler/riscv64/src/encoding/mod.rs @@ -1,5 +1,7 @@ // SPDX-License-Identifier: MPL-2.0 -//! RV64I instruction formats and control-transfer bit layouts. +#[cfg(test)] pub(crate) mod branch; -pub(crate) mod formats; +#[cfg(any(test, not(whale_wave_riscv64)))] +#[path = "../encoding_reference.rs"] +pub(crate) mod reference; diff --git a/assembler/riscv64/src/encoding_reference.rs b/assembler/riscv64/src/encoding_reference.rs new file mode 100644 index 0000000..047e779 --- /dev/null +++ b/assembler/riscv64/src/encoding_reference.rs @@ -0,0 +1,6 @@ +// SPDX-License-Identifier: MPL-2.0 +#[path = "encoding/branch_reference.rs"] +pub(crate) mod branch; + +#[path = "encoding/formats.rs"] +pub(crate) mod formats; diff --git a/assembler/riscv64/src/lib.rs b/assembler/riscv64/src/lib.rs index e2e1b10..7e41a38 100644 --- a/assembler/riscv64/src/lib.rs +++ b/assembler/riscv64/src/lib.rs @@ -1,18 +1,24 @@ // SPDX-License-Identifier: MPL-2.0 //! RiscV64 assembler entry point; instruction handling lives in the ISA modules. use assembler::{ - fixed::{self, Context, FixedIsa, Instruction}, + fixed::{Context, FixedIsa, Instruction}, AsmError, AssemblerOutput, AssemblyLimits, }; mod encoder; +#[cfg(any(test, not(whale_wave_riscv64)))] mod encoding; +#[cfg(any(test, not(whale_wave_riscv64)))] mod parser; +#[cfg(any(test, not(whale_wave_riscv64)))] mod tables; +#[cfg(whale_wave_riscv64)] +mod wave; + pub struct RiscV64; impl assembler::extension::Assembler for RiscV64 { @@ -30,7 +36,10 @@ impl assembler::extension::Assembler for RiscV64 { source: &str, limits: &AssemblyLimits, ) -> Result { - fixed::assemble(self, name, source, limits) + #[cfg(whale_wave_riscv64)] + return wave::assemble(name, source, limits); + #[cfg(not(whale_wave_riscv64))] + assembler::fixed::assemble(self, name, source, limits) } } @@ -39,6 +48,16 @@ impl FixedIsa for RiscV64 { "riscv64" } + #[cfg(whale_wave_riscv64)] + fn native_assemble( + &self, + name: &str, + source: &str, + limits: &AssemblyLimits, + ) -> Option> { + Some(wave::assemble(name, source, limits)) + } + fn encode( &self, instruction: &Instruction, @@ -47,3 +66,110 @@ impl FixedIsa for RiscV64 { encoder::encode(instruction, context) } } + +#[cfg(all(test, whale_wave_riscv64))] +mod wave_tests { + use super::*; + + struct Reference; + + impl FixedIsa for Reference { + fn id(&self) -> &'static str { + "riscv64" + } + + fn encode( + &self, + instruction: &Instruction, + context: &mut Context<'_>, + ) -> Result { + encoder::reference::encode(instruction, context) + } + } + + fn snapshot(output: AssemblerOutput) -> String { + let mut value = String::new(); + for section in output.sections { + value.push_str(&format!( + "{:?}|{}|{}|{}|{:?}|", + section.kind, section.name, section.align, section.zero_fill, section.data + )); + for relocation in section.relocs { + value.push_str(&format!( + "{}|{}|{:?}|{}|", + relocation.offset, relocation.symbol, relocation.kind, relocation.addend + )); + } + } + for symbol in output.symbols { + value.push_str(&format!( + "{}|{:?}|{}|{}|{:?}|{}|{:?}|", + symbol.name, + symbol.section_index, + symbol.offset, + symbol.is_global, + symbol.kind, + symbol.size, + symbol.visibility + )); + } + value + } + + #[test] + fn whole_wave_source_pipeline_matches_independent_retained_implementation() { + use assembler::extension::Assembler; + for source in [ + ".text\n.global entry\nentry: addi a0,zero,42\nret\n", + ".text\n.extern ext\n.global entry\nentry: beq a0,a1,tail\njal ra,ext+4\ntail: ret\n.data\n.word entry+4,ext\n.quad entry\n.bss\n.space 1099511627776\n", + ".text\nstart: nop\n.balign 16\nbeqz a0,start\nfence rw,0\njalr a0,12(sp)\n", + ".data\n.byte 255,-128\n.hword 65535,-32768\n.word 4294967295\n.quad 18446744073709551615\n", + ".section .custom\n.zero 13\n.balign 8\n.global data\ndata: .quad 1\n", + ] { + let actual = RiscV64.assemble("test.s", source, &AssemblyLimits::default()).unwrap(); + let expected = assembler::fixed::reference::assemble(&Reference, "test.s", source, + &AssemblyLimits::default()).unwrap(); + let expected = snapshot(expected); + assert_eq!(snapshot(actual), expected, "{source}"); + // Public FixedIsa::encode remains native when invoked by the + // retained generic driver, exercising the Rust Context snapshot. + let compatibility = assembler::fixed::reference::assemble(&RiscV64, "test.s", source, + &AssemblyLimits::default()).unwrap(); + assert_eq!(snapshot(compatibility), expected, "compatibility: {source}"); + + } + } + + #[test] + fn native_errors_preserve_reference_diagnostics_and_source_ranges() { + use assembler::extension::Assembler; + for source in [ + "addi x01,a0,1\n", + "addi a0,a1,2048\n", + "lui bad,-1\n", + "slli bad,bad,64\n", + "lw bad,2048(sp)\n", + "fence RW,0\n", + "jal ra,3\n", + "beq a0,a1,4096\n", + ".global absent\n", + "label: nop\nlabel: ret\n", + ".bss\n.word 1\n", + ".data\n.byte 256\n", + "mul a0,a1,a2\n", + ".unknown 1\n", + ] { + let actual = + RiscV64.assemble("test.s", source, &AssemblyLimits::default()).err().unwrap(); + let expected = assembler::fixed::reference::assemble( + &Reference, + "test.s", + source, + &AssemblyLimits::default(), + ) + .err() + .unwrap(); + assert_eq!(actual.to_string(), expected.to_string(), "{source}"); + } + } +} diff --git a/assembler/riscv64/src/parser.rs b/assembler/riscv64/src/parser.rs index 25ac303..5c61892 100644 --- a/assembler/riscv64/src/parser.rs +++ b/assembler/riscv64/src/parser.rs @@ -1,62 +1,42 @@ // SPDX-License-Identifier: MPL-2.0 -//! RV64 register aliases, offset(base) operands and FENCE flag syntax. -use crate::tables::REGISTER_ALIASES; +//! RV64 operand transport. All native classification and validation run in Wave. +#[cfg(test)] +use assembler::AsmError; -use assembler::{ - fixed::{error, signed}, - AsmError, -}; +#[cfg(any(test, not(whale_wave_riscv64)))] +#[path = "parser_reference.rs"] +pub(crate) mod reference; +#[cfg(test)] pub(crate) fn reg(text: &str) -> Result { - let text = text.trim().to_ascii_lowercase(); - if text == "fp" { - return Ok(8); - } - if let Some(i) = REGISTER_ALIASES.iter().position(|&name| name == text) { - return Ok(i as u32); - } - text.strip_prefix('x') - .filter(|n| n.bytes().all(|b| b.is_ascii_digit()) && (n.len() == 1 || !n.starts_with('0'))) - .and_then(|n| n.parse::().ok()) - .filter(|n| *n < 32) - .ok_or_else(|| error(format!("invalid RV64 register {text:?}"))) + #[cfg(whale_wave_riscv64)] + return crate::wave::reg(text); + #[cfg(not(whale_wave_riscv64))] + reference::reg(text) } +#[cfg(test)] pub(crate) fn memory(text: &str) -> Result<(u32, u32), AsmError> { - let (offset, rest) = - text.split_once('(').ok_or_else(|| error("memory operand requires offset(base)"))?; - let base = rest - .strip_suffix(')') - .filter(|s| !s.contains(['(', ')'])) - .ok_or_else(|| error("invalid memory operand"))?; - Ok((reg(base)?, signed(if offset.trim().is_empty() { "0" } else { offset.trim() }, 12)?)) + #[cfg(whale_wave_riscv64)] + return crate::wave::memory(text); + #[cfg(not(whale_wave_riscv64))] + reference::memory(text) } -pub(crate) fn fence_mask(s: &str) -> Result { - if s == "0" { - return Ok(0); - } - let mut value = 0; - for c in s.chars() { - let bit = match c { - 'i' => 8, - 'o' => 4, - 'r' => 2, - 'w' => 1, - _ => return Err(error("fence sets use i,o,r,w or literal 0")), - }; - if value & bit != 0 { - return Err(error("duplicate fence flag")); - } - value |= bit; - } - Ok(value) +#[cfg(test)] +pub(crate) fn fence_mask(text: &str) -> Result { + #[cfg(whale_wave_riscv64)] + return crate::wave::fence_mask(text); + #[cfg(not(whale_wave_riscv64))] + reference::fence_mask(text) } #[cfg(test)] mod tests { use super::*; + use crate::tables::REGISTER_ALIASES; + #[test] fn numeric_register_names_are_canonical() { for index in 0..32 { diff --git a/assembler/riscv64/src/parser_reference.rs b/assembler/riscv64/src/parser_reference.rs new file mode 100644 index 0000000..8e8b662 --- /dev/null +++ b/assembler/riscv64/src/parser_reference.rs @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: MPL-2.0 +//! RV64 register aliases, offset(base) operands and FENCE flag syntax. +use crate::tables::REGISTER_ALIASES; + +use assembler::{ + fixed::reference::{error, signed}, + AsmError, +}; + +pub(crate) fn reg(text: &str) -> Result { + let text = text.trim().to_ascii_lowercase(); + if text == "fp" { + return Ok(8); + } + if let Some(i) = REGISTER_ALIASES.iter().position(|&name| name == text) { + return Ok(i as u32); + } + text.strip_prefix('x') + .filter(|n| n.bytes().all(|b| b.is_ascii_digit()) && (n.len() == 1 || !n.starts_with('0'))) + .and_then(|n| n.parse::().ok()) + .filter(|n| *n < 32) + .ok_or_else(|| error(format!("invalid RV64 register {text:?}"))) +} + +pub(crate) fn memory(text: &str) -> Result<(u32, u32), AsmError> { + let (offset, rest) = + text.split_once('(').ok_or_else(|| error("memory operand requires offset(base)"))?; + let base = rest + .strip_suffix(')') + .filter(|s| !s.contains(['(', ')'])) + .ok_or_else(|| error("invalid memory operand"))?; + Ok((reg(base)?, signed(if offset.trim().is_empty() { "0" } else { offset.trim() }, 12)?)) +} + +pub(crate) fn fence_mask(s: &str) -> Result { + if s == "0" { + return Ok(0); + } + let mut value = 0; + for c in s.chars() { + let bit = match c { + 'i' => 8, + 'o' => 4, + 'r' => 2, + 'w' => 1, + _ => return Err(error("fence sets use i,o,r,w or literal 0")), + }; + if value & bit != 0 { + return Err(error("duplicate fence flag")); + } + value |= bit; + } + Ok(value) +} diff --git a/assembler/riscv64/src/wave.rs b/assembler/riscv64/src/wave.rs new file mode 100644 index 0000000..cd4e05e --- /dev/null +++ b/assembler/riscv64/src/wave.rs @@ -0,0 +1,119 @@ +// SPDX-License-Identifier: MPL-2.0 +//! RV64I typed transport. Classification, validation and encoding run in Wave. +use assembler::fixed::{native, Context, Instruction}; + +use assembler::{AsmError, AssemblerOutput, AssemblyLimits}; + +#[cfg(test)] +use native::FixedText; + +use native::{FixedContext, FixedInput, FixedInstruction, FixedResult}; + +unsafe extern "C" { + fn whale_riscv64_entry(input: *const FixedInput, result: *mut FixedResult) -> i32; + + fn whale_riscv64_instruction( + instruction: *const FixedInstruction, + context: *mut FixedContext, + result: *mut FixedResult, + ) -> i32; + + #[cfg(test)] + fn whale_riscv64_operand(mode: u64, text: *const FixedText, result: *mut FixedResult) -> i32; + + #[cfg(test)] + fn whale_riscv64_branch( + jump: u64, + f3: u64, + rs1: u64, + rs2: u64, + displacement: i64, + result: *mut FixedResult, + ) -> i32; +} + +pub(crate) fn render(code: u64, text: &str, _: u64) -> AsmError { + assembler::fixed::error(match code { + 2000 => format!("invalid RV64 register {text:?}"), + 2001 => "memory operand requires offset(base)".into(), + 2002 => "invalid memory operand".into(), + 2003 => "fence sets use i,o,r,w or literal 0".into(), + 2004 => "duplicate fence flag".into(), + 2006 => format!("unsupported RV64I instruction {text:?}"), + _ => return AsmError::Backend("RV64I diagnostic transport"), + }) +} + +pub(crate) fn assemble( + name: &str, + source: &str, + limits: &AssemblyLimits, +) -> Result { + native::assemble(name, source, limits, "riscv64", true, whale_riscv64_entry, render) +} + +pub(crate) fn encode( + instruction: &Instruction, + context: &mut Context<'_>, +) -> Result { + native::encode(instruction, context, whale_riscv64_instruction, render) +} + +#[cfg(test)] +fn operand(mode: u64, text: &str) -> Result<(u64, u64), AsmError> { + let text_record = FixedText::new(text); + let mut result = FixedResult::new(); + let status = unsafe { whale_riscv64_operand(mode, &text_record, &mut result) }; + native::check(status, &result, &[text], render)?; + Ok((result.word, result.detail)) +} + +#[cfg(test)] +pub(crate) fn reg(text: &str) -> Result { + let (word, detail) = operand(0, text)?; + if word >= 32 || detail != 0 { + return Err(AsmError::Backend("RV64I register transport")); + } + Ok(word as u32) +} + +#[cfg(test)] +pub(crate) fn memory(text: &str) -> Result<(u32, u32), AsmError> { + let (word, detail) = operand(1, text)?; + if word >= 32 || detail >= 4096 { + return Err(AsmError::Backend("RV64I memory transport")); + } + Ok((word as u32, detail as u32)) +} + +#[cfg(test)] +pub(crate) fn fence_mask(text: &str) -> Result { + let (word, detail) = operand(2, text)?; + if word >= 16 || detail != 0 { + return Err(AsmError::Backend("RV64I fence transport")); + } + Ok(word as u32) +} + +#[cfg(test)] +pub(crate) fn branch( + jump: bool, + f3: u32, + rs1: u32, + rs2: u32, + displacement: i64, +) -> Result { + let mut result = FixedResult::new(); + let status = unsafe { + whale_riscv64_branch( + u64::from(jump), + f3.into(), + rs1.into(), + rs2.into(), + displacement, + &mut result, + ) + }; + native::check(status, &result, &[], render)?; + u32::try_from(result.word).map_err(|_| AsmError::Backend("RV64I branch transport")) +} diff --git a/assembler/riscv64/tests/standard_sections.rs b/assembler/riscv64/tests/standard_sections.rs new file mode 100644 index 0000000..7feb9d3 --- /dev/null +++ b/assembler/riscv64/tests/standard_sections.rs @@ -0,0 +1,23 @@ +use assembler::{extension::Assembler, AsmSectionKind, AssemblyLimits}; + +use riscv64::RiscV64; + +#[test] +fn named_standard_sections_reuse_canonical_sections_and_keep_their_kinds() { + let source = ".text\nfirst: nop\n.section .text\nsecond: nop\n.data\n.word 1\n.section .data\n.word 2\n.rodata\n.byte 3\n.section .rodata\n.byte 4\n.bss\n.zero 5\n.section .bss\n.zero 7\n"; + let output = RiscV64.assemble("sections.s", source, &AssemblyLimits::default()).unwrap(); + assert_eq!(output.sections.len(), 4); + for (section, name, kind, bytes, zero) in [ + (&output.sections[0], ".text", AsmSectionKind::Text, 8, 0), + (&output.sections[1], ".data", AsmSectionKind::Data, 8, 0), + (&output.sections[2], ".rodata", AsmSectionKind::ReadOnlyData, 2, 0), + (&output.sections[3], ".bss", AsmSectionKind::Bss, 0, 12), + ] { + assert_eq!(section.name, name); + assert_eq!(section.kind, kind); + assert_eq!(section.data.len(), bytes); + assert_eq!(section.zero_fill, zero); + } + assert_eq!(output.sections[0].data, [0x13, 0, 0, 0, 0x13, 0, 0, 0]); + assert_eq!(output.sections[1].data, [1, 0, 0, 0, 2, 0, 0, 0]); +} diff --git a/assembler/src/fixed.rs b/assembler/src/fixed.rs index 5b5a630..408b837 100644 --- a/assembler/src/fixed.rs +++ b/assembler/src/fixed.rs @@ -20,6 +20,16 @@ pub trait FixedIsa { true } + #[doc(hidden)] + fn native_assemble( + &self, + _name: &str, + _source: &str, + _limits: &AssemblyLimits, + ) -> Option> { + None + } + fn encode(&self, instruction: &Instruction, context: &mut Context<'_>) -> Result; } @@ -38,34 +48,26 @@ pub struct Context<'a> { relocations: &'a mut Vec, } +#[doc(hidden)] +#[path = "fixed_reference.rs"] +pub mod reference; + +#[cfg(whale_wave_assembler)] +#[doc(hidden)] +#[path = "fixed_wave.rs"] +pub mod native; + impl Context<'_> { - /// Numeric operands are byte displacements. Local labels use this instruction's - /// PC; cross-section and external symbols retain an ELF relocation. pub fn pc_relative(&mut self, operand: &str, code: u32) -> Result { - match expression(operand)? { - Expression::Number(value) => { - i64::try_from(value).map_err(|_| error("branch displacement exceeds i64")) - }, - Expression::Symbol(name, addend) => { - let symbol = self.symbols.get(&name).ok_or_else(|| { - error(format!("undefined symbol {name:?}; use .extern for external references")) - })?; - if symbol.section == Some(self.section) { - i64::try_from( - i128::from(symbol.offset) + i128::from(addend) - i128::from(self.offset), - ) - .map_err(|_| error("branch displacement exceeds i64")) - } else { - self.relocations.push(Relocation { - offset: self.offset as usize, - symbol: name, - addend, - kind: RelocKind::TargetSpecific { namespace: self.namespace.into(), code }, - }); - Ok(0) - } - }, - } + #[cfg(whale_wave_assembler)] + return native::pc_relative(self, operand, code); + #[cfg(not(whale_wave_assembler))] + reference::pc_relative(self, operand, code) + } + + #[doc(hidden)] + pub fn pc_relative_reference(&mut self, operand: &str, code: u32) -> Result { + reference::pc_relative(self, operand, code) } } @@ -74,459 +76,58 @@ pub fn error(message: impl Into) -> AsmError { } pub fn count(instruction: &Instruction, expected: usize) -> Result<&[String], AsmError> { - if instruction.operands.len() != expected { - return Err(error(format!("{} requires {expected} operands", instruction.mnemonic))); + #[cfg(whale_wave_assembler)] + { + native::count(instruction, expected)?; + Ok(&instruction.operands) } - Ok(&instruction.operands) + #[cfg(not(whale_wave_assembler))] + reference::count(instruction, expected) } pub fn integer(text: &str) -> Result { - let text = text.trim().strip_prefix('#').unwrap_or(text.trim()).trim(); - let (negative, text) = if let Some(s) = text.strip_prefix('-') { - (true, s) - } else { - (false, text.strip_prefix('+').unwrap_or(text)) - }; - let text = text.trim(); - if !text.starts_with(|c: char| c.is_ascii_digit()) { - return Err(error(format!("invalid integer {text:?}"))); - } - let clean = text.replace('_', ""); - let (digits, radix) = - if let Some(s) = clean.strip_prefix("0x").or_else(|| clean.strip_prefix("0X")) { - (s, 16) - } else if let Some(s) = clean.strip_prefix("0b").or_else(|| clean.strip_prefix("0B")) { - (s, 2) - } else { - (clean.as_str(), 10) - }; - let value = i128::from_str_radix(digits, radix) - .map_err(|_| error(format!("invalid integer {text:?}")))?; - if negative { - value.checked_neg().ok_or_else(|| error("integer overflow")) - } else { - Ok(value) - } + #[cfg(whale_wave_assembler)] + return native::integer(text); + #[cfg(not(whale_wave_assembler))] + reference::integer(text) } pub fn signed(text: &str, bits: u32) -> Result { - if !(1..=32).contains(&bits) { - return Err(error("invalid immediate field width")); - } - let value = integer(text)?; - if value < -(1i128 << (bits - 1)) || value >= (1i128 << (bits - 1)) { - return Err(error(format!("immediate must fit signed {bits} bits"))); - } - Ok((value as u32) & ((1u64 << bits) - 1) as u32) + #[cfg(whale_wave_assembler)] + return native::field(text, bits, false); + #[cfg(not(whale_wave_assembler))] + reference::signed(text, bits) } pub fn unsigned(text: &str, bits: u32) -> Result { - if !(1..=32).contains(&bits) { - return Err(error("invalid immediate field width")); - } - let value = integer(text)?; - if value < 0 || value >= (1i128 << bits) { - return Err(error(format!("immediate must fit unsigned {bits} bits"))); - } - Ok(value as u32) + #[cfg(whale_wave_assembler)] + return native::field(text, bits, true); + #[cfg(not(whale_wave_assembler))] + reference::unsigned(text, bits) } pub fn displacement(value: i64, bits: u32, alignment: i64) -> Result { - if !(1..=32).contains(&bits) || alignment <= 0 { - return Err(error("invalid displacement field")); - } - if value % alignment != 0 { - return Err(error(format!("branch displacement must be aligned to {alignment} bytes"))); - } - let scaled = value / alignment; - if scaled < -(1i64 << (bits - 1)) || scaled >= (1i64 << (bits - 1)) { - return Err(error(format!("branch displacement exceeds signed {bits}-bit scaled range"))); - } - Ok((scaled as u32) & ((1u64 << bits) - 1) as u32) -} - -enum Expression { - Number(i128), - Symbol(String, i64), -} - -fn expression(text: &str) -> Result { - if let Ok(value) = integer(text) { - return Ok(Expression::Number(value)); - } - let text = text.trim(); - let split = text.char_indices().skip(1).find(|(_, c)| matches!(c, '+' | '-')).map(|(i, _)| i); - let (name, addend) = if let Some(i) = split { - ( - text[..i].trim(), - i64::try_from(integer(&text[i..])?).map_err(|_| error("symbol addend exceeds i64"))?, - ) - } else { - (text, 0) - }; - identifier(name)?; - Ok(Expression::Symbol(name.into(), addend)) -} - -fn identifier(name: &str) -> Result<(), AsmError> { - let mut chars = name.chars(); - if !chars.next().is_some_and(|c| c.is_ascii_alphabetic() || matches!(c, '_' | '.' | '$')) - || !chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '$')) - { - return Err(error(format!("invalid symbol name {name:?}"))); - } - Ok(()) + #[cfg(whale_wave_assembler)] + return native::displacement(value, bits, alignment); + #[cfg(not(whale_wave_assembler))] + reference::displacement(value, bits, alignment) } pub fn operands(text: &str) -> Result, AsmError> { - if text.trim().is_empty() { - return Ok(Vec::new()); - } - let mut result = Vec::new(); - let mut stack = Vec::new(); - let mut start = 0; - for (i, c) in text.char_indices() { - match c { - '[' | '(' => stack.push(c), - ']' | ')' => { - let expected = if c == ']' { '[' } else { '(' }; - if stack.pop() != Some(expected) { - return Err(error("unbalanced memory operand")); - } - }, - ',' if stack.is_empty() => { - if result.len() >= 65536 { - return Err(error("operand count exceeds 65536")); - } - result.push(text[start..i].trim().into()); - start = i + 1; - }, - _ => {}, - } - } - if !stack.is_empty() { - return Err(error("unclosed memory operand")); - } - result.push(text[start..].trim().into()); - if result.len() > 65536 { - return Err(error("operand count exceeds 65536")); - } - if result.iter().any(String::is_empty) { - return Err(error("empty operand")); - } - Ok(result) -} - -enum Action { - Instruction(Instruction), - Data(usize, Vec), - Zero(usize), - Align(u64), + #[cfg(whale_wave_assembler)] + return native::operands(text); + #[cfg(not(whale_wave_assembler))] + reference::operands(text) } -struct Record { - section: usize, - offset: u64, - span: SourceSpan, - action: Action, -} - -/// No expansion, relaxation or external process: every instruction is four bytes. pub fn assemble( isa: &impl FixedIsa, name: &str, source: &str, limits: &AssemblyLimits, ) -> Result { - if source.len() > 8 * 1024 * 1024 { - return Err(error("assembly input exceeds 8388608 bytes")); - } - if limits.max_relax_iterations == 0 { - return Err(error("assembly pass budget must be nonzero")); - } - let mut sections = vec![AsmSection { - name: ".text".into(), - kind: AsmSectionKind::Text, - align: 4, - data: vec![], - zero_fill: 0, - relocs: vec![], - }]; - let mut section_names = BTreeMap::from([(".text".to_owned(), 0usize)]); - let mut sizes = vec![0u64]; - let mut selected = 0; - let mut symbols: BTreeMap = BTreeMap::new(); - let mut globals = BTreeMap::new(); - let mut records = Vec::new(); - let mut materialized = 0usize; - let mut byte_start = 0; - for (line_index, original) in source.split_inclusive('\n').enumerate() { - let span = SourceSpan { - start: byte_start, - end: byte_start + original.trim_end_matches(['\r', '\n']).len(), - line: line_index + 1, - column: 1, - }; - byte_start += original.len(); - let process = (|| -> Result<(), AsmError> { - let end = original - .find("//") - .into_iter() - .chain(original.find(';')) - .chain(if isa.hash_comments() { original.find('#') } else { None }) - .min() - .unwrap_or(original.len()); - let mut text = original[..end].trim(); - while let Some(colon) = text.find(':') { - let label = text[..colon].trim(); - identifier(label)?; - if symbols.len() >= 65536 { - return Err(error("symbol count exceeds 65536")); - } - if let Some(previous) = symbols.get(label) { - return Err(error(format!("duplicate symbol {label:?}")).at( - name, - span, - Some(previous.span), - )); - } - symbols.insert( - label.into(), - Symbol { section: Some(selected), offset: sizes[selected], span }, - ); - text = text[colon + 1..].trim(); - } - if text.is_empty() { - return Ok(()); - } - let word_end = text.find(char::is_whitespace).unwrap_or(text.len()); - let mnemonic = text[..word_end].to_ascii_lowercase(); - let tail = text[word_end..].trim(); - if matches!(mnemonic.as_str(), ".text" | ".data" | ".rodata" | ".bss" | ".section") { - let section_name = if mnemonic == ".section" { - tail - } else { - if !tail.is_empty() { - return Err(error("section directive takes no operands")); - } - &mnemonic - }; - identifier(section_name)?; - selected = if let Some(&index) = section_names.get(section_name) { - index - } else { - let index = sections.len(); - if index >= 4096 { - return Err(error("section count exceeds 4096")); - } - let kind = AsmSectionKind::default_for_name(section_name); - sections.push(AsmSection { - name: section_name.into(), - kind, - align: if kind == AsmSectionKind::Text { 4 } else { 1 }, - data: vec![], - zero_fill: 0, - relocs: vec![], - }); - sizes.push(0); - section_names.insert(section_name.into(), index); - index - }; - return Ok(()); - } - if matches!(mnemonic.as_str(), ".global" | ".globl" | ".extern") { - let names = operands(tail)?; - if names.is_empty() { - return Err(error("symbol directive requires a name")); - } - for symbol in names { - identifier(&symbol)?; - if globals.len() >= 65536 { - return Err(error("global count exceeds 65536")); - } - globals.insert(symbol.clone(), span); - if mnemonic == ".extern" { - if let Some(previous) = symbols.get(&symbol) { - if previous.section.is_some() { - return Err(error("external symbol is already defined")); - } - } else { - if symbols.len() >= 65536 { - return Err(error("symbol count exceeds 65536")); - } - symbols.insert(symbol, Symbol { section: None, offset: 0, span }); - } - } - } - return Ok(()); - } - let action = match mnemonic.as_str() { - ".byte" | ".hword" | ".short" | ".word" | ".long" | ".quad" => { - let width = match mnemonic.as_str() { - ".byte" => 1, - ".hword" | ".short" => 2, - ".quad" => 8, - _ => 4, - }; - let values = operands(tail)?; - if values.is_empty() { - return Err(error("data directive requires values")); - } - Action::Data(width, values) - }, - ".zero" | ".space" => Action::Zero( - usize::try_from(integer(tail)?) - .map_err(|_| error("invalid reservation size"))?, - ), - ".balign" | ".p2align" | ".align" => { - let value = - u64::try_from(integer(tail)?).map_err(|_| error("invalid alignment"))?; - let alignment = if mnemonic == ".balign" { - value - } else { - 1u64.checked_shl(u32::try_from(value).unwrap_or(u32::MAX)) - .ok_or_else(|| error("alignment overflow"))? - }; - if !alignment.is_power_of_two() { - return Err(error("alignment must be a nonzero power of two")); - } - sections[selected].align = sections[selected].align.max(alignment); - Action::Align(alignment) - }, - _ if mnemonic.starts_with('.') => { - return Err(error(format!("unsupported directive {mnemonic}"))) - }, - _ => Action::Instruction(Instruction { mnemonic, operands: operands(tail)? }), - }; - if sections[selected].kind == AsmSectionKind::Bss - && !matches!(action, Action::Zero(_) | Action::Align(_)) - { - return Err(error("BSS accepts only labels, alignment and zero reservations")); - } - if matches!(action, Action::Instruction(_)) - && (sections[selected].kind != AsmSectionKind::Text || sizes[selected] % 4 != 0) - { - return Err(error("instructions require four-byte alignment in a text section")); - } - let size = match &action { - Action::Instruction(_) => 4, - Action::Data(width, values) => { - width.checked_mul(values.len()).ok_or_else(|| error("data size overflow"))? - as u64 - }, - Action::Zero(size) => *size as u64, - Action::Align(align) => (align - sizes[selected] % align) % align, - }; - let offset = sizes[selected]; - sizes[selected] = - offset.checked_add(size).ok_or_else(|| error("section size overflow"))?; - if sections[selected].kind != AsmSectionKind::Bss { - materialized = materialized - .checked_add( - usize::try_from(size) - .map_err(|_| error("output size exceeds host capacity"))?, - ) - .filter(|n| *n <= limits.max_output_bytes.min(256 * 1024 * 1024)) - .ok_or_else(|| error("Assembly output limit exceeded"))?; - } - if records.len() >= 262144 { - return Err(error("record count exceeds 262144")); - } - records.push(Record { section: selected, offset, span, action }); - Ok(()) - })(); - process.map_err(|e| e.at(name, span, None))?; - } - for (global, span) in &globals { - if !symbols.contains_key(global) { - return Err(error(format!( - "global symbol {global:?} has no definition; use .extern for external declarations" - )) - .at(name, *span, None)); - } - } - for (index, section) in sections.iter_mut().enumerate() { - if section.kind == AsmSectionKind::Bss { - section.zero_fill = sizes[index]; - } else { - section - .data - .try_reserve_exact(sizes[index] as usize) - .map_err(|_| error("unable to reserve assembly output"))?; - } - } - for record in records { - let section = &mut sections[record.section]; - if section.kind == AsmSectionKind::Bss { - continue; - } - let result = (|| -> Result<(), AsmError> { - match record.action { - Action::Instruction(instruction) => { - let mut context = Context { - namespace: isa.id(), - section: record.section, - offset: record.offset, - symbols: &symbols, - relocations: &mut section.relocs, - }; - section - .data - .extend_from_slice(&isa.encode(&instruction, &mut context)?.to_le_bytes()); - }, - Action::Data(width, values) => { - for value in values { - let bits = match expression(&value)? { - Expression::Number(n) => { - if n < -(1i128 << (width * 8 - 1)) || n >= (1i128 << (width * 8)) { - return Err(error("data value does not fit its width")); - } - n as u64 - }, - Expression::Symbol(symbol, addend) => { - if !symbols.contains_key(&symbol) { - return Err(error(format!("undefined symbol {symbol:?}"))); - } - let kind = match width { - 4 => RelocKind::Absolute32, - 8 => RelocKind::Absolute64, - _ => return Err(error("symbol data requires .word or .quad")), - }; - section.relocs.push(Relocation { - offset: section.data.len(), - symbol, - kind, - addend, - }); - 0 - }, - }; - section.data.extend_from_slice(&bits.to_le_bytes()[..width]); - } - }, - Action::Zero(size) => section.data.resize(section.data.len() + size, 0), - Action::Align(align) => { - let padding = (align - record.offset % align) % align; - section.data.resize(section.data.len() + padding as usize, 0); - }, - } - Ok(()) - })(); - result.map_err(|e| e.at(name, record.span, None))?; + if let Some(output) = isa.native_assemble(name, source, limits) { + return output; } - Ok(AssemblerOutput { - sections, - symbols: symbols - .into_iter() - .map(|(name, symbol)| AsmSymbol { - is_global: globals.contains_key(&name), - name, - section_index: symbol.section, - offset: symbol.offset, - kind: SymbolKind::NoType, - size: 0, - visibility: SymbolVisibility::Default, - }) - .collect(), - }) + reference::assemble(isa, name, source, limits) } diff --git a/assembler/src/fixed_reference.rs b/assembler/src/fixed_reference.rs new file mode 100644 index 0000000..6805b64 --- /dev/null +++ b/assembler/src/fixed_reference.rs @@ -0,0 +1,492 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Explicit retained oracle; production facade calls native Wave when selected. +use super::*; + +pub fn pc_relative(context: &mut Context<'_>, operand: &str, code: u32) -> Result { + match expression(operand)? { + Expression::Number(value) => { + i64::try_from(value).map_err(|_| error("branch displacement exceeds i64")) + }, + Expression::Symbol(name, addend) => { + let symbol = context.symbols.get(&name).ok_or_else(|| { + error(format!("undefined symbol {name:?}; use .extern for external references")) + })?; + if symbol.section == Some(context.section) { + i64::try_from( + i128::from(symbol.offset) + i128::from(addend) - i128::from(context.offset), + ) + .map_err(|_| error("branch displacement exceeds i64")) + } else { + context.relocations.push(Relocation { + offset: context.offset as usize, + symbol: name, + addend, + kind: RelocKind::TargetSpecific { namespace: context.namespace.into(), code }, + }); + Ok(0) + } + }, + } +} + +pub fn error(message: impl Into) -> AsmError { + AsmError::EncodeError(message.into()) +} + +pub fn count(instruction: &Instruction, expected: usize) -> Result<&[String], AsmError> { + if instruction.operands.len() != expected { + return Err(error(format!("{} requires {expected} operands", instruction.mnemonic))); + } + Ok(&instruction.operands) +} + +pub fn integer(text: &str) -> Result { + let text = text.trim().strip_prefix('#').unwrap_or(text.trim()).trim(); + let (negative, text) = if let Some(s) = text.strip_prefix('-') { + (true, s) + } else { + (false, text.strip_prefix('+').unwrap_or(text)) + }; + let text = text.trim(); + if !text.starts_with(|c: char| c.is_ascii_digit()) { + return Err(error(format!("invalid integer {text:?}"))); + } + let clean = text.replace('_', ""); + let (digits, radix) = + if let Some(s) = clean.strip_prefix("0x").or_else(|| clean.strip_prefix("0X")) { + (s, 16) + } else if let Some(s) = clean.strip_prefix("0b").or_else(|| clean.strip_prefix("0B")) { + (s, 2) + } else { + (clean.as_str(), 10) + }; + let value = i128::from_str_radix(digits, radix) + .map_err(|_| error(format!("invalid integer {text:?}")))?; + if negative { + value.checked_neg().ok_or_else(|| error("integer overflow")) + } else { + Ok(value) + } +} + +pub fn signed(text: &str, bits: u32) -> Result { + if !(1..=32).contains(&bits) { + return Err(error("invalid immediate field width")); + } + let value = integer(text)?; + if value < -(1i128 << (bits - 1)) || value >= (1i128 << (bits - 1)) { + return Err(error(format!("immediate must fit signed {bits} bits"))); + } + Ok((value as u32) & ((1u64 << bits) - 1) as u32) +} + +pub fn unsigned(text: &str, bits: u32) -> Result { + if !(1..=32).contains(&bits) { + return Err(error("invalid immediate field width")); + } + let value = integer(text)?; + if value < 0 || value >= (1i128 << bits) { + return Err(error(format!("immediate must fit unsigned {bits} bits"))); + } + Ok(value as u32) +} + +pub fn displacement(value: i64, bits: u32, alignment: i64) -> Result { + if !(1..=32).contains(&bits) || alignment <= 0 { + return Err(error("invalid displacement field")); + } + if value % alignment != 0 { + return Err(error(format!("branch displacement must be aligned to {alignment} bytes"))); + } + let scaled = value / alignment; + if scaled < -(1i64 << (bits - 1)) || scaled >= (1i64 << (bits - 1)) { + return Err(error(format!("branch displacement exceeds signed {bits}-bit scaled range"))); + } + Ok((scaled as u32) & ((1u64 << bits) - 1) as u32) +} + +enum Expression { + Number(i128), + Symbol(String, i64), +} + +fn expression(text: &str) -> Result { + if let Ok(value) = integer(text) { + return Ok(Expression::Number(value)); + } + let text = text.trim(); + let split = text.char_indices().skip(1).find(|(_, c)| matches!(c, '+' | '-')).map(|(i, _)| i); + let (name, addend) = if let Some(i) = split { + ( + text[..i].trim(), + i64::try_from(integer(&text[i..])?).map_err(|_| error("symbol addend exceeds i64"))?, + ) + } else { + (text, 0) + }; + identifier(name)?; + Ok(Expression::Symbol(name.into(), addend)) +} + +fn identifier(name: &str) -> Result<(), AsmError> { + let mut chars = name.chars(); + if !chars.next().is_some_and(|c| c.is_ascii_alphabetic() || matches!(c, '_' | '.' | '$')) + || !chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '$')) + { + return Err(error(format!("invalid symbol name {name:?}"))); + } + Ok(()) +} + +pub fn operands(text: &str) -> Result, AsmError> { + if text.trim().is_empty() { + return Ok(Vec::new()); + } + let mut result = Vec::new(); + let mut stack = Vec::new(); + let mut start = 0; + for (i, c) in text.char_indices() { + match c { + '[' | '(' => stack.push(c), + ']' | ')' => { + let expected = if c == ']' { '[' } else { '(' }; + if stack.pop() != Some(expected) { + return Err(error("unbalanced memory operand")); + } + }, + ',' if stack.is_empty() => { + if result.len() >= 65536 { + return Err(error("operand count exceeds 65536")); + } + result.push(text[start..i].trim().into()); + start = i + 1; + }, + _ => {}, + } + } + if !stack.is_empty() { + return Err(error("unclosed memory operand")); + } + result.push(text[start..].trim().into()); + if result.len() > 65536 { + return Err(error("operand count exceeds 65536")); + } + if result.iter().any(String::is_empty) { + return Err(error("empty operand")); + } + Ok(result) +} + +enum Action { + Instruction(Instruction), + Data(usize, Vec), + Zero(usize), + Align(u64), +} + +struct Record { + section: usize, + offset: u64, + span: SourceSpan, + action: Action, +} + +/// No expansion, relaxation or external process: every instruction is four bytes. +pub fn assemble( + isa: &impl FixedIsa, + name: &str, + source: &str, + limits: &AssemblyLimits, +) -> Result { + if source.len() > 8 * 1024 * 1024 { + return Err(error("assembly input exceeds 8388608 bytes")); + } + if limits.max_relax_iterations == 0 { + return Err(error("assembly pass budget must be nonzero")); + } + let mut sections = vec![AsmSection { + name: ".text".into(), + kind: AsmSectionKind::Text, + align: 4, + data: vec![], + zero_fill: 0, + relocs: vec![], + }]; + let mut section_names = BTreeMap::from([(".text".to_owned(), 0usize)]); + let mut sizes = vec![0u64]; + let mut selected = 0; + let mut symbols: BTreeMap = BTreeMap::new(); + let mut globals = BTreeMap::new(); + let mut records = Vec::new(); + let mut materialized = 0usize; + let mut byte_start = 0; + for (line_index, original) in source.split_inclusive('\n').enumerate() { + let span = SourceSpan { + start: byte_start, + end: byte_start + original.trim_end_matches(['\r', '\n']).len(), + line: line_index + 1, + column: 1, + }; + byte_start += original.len(); + let process = (|| -> Result<(), AsmError> { + let end = original + .find("//") + .into_iter() + .chain(original.find(';')) + .chain(if isa.hash_comments() { original.find('#') } else { None }) + .min() + .unwrap_or(original.len()); + let mut text = original[..end].trim(); + while let Some(colon) = text.find(':') { + let label = text[..colon].trim(); + identifier(label)?; + if symbols.len() >= 65536 { + return Err(error("symbol count exceeds 65536")); + } + if let Some(previous) = symbols.get(label) { + return Err(error(format!("duplicate symbol {label:?}")).at( + name, + span, + Some(previous.span), + )); + } + symbols.insert( + label.into(), + Symbol { section: Some(selected), offset: sizes[selected], span }, + ); + text = text[colon + 1..].trim(); + } + if text.is_empty() { + return Ok(()); + } + let word_end = text.find(char::is_whitespace).unwrap_or(text.len()); + let mnemonic = text[..word_end].to_ascii_lowercase(); + let tail = text[word_end..].trim(); + if matches!(mnemonic.as_str(), ".text" | ".data" | ".rodata" | ".bss" | ".section") { + let section_name = if mnemonic == ".section" { + tail + } else { + if !tail.is_empty() { + return Err(error("section directive takes no operands")); + } + &mnemonic + }; + identifier(section_name)?; + selected = if let Some(&index) = section_names.get(section_name) { + index + } else { + let index = sections.len(); + if index >= 4096 { + return Err(error("section count exceeds 4096")); + } + let kind = AsmSectionKind::default_for_name(section_name); + sections.push(AsmSection { + name: section_name.into(), + kind, + align: if kind == AsmSectionKind::Text { 4 } else { 1 }, + data: vec![], + zero_fill: 0, + relocs: vec![], + }); + sizes.push(0); + section_names.insert(section_name.into(), index); + index + }; + return Ok(()); + } + if matches!(mnemonic.as_str(), ".global" | ".globl" | ".extern") { + let names = operands(tail)?; + if names.is_empty() { + return Err(error("symbol directive requires a name")); + } + for symbol in names { + identifier(&symbol)?; + if globals.len() >= 65536 { + return Err(error("global count exceeds 65536")); + } + globals.insert(symbol.clone(), span); + if mnemonic == ".extern" { + if let Some(previous) = symbols.get(&symbol) { + if previous.section.is_some() { + return Err(error("external symbol is already defined")); + } + } else { + if symbols.len() >= 65536 { + return Err(error("symbol count exceeds 65536")); + } + symbols.insert(symbol, Symbol { section: None, offset: 0, span }); + } + } + } + return Ok(()); + } + let action = match mnemonic.as_str() { + ".byte" | ".hword" | ".short" | ".word" | ".long" | ".quad" => { + let width = match mnemonic.as_str() { + ".byte" => 1, + ".hword" | ".short" => 2, + ".quad" => 8, + _ => 4, + }; + let values = operands(tail)?; + if values.is_empty() { + return Err(error("data directive requires values")); + } + Action::Data(width, values) + }, + ".zero" | ".space" => Action::Zero( + usize::try_from(integer(tail)?) + .map_err(|_| error("invalid reservation size"))?, + ), + ".balign" | ".p2align" | ".align" => { + let value = + u64::try_from(integer(tail)?).map_err(|_| error("invalid alignment"))?; + let alignment = if mnemonic == ".balign" { + value + } else { + 1u64.checked_shl(u32::try_from(value).unwrap_or(u32::MAX)) + .ok_or_else(|| error("alignment overflow"))? + }; + if !alignment.is_power_of_two() { + return Err(error("alignment must be a nonzero power of two")); + } + sections[selected].align = sections[selected].align.max(alignment); + Action::Align(alignment) + }, + _ if mnemonic.starts_with('.') => { + return Err(error(format!("unsupported directive {mnemonic}"))) + }, + _ => Action::Instruction(Instruction { mnemonic, operands: operands(tail)? }), + }; + if sections[selected].kind == AsmSectionKind::Bss + && !matches!(action, Action::Zero(_) | Action::Align(_)) + { + return Err(error("BSS accepts only labels, alignment and zero reservations")); + } + if matches!(action, Action::Instruction(_)) + && (sections[selected].kind != AsmSectionKind::Text || sizes[selected] % 4 != 0) + { + return Err(error("instructions require four-byte alignment in a text section")); + } + let size = match &action { + Action::Instruction(_) => 4, + Action::Data(width, values) => { + width.checked_mul(values.len()).ok_or_else(|| error("data size overflow"))? + as u64 + }, + Action::Zero(size) => *size as u64, + Action::Align(align) => (align - sizes[selected] % align) % align, + }; + let offset = sizes[selected]; + sizes[selected] = + offset.checked_add(size).ok_or_else(|| error("section size overflow"))?; + if sections[selected].kind != AsmSectionKind::Bss { + materialized = materialized + .checked_add( + usize::try_from(size) + .map_err(|_| error("output size exceeds host capacity"))?, + ) + .filter(|n| *n <= limits.max_output_bytes.min(256 * 1024 * 1024)) + .ok_or_else(|| error("Assembly output limit exceeded"))?; + } + if records.len() >= 262144 { + return Err(error("record count exceeds 262144")); + } + records.push(Record { section: selected, offset, span, action }); + Ok(()) + })(); + process.map_err(|e| e.at(name, span, None))?; + } + for (global, span) in &globals { + if !symbols.contains_key(global) { + return Err(error(format!( + "global symbol {global:?} has no definition; use .extern for external declarations" + )) + .at(name, *span, None)); + } + } + for (index, section) in sections.iter_mut().enumerate() { + if section.kind == AsmSectionKind::Bss { + section.zero_fill = sizes[index]; + } else { + section + .data + .try_reserve_exact(sizes[index] as usize) + .map_err(|_| error("unable to reserve assembly output"))?; + } + } + for record in records { + let section = &mut sections[record.section]; + if section.kind == AsmSectionKind::Bss { + continue; + } + let result = (|| -> Result<(), AsmError> { + match record.action { + Action::Instruction(instruction) => { + let mut context = Context { + namespace: isa.id(), + section: record.section, + offset: record.offset, + symbols: &symbols, + relocations: &mut section.relocs, + }; + section + .data + .extend_from_slice(&isa.encode(&instruction, &mut context)?.to_le_bytes()); + }, + Action::Data(width, values) => { + for value in values { + let bits = match expression(&value)? { + Expression::Number(n) => { + if n < -(1i128 << (width * 8 - 1)) || n >= (1i128 << (width * 8)) { + return Err(error("data value does not fit its width")); + } + n as u64 + }, + Expression::Symbol(symbol, addend) => { + if !symbols.contains_key(&symbol) { + return Err(error(format!("undefined symbol {symbol:?}"))); + } + let kind = match width { + 4 => RelocKind::Absolute32, + 8 => RelocKind::Absolute64, + _ => return Err(error("symbol data requires .word or .quad")), + }; + section.relocs.push(Relocation { + offset: section.data.len(), + symbol, + kind, + addend, + }); + 0 + }, + }; + section.data.extend_from_slice(&bits.to_le_bytes()[..width]); + } + }, + Action::Zero(size) => section.data.resize(section.data.len() + size, 0), + Action::Align(align) => { + let padding = (align - record.offset % align) % align; + section.data.resize(section.data.len() + padding as usize, 0); + }, + } + Ok(()) + })(); + result.map_err(|e| e.at(name, record.span, None))?; + } + Ok(AssemblerOutput { + sections, + symbols: symbols + .into_iter() + .map(|(name, symbol)| AsmSymbol { + is_global: globals.contains_key(&name), + name, + section_index: symbol.section, + offset: symbol.offset, + kind: SymbolKind::NoType, + size: 0, + visibility: SymbolVisibility::Default, + }) + .collect(), + }) +} diff --git a/assembler/src/fixed_wave.rs b/assembler/src/fixed_wave.rs new file mode 100644 index 0000000..bca7448 --- /dev/null +++ b/assembler/src/fixed_wave.rs @@ -0,0 +1,1156 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Typed allocation/snapshot transport for the Wave fixed-width source modules. +use super::*; + +use std::borrow::Cow; + +#[repr(C)] +#[derive(Clone, Copy)] +pub struct FixedText { + pub data: *const u8, + pub count: u64, +} + +impl Default for FixedText { + fn default() -> Self { + Self { data: std::ptr::null(), count: 0 } + } +} + +#[repr(C)] +#[derive(Clone, Copy)] +pub struct FixedInstruction { + pub mnemonic: FixedText, + pub operands: *const FixedText, + pub count: u64, + pub fold: u64, +} + +impl Default for FixedInstruction { + fn default() -> Self { + Self { mnemonic: FixedText::default(), operands: std::ptr::null(), count: 0, fold: 0 } + } +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +pub struct FixedSymbol { + pub name: FixedText, + pub section: u64, + pub offset: u64, + pub start: u64, + pub end: u64, + pub line: u64, + pub flags: u64, +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +pub struct FixedRelocation { + pub section: u64, + pub offset: u64, + pub symbol: u64, + pub code: u64, + pub addend: i64, +} + +#[repr(C)] +#[derive(Clone, Copy)] +pub struct FixedContext { + pub source: FixedText, + pub namespace: FixedText, + pub symbols: *mut FixedSymbol, + pub symbol_count: u64, + pub table: *mut u64, + pub table_capacity: u64, + pub section: u64, + pub offset: u64, + pub relocations: *mut FixedRelocation, + pub relocation_count: u64, + pub relocation_capacity: u64, +} + +impl Default for FixedContext { + fn default() -> Self { + Self { + source: FixedText::default(), + namespace: FixedText::default(), + symbols: std::ptr::null_mut(), + symbol_count: 0, + table: std::ptr::null_mut(), + table_capacity: 0, + section: 0, + offset: 0, + relocations: std::ptr::null_mut(), + relocation_count: 0, + relocation_capacity: 0, + } + } +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +pub struct FixedResult { + pub status: u64, + pub error: u64, + pub start: u64, + pub end: u64, + pub line: u64, + pub previous_start: u64, + pub previous_end: u64, + pub previous_line: u64, + pub text: FixedText, + pub detail: u64, + pub display: u64, + pub word: u64, + pub sections: u64, + pub symbols: u64, + pub relocations: u64, + pub records: u64, + pub operands: u64, + pub bytes: u64, + pub work: u64, + pub max_work: u64, +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +pub struct FixedSection { + pub name: FixedText, + pub kind: u64, + pub align: u64, + pub size: u64, + pub first: u64, +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +pub struct FixedRecord { + pub section: u64, + pub offset: u64, + pub start: u64, + pub end: u64, + pub line: u64, + pub kind: u64, + pub unit: u64, + pub first: u64, + pub count: u64, + pub size: u64, + pub mnemonic: FixedText, +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +pub struct FixedGlobal { + pub start: u64, + pub end: u64, + pub line: u64, +} + +#[repr(C)] +#[derive(Clone, Copy)] +pub struct FixedInput { + pub source: FixedText, + pub namespace: FixedText, + pub hash_comments: u64, + pub mode: u64, + pub max_output: u64, + pub max_passes: u64, + pub max_work: u64, + pub sections: *mut FixedSection, + pub section_capacity: u64, + pub symbols: *mut FixedSymbol, + pub symbol_capacity: u64, + pub table: *mut u64, + pub table_capacity: u64, + pub globals: *mut FixedGlobal, + pub global_capacity: u64, + pub records: *mut FixedRecord, + pub record_capacity: u64, + pub operands: *mut FixedText, + pub operand_capacity: u64, + pub order: *mut u64, + pub order_capacity: u64, + pub relocations: *mut FixedRelocation, + pub relocation_capacity: u64, + pub bytes: *mut u8, + pub byte_capacity: u64, +} + +impl Default for FixedInput { + fn default() -> Self { + Self { + source: FixedText::default(), + namespace: FixedText::default(), + hash_comments: 0, + mode: 0, + max_output: 0, + max_passes: 0, + max_work: 0, + sections: std::ptr::null_mut(), + section_capacity: 0, + symbols: std::ptr::null_mut(), + symbol_capacity: 0, + table: std::ptr::null_mut(), + table_capacity: 0, + globals: std::ptr::null_mut(), + global_capacity: 0, + records: std::ptr::null_mut(), + record_capacity: 0, + operands: std::ptr::null_mut(), + operand_capacity: 0, + order: std::ptr::null_mut(), + order_capacity: 0, + relocations: std::ptr::null_mut(), + relocation_capacity: 0, + bytes: std::ptr::null_mut(), + byte_capacity: 0, + } + } +} + +#[repr(C)] +#[derive(Clone, Copy)] +pub struct FixedState { + pub packet: *mut FixedInput, + pub context: FixedContext, + pub section_count: u64, + pub symbol_count: u64, + pub definition_count: u64, + pub global_count: u64, + pub record_count: u64, + pub operand_count: u64, + pub selected: u64, + pub materialized: u64, + pub next: u64, + pub pending: u64, +} + +impl Default for FixedState { + fn default() -> Self { + Self { + packet: std::ptr::null_mut(), + context: FixedContext::default(), + section_count: 0, + symbol_count: 0, + definition_count: 0, + global_count: 0, + record_count: 0, + operand_count: 0, + selected: 0, + materialized: 0, + next: 0, + pending: 0, + } + } +} + +pub type Render = fn(u64, &str, u64) -> AsmError; + +pub type Entry = unsafe extern "C" fn(*const FixedInput, *mut FixedResult) -> i32; +pub type Encode = + unsafe extern "C" fn(*const FixedInstruction, *mut FixedContext, *mut FixedResult) -> i32; + +const WORK: u64 = 512 * 1024 * 1024; + +const WORKSPACE: usize = 128 * 1024 * 1024; + +const MISSING: u64 = u64::MAX; + +unsafe extern "C" { + fn whale_fixed_probe( + source: *const FixedText, + hash_comments: u64, + result: *mut FixedResult, + ) -> i32; + + fn whale_fixed_scalar( + mode: u64, + text: *const FixedText, + bits: u64, + value: i64, + alignment: i64, + result: *mut FixedResult, + ) -> i32; + + fn whale_fixed_operands( + text: *const FixedText, + output: *mut FixedText, + capacity: u64, + count: *mut u64, + result: *mut FixedResult, + ) -> i32; + + fn whale_fixed_context_index(context: *mut FixedContext, result: *mut FixedResult) -> i32; + + fn whale_fixed_relative( + context: *mut FixedContext, + text: *const FixedText, + code: u64, + result: *mut FixedResult, + ) -> i32; + + fn asm_fixed_count( + instruction: *const FixedInstruction, + count: u64, + result: *mut FixedResult, + ) -> bool; +} + +impl FixedText { + pub fn new(text: &str) -> Self { + Self { data: text.as_ptr(), count: text.len() as u64 } + } +} + +impl FixedResult { + pub fn new() -> Self { + Self { max_work: WORK, ..Self::default() } + } +} + +fn backend() -> AsmError { + AsmError::Backend("fixed-width Wave transport") +} + +fn allocation() -> AsmError { + error("unable to reserve assembly output") +} + +fn workspace() -> AsmError { + error("assembly workspace limit exceeded") +} + +fn allocate(count: usize) -> Result, AsmError> { + let mut output = Vec::new(); + output.try_reserve_exact(count).map_err(|_| allocation())?; + output.resize(count, T::default()); + Ok(output) +} + +fn charge(used: &mut usize, count: usize, width: usize) -> Result<(), AsmError> { + *used = used + .checked_add(count.checked_mul(width).ok_or_else(workspace)?) + .filter(|n| *n <= WORKSPACE) + .ok_or_else(workspace)?; + Ok(()) +} + +fn owned(text: &str) -> Result { + let mut value = String::new(); + value.try_reserve_exact(text.len()).map_err(|_| allocation())?; + value.push_str(text); + Ok(value) +} + +fn borrowed<'a>(text: FixedText, inputs: &[&'a str]) -> Result<&'a str, AsmError> { + if text.count == 0 { + return Ok(""); + } + let start = text.data as usize; + let count = usize::try_from(text.count).map_err(|_| backend())?; + let end = start.checked_add(count).ok_or_else(backend)?; + for input in inputs { + let base = input.as_ptr() as usize; + let limit = base.checked_add(input.len()).ok_or_else(backend)?; + if start >= base && end <= limit { + return input.get(start - base..end - base).ok_or_else(backend); + } + } + Err(backend()) +} + +fn common_error(code: u64, text: &str, detail: u64) -> Option { + let message = match code { + 1 => format!("{text} requires {detail} operands"), + 2 => format!("invalid integer {text:?}"), + 3 => "integer overflow".into(), + 4 => "invalid immediate field width".into(), + 5 => format!("immediate must fit signed {detail} bits"), + 6 => format!("immediate must fit unsigned {detail} bits"), + 7 => "invalid displacement field".into(), + 8 => format!("branch displacement must be aligned to {detail} bytes"), + 9 => format!("branch displacement exceeds signed {detail}-bit scaled range"), + 10 => "symbol addend exceeds i64".into(), + 11 => format!("invalid symbol name {text:?}"), + 12 => format!("undefined symbol {text:?}; use .extern for external references"), + 13 => format!("undefined symbol {text:?}"), + 14 => "branch displacement exceeds i64".into(), + 15 => "unbalanced memory operand".into(), + 16 => "unclosed memory operand".into(), + 17 => "operand count exceeds 65536".into(), + 18 => "empty operand".into(), + 30 => "section directive takes no operands".into(), + 31 => "symbol directive requires a name".into(), + 32 => "data directive requires values".into(), + 33 => "invalid reservation size".into(), + 34 => "BSS accepts only labels, alignment and zero reservations".into(), + 35 => "instructions require four-byte alignment in a text section".into(), + 36 => "invalid alignment".into(), + 37 => "alignment overflow".into(), + 38 => "alignment must be a nonzero power of two".into(), + 39 => format!("unsupported directive {text}"), + 40 => "data size overflow".into(), + 70 => "symbol count exceeds 65536".into(), + 71 => format!("duplicate symbol {text:?}"), + 72 => "global count exceeds 65536".into(), + 73 => "external symbol is already defined".into(), + 74 => format!( + "global symbol {text:?} has no definition; use .extern for external declarations" + ), + 75 => "section count exceeds 4096".into(), + 76 => "section size overflow".into(), + 77 => "Assembly output limit exceeded".into(), + 78 => "record count exceeds 262144".into(), + 79 => "data value does not fit its width".into(), + 80 => "symbol data requires .word or .quad".into(), + 41 | 90 => "assembly input exceeds 8388608 bytes".into(), + 42 | 91 => "assembly pass budget must be nonzero".into(), + 92 => "unable to reserve assembly output".into(), + 93 => "Assembly work limit exceeded".into(), + 94 => return Some(backend()), + _ => return None, + }; + Some(error(message)) +} + +fn no_isa_error(_: u64, _: &str, _: u64) -> AsmError { + backend() +} + +fn failure( + result: &FixedResult, + inputs: &[&str], + render: Render, + source: Option<(&str, &str)>, +) -> AsmError { + if result.status != 1 + || result.error == 0 + || result.display > 1 + || result.work > result.max_work + { + return backend(); + } + let text = match borrowed(result.text, inputs) { + Ok(text) => text, + Err(error) => return error, + }; + let name_bytes = source.map_or(0, |(name, _)| name.len()); + if text + .len() + .checked_mul(6) + .and_then(|n| n.checked_add(name_bytes)) + .is_none_or(|n| n > WORKSPACE.saturating_sub(256)) + { + return workspace(); + } + let text = if result.display == 1 { + let mut value = match owned(text) { + Ok(value) => value, + Err(error) => return error, + }; + value.make_ascii_lowercase(); + Cow::Owned(value) + } else { + Cow::Borrowed(text) + }; + let output = common_error(result.error, &text, result.detail) + .unwrap_or_else(|| render(result.error, &text, result.detail)); + if matches!(output, AsmError::Backend(_)) { + return output; + } + let Some((name, source)) = source else { return output }; + if result.line == 0 { + return output; + } + let span = |start: u64, end: u64, line: u64| -> Option { + (start <= end && end <= source.len() as u64 && line > 0).then_some(SourceSpan { + start: start as usize, + end: end as usize, + line: usize::try_from(line).ok()?, + column: 1, + }) + }; + let Some(current) = span(result.start, result.end, result.line) else { return backend() }; + let previous = if result.previous_line == 0 { + None + } else { + let Some(previous) = span(result.previous_start, result.previous_end, result.previous_line) + else { + return backend(); + }; + Some(previous) + }; + output.at(name, current, previous) +} + +fn failed( + status: i32, + result: &FixedResult, + inputs: &[&str], + render: Render, + source: Option<(&str, &str)>, +) -> AsmError { + if status != 1 || i32::try_from(result.status).ok() != Some(status) { + return backend(); + } + failure(result, inputs, render, source) +} + +fn success(status: i32, result: &FixedResult) -> bool { + status == 0 && result.status == 0 && result.error == 0 && result.work <= result.max_work +} + +pub fn check( + status: i32, + result: &FixedResult, + inputs: &[&str], + render: Render, +) -> Result<(), AsmError> { + if success(status, result) { + Ok(()) + } else { + Err(failed(status, result, inputs, render, None)) + } +} + +fn scalar( + mode: u64, + text: &str, + bits: u32, + value: i64, + alignment: i64, +) -> Result { + let input = FixedText::new(text); + let mut result = FixedResult::new(); + let status = + unsafe { whale_fixed_scalar(mode, &input, bits.into(), value, alignment, &mut result) }; + if !success(status, &result) { + return Err(failed(status, &result, &[text], no_isa_error, None)); + } + Ok(result) +} + +pub fn integer(text: &str) -> Result { + let result = scalar(0, text, 0, 0, 0)?; + Ok((u128::from(result.word) | (u128::from(result.detail) << 64)) as i128) +} + +pub fn field(text: &str, bits: u32, unsigned: bool) -> Result { + u32::try_from(scalar(if unsigned { 2 } else { 1 }, text, bits, 0, 0)?.word) + .map_err(|_| backend()) +} + +pub fn displacement(value: i64, bits: u32, alignment: i64) -> Result { + u32::try_from(scalar(3, "", bits, value, alignment)?.word).map_err(|_| backend()) +} + +pub fn count(instruction: &Instruction, expected: usize) -> Result<(), AsmError> { + let raw = FixedInstruction { + mnemonic: FixedText::new(&instruction.mnemonic), + count: instruction.operands.len() as u64, + ..FixedInstruction::default() + }; + let mut result = FixedResult::new(); + if !unsafe { asm_fixed_count(&raw, expected as u64, &mut result) } { + return Err(failure(&result, &[&instruction.mnemonic], no_isa_error, None)); + } + if !success(0, &result) { + return Err(backend()); + } + Ok(()) +} + +pub fn operands(text: &str) -> Result, AsmError> { + let capacity = text.len().saturating_add(1).min(65536); + let mut raw = allocate::(capacity)?; + let input = FixedText::new(text); + let mut count = 0u64; + let mut result = FixedResult::new(); + let status = unsafe { + whale_fixed_operands(&input, raw.as_mut_ptr(), capacity as u64, &mut count, &mut result) + }; + if !success(status, &result) { + return Err(failed(status, &result, &[text], no_isa_error, None)); + } + if count > raw.len() as u64 { + return Err(backend()); + } + let mut used = raw.len() * std::mem::size_of::(); + charge(&mut used, count as usize, std::mem::size_of::())?; + let mut output = Vec::new(); + output.try_reserve_exact(count as usize).map_err(|_| allocation())?; + for raw in raw.into_iter().take(count as usize) { + let value = borrowed(raw, &[text])?; + charge(&mut used, value.len(), 1)?; + output.push(owned(value)?); + } + Ok(output) +} + +fn table_capacity(symbols: usize) -> Result { + symbols.checked_mul(2).and_then(|n| n.max(2).checked_next_power_of_two()).ok_or_else(workspace) +} + +fn section_name(text: FixedText, source: &str) -> Result<&str, AsmError> { + if text.data.is_null() { + return match text.count { + 0 => Ok(".text"), + 1 => Ok(".data"), + 2 => Ok(".rodata"), + 3 => Ok(".bss"), + _ => Err(backend()), + }; + } + borrowed(text, &[source]) +} + +fn relocation_kind(namespace: &str, code: u64) -> Result { + Ok(match code { + u64::MAX => RelocKind::Absolute32, + value if value == u64::MAX - 1 => RelocKind::Absolute64, + value => RelocKind::TargetSpecific { + namespace: owned(namespace)?, + code: u32::try_from(value).map_err(|_| backend())?, + }, + }) +} + +pub fn assemble( + name: &str, + source: &str, + limits: &AssemblyLimits, + namespace: &str, + hash_comments: bool, + entry: Entry, + render: Render, +) -> Result { + // Validate allocation metadata before probing source-sized scratch buffers. + // The Wave driver independently enforces these same execution limits. + if source.len() > 8 * 1024 * 1024 { + return Err(error("assembly input exceeds 8388608 bytes")); + } + if limits.max_relax_iterations == 0 { + return Err(error("assembly pass budget must be nonzero")); + } + let source_text = FixedText::new(source); + let mut probe = FixedResult::new(); + let status = unsafe { whale_fixed_probe(&source_text, u64::from(hash_comments), &mut probe) }; + if !success(status, &probe) { + return Err(failed(status, &probe, &[source, namespace], render, Some((name, source)))); + } + let sections = usize::try_from(probe.sections).map_err(|_| backend())?; + let symbols = usize::try_from(probe.symbols).map_err(|_| backend())?; + let records = usize::try_from(probe.records).map_err(|_| backend())?; + let operands = usize::try_from(probe.operands).map_err(|_| backend())?; + let relocations = usize::try_from(probe.relocations).map_err(|_| backend())?; + let table_size = table_capacity(symbols)?; + let mut used = 0; + charge(&mut used, sections, std::mem::size_of::())?; + charge( + &mut used, + symbols, + std::mem::size_of::() + std::mem::size_of::() + 8, + )?; + charge(&mut used, table_size, 8)?; + charge(&mut used, records, std::mem::size_of::())?; + charge(&mut used, operands, std::mem::size_of::())?; + charge(&mut used, relocations, std::mem::size_of::())?; + let mut raw_sections = allocate::(sections)?; + let mut raw_symbols = allocate::(symbols)?; + let mut globals = allocate::(symbols)?; + let mut table = allocate::(table_size)?; + let mut raw_records = allocate::(records)?; + let mut raw_operands = allocate::(operands)?; + let mut order = allocate::(symbols)?; + let mut raw_relocations = allocate::(relocations)?; + let mut input = FixedInput { + source: source_text, + namespace: FixedText::new(namespace), + hash_comments: u64::from(hash_comments), + mode: 0, + max_output: limits.max_output_bytes as u64, + max_passes: limits.max_relax_iterations as u64, + max_work: WORK.saturating_sub(probe.work), + sections: raw_sections.as_mut_ptr(), + section_capacity: sections as u64, + symbols: raw_symbols.as_mut_ptr(), + symbol_capacity: symbols as u64, + table: table.as_mut_ptr(), + table_capacity: table_size as u64, + globals: globals.as_mut_ptr(), + global_capacity: symbols as u64, + records: raw_records.as_mut_ptr(), + record_capacity: records as u64, + operands: raw_operands.as_mut_ptr(), + operand_capacity: operands as u64, + order: order.as_mut_ptr(), + order_capacity: symbols as u64, + relocations: raw_relocations.as_mut_ptr(), + relocation_capacity: relocations as u64, + bytes: std::ptr::null_mut(), + byte_capacity: 0, + }; + let valid = |result: &FixedResult, input: &FixedInput| { + result.sections <= input.section_capacity + && result.symbols <= input.symbol_capacity + && result.records <= input.record_capacity + && result.operands <= input.operand_capacity + && result.relocations <= input.relocation_capacity + && result.bytes <= input.max_output + && result.bytes <= 256 * 1024 * 1024 + && result.work <= input.max_work + }; + let mut result = FixedResult::new(); + let status = unsafe { entry(&input, &mut result) }; + if !success(status, &result) { + return Err(failed(status, &result, &[source, namespace], render, Some((name, source)))); + } + if !valid(&result, &input) { + return Err(backend()); + } + let size = usize::try_from(result.bytes).map_err(|_| backend())?; + // The final payload is bounded separately by max_output. Its native staging + // copy and every reconstructed name/container are admitted as workspace. + charge(&mut used, size, 1)?; + let mut bytes = allocate::(size)?; + input.mode = 1; + input.bytes = bytes.as_mut_ptr(); + input.byte_capacity = bytes.len() as u64; + input.max_work = input.max_work.saturating_sub(result.work); + let status = unsafe { entry(&input, &mut result) }; + if !success(status, &result) { + return Err(failed(status, &result, &[source, namespace], render, Some((name, source)))); + } + if !valid(&result, &input) || result.bytes != bytes.len() as u64 { + return Err(backend()); + } + charge(&mut used, result.sections as usize, std::mem::size_of::())?; + charge(&mut used, result.symbols as usize, std::mem::size_of::() + 1)?; + charge(&mut used, result.relocations as usize, 2 * std::mem::size_of::())?; + for section in raw_sections.iter().take(result.sections as usize) { + charge(&mut used, section_name(section.name, source)?.len(), 1)?; + } + for symbol in raw_symbols.iter().take(result.symbols as usize) { + charge(&mut used, borrowed(symbol.name, &[source])?.len(), 1)?; + } + for relocation in raw_relocations.iter().take(result.relocations as usize) { + let symbol = raw_symbols + .get(usize::try_from(relocation.symbol).map_err(|_| backend())?) + .filter(|_| relocation.symbol < result.symbols) + .ok_or_else(backend)?; + charge(&mut used, borrowed(symbol.name, &[source])?.len(), 1)?; + if relocation.code < u64::MAX - 1 { + charge(&mut used, namespace.len(), 1)?; + } + } + let mut output = AssemblerOutput { sections: Vec::new(), symbols: Vec::new() }; + output.sections.try_reserve_exact(result.sections as usize).map_err(|_| allocation())?; + let mut first = 0usize; + for section in raw_sections.iter().take(result.sections as usize) { + if !section.align.is_power_of_two() || section.first != first as u64 { + return Err(backend()); + } + let kind = match section.kind { + 0 => AsmSectionKind::Text, + 1 => AsmSectionKind::Data, + 2 => AsmSectionKind::ReadOnlyData, + 3 => AsmSectionKind::Bss, + _ => return Err(backend()), + }; + let data = if kind == AsmSectionKind::Bss { + Vec::new() + } else { + let length = usize::try_from(section.size).map_err(|_| backend())?; + let end = first.checked_add(length).ok_or_else(backend)?; + let slice = bytes.get(first..end).ok_or_else(backend)?; + let mut data = Vec::new(); + data.try_reserve_exact(length).map_err(|_| allocation())?; + data.extend_from_slice(slice); + first = end; + data + }; + output.sections.push(AsmSection { + name: owned(section_name(section.name, source)?)?, + kind, + align: section.align, + data, + zero_fill: if kind == AsmSectionKind::Bss { section.size } else { 0 }, + relocs: Vec::new(), + }); + } + if first != bytes.len() { + return Err(backend()); + } + let mut seen = allocate::(result.symbols as usize)?; + output.symbols.try_reserve_exact(result.symbols as usize).map_err(|_| allocation())?; + for id in order.into_iter().take(result.symbols as usize) { + let index = usize::try_from(id).map_err(|_| backend())?; + let seen = seen.get_mut(index).ok_or_else(backend)?; + if *seen { + return Err(backend()); + } + *seen = true; + let symbol = raw_symbols.get(index).ok_or_else(backend)?; + if symbol.flags & !7 != 0 || symbol.flags & 6 == 0 { + return Err(backend()); + } + let section_index = if symbol.section == MISSING { + None + } else { + let index = usize::try_from(symbol.section).map_err(|_| backend())?; + let section = output.sections.get(index).ok_or_else(backend)?; + if symbol.offset > section.data.len() as u64 + section.zero_fill { + return Err(backend()); + } + Some(index) + }; + output.symbols.push(AsmSymbol { + name: owned(borrowed(symbol.name, &[source])?)?, + section_index, + offset: symbol.offset, + is_global: symbol.flags & 1 != 0, + kind: SymbolKind::NoType, + size: 0, + visibility: SymbolVisibility::Default, + }); + } + for relocation in raw_relocations.into_iter().take(result.relocations as usize) { + let section = output + .sections + .get_mut(usize::try_from(relocation.section).map_err(|_| backend())?) + .ok_or_else(backend)?; + let symbol = raw_symbols + .get(usize::try_from(relocation.symbol).map_err(|_| backend())?) + .ok_or_else(backend)?; + let width = if relocation.code == u64::MAX - 1 { 8 } else { 4 }; + let offset = usize::try_from(relocation.offset).map_err(|_| backend())?; + if offset.checked_add(width).is_none_or(|end| end > section.data.len()) { + return Err(backend()); + } + section.relocs.try_reserve(1).map_err(|_| allocation())?; + section.relocs.push(Relocation { + offset, + symbol: owned(borrowed(symbol.name, &[source])?)?, + addend: relocation.addend, + kind: relocation_kind(namespace, relocation.code)?, + }); + } + Ok(output) +} + +struct Snapshot<'a> { + symbols: Vec, + table: Vec, + relocations: Vec, + operands: Vec, + inputs: Vec<&'a str>, + namespace: &'a str, + section: u64, + offset: u64, +} + +impl<'a> Snapshot<'a> { + fn new(context: &Context<'a>, instruction: &'a Instruction) -> Result { + let capacity = table_capacity(context.symbols.len())?; + let mut used = 0usize; + charge( + &mut used, + context.symbols.len(), + std::mem::size_of::() + std::mem::size_of::<&str>(), + )?; + charge(&mut used, capacity, 8)?; + charge( + &mut used, + instruction.operands.len(), + std::mem::size_of::() + std::mem::size_of::<&str>(), + )?; + let mut symbols = Vec::new(); + symbols.try_reserve_exact(context.symbols.len()).map_err(|_| allocation())?; + let mut operands = Vec::new(); + operands.try_reserve_exact(instruction.operands.len()).map_err(|_| allocation())?; + let mut inputs = Vec::new(); + inputs + .try_reserve_exact( + context + .symbols + .len() + .checked_add(instruction.operands.len()) + .and_then(|n| n.checked_add(2)) + .ok_or_else(workspace)?, + ) + .map_err(|_| allocation())?; + inputs.push(instruction.mnemonic.as_str()); + inputs.push(context.namespace); + for operand in &instruction.operands { + operands.push(FixedText::new(operand)); + inputs.push(operand.as_str()); + } + for (name, symbol) in context.symbols { + symbols.push(FixedSymbol { + name: FixedText::new(name), + section: symbol.section.map_or(MISSING, |index| index as u64), + offset: symbol.offset, + start: symbol.span.start as u64, + end: symbol.span.end as u64, + line: symbol.span.line as u64, + flags: if symbol.section.is_some() { 2 } else { 4 }, + }); + inputs.push(name.as_str()); + } + Ok(Self { + symbols, + table: allocate(capacity)?, + relocations: allocate(1)?, + operands, + inputs, + namespace: context.namespace, + section: context.section as u64, + offset: context.offset, + }) + } + + fn context(&mut self) -> FixedContext { + FixedContext { + namespace: FixedText::new(self.namespace), + symbols: self.symbols.as_mut_ptr(), + symbol_count: self.symbols.len() as u64, + table: self.table.as_mut_ptr(), + table_capacity: self.table.len() as u64, + section: self.section, + offset: self.offset, + relocations: self.relocations.as_mut_ptr(), + relocation_capacity: self.relocations.len() as u64, + ..FixedContext::default() + } + } + + fn additions(&self, count: u64) -> Result, AsmError> { + if count > self.relocations.len() as u64 { + return Err(backend()); + } + let mut output = Vec::new(); + output.try_reserve_exact(count as usize).map_err(|_| allocation())?; + let mut used = 0usize; + for relocation in self.relocations.iter().take(count as usize) { + if relocation.section != self.section || relocation.offset != self.offset { + return Err(backend()); + } + let symbol = self + .symbols + .get(usize::try_from(relocation.symbol).map_err(|_| backend())?) + .ok_or_else(backend)?; + let name = borrowed(symbol.name, &self.inputs)?; + charge(&mut used, name.len(), 1)?; + charge(&mut used, self.namespace.len(), 1)?; + output.push(Relocation { + offset: usize::try_from(relocation.offset).map_err(|_| backend())?, + symbol: owned(name)?, + kind: relocation_kind(self.namespace, relocation.code)?, + addend: relocation.addend, + }); + } + Ok(output) + } +} + +pub fn encode( + instruction: &Instruction, + context: &mut Context<'_>, + encode: Encode, + render: Render, +) -> Result { + let mut snapshot = Snapshot::new(context, instruction)?; + let mut raw_context = snapshot.context(); + let raw = FixedInstruction { + mnemonic: FixedText::new(&instruction.mnemonic), + operands: snapshot.operands.as_ptr(), + count: snapshot.operands.len() as u64, + fold: 0, + }; + let mut result = FixedResult::new(); + let status = unsafe { whale_fixed_context_index(&mut raw_context, &mut result) }; + if !success(status, &result) { + return Err(failed(status, &result, &snapshot.inputs, render, None)); + } + let status = unsafe { encode(&raw, &mut raw_context, &mut result) }; + if !success(status, &result) { + return Err(failed(status, &result, &snapshot.inputs, render, None)); + } + let word = u32::try_from(result.word).map_err(|_| backend())?; + let additions = snapshot.additions(raw_context.relocation_count)?; + context.relocations.try_reserve(additions.len()).map_err(|_| allocation())?; + context.relocations.extend(additions); + Ok(word) +} + +pub fn pc_relative(context: &mut Context<'_>, text: &str, code: u32) -> Result { + let instruction = Instruction { mnemonic: String::new(), operands: vec![owned(text)?] }; + let mut snapshot = Snapshot::new(context, &instruction)?; + let mut raw_context = snapshot.context(); + let raw_text = FixedText::new(text); + let mut result = FixedResult::new(); + let status = unsafe { whale_fixed_context_index(&mut raw_context, &mut result) }; + if !success(status, &result) { + return Err(failed(status, &result, &snapshot.inputs, no_isa_error, None)); + } + let status = + unsafe { whale_fixed_relative(&mut raw_context, &raw_text, code.into(), &mut result) }; + if !success(status, &result) { + return Err(failed(status, &result, &[text], no_isa_error, None)); + } + let additions = snapshot.additions(raw_context.relocation_count)?; + context.relocations.try_reserve(additions.len()).map_err(|_| allocation())?; + context.relocations.extend(additions); + Ok(result.word as i64) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn malformed_native_faults_cannot_be_reclassified_as_source_errors() { + let mut result = FixedResult { + status: 1, + error: 5, + detail: 12, + text: FixedText::new("4096"), + ..FixedResult::new() + }; + assert!(matches!( + check(1, &result, &["4096"], no_isa_error), + Err(AsmError::EncodeError(_)) + )); + assert!(matches!(check(2, &result, &["4096"], no_isa_error), Err(AsmError::Backend(_)))); + result.text = FixedText { data: std::ptr::null(), count: 1 }; + assert!(matches!(check(1, &result, &["4096"], no_isa_error), Err(AsmError::Backend(_)))); + result.text = FixedText::new("4096"); + result.work = result.max_work + 1; + assert!(matches!(check(1, &result, &["4096"], no_isa_error), Err(AsmError::Backend(_)))); + } + + #[test] + fn public_context_relative_transport_matches_reference_and_appends_only_native_relocations() { + let span = SourceSpan { start: 0, end: 1, line: 1, column: 1 }; + let symbols = BTreeMap::from([ + ("target".into(), Symbol { section: Some(2), offset: 8, span }), + ("ext".into(), Symbol { section: None, offset: 0, span }), + ]); + for text in ["target+2", "ext-4", "missing", "4", "18446744073709551616"] { + let mut actual_relocations = Vec::new(); + let mut reference_relocations = Vec::new(); + let mut actual = Context { + namespace: "riscv64", + section: 2, + offset: 4, + symbols: &symbols, + relocations: &mut actual_relocations, + }; + let mut expected = Context { + namespace: "riscv64", + section: 2, + offset: 4, + symbols: &symbols, + relocations: &mut reference_relocations, + }; + match (actual.pc_relative(text, 17), expected.pc_relative_reference(text, 17)) { + (Ok(actual), Ok(expected)) => assert_eq!(actual, expected), + (Err(actual), Err(expected)) => { + assert_eq!(actual.to_string(), expected.to_string()) + }, + _ => panic!("relative status differs for {text:?}"), + } + let snapshot = |relocations: &[Relocation]| { + relocations + .iter() + .map(|r| format!("{}:{:?}:{}:{}", r.offset, r.kind, r.symbol, r.addend)) + .collect::>() + }; + assert_eq!(snapshot(&actual_relocations), snapshot(&reference_relocations)); + } + } + + #[test] + fn common_numeric_and_operand_facades_match_explicit_rust_reference() { + for text in [ + "0", + "-0", + "+0", + "# 42", + " - 17 ", + "0xFF", + "0x+1", + "0b+1", + "0x-1", + "-0x-1", + "0x__+1", + "0x-_1", + "0x-80000000000000000000000000000000", + "-0x-80000000000000000000000000000000", + "0b1010", + "0_1", + "0x__FF", + "170141183460469231731687303715884105727", + "-170141183460469231731687303715884105727", + "170141183460469231731687303715884105728", + "-170141183460469231731687303715884105728", + "", + "#", + "_1", + "--1", + "1_", + "12", + "\u{2003}42\u{0085}", + ] { + let actual = integer(text); + let expected = reference::integer(text); + match (actual, expected) { + (Ok(actual), Ok(expected)) => assert_eq!(actual, expected, "{text:?}"), + (Err(actual), Err(expected)) => { + assert_eq!(actual.to_string(), expected.to_string(), "{text:?}") + }, + _ => panic!("numeric status differs for {text:?}"), + } + for width in [0, 1, 5, 8, 12, 16, 20, 32, 33] { + for unsigned in [false, true] { + let actual = field(text, width, unsigned); + let expected = if unsigned { + reference::unsigned(text, width) + } else { + reference::signed(text, width) + }; + match (actual, expected) { + (Ok(actual), Ok(expected)) => assert_eq!(actual, expected), + (Err(actual), Err(expected)) => assert_eq!( + actual.to_string(), + expected.to_string(), + "{text:?}, {width}" + ), + _ => panic!("field status differs"), + } + } + } + } + for text in [ + "", + "a0,a1,12(sp)", + " [x0, x1], x2 ", + "((a,b)),c", + "a,,b", + "(a]", + "(a", + ",", + "a,", + "\u{2003}a\u{0085},b", + ] { + match (operands(text), reference::operands(text)) { + (Ok(actual), Ok(expected)) => assert_eq!(actual, expected), + (Err(actual), Err(expected)) => { + assert_eq!(actual.to_string(), expected.to_string()) + }, + _ => panic!("operand status differs for {text:?}"), + } + } + } +} diff --git a/meson.build b/meson.build index 74a7467..c81d073 100644 --- a/meson.build +++ b/meson.build @@ -40,9 +40,11 @@ wave_bootstrap = [] needs_wave_bootstrap = asmobj_directory == '' if wave_source != '' needs_wave_bootstrap = needs_wave_bootstrap or get_option('wave-ir-dir') == '' or get_option('wave-assembler-dir') == '' - if get_option('asm-amd64') - needs_wave_bootstrap = needs_wave_bootstrap or get_option('wave-amd64-dir') == '' - endif + foreach arch : ['amd64', 'aarch64', 'riscv64', 'loongarch64'] + if get_option('asm-' + arch) + needs_wave_bootstrap = needs_wave_bootstrap or get_option('wave-' + arch + '-dir') == '' + endif + endforeach endif if needs_wave_bootstrap if wave_source == '' or not fs.is_absolute(wave_source) or not fs.is_dir(wave_source) @@ -102,6 +104,15 @@ endif if wave_amd64_directory != '' build_arguments += ['--wave-amd64-dir', wave_amd64_directory] endif +if wave_aarch64_directory != '' + build_arguments += ['--wave-aarch64-dir', wave_aarch64_directory] +endif +if wave_riscv64_directory != '' + build_arguments += ['--wave-riscv64-dir', wave_riscv64_directory] +endif +if wave_loongarch64_directory != '' + build_arguments += ['--wave-loongarch64-dir', wave_loongarch64_directory] +endif foreach feature : selected_features build_arguments += ['--feature', feature] endforeach diff --git a/meson.options b/meson.options index ff8149f..9033647 100644 --- a/meson.options +++ b/meson.options @@ -17,6 +17,12 @@ option('wave-assembler-dir', type: 'string', value: '', description: 'Absolute directory of the shared Wave assembler archive for the executable host') option('wave-amd64-dir', type: 'string', value: '', description: 'Absolute directory of the Wave AMD64 parser/encoder archive for the executable host') +option('wave-aarch64-dir', type: 'string', value: '', + description: 'Absolute directory of the Wave aarch64 module for the executable host') +option('wave-riscv64-dir', type: 'string', value: '', + description: 'Absolute directory of the Wave riscv64 module for the executable host') +option('wave-loongarch64-dir', type: 'string', value: '', + description: 'Absolute directory of the Wave loongarch64 module for the executable host') option('wave-source', type: 'string', value: '', description: 'Read-only Wave Git checkout containing the pinned bootstrap revision') option('wave-bootstrap-dir', type: 'string', value: '', diff --git a/toolchain/build.rs b/toolchain/build.rs index 66ea28f..7f407e6 100644 --- a/toolchain/build.rs +++ b/toolchain/build.rs @@ -90,10 +90,19 @@ fn main() { let root = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap()).join("../assembler/asmobj"); let mut source = Vec::new(); - for (index, name) in - ["model.wave", "sections.wave", "symbols.wave", "relocations.wave", "entry.wave"] - .iter() - .enumerate() + for (index, name) in [ + "model.wave", + "sections.wave", + "symbols.wave", + "relocations/amd64.wave", + "relocations/aarch64.wave", + "relocations/riscv64.wave", + "relocations/loongarch64.wave", + "relocations.wave", + "entry.wave", + ] + .iter() + .enumerate() { let path = root.join(name); println!("cargo:rerun-if-changed={}", path.display()); diff --git a/tools/build_asmobj.py b/tools/build_asmobj.py index 8148e9c..3dac442 100644 --- a/tools/build_asmobj.py +++ b/tools/build_asmobj.py @@ -9,7 +9,12 @@ import tempfile from wave_bootstrap import DEFAULT_RUST_TOOLCHAIN, RUST_VERSION, WAVE_REVISION, ensure_bootstrap, run, digest -SOURCES = ('model.wave', 'sections.wave', 'symbols.wave', 'relocations.wave', 'entry.wave') +SOURCES = ( + 'model.wave', 'sections.wave', 'symbols.wave', + 'relocations/amd64.wave', 'relocations/aarch64.wave', + 'relocations/riscv64.wave', 'relocations/loongarch64.wave', + 'relocations.wave', 'entry.wave', +) ABI_SOURCE = 'toolchain/src/assembly_object.rs' TARGETS = ('x86_64-unknown-linux-gnu', 'aarch64-unknown-linux-gnu', 'riscv64gc-unknown-linux-gnu', 'x86_64-pc-windows-msvc', diff --git a/tools/build_wave_assembler.py b/tools/build_wave_assembler.py index f16ea14..11ad067 100644 --- a/tools/build_wave_assembler.py +++ b/tools/build_wave_assembler.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 # SPDX-License-Identifier: MPL-2.0 -"""Build the explicit shared or AMD64 Wave assembler module with the pinned compiler, without editing Wave.""" +"""Build the explicit shared or ISA Wave assembler module with the pinned compiler, without editing Wave.""" import argparse import hashlib @@ -21,10 +21,21 @@ 'assembler/numeric.wave', 'assembler/output.wave', 'assembler/lexer.wave', + 'assembler/fixed_model.wave', + 'assembler/fixed_text.wave', + 'assembler/fixed_numbers.wave', + 'assembler/fixed_operands.wave', + 'assembler/fixed_namespace.wave', + 'assembler/fixed_relative.wave', + 'assembler/fixed_scalar.wave', + 'assembler/fixed_source.wave', + 'assembler/fixed_driver.wave', ), 'abi': ( 'assembler/src/tokens.rs', 'assembler/src/tokens_wave.rs', + 'assembler/src/fixed.rs', + 'assembler/src/fixed_wave.rs', ), 'name': 'assembler', }, @@ -64,6 +75,71 @@ ), 'name': 'amd64', }, + 'aarch64': { + 'sources': ( + 'assembler/model.wave', + 'assembler/declarations.wave', + 'assembler/fixed_model.wave', + 'assembler/fixed_declarations.wave', + 'assembler/aarch64/registers.wave', + 'assembler/aarch64/parser.wave', + 'assembler/aarch64/operands.wave', + 'assembler/aarch64/encoding.wave', + 'assembler/aarch64/encoder.wave', + 'assembler/aarch64/entry.wave', + ), + 'abi': ( + 'assembler/aarch64/src/wave.rs', + 'assembler/aarch64/src/lib.rs', + 'assembler/aarch64/src/encoder.rs', + 'assembler/aarch64/src/parser.rs', + ), + 'name': 'aarch64', + }, + 'riscv64': { + 'sources': ( + 'assembler/model.wave', + 'assembler/declarations.wave', + 'assembler/fixed_model.wave', + 'assembler/fixed_declarations.wave', + 'assembler/riscv64/registers.wave', + 'assembler/riscv64/operands.wave', + 'assembler/riscv64/encoding.wave', + 'assembler/riscv64/encoder.wave', + 'assembler/riscv64/parser.wave', + 'assembler/riscv64/entry.wave', + ), + 'abi': ( + 'assembler/riscv64/src/wave.rs', + 'assembler/riscv64/src/lib.rs', + 'assembler/riscv64/src/encoder.rs', + 'assembler/riscv64/src/parser.rs', + ), + 'name': 'riscv64', + }, + 'loongarch64': { + 'sources': ( + 'assembler/model.wave', + 'assembler/declarations.wave', + 'assembler/fixed_model.wave', + 'assembler/fixed_declarations.wave', + 'assembler/loongarch64/model.wave', + 'assembler/loongarch64/registers.wave', + 'assembler/loongarch64/tables.wave', + 'assembler/loongarch64/operands.wave', + 'assembler/loongarch64/formats.wave', + 'assembler/loongarch64/branch.wave', + 'assembler/loongarch64/encoder.wave', + 'assembler/loongarch64/entry.wave', + ), + 'abi': ( + 'assembler/loongarch64/src/wave.rs', + 'assembler/loongarch64/src/lib.rs', + 'assembler/loongarch64/src/encoder.rs', + 'assembler/loongarch64/src/parser.rs', + ), + 'name': 'loongarch64', + }, } TARGETS = ( 'x86_64-unknown-linux-gnu', diff --git a/tools/check_asmobj.py b/tools/check_asmobj.py index de78f60..1ae655c 100644 --- a/tools/check_asmobj.py +++ b/tools/check_asmobj.py @@ -2,7 +2,7 @@ # SPDX-License-Identifier: MPL-2.0 """Compare the compiled asmobj source module with an independent Python oracle. -Build the five explicit Wave sources with the pinned helper, link its object as +Build the explicit Wave role sources with the pinned helper, link its object as a shared library, then pass --library. No Rust asmobj implementation is involved. """ from __future__ import annotations diff --git a/tools/check_wave_fixed.py b/tools/check_wave_fixed.py new file mode 100644 index 0000000..bfe4133 --- /dev/null +++ b/tools/check_wave_fixed.py @@ -0,0 +1,226 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Independent scalar, operand, probe and generic fixed-width driver checks.""" +import argparse +import ctypes as C +from pathlib import Path +import random +import re + +ROOT = Path(__file__).resolve().parents[1] +U, NONE = C.c_uint64, (1 << 64) - 1 +MIN, MAX = -(1 << 127), (1 << 127) - 1 +SPACE = '\t\n\v\f\r \u0085\u00a0\u1680' + ''.join(chr(n) for n in range(0x2000, 0x200B)) + '\u2028\u2029\u202f\u205f\u3000' +TYPES = {'u64': U, 'i64': C.c_int64, 'u8': C.c_uint8, 'bool': C.c_bool} +for name, body in re.findall(r'struct (\w+)\s*\{([^}]+)\}', + (ROOT / 'assembler/fixed_model.wave').read_text()): + fields = [] + for field, kind in re.findall(r'(\w+):\s*([^;]+);', body): + pointer = re.fullmatch(r'ptr<(.+)>', kind) + fields.append((field, C.POINTER(TYPES[pointer[1]]) if pointer else TYPES[kind])) + TYPES[name] = type(name, (C.Structure,), {'_fields_': fields}) +Text, Result = TYPES['FixedText'], TYPES['FixedResult'] + + +def text(value): + data = value.encode() + owner = (C.c_uint8 * len(data)).from_buffer_copy(data) + return Text(owner, len(data)), owner + + +def integer_reference(source): + value = source.strip(SPACE) + if value.startswith('#'): + value = value[1:].strip(SPACE) + negative = value.startswith('-') + if negative or value.startswith('+'): + value = value[1:] + value = value.strip(SPACE) + if not value or value[0] not in '0123456789': + return 2, None + clean = value.replace('_', '') + radix, digits = 10, clean + if clean[:2].lower() == '0x': + radix, digits = 16, clean[2:] + elif clean[:2].lower() == '0b': + radix, digits = 2, clean[2:] + raw = digits[1:] if digits[:1] in ('+', '-') else digits + alphabet = '0123456789abcdef'[:radix] + if not raw or any(ch.lower() not in alphabet for ch in raw): + return 2, None + result = int(digits, radix) + if not MIN <= result <= MAX: + return 2, None + if negative: + result = -result + if not MIN <= result <= MAX: + return 3, None + return 0, result + + +def operands_reference(source): + if not source.strip(SPACE): + return 0, [] + stack, parts, start = [], [], 0 + for at, ch in enumerate(source): + if ch in '[(': + stack.append(ch) + elif ch in '])': + expected = '[' if ch == ']' else '(' + if not stack or stack.pop() != expected: + return 15, None + elif ch == ',' and not stack: + if len(parts) >= 65536: + return 17, None + parts.append(source[start:at].strip(SPACE)) + start = at + 1 + if stack: + return 16, None + parts.append(source[start:].strip(SPACE)) + if len(parts) > 65536: + return 17, None + if any(not part for part in parts): + return 18, None + return 0, parts + + +def scalar_checks(library, cases, rng): + scalar = library.whale_fixed_scalar + scalar.argtypes = [U, C.POINTER(Text), U, C.c_int64, C.c_int64, C.POINTER(Result)] + retained = ['0', '-0', '# +0_xf', '0x-1', '-0x-1', '0x_+_f', '0b-1', + '0x-80000000000000000000000000000000', '-0x-80000000000000000000000000000000', + '-170141183460469231731687303715884105728', '0x+', '0b2', '0x+-1', + '_1', '# #1', '\u2003- 128\u3000', '\x1c1', '12', '0__x10', '1__2_3'] + sources = list(retained) + for _ in range(cases): + number = rng.randrange(MIN-2, MAX+3) + radix = rng.choice([2, 10, 16]) + digits = format(abs(number), {2: 'b', 10: 'd', 16: 'x'}[radix]) + prefix = {2: '0b', 10: '', 16: '0x'}[radix] + if rng.randrange(2): + digits = '_'.join(digits) + sign = '-' if number < 0 else rng.choice(['', '+']) + if radix != 10 and rng.randrange(2): + source = prefix + sign + digits + else: + source = sign + prefix + digits + if rng.randrange(4) == 0: + source = '\u2003# ' + source + '\u3000' + sources.append(source) + for source in sources: + raw, keep = text(source) + expected_error, value = integer_reference(source) + result = Result(max_work=256 * 1024 * 1024) + status = scalar(0, C.byref(raw), 0, 0, 0, C.byref(result)) + assert status == result.status and result.work <= result.max_work + assert result.error == expected_error, (source, result.error, expected_error) + if not expected_error: + assert result.word | result.detail << 64 == value & ((1 << 128)-1), source + for _ in range(cases): + number = rng.randrange(-(1 << 40), 1 << 40) + bits = rng.randrange(0, 35) + raw, keep = text(str(number)) + for mode in [1, 2]: + expected = 4 if bits == 0 or bits > 32 else 0 + if not expected and mode == 1 and not -(1 << (bits-1)) <= number < 1 << (bits-1): + expected = 5 + if not expected and mode == 2 and not 0 <= number < 1 << bits: + expected = 6 + result = Result(max_work=256 * 1024 * 1024) + assert scalar(mode, C.byref(raw), bits, 0, 0, C.byref(result)) == result.status + assert result.error == expected + if not expected: + assert result.word == number & ((1 << bits)-1) + alignment = rng.choice([-1, 0, 1, 2, 4, 8]) + result = Result(max_work=256 * 1024 * 1024) + expected = 7 if bits == 0 or bits > 32 or alignment <= 0 else 0 + if not expected and number % alignment: + expected = 8 + if not expected and not -(1 << (bits-1)) <= number // alignment < 1 << (bits-1): + expected = 9 + assert scalar(3, C.byref(raw), bits, number, alignment, C.byref(result)) == result.status + assert result.error == expected + if not expected: + assert result.word == (number // alignment) & ((1 << bits)-1) + raw, keep = text('1') + result = Result(max_work=0) + assert scalar(0, C.byref(raw), 0, 0, 0, C.byref(result)) == 1 and result.error == 93 + + +def operand_checks(library, cases, rng): + parse = library.whale_fixed_operands + parse.argtypes = [C.POINTER(Text), C.POINTER(Text), U, C.POINTER(U), C.POINTER(Result)] + sources = ['', 'a,b', '[a,(b,c)],d', 'a,,b', '(a,b', 'a],b', ',' + '(' * 90, + '[' * 100 + 'a' + ']' * 100, '[' * 100 + 'a' + ')' * 100, + ','.join(['a'] * 65536), ','.join(['a'] * 65537)] + alphabet = 'abé한0123[](), \t\u2003' + sources += [''.join(rng.choice(alphabet) for _ in range(rng.randrange(80))) + for _ in range(cases)] + for source in sources: + expected, parts = operands_reference(source) + raw, keep = text(source) + result, count = Result(max_work=256 * 1024 * 1024), U() + status = parse(C.byref(raw), None, 0, C.byref(count), C.byref(result)) + assert status == result.status and result.error == expected, (source[:100], result.error, expected) + if expected: + continue + assert count.value == len(parts) + output = (Text * count.value)() + result = Result(max_work=256 * 1024 * 1024) + assert parse(C.byref(raw), output, len(output), C.byref(count), C.byref(result)) == 0 + actual = [C.string_at(value.data, value.count).decode() for value in output] + assert actual == parts, source + if parts: + sentinel = (Text * 1)() + C.memset(sentinel, 0xA5, C.sizeof(sentinel)) + before = bytes(sentinel) + result = Result(max_work=256 * 1024 * 1024) + assert parse(C.byref(raw), sentinel, 0, C.byref(count), C.byref(result)) == 2 + assert bytes(sentinel) == before + + + for source in [' ' * 100, '\u2003' * 100]: + raw, keep = text(source) + result, count = Result(max_work=0), U() + assert parse(C.byref(raw), None, 0, C.byref(count), C.byref(result)) == 1 + assert result.error == 93 + + +def probe_checks(library): + probe = library.whale_fixed_probe + probe.argtypes = [C.POINTER(Text), U, C.POINTER(Result)] + def inspect(source, comments=1): + raw, keep = text(source) + result = Result(max_work=256 * 1024 * 1024) + assert probe(C.byref(raw), comments, C.byref(result)) == 0 + return result + result = inspect('.word ' + ','.join(['0'] * 60000)) + assert (result.symbols, result.records, result.operands, result.relocations) == (0, 1, 60000, 0) + result = inspect('nop\n' * 300000) + assert result.records == result.relocations == 262145 and result.symbols == 0 + assert inspect('; a,b,c\n# x:y,z\n').records == 0 + assert inspect('add x0,x1,#1\n', comments=0).operands >= 3 + result = inspect('.global foo,bar\nfoo: nop\n.extern bar\n.quad foo,0,bar+4') + assert result.symbols >= 4 and result.relocations == 3 + result = inspect('left:right:nop\n.section custom\n.data\n.word 0') + assert result.sections == 3 and result.symbols >= 2 and result.records == 2 + raw, keep = text(';' * (8 * 1024 * 1024 + 1)) + result = Result(max_work=256 * 1024 * 1024) + assert probe(C.byref(raw), 1, C.byref(result)) == 1 and result.error == 41 + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--library', type=Path, required=True) + parser.add_argument('--cases', type=int, default=10000) + args = parser.parse_args() + library = C.CDLL(str(args.library.resolve())) + rng = random.Random(0x5748414C45465836) + scalar_checks(library, args.cases, rng) + operand_checks(library, args.cases, rng) + probe_checks(library) + print(f'Wave fixed core: {args.cases} integer literals + {args.cases * 3} immediate/displacement vectors + {args.cases} operand streams, radix-sign quirks, Unicode trim, probe/resource and transactional-capacity regressions passed') + + +if __name__ == '__main__': + main() diff --git a/tools/check_wave_loongarch64.py b/tools/check_wave_loongarch64.py new file mode 100644 index 0000000..e0b293e --- /dev/null +++ b/tools/check_wave_loongarch64.py @@ -0,0 +1,211 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Independent LLVM fixtures and mathematical LoongArch64 integer encodings.""" +import argparse +import ctypes as C +from pathlib import Path +import random +import re + +ROOT = Path(__file__).resolve().parents[1] +U = C.c_uint64 +NONE = (1 << 64) - 1 +TYPES = {'u64': U, 'i64': C.c_int64, 'u8': C.c_uint8, 'bool': C.c_bool} +for name, body in re.findall(r'struct (\w+)\s*\{([^}]+)\}', + (ROOT / 'assembler/fixed_model.wave').read_text()): + fields = [] + for field, kind in re.findall(r'(\w+):\s*([^;]+);', body): + pointer = re.fullmatch(r'ptr<(.+)>', kind) + fields.append((field, C.POINTER(TYPES[pointer[1]]) if pointer else TYPES[kind])) + TYPES[name] = type(name, (C.Structure,), {'_fields_': fields}) +Text, Instruction, Context, Result = [TYPES[n] for n in + ['FixedText', 'FixedInstruction', 'FixedContext', 'FixedResult']] + + +def text(value): + data = value.encode() + buffer = (C.c_uint8 * len(data)).from_buffer_copy(data) + return Text(buffer, len(data)), buffer + + +def execute(kernel, source, fold=0, max_work=10000000): + mnemonic, _, tail = source.partition(' ') + operands = [operand.strip() for operand in tail.split(',')] if tail.strip() else [] + name, keep = text(mnemonic) + values = [text(operand) for operand in operands] + array = (Text * len(values))(*(value for value, _ in values)) + instruction = Instruction(name, array, len(array), fold) + namespace, namespace_keep = text('loongarch64') + table = (U * 2)(NONE, NONE) + relocations = (TYPES['FixedRelocation'] * 4)() + context = Context(namespace=namespace, table=table, table_capacity=2, + relocations=relocations, relocation_capacity=4) + result = Result(max_work=max_work) + code = kernel(C.byref(instruction), C.byref(context), C.byref(result)) + assert code == result.status and result.work <= result.max_work + return result + + +def assemble(library, source, limit=1000000): + encoded, keep = text(source) + namespace, namespace_keep = text('loongarch64') + result = Result(max_work=256 * 1024 * 1024) + probe = library.whale_fixed_probe + probe.argtypes = [C.POINTER(Text), U, C.POINTER(Result)] + code = probe(C.byref(encoded), 1, C.byref(result)) + assert code == result.status + if code: + return result, {}, b'' + values = {} + packet = TYPES['FixedInput'](source=encoded, namespace=namespace, hash_comments=1, + max_output=limit, max_passes=1024, + max_work=result.max_work-result.work) + symbols = result.symbols + table_capacity = 1 << max(1, (symbols * 2 - 1).bit_length()) + for field, name, count in [ + ('sections', 'FixedSection', result.sections), ('symbols', 'FixedSymbol', symbols), + ('globals', 'FixedGlobal', symbols), ('records', 'FixedRecord', result.records), + ('operands', 'FixedText', result.operands), + ('relocations', 'FixedRelocation', result.relocations), + ]: + array = (TYPES[name] * count)() + values[field] = array + setattr(packet, field, array) + setattr(packet, field[:-1] + '_capacity', count) + values['table'], values['order'] = (U * table_capacity)(), (U * symbols)() + packet.table, packet.table_capacity = values['table'], table_capacity + packet.order, packet.order_capacity = values['order'], symbols + entry = library.whale_loongarch64_assemble + entry.argtypes = [C.POINTER(TYPES['FixedInput']), C.POINTER(Result)] + result = Result() + code = entry(C.byref(packet), C.byref(result)) + assert code == result.status + if code: + return result, values, b'' + size = result.bytes + values['bytes'] = (C.c_uint8 * size)() + packet.bytes, packet.byte_capacity, packet.mode = values['bytes'], size, 1 + packet.max_work -= result.work + code = entry(C.byref(packet), C.byref(result)) + assert code == result.status == 0, (source, code, result.error) + return result, values, bytes(values['bytes']) + + +def expected_branch(opcode, register_a, register_b, displacement, bits): + assert displacement % 4 == 0 + immediate = (displacement // 4) & ((1 << bits) - 1) + if bits == 26: + return opcode | (immediate & 0xFFFF) << 10 | immediate >> 16 + if bits == 21: + return opcode | register_a << 5 | (immediate & 0xFFFF) << 10 | immediate >> 16 + return opcode | register_b | register_a << 5 | immediate << 10 + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--library', type=Path, required=True) + parser.add_argument('--cases', type=int, default=10000) + args = parser.parse_args() + library = C.CDLL(str(args.library.resolve())) + kernel = library.whale_loongarch64_encode + kernel.argtypes = [C.POINTER(Instruction), C.POINTER(Context), C.POINTER(Result)] + fixtures = 0 + for line in (ROOT / 'assembler/loongarch64/tests/fixtures/encodings.tsv').read_text().splitlines(): + if not line or line.startswith('#'): + continue + encoded, source = line.split('\t') + result = execute(kernel, source) + assert result.status == 0, (source, result.error) + assert result.word == int.from_bytes(bytes.fromhex(encoded), 'little'), source + fixtures += 1 + for source, error in [ + ('ld.d BAD,$r0,99999', 3000), ('slli.d BAD,$r0,99999', 3000), + ('lu12i.w BAD,524288', 3001), ('jirl BAD,BAD,18446744073709551616', 3002), + ('li.d BAD,99999', 3000), ('ADD.D $r0,$r0,$r0', 3003), + ]: + result = execute(kernel, source) + assert result.status and result.error == error, (source, result.error, error) + assert execute(kernel, 'ADD.D $R0,$R1,$R2', fold=1).word == 0x00108820 + for register in ['r+1', 'r-1', 'r00', 'r01', 'r031', 'r32', '$$sp', 'r1', '']: + result = execute(kernel, f'move {register},$r0') + assert result.status and result.error == 3000, (register, result.error) + for offset in [-(1 << 27), -4, 0, (1 << 27) - 4]: + result = execute(kernel, f'b {offset}') + assert result.status == 0 and result.word == expected_branch(0x50000000, 0, 0, offset, 26) + for opcode, name, bits, registers in [ + (0x50000000, 'b', 26, ''), (0x54000000, 'bl', 26, ''), + (0x58000000, 'beq', 16, '$r1,$r2,'), + (0x40000000, 'beqz', 21, '$r1,'), + (0x4C000000, 'jirl', 16, '$r2,$r1,'), + ]: + for offset in [-(1 << (bits+1))-4, 1 << (bits+1), -2, 2]: + result = execute(kernel, f'{name} {registers}{offset}') + assert result.status, (name, offset) + assert execute(kernel, 'nop', max_work=0).status + for source, expected in [ + ('NOP\nret', bytes.fromhex('000040032000004c')), + ('.data\n.byte -1,255\n.short 65535\n.long 4294967295\n.quad -1', b'\xff' * 16), + ('here: b here', bytes.fromhex('00000050')), + ('.data\n.byte 1,2\n.short 0x1234\n.long 0x12345678\n.quad 0x0123456789abcdef', bytes.fromhex('0102341278563412efcdab8967452301')), + ('.bss\n.zero 1099511627776\n.balign 4096\n.text\nret', bytes.fromhex('2000004c')), + ]: + result, arrays, data = assemble(library, source) + assert result.status == 0 and data == expected, (source, result.error, data) + for source, error in [('.global missing\nINVALID', 74), ('here: here: nop', 71), + ('.text\n.byte 0\nnop', 35), ('.bss\n.word 0', 34), + ('.data\n.byte 256', 79), ('.quad missing', 13)]: + result, arrays, data = assemble(library, source) + assert result.status and result.error == error, (source, result.error, error) + result, arrays, data = assemble(library, '.global start\nstart: nop\nbl external+8\n.extern external\n.data\n.quad start+4') + assert result.status == 0 and data == bytes.fromhex('0000400300000054') + b'\0' * 8 + assert result.relocations == 2 + branch, absolute = arrays['relocations'][:2] + assert (branch.section, branch.offset, branch.code, branch.addend) == (0, 4, 66, 8) + assert (absolute.section, absolute.offset, absolute.code, absolute.addend) == (1, 0, NONE-1, 4) + numeric = '.word ' + ','.join(['0'] * 60000) + raw, raw_keep = text(numeric) + probe_result = Result(max_work=256 * 1024 * 1024) + assert library.whale_fixed_probe(C.byref(raw), 1, C.byref(probe_result)) == 0 + assert (probe_result.symbols, probe_result.records, probe_result.operands, probe_result.relocations) == (0, 1, 60000, 0) + result, arrays, data = assemble(library, numeric) + assert result.status == 0 and data == b'\0' * 240000 + raw, raw_keep = text('nop\n' * 300000) + probe_result = Result(max_work=256 * 1024 * 1024) + assert library.whale_fixed_probe(C.byref(raw), 1, C.byref(probe_result)) == 0 + assert probe_result.records == probe_result.relocations == 262145 + result, arrays, data = assemble(library, 'nop\n' * 300000, limit=2000000) + assert result.status and result.error == 78 + result, arrays, data = assemble(library, 'nop', limit=0) + assert result.status and result.error == 77 + result, arrays, data = assemble(library, '.bss\n.zero 1099511627776', limit=0) + assert result.status == 0 and result.bytes == 0 and arrays['sections'][1].size == 1 << 40 + for index, alias in enumerate(['zero', 'ra', 'tp', 'sp', 'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 't0', 't1', 't2', 't3', 't4', 't5', 't6', 't7', 't8', 'u0', 'fp', 's0', 's1', 's2', 's3', 's4', 's5', 's6', 's7', 's8']): + for spelling in [alias, '$'+alias, '$'+alias.upper()]: + result = execute(kernel, f'move {spelling},$r0') + assert result.status == 0 and result.word == 0x00150000 | index + rng = random.Random(0x5748414C454C4136) + for _ in range(args.cases): + rd, rj, rk = [rng.randrange(32) for _ in range(3)] + displacement = rng.randrange(-(1 << 25), 1 << 25) * 4 + source = f'b {displacement}' + result = execute(kernel, source) + assert result.status == 0 and result.word == expected_branch(0x50000000, 0, 0, displacement, 26) + displacement = rng.randrange(-(1 << 15), 1 << 15) * 4 + result = execute(kernel, f'beq $r{rj},$r{rd},{displacement}') + assert result.status == 0 and result.word == expected_branch(0x58000000, rj, rd, displacement, 16) + displacement = rng.randrange(-(1 << 20), 1 << 20) * 4 + result = execute(kernel, f'bnez $r{rj},{displacement}') + assert result.status == 0 and result.word == expected_branch(0x44000000, rj, 0, displacement, 21) + immediate = rng.randrange(-2048, 2048) + result = execute(kernel, f'addi.d $r{rd},$r{rj},{immediate}') + assert result.status == 0 and result.word == 0x02C00000 | rd | rj << 5 | (immediate & 4095) << 10 + for mnemonic, opcode in [('li.w', 0x02800000), ('li.d', 0x02C00000)]: + result = execute(kernel, f'{mnemonic} $r{rd},{immediate}') + assert result.status == 0 and result.word == opcode | rd | (immediate & 4095) << 10 + result = execute(kernel, f'xor $r{rd},$r{rj},$r{rk}') + assert result.status == 0 and result.word == 0x00158000 | rd | rj << 5 | rk << 10 + print(f'Wave LoongArch64: {fixtures} LLVM fixtures + {args.cases * 7} independent split-field/integer vectors, invalid registers, exact validation precedence and work limits passed') + + +if __name__ == '__main__': + main() diff --git a/tools/check_wave_riscv64.py b/tools/check_wave_riscv64.py new file mode 100755 index 0000000..c679739 --- /dev/null +++ b/tools/check_wave_riscv64.py @@ -0,0 +1,383 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Independent RV64I native scalar, operand and instruction conformance.""" + +import argparse +import ctypes as c +import itertools +import random + + +class Text(c.Structure): + _fields_ = [("data", c.POINTER(c.c_uint8)), ("count", c.c_uint64)] + + +class Instruction(c.Structure): + _fields_ = [ + ("mnemonic", Text), + ("operands", c.POINTER(Text)), + ("count", c.c_uint64), + ("fold", c.c_uint64), + ] + + +class Symbol(c.Structure): + _fields_ = [("name", Text)] + [ + (field, c.c_uint64) for field in ("section", "offset", "start", "end", "line", "flags") + ] + + +class Relocation(c.Structure): + _fields_ = [(field, c.c_uint64) for field in ("section", "offset", "symbol", "code")] + [ + ("addend", c.c_int64) + ] + + +class Context(c.Structure): + _fields_ = [ + ("source", Text), + ("namespace", Text), + ("symbols", c.POINTER(Symbol)), + ("symbol_count", c.c_uint64), + ("table", c.POINTER(c.c_uint64)), + ("table_capacity", c.c_uint64), + ("section", c.c_uint64), + ("offset", c.c_uint64), + ("relocations", c.POINTER(Relocation)), + ("relocation_count", c.c_uint64), + ("relocation_capacity", c.c_uint64), + ] + + +class Result(c.Structure): + _fields_ = [ + (field, c.c_uint64) + for field in ( + "status", + "error", + "start", + "end", + "line", + "previous_start", + "previous_end", + "previous_line", + ) + ] + _fields_ += [("text", Text)] + _fields_ += [ + (field, c.c_uint64) + for field in ( + "detail", + "display", + "word", + "sections", + "symbols", + "relocations", + "records", + "operands", + "bytes", + "work", + "max_work", + ) + ] + + +ALIASES = [ + "zero", + "ra", + "sp", + "gp", + "tp", + "t0", + "t1", + "t2", + "s0", + "s1", + "a0", + "a1", + "a2", + "a3", + "a4", + "a5", + "a6", + "a7", + "s2", + "s3", + "s4", + "s5", + "s6", + "s7", + "s8", + "s9", + "s10", + "s11", + "t3", + "t4", + "t5", + "t6", +] +REGISTER = { + "add": (51, 0, 0), + "sub": (51, 0, 32), + "sll": (51, 1, 0), + "slt": (51, 2, 0), + "sltu": (51, 3, 0), + "xor": (51, 4, 0), + "srl": (51, 5, 0), + "sra": (51, 5, 32), + "or": (51, 6, 0), + "and": (51, 7, 0), + "addw": (59, 0, 0), + "subw": (59, 0, 32), + "sllw": (59, 1, 0), + "srlw": (59, 5, 0), + "sraw": (59, 5, 32), +} +IMMEDIATE = { + "addi": (19, 0), + "slti": (19, 2), + "sltiu": (19, 3), + "xori": (19, 4), + "ori": (19, 6), + "andi": (19, 7), + "addiw": (27, 0), +} +BRANCH = {"beq": 0, "bne": 1, "blt": 4, "bge": 5, "bltu": 6, "bgeu": 7} +LOAD = {"lb": 0, "lh": 1, "lw": 2, "ld": 3, "lbu": 4, "lhu": 5, "lwu": 6} +STORE = {"sb": 0, "sh": 1, "sw": 2, "sd": 3} +MASK32 = (1 << 32) - 1 + + +def r(opcode, f3, f7, rd, rs1, rs2): + return opcode | rd << 7 | f3 << 12 | rs1 << 15 | rs2 << 20 | f7 << 25 + + +def i(opcode, f3, rd, rs1, immediate): + return opcode | rd << 7 | f3 << 12 | rs1 << 15 | (immediate & 4095) << 20 + + +def jump(rd, displacement): + value = displacement & ((1 << 21) - 1) + return ( + 111 + | rd << 7 + | (value >> 20) << 31 + | ((value >> 1) & 1023) << 21 + | ((value >> 11) & 1) << 20 + | ((value >> 12) & 255) << 12 + ) + + +def branch(f3, rs1, rs2, displacement): + value = displacement & 8191 + return ( + 99 + | ((value >> 11) & 1) << 7 + | ((value >> 1) & 15) << 8 + | f3 << 12 + | rs1 << 15 + | (rs2 << 20) + | ((value >> 5) & 63) << 25 + | (value >> 12) << 31 + ) + + +class Native: + def __init__(self, path): + self.lib = c.CDLL(path) + self.lib.whale_riscv64_instruction.argtypes = [ + c.POINTER(Instruction), + c.POINTER(Context), + c.POINTER(Result), + ] + self.lib.whale_riscv64_operand.argtypes = [c.c_uint64, c.POINTER(Text), c.POINTER(Result)] + self.lib.whale_riscv64_branch.argtypes = [c.c_uint64] * 4 + [c.c_int64, c.POINTER(Result)] + self.count = 0 + + @staticmethod + def text(value): + data = value.encode() + buffer = (c.c_uint8 * len(data))(*data) + return Text(buffer, len(data)), buffer + + def instruction(self, mnemonic, operands, expected, fold=0): + texts = [self.text(value) for value in [mnemonic, *operands]] + raw = (Text * len(operands))(*(text for text, _ in texts[1:])) + instruction = Instruction(texts[0][0], raw, len(operands), fold) + table = (c.c_uint64 * 2)((1 << 64) - 1, (1 << 64) - 1) + relocs = (Relocation * 2)() + context = Context(table=table, table_capacity=2, relocations=relocs, relocation_capacity=2) + result = Result(max_work=1_000_000) + status = self.lib.whale_riscv64_instruction( + c.byref(instruction), c.byref(context), c.byref(result) + ) + self.count += 1 + if expected is None: + assert status != 0 and result.status == status, (mnemonic, operands, result.error) + else: + assert status == 0 and result.status == 0 and result.word == expected & MASK32, ( + mnemonic, + operands, + status, + result.error, + hex(result.word), + hex(expected), + ) + + def operand(self, mode, value, expected): + text, buffer = self.text(value) + result = Result() + status = self.lib.whale_riscv64_operand(mode, c.byref(text), c.byref(result)) + self.count += 1 + if expected is None: + assert status != 0 and result.status == status, (mode, value, result.error) + else: + assert status == 0 and (result.word, result.detail) == expected, ( + mode, + value, + status, + result.error, + result.word, + result.detail, + ) + assert buffer is not None + + +def boundaries(native): + for code, alias in enumerate(ALIASES): + for name in [alias, alias.upper(), f"x{code}", f"X{code}", f"\u2003{alias}\u0085"]: + native.operand(0, name, (code, 0)) + native.operand(0, "fp", (8, 0)) + for name in ["x00", "x01", "x031", "x+1", "x-0", "x-1", "x32", "x1", "$ra", "", "a8"]: + native.operand(0, name, None) + for offset in [-2049, -2048, -1, 0, 2047, 2048]: + native.operand(1, f"{offset}(sp)", (2, offset & 4095) if -2048 <= offset <= 2047 else None) + native.operand(1, "(sp)", (2, 0)) + for memory in ["4((sp))", "4(sp))", "4(sp", "4(x32)", "4(x+1)", "4(x01)", "4(sp) "]: + native.operand(1, memory, None) + for length in range(5): + for flags in itertools.permutations("iorw", length): + spelling = "".join(flags) + mask = sum({"i": 8, "o": 4, "r": 2, "w": 1}[flag] for flag in flags) + native.operand(2, spelling, (mask, 0)) + native.operand(2, "0", (0, 0)) + for bad in ["rr", "ii", "rwz", "RW", "0r", "r0", "00", "+0", "-0", "0x0"]: + native.operand(2, bad, None) + for mnemonic, f3 in BRANCH.items(): + for value in [-4098, -4096, -2, -1, 0, 1, 4094, 4096]: + native.instruction( + mnemonic, + ["x1", "x31", str(value)], + branch(f3, 1, 31, value) if -4096 <= value <= 4094 and value % 2 == 0 else None, + ) + for value in [-(1 << 20) - 2, -(1 << 20), -2, -1, 0, 1, (1 << 20) - 2, 1 << 20]: + expected = jump(1, value) if -(1 << 20) <= value < 1 << 20 and value % 2 == 0 else None + native.instruction("jal", ["ra", str(value)], expected) + for mnemonic, (op, f3) in IMMEDIATE.items(): + for value in [-2049, -2048, -1, 0, 2047, 2048, 1 << 127]: + native.instruction( + mnemonic, + ["a0", "a1", str(value)], + i(op, f3, 10, 11, value) if -2048 <= value <= 2047 else None, + ) + for mnemonic, opcode in [("lui", 55), ("auipc", 23)]: + for value in [-1, 0, 1048575, 1048576]: + native.instruction( + mnemonic, + ["a0", str(value)], + opcode | 10 << 7 | value << 12 if 0 <= value < 1 << 20 else None, + ) + for mnemonic in ["slli", "srli", "srai", "slliw", "srliw", "sraiw"]: + word = mnemonic.endswith("w") + for count in [-1, 0, 31, 32, 63, 64]: + expected = None + if 0 <= count < (32 if word else 64): + immediate = count | (1024 if mnemonic.startswith("sra") else 0) + expected = i( + 27 if word else 19, 1 if mnemonic.startswith("sll") else 5, 10, 11, immediate + ) + native.instruction(mnemonic, ["a0", "a1", str(count)], expected) + for name, expected in [("nop", 19), ("ret", 32871), ("ecall", 115), ("ebreak", 1048691)]: + native.instruction(name, [], expected) + native.instruction(name, ["x1"], None) + for name, expected in [ + ("mv", i(19, 0, 10, 11, 0)), + ("not", i(19, 4, 10, 11, 4095)), + ("neg", r(51, 0, 32, 10, 0, 11)), + ("negw", r(59, 0, 32, 10, 0, 11)), + ]: + native.instruction(name, ["a0", "a1"], expected) + native.instruction("fence", [], 0x0FF0000F) + native.instruction("fence", ["rw", "0"], 0x0300000F) + native.instruction("fence", ["RW", "0"], None) + native.instruction("ADD", ["a0", "a1", "a2"], r(51, 0, 0, 10, 11, 12), fold=1) + native.instruction("ADD", ["a0", "a1", "a2"], None) + for extension in ["mul", "fadd.d", "c.add", "lr.d", "amoadd.d", "vadd.vv"]: + native.instruction(extension, ["a0", "a1", "a2"], None) + + +def generated(native, count): + rng = random.Random(0x359) + for _ in range(count): + rd, rs1, rs2 = (rng.randrange(32) for _ in range(3)) + family = rng.randrange(5) + if family == 0: + mnemonic = rng.choice(list(REGISTER)) + op, f3, f7 = REGISTER[mnemonic] + native.instruction( + mnemonic, [f"x{rd}", f"x{rs1}", f"x{rs2}"], r(op, f3, f7, rd, rs1, rs2) + ) + elif family == 1: + mnemonic = rng.choice(list(IMMEDIATE)) + op, f3 = IMMEDIATE[mnemonic] + immediate = rng.randrange(-2048, 2048) + native.instruction( + mnemonic, [f"x{rd}", f"x{rs1}", str(immediate)], i(op, f3, rd, rs1, immediate) + ) + elif family == 2: + mnemonic = rng.choice(list(LOAD)) + immediate = rng.randrange(-2048, 2048) + native.instruction( + mnemonic, + [f"x{rd}", f"{immediate}(x{rs1})"], + i(3, LOAD[mnemonic], rd, rs1, immediate), + ) + elif family == 3: + mnemonic = rng.choice(list(STORE)) + immediate = rng.randrange(-2048, 2048) & 4095 + expected = ( + 35 + | (immediate & 31) << 7 + | STORE[mnemonic] << 12 + | rs1 << 15 + | rs2 << 20 + | (immediate >> 5) << 25 + ) + native.instruction( + mnemonic, + [f"x{rs2}", f"{immediate if immediate < 2048 else immediate - 4096}(x{rs1})"], + expected, + ) + else: + mnemonic = rng.choice(list(BRANCH)) + displacement = rng.randrange(-2048, 2048) * 2 + native.instruction( + mnemonic, + [f"x{rs1}", f"x{rs2}", str(displacement)], + branch(BRANCH[mnemonic], rs1, rs2, displacement), + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", required=True) + parser.add_argument("--cases", type=int, default=100_000) + args = parser.parse_args() + native = Native(args.library) + boundaries(native) + generated(native, args.cases) + print(f"Wave RV64I: {native.count} independent instruction/operand mathematical vectors passed") + + +if __name__ == "__main__": + main() diff --git a/tools/meson_cargo.py b/tools/meson_cargo.py index ff8a956..e46490e 100644 --- a/tools/meson_cargo.py +++ b/tools/meson_cargo.py @@ -37,12 +37,17 @@ def validate_features(features): def cargo_environment(target_dir, asmobj_directory, profile, optimization, debug_info, wave_ir_directory=None, wave_assembler_directory=None, - wave_amd64_directory=None): + wave_amd64_directory=None, wave_aarch64_directory=None, + wave_riscv64_directory=None, wave_loongarch64_directory=None): environment = os.environ.copy() environment.pop("WHALE_ASMOBJ_DIR", None) environment.pop("WHALE_WAVE_IR_DIR", None) environment.pop("WHALE_WAVE_ASSEMBLER_DIR", None) environment.pop("WHALE_WAVE_AMD64_DIR", None) + environment.pop("WHALE_WAVE_AARCH64_DIR", None) + environment.pop("WHALE_WAVE_RISCV64_DIR", None) + environment.pop("WHALE_WAVE_LOONGARCH64_DIR", None) + environment.pop("CARGO_BUILD_TARGET", None) environment["CARGO_TARGET_DIR"] = str(target_dir) environment["CARGO_INCREMENTAL"] = "0" @@ -57,6 +62,12 @@ def cargo_environment(target_dir, asmobj_directory, profile, optimization, debug environment["WHALE_WAVE_ASSEMBLER_DIR"] = str(wave_assembler_directory) if wave_amd64_directory: environment["WHALE_WAVE_AMD64_DIR"] = str(wave_amd64_directory) + if wave_aarch64_directory: + environment["WHALE_WAVE_AARCH64_DIR"] = str(wave_aarch64_directory) + if wave_riscv64_directory: + environment["WHALE_WAVE_RISCV64_DIR"] = str(wave_riscv64_directory) + if wave_loongarch64_directory: + environment["WHALE_WAVE_LOONGARCH64_DIR"] = str(wave_loongarch64_directory) return environment @@ -202,6 +213,24 @@ def build(arguments): amd64_path = getattr(arguments, "wave_amd64_dir", None) wave_assembler_directory = shared_path.resolve() if shared_path else None wave_amd64_directory = amd64_path.resolve() if amd64_path else None + aarch64_path = getattr(arguments, "wave_aarch64_dir", None) + wave_aarch64_directory = aarch64_path.resolve() if aarch64_path else None + if wave_aarch64_directory and "asm-aarch64" not in features: + raise BuildError("a Wave aarch64 archive requires its selected assembler output") + if wave_aarch64_directory and not wave_assembler_directory: + raise BuildError("a Wave ISA archive requires the shared Wave assembler archive") + riscv64_path = getattr(arguments, "wave_riscv64_dir", None) + wave_riscv64_directory = riscv64_path.resolve() if riscv64_path else None + if wave_riscv64_directory and "asm-riscv64" not in features: + raise BuildError("a Wave riscv64 archive requires its selected assembler output") + if wave_riscv64_directory and not wave_assembler_directory: + raise BuildError("a Wave ISA archive requires the shared Wave assembler archive") + loongarch64_path = getattr(arguments, "wave_loongarch64_dir", None) + wave_loongarch64_directory = loongarch64_path.resolve() if loongarch64_path else None + if wave_loongarch64_directory and "asm-loongarch64" not in features: + raise BuildError("a Wave loongarch64 archive requires its selected assembler output") + if wave_loongarch64_directory and not wave_assembler_directory: + raise BuildError("a Wave ISA archive requires the shared Wave assembler archive") if wave_amd64_directory and "asm-amd64" not in features: raise BuildError("a Wave AMD64 archive requires the AMD64 product output") if wave_amd64_directory and not wave_assembler_directory: @@ -210,7 +239,9 @@ def build(arguments): raise BuildError("Meson requires its own private Cargo target directory") environment = cargo_environment(target_dir, asmobj_directory, arguments.profile, arguments.opt_level, arguments.debug_info, - wave_ir_directory, wave_assembler_directory, wave_amd64_directory) + wave_ir_directory, wave_assembler_directory, wave_amd64_directory, + wave_aarch64_directory, wave_riscv64_directory, + wave_loongarch64_directory) target = arguments.host_target or native_target(arguments.cargo, source, environment) if not TRIPLE.fullmatch(target): raise BuildError("cargo host target must be a Rust target triple") @@ -231,7 +262,9 @@ def build(arguments): if wave_ir_directory: archive = "whale_wave_ir.lib" if "msvc" in target else "libwhale_wave_ir.a" dependencies.update(wave_ir_directory / name for name in [archive, "wave-ir.meta", "provenance.json"]) - for name, directory in [("assembler", wave_assembler_directory), ("amd64", wave_amd64_directory)]: + for name, directory in [("assembler", wave_assembler_directory), ("amd64", wave_amd64_directory), + ("aarch64", wave_aarch64_directory), ("riscv64", wave_riscv64_directory), + ("loongarch64", wave_loongarch64_directory)]: if directory: archive = f"whale_wave_{name}.lib" if "msvc" in target else f"libwhale_wave_{name}.a" dependencies.update(directory / file for file in @@ -342,6 +375,9 @@ def main(argv=None): compile_parser.add_argument("--wave-ir-dir", type=Path) compile_parser.add_argument("--wave-assembler-dir", type=Path) compile_parser.add_argument("--wave-amd64-dir", type=Path) + compile_parser.add_argument("--wave-aarch64-dir", type=Path) + compile_parser.add_argument("--wave-riscv64-dir", type=Path) + compile_parser.add_argument("--wave-loongarch64-dir", type=Path) smoke_parser = commands.add_parser("smoke") smoke_parser.add_argument("--binary", type=Path, required=True) smoke_parser.add_argument("--feature", action="append", default=[]) diff --git a/tools/test_build_asmobj.py b/tools/test_build_asmobj.py index e3c949a..7558df8 100644 --- a/tools/test_build_asmobj.py +++ b/tools/test_build_asmobj.py @@ -218,6 +218,7 @@ def make_project(root, target=NATIVE): sources = root / "assembler/asmobj" sources.mkdir(parents=True) for index, name in enumerate(helper.SOURCES): + (sources / name).parent.mkdir(parents=True, exist_ok=True) (sources / name).write_bytes(f"source {index}: {name}\n".encode()) archive_dir = root / "archive" archive_dir.mkdir() @@ -275,7 +276,7 @@ def run_guard(self, corruption=None, *, enabled=True, target=NATIVE): environment["WHALE_ASMOBJ_DIR"] = str(archive_dir) return subprocess.run([str(self.guard)], env=environment, capture_output=True, text=True) - def test_matching_guard_watches_all_five_sources_and_published_artifacts(self): + def test_matching_guard_watches_all_sources_and_published_artifacts(self): result = self.run_guard() self.assertEqual(result.returncode, 0, result.stderr) for name in (*helper.SOURCES, "asmobj.meta", "provenance.json", "libwhale_asmobj.a", @@ -306,6 +307,21 @@ def test_mismatched_or_invalid_artifacts_fail_before_link_selection(self): self.assertNotIn("cargo:rustc-link-lib", result.stdout) self.assertNotIn("cargo:rustc-cfg=whale_asmobj", result.stdout) + def test_each_isa_relocation_source_invalidates_the_guard(self): + for name in helper.SOURCES: + if "/" not in name: + continue + with self.subTest(source=name), tempfile.TemporaryDirectory() as temporary: + manifest, sources, archive_dir, _, _ = self.make_project(Path(temporary).resolve()) + (sources / name).write_bytes(b"changed architecture mapping") + environment = os.environ.copy() + environment.update(CARGO_MANIFEST_DIR=str(manifest), HOST=NATIVE, TARGET=NATIVE, + WHALE_ASMOBJ_DIR=str(archive_dir)) + result = subprocess.run([str(self.guard)], env=environment, capture_output=True, text=True) + self.assertNotEqual(result.returncode, 0) + self.assertIn("stale asmobj archive", result.stderr) + self.assertNotIn("cargo:rustc-link-lib", result.stdout) + def test_plain_cargo_build_needs_neither_compiler_nor_wave_artifact(self): result = self.run_guard("missing-metadata", enabled=False) self.assertEqual(result.returncode, 0, result.stderr) @@ -384,6 +400,7 @@ def test_autocrlf_checkout_preserves_wave_source_fingerprint(self): abi.parent.mkdir(parents=True) shutil.copyfile(ROOT / ".gitattributes", root / ".gitattributes") for name in helper.SOURCES: + (sources / name).parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(ROOT / "assembler/asmobj" / name, sources / name) shutil.copyfile(ROOT / helper.ABI_SOURCE, abi) original = helper.source_bytes(root) @@ -409,9 +426,9 @@ def test_autocrlf_checkout_preserves_wave_source_fingerprint(self): self.assertNotIn(b"\r\n", abi.read_bytes()) self.assertEqual(abi.read_bytes(), original_abi) - def test_asmobj_is_a_complete_wave_module_with_five_role_files(self): + def test_asmobj_is_a_complete_wave_module_with_isa_owned_role_files(self): module = ROOT / "assembler/asmobj" - self.assertEqual(sorted(path.name for path in module.glob("*.wave")), sorted(helper.SOURCES)) + self.assertEqual(sorted(path.relative_to(module).as_posix() for path in module.rglob("*.wave")), sorted(helper.SOURCES)) self.assertEqual(list(module.rglob("*.rs")), []) self.assertFalse((module / "Cargo.toml").exists()) for directory in ("assembler", "object", "reverse", "ir", "toolchain", "src"): diff --git a/tools/test_build_wave_assembler.py b/tools/test_build_wave_assembler.py index 2a17c40..183f23f 100644 --- a/tools/test_build_wave_assembler.py +++ b/tools/test_build_wave_assembler.py @@ -21,7 +21,8 @@ class PublicationTests(unittest.TestCase): def test_all_owned_wave_roles_are_in_the_explicit_build_lists(self): owned = {path.relative_to(ROOT).as_posix() - for directory in (ROOT / "assembler", ROOT / "assembler/amd64") + for directory in (ROOT / "assembler", *(ROOT / "assembler" / name + for name in helper.MODULES if name != "common")) for path in directory.glob("*.wave")} configured = {file for config in helper.MODULES.values() for file in config["sources"]} self.assertEqual(owned, configured) diff --git a/tools/test_meson_build.py b/tools/test_meson_build.py index b281b0f..35d3ad2 100644 --- a/tools/test_meson_build.py +++ b/tools/test_meson_build.py @@ -35,12 +35,18 @@ def test_ambient_wave_and_cargo_target_cannot_change_selection(self): with patch.dict(os.environ, {"WHALE_ASMOBJ_DIR": "old", "WHALE_WAVE_IR_DIR": "old", "WHALE_WAVE_ASSEMBLER_DIR": "old", "WHALE_WAVE_AMD64_DIR": "old", + "WHALE_WAVE_AARCH64_DIR": "old", + "WHALE_WAVE_RISCV64_DIR": "old", + "WHALE_WAVE_LOONGARCH64_DIR": "old", "CARGO_BUILD_TARGET": "old"}): environment = cargo_environment("private", None, "dev", "2", "2") self.assertNotIn("WHALE_ASMOBJ_DIR", environment) self.assertNotIn("WHALE_WAVE_IR_DIR", environment) self.assertNotIn("WHALE_WAVE_ASSEMBLER_DIR", environment) self.assertNotIn("WHALE_WAVE_AMD64_DIR", environment) + self.assertNotIn("WHALE_WAVE_AARCH64_DIR", environment) + self.assertNotIn("WHALE_WAVE_RISCV64_DIR", environment) + self.assertNotIn("WHALE_WAVE_LOONGARCH64_DIR", environment) self.assertNotIn("CARGO_BUILD_TARGET", environment) self.assertEqual(environment["CARGO_TARGET_DIR"], "private") self.assertEqual(environment["CARGO_PROFILE_DEV_OPT_LEVEL"], "2") From 3877d354e7cc2374577ad3ae03371fcedfb79be0 Mon Sep 17 00:00:00 2001 From: LunaStev Date: Sat, 31 Oct 2026 14:31:13 +0900 Subject: [PATCH 7/8] bytecode: compile, verify and execute versioned Wave images Define canonical bounded little-endian bytecode and admit complete images in Wave, deriving type, CFG, SSA, call and source facts before execution. Compile verified IR through the Wave writer and use the resumable Wave runtime with typed allocation and memory transport. Compose the explicit bytecode target and bounded atomic CLI commands. Allow products without an assembler or native linker. Check independent binary fixtures, exact writer goldens, O0/O2 mutations and Rust reference execution. References #362, #363, #364, #365. Signed-off-by: LunaStev --- Cargo.lock | 3 + Cargo.toml | 8 +- ir/BYTECODE.md | 79 ++ ir/build.rs | 10 + ir/bytecode_inventory.wave | 185 +++ ir/bytecode_loader.wave | 200 ++++ ir/bytecode_model.wave | 149 +++ ir/bytecode_runtime.wave | 32 + ir/bytecode_verify.wave | 337 ++++++ ir/bytecode_verify_flow.wave | 296 +++++ ir/bytecode_verify_instructions.wave | 303 +++++ ir/bytecode_verify_types.wave | 298 +++++ ir/bytecode_writer.wave | 162 +++ ir/meson.build | 10 + ir/runtime_prepare.wave | 2 +- ir/src/bytecode.rs | 1039 +++++++++++++++++ ir/src/interpreter/mod.rs | 14 +- ir/src/interpreter/runtime_wave.rs | 462 +++++++- ir/src/lib.rs | 2 + ir/src/limits.rs | 6 +- ir/src/lower_ast/o0.rs | 10 +- ir/src/lower_ast/wave_lower.rs | 12 +- ir/src/verifier.rs | 3 + ir/tests/bytecode_execution.rs | 360 ++++++ ir/tests/bytecode_output_ceiling.rs | 17 + .../fixtures/bytecode/constant_source.wbc | Bin 0 -> 1360 bytes ir/tests/fixtures/bytecode/empty.wbc | Bin 0 -> 576 bytes .../fixtures/bytecode/invalid_block_count.wbc | Bin 0 -> 1216 bytes .../fixtures/bytecode/invalid_block_owner.wbc | Bin 0 -> 1216 bytes .../bytecode/invalid_count_overflow.wbc | Bin 0 -> 1216 bytes .../invalid_cross_function_target.wbc | Bin 0 -> 2248 bytes .../fixtures/bytecode/invalid_destination.wbc | Bin 0 -> 1216 bytes .../bytecode/invalid_directory_overlap.wbc | Bin 0 -> 1216 bytes .../bytecode/invalid_duplicate_ssa_id.wbc | Bin 0 -> 2248 bytes .../bytecode/invalid_early_terminal.wbc | Bin 0 -> 1216 bytes ir/tests/fixtures/bytecode/invalid_entry.wbc | Bin 0 -> 1216 bytes ir/tests/fixtures/bytecode/invalid_flags.wbc | Bin 0 -> 1216 bytes .../fixtures/bytecode/invalid_function_id.wbc | Bin 0 -> 1216 bytes ir/tests/fixtures/bytecode/invalid_header.wbc | Bin 0 -> 1216 bytes ir/tests/fixtures/bytecode/invalid_layout.wbc | Bin 0 -> 1216 bytes ir/tests/fixtures/bytecode/invalid_length.wbc | Bin 0 -> 1216 bytes .../bytecode/invalid_nondominating_return.wbc | Bin 0 -> 2248 bytes ir/tests/fixtures/bytecode/invalid_opcode.wbc | Bin 0 -> 1216 bytes .../bytecode/invalid_phi_duplicate_edge.wbc | Bin 0 -> 2248 bytes .../bytecode/invalid_phi_missing_edge.wbc | Bin 0 -> 2248 bytes .../bytecode/invalid_phi_nonpredecessor.wbc | Bin 0 -> 2248 bytes .../fixtures/bytecode/invalid_phi_slot.wbc | Bin 0 -> 2248 bytes .../fixtures/bytecode/invalid_phi_type.wbc | Bin 0 -> 2248 bytes .../fixtures/bytecode/invalid_return_slot.wbc | Bin 0 -> 1216 bytes .../fixtures/bytecode/invalid_return_type.wbc | Bin 0 -> 1216 bytes .../fixtures/bytecode/invalid_semantics.wbc | Bin 0 -> 1216 bytes .../fixtures/bytecode/invalid_signature.wbc | Bin 0 -> 1216 bytes ir/tests/fixtures/bytecode/invalid_site.wbc | Bin 0 -> 1216 bytes ir/tests/fixtures/bytecode/invalid_ssa_id.wbc | Bin 0 -> 1216 bytes ir/tests/fixtures/bytecode/invalid_stride.wbc | Bin 0 -> 1216 bytes .../fixtures/bytecode/invalid_table_count.wbc | Bin 0 -> 1216 bytes .../bytecode/invalid_text_overlap.wbc | Bin 0 -> 1251 bytes .../fixtures/bytecode/invalid_trailing.wbc | Bin 0 -> 1217 bytes .../fixtures/bytecode/invalid_truncated.wbc | Bin 0 -> 1215 bytes .../fixtures/bytecode/invalid_type_cycle.wbc | Bin 0 -> 1216 bytes .../fixtures/bytecode/invalid_type_kind.wbc | Bin 0 -> 1216 bytes ir/tests/fixtures/bytecode/invalid_utf8.wbc | Bin 0 -> 1234 bytes .../fixtures/bytecode/invalid_version.wbc | Bin 0 -> 1216 bytes ir/tests/fixtures/bytecode/phi_diamond.wbc | Bin 0 -> 2248 bytes ir/tests/fixtures/bytecode/return42.wbc | Bin 0 -> 1216 bytes meson.build | 3 + meson.options | 2 + src/backends/bytecode.rs | 30 + src/backends/mod.rs | 1 + src/builtins.rs | 10 + src/cli.rs | 18 +- src/commands/bytecode.rs | 167 +++ src/commands/ir.rs | 54 +- src/commands/mod.rs | 3 + src/commands/output.rs | 1 + src/lib.rs | 2 + target-spec/src/extension.rs | 23 + target-spec/src/lib.rs | 2 +- tests/bytecode_cli.rs | 142 +++ tests/command_status.rs | 3 +- tests/module_selection.rs | 24 + tests/multi_isa.rs | 10 +- tests/static_link_cli.rs | 2 +- tools/build_wave_ir.py | 10 + tools/check_product_graph.py | 17 +- tools/check_wave_bytecode.py | 286 +++++ tools/check_wave_bytecode_cli.py | 94 ++ tools/check_wave_bytecode_writer.py | 405 +++++++ tools/meson_cargo.py | 2 +- tools/test_product_graph.py | 8 + 90 files changed, 5219 insertions(+), 99 deletions(-) create mode 100644 ir/BYTECODE.md create mode 100644 ir/bytecode_inventory.wave create mode 100644 ir/bytecode_loader.wave create mode 100644 ir/bytecode_model.wave create mode 100644 ir/bytecode_runtime.wave create mode 100644 ir/bytecode_verify.wave create mode 100644 ir/bytecode_verify_flow.wave create mode 100644 ir/bytecode_verify_instructions.wave create mode 100644 ir/bytecode_verify_types.wave create mode 100644 ir/bytecode_writer.wave create mode 100644 ir/src/bytecode.rs create mode 100644 ir/tests/bytecode_execution.rs create mode 100644 ir/tests/bytecode_output_ceiling.rs create mode 100644 ir/tests/fixtures/bytecode/constant_source.wbc create mode 100644 ir/tests/fixtures/bytecode/empty.wbc create mode 100644 ir/tests/fixtures/bytecode/invalid_block_count.wbc create mode 100644 ir/tests/fixtures/bytecode/invalid_block_owner.wbc create mode 100644 ir/tests/fixtures/bytecode/invalid_count_overflow.wbc create mode 100644 ir/tests/fixtures/bytecode/invalid_cross_function_target.wbc create mode 100644 ir/tests/fixtures/bytecode/invalid_destination.wbc create mode 100644 ir/tests/fixtures/bytecode/invalid_directory_overlap.wbc create mode 100644 ir/tests/fixtures/bytecode/invalid_duplicate_ssa_id.wbc create mode 100644 ir/tests/fixtures/bytecode/invalid_early_terminal.wbc create mode 100644 ir/tests/fixtures/bytecode/invalid_entry.wbc create mode 100644 ir/tests/fixtures/bytecode/invalid_flags.wbc create mode 100644 ir/tests/fixtures/bytecode/invalid_function_id.wbc create mode 100644 ir/tests/fixtures/bytecode/invalid_header.wbc create mode 100644 ir/tests/fixtures/bytecode/invalid_layout.wbc create mode 100644 ir/tests/fixtures/bytecode/invalid_length.wbc create mode 100644 ir/tests/fixtures/bytecode/invalid_nondominating_return.wbc create mode 100644 ir/tests/fixtures/bytecode/invalid_opcode.wbc create mode 100644 ir/tests/fixtures/bytecode/invalid_phi_duplicate_edge.wbc create mode 100644 ir/tests/fixtures/bytecode/invalid_phi_missing_edge.wbc create mode 100644 ir/tests/fixtures/bytecode/invalid_phi_nonpredecessor.wbc create mode 100644 ir/tests/fixtures/bytecode/invalid_phi_slot.wbc create mode 100644 ir/tests/fixtures/bytecode/invalid_phi_type.wbc create mode 100644 ir/tests/fixtures/bytecode/invalid_return_slot.wbc create mode 100644 ir/tests/fixtures/bytecode/invalid_return_type.wbc create mode 100644 ir/tests/fixtures/bytecode/invalid_semantics.wbc create mode 100644 ir/tests/fixtures/bytecode/invalid_signature.wbc create mode 100644 ir/tests/fixtures/bytecode/invalid_site.wbc create mode 100644 ir/tests/fixtures/bytecode/invalid_ssa_id.wbc create mode 100644 ir/tests/fixtures/bytecode/invalid_stride.wbc create mode 100644 ir/tests/fixtures/bytecode/invalid_table_count.wbc create mode 100644 ir/tests/fixtures/bytecode/invalid_text_overlap.wbc create mode 100644 ir/tests/fixtures/bytecode/invalid_trailing.wbc create mode 100644 ir/tests/fixtures/bytecode/invalid_truncated.wbc create mode 100644 ir/tests/fixtures/bytecode/invalid_type_cycle.wbc create mode 100644 ir/tests/fixtures/bytecode/invalid_type_kind.wbc create mode 100644 ir/tests/fixtures/bytecode/invalid_utf8.wbc create mode 100644 ir/tests/fixtures/bytecode/invalid_version.wbc create mode 100644 ir/tests/fixtures/bytecode/phi_diamond.wbc create mode 100644 ir/tests/fixtures/bytecode/return42.wbc create mode 100644 src/backends/bytecode.rs create mode 100644 src/backends/mod.rs create mode 100644 src/commands/bytecode.rs create mode 100644 tests/bytecode_cli.rs create mode 100644 tools/check_wave_bytecode.py create mode 100644 tools/check_wave_bytecode_cli.py create mode 100755 tools/check_wave_bytecode_writer.py diff --git a/Cargo.lock b/Cargo.lock index 4b0a24c..abc1076 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -312,6 +312,8 @@ dependencies = [ "aarch64", "amd64", "assembler", + "backend-api", + "diagnostic", "ir", "linker", "loongarch64", @@ -321,6 +323,7 @@ dependencies = [ "same-file", "serde", "serde_json", + "target-spec", "tempfile", "toolchain", ] diff --git a/Cargo.toml b/Cargo.toml index 16dcad0..da1bf23 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -25,13 +25,14 @@ edition = "2021" rust-version.workspace = true [features] -default = ["builtin-assemblers"] +default = ["builtin-assemblers", "native-linker"] builtin-assemblers = ["asm-amd64", "asm-aarch64", "asm-riscv64", "asm-loongarch64"] asm-amd64 = ["dep:amd64"] asm-aarch64 = ["dep:aarch64"] asm-riscv64 = ["dep:riscv64"] asm-loongarch64 = ["dep:loongarch64"] socket-cli = ["ir/socket"] +native-linker = ["dep:linker"] [dependencies] assembler = { path = "assembler" } @@ -41,7 +42,10 @@ riscv64 = { path = "assembler/riscv64", optional = true } loongarch64 = { path = "assembler/loongarch64", optional = true } toolchain = { path = "toolchain" } reverse = { path = "reverse" } -linker = { path = "linker" } +linker = { path = "linker", optional = true } +backend-api = { path = "backend-api" } +diagnostic = { path = "diagnostic" } +target-spec = { path = "target-spec" } object = { path = "object" } ir = { path = "ir", version = "0.1.0", default-features = false } serde_json = "1" diff --git a/ir/BYTECODE.md b/ir/BYTECODE.md new file mode 100644 index 0000000..afe2595 --- /dev/null +++ b/ir/BYTECODE.md @@ -0,0 +1,79 @@ +# Whale bytecode v1 + +The internal `whale-bytecode-v1` target uses tracked 64-bit little-endian storage, +with scalar alignments 1/2/4/8/16, pointer alignment 8, and 16-byte allocation +alignment for arrays of at least 16 bytes. Wave writes, loads, verifies and +executes it. Rust owns files, initialized buffers and typed runtime requests. +The initial executable Wave host is Linux AMD64. + +```sh +whale ir emit program.wir --target whale-bytecode-v1 -o program.wbc +whale bytecode verify program.wbc +whale bytecode run program.wbc --function @f7 --arg 42 +``` + +The source IR must name this target; compilation does not relabel another target. +Input, decoded bytes, workspace and work have cumulative bounds. Execution also +limits steps, call depth, frames, values and tracked memory. No assembler or +native executable linker is required. V1 has no runtime imports: referenced +external declarations fail before publication or execution. + +## File layout + +All integers are unsigned little-endian u64 fields; signed literals use their +exact sign-extended 128-bit low/high representation. No native struct padding, +address, capability, allocation generation or runtime state appears in a file. + +The 64-byte header contains eight words: magic bytes `WHALEBC\0`, format 1, +IR semantics 1, storage profile 1, total file bytes, table count 16, flags 0, +and header-plus-directory size 576. Sixteen 32-byte directory entries follow: +`kind, offset, count, stride`. Kinds are ordered 1–16; payloads are contiguous +in that order. Gaps, overlaps, unknown versions and trailing bytes are rejected. + +| Kind | Table | Bytes per record | +| --- | --- | --- | +| 1 | Type: kind, child, first, count, extra | 40 | +| 2 | Type-edge index | 8 | +| 3 | Function: id, signature, entry, first_block, block_count, first_parameter, parameter_count, value_count, first_value_type, has_body, linkage | 88 | +| 4 | Block: id, function, first_instruction, instruction_count | 32 | +| 5 | Instruction, fields below | 136 | +| 6 | Operand word | 8 | +| 7 | Dense-slot type index | 8 | +| 8 | Storage global: id, type, align, readonly, initialized, literal, low, high | 64 | +| 9 | Site: original function, block, instruction ordinal, value ID | 32 | +| 10 | Text slice: first byte, byte count | 16 | +| 11 | UTF-8 text bytes | 1 | +| 12 | Source file: original ID, text index | 16 | +| 13 | Original node: id, has_span, file, line, column, end_line, end_column | 56 | +| 14 | Source mapping: kind, function, block, index, original | 40 | +| 15 | Original SSA ID, parallel to dense-slot types | 8 | +| 16 | Folded constant-global ID | 8 | + +Instruction fields are `op, sub, type, other_type, dst, a, b, c, align, first, +count, low, high, literal, signature, flags, global`. `u64::MAX` means no value +or destination. Type and opcode tags match `runtime_model.wave` and the typed +runtime transport. Types are postorder: children precede parents. Type kinds +0–21 denote Void, Bool, I1, U1, I8/I16/I32/I64/I128, U8/U16/U32/U64/U128, +F16/F32/F64, Ptr, FnPtr, Array, Struct and Tuple. Derived layout sizes and GEP +plans are recomputed, never loaded. Text slices cover the blob contiguously; +repeated filename copies and expanded type trees consume workspace limits. + +Opcodes 0–35 are GlobalAddr, LifetimeEnd, PtrDiff, ConstDecl, Const, Undef, +Mov, Bin, Neg, Not, Cmp, ICmp, FCmp, Select, Cast, Phi, Extract, Checked, +Alloca, VolatileLoad, VolatileStore, Load, Store, Uninit, GEP, Memcpy, Memset, +NullFunction, FunctionAddr, Call, TrapIf, Br, CBr, Switch, Ret and Trap. +Undef and unsupported aggregate value operations are rejected even in unused +functions. Aggregate tracked storage is supported. Numeric subcodes retain +the IR runtime mappings; unknown subcodes are rejected, never executed. + +Phi operands are `(slot, predecessor block)` pairs; switch operands are +`(low, high, target block)` triples; calls and GEP use slot lists. Block indices +are global table indices; SSA slots are local to each function. Source mapping +kinds are instruction 0, terminator 1 and global 2. Sites preserve sparse IR IDs. +Each block ends in exactly one terminator. Wave derives definitions, predecessors, +reachability and dominators before checking types, phi edges and SSA availability. +Only complete admission can reach the resumable Wave runtime and memory effects. + +`tools/check_wave_bytecode.py` builds independent LE fixtures and mutations. +`tests/fixtures/bytecode` contains valid and malformed binaries generated without +the Wave writer. The separate writer checker compares exact expected bytes. diff --git a/ir/build.rs b/ir/build.rs index 2d30730..9131468 100644 --- a/ir/build.rs +++ b/ir/build.rs @@ -46,6 +46,15 @@ const SOURCES: &[&str] = &[ "runtime_prepare.wave", "runtime_execute.wave", "runtime_driver.wave", + "bytecode_model.wave", + "bytecode_inventory.wave", + "bytecode_loader.wave", + "bytecode_verify_types.wave", + "bytecode_verify_instructions.wave", + "bytecode_verify_flow.wave", + "bytecode_verify.wave", + "bytecode_writer.wave", + "bytecode_runtime.wave", "entry.wave", ]; @@ -58,6 +67,7 @@ const ABI_SOURCES: &[&str] = &[ "src/fold_integer_wave.rs", "src/constant_wave.rs", "src/interpreter/runtime_wave.rs", + "src/bytecode.rs", "src/verifier/wave_constants.rs", "src/source_wave.rs", "src/interpreter/memory_wave.rs", diff --git a/ir/bytecode_inventory.wave b/ir/bytecode_inventory.wave new file mode 100644 index 0000000..78da2c4 --- /dev/null +++ b/ir/bytecode_inventory.wave @@ -0,0 +1,185 @@ +// SPDX-License-Identifier: MPL-2.0 +// Whole-program executable admission. Structural verification runs first, so +// every index below already names a validated record. Unreachable bodies are +// deliberately checked as well: a file never advertises a partly executable VM. +fun ir_bytecode_known_sub(inst: ptr) -> bool { + if (inst.op == 1) { + return inst.sub == 1; + } + if (inst.op == 7) { + return inst.sub <= 17; + } + if (inst.op == 10 || inst.op == 12) { + return inst.sub <= 15; + } + if (inst.op == 11) { + return inst.sub <= 9; + } + if (inst.op == 14) { + return inst.sub <= 12; + } + if (inst.op == 16) { + return inst.sub <= 4294967295; + } + if (inst.op == 17) { + return inst.sub <= 5; + } + if (inst.op == 29) { + return inst.sub <= 1; + } + return inst.sub == 0; +} + +fun ir_bytecode_callable(program: ptr, signature: u64, + limits: ptr, result: ptr) -> bool { + var node: ptr = &program.types[signature]; + if (node.kind != 18 || node.extra != 0 || node.count == 0) { + return false; + } + var index: u64 = 0; + var kind: u64 = 0; + while (index < node.count) { + if (!ir_bytecode_charge(result, limits, 1)) { + return false; + } + kind = program.types[program.edges[node.first + index]].kind; + if (!(index == 0 && kind == 0) && !(kind >= 1 && kind <= 18)) { + return false; + } + index += 1; + } + return true; +} + +fun ir_bytecode_executable_instruction(program: ptr, + function: ptr, inst: ptr, + limits: ptr, result: ptr) -> bool { + var op: u64 = inst.op; + var kind: u64 = program.types[inst.ty].kind; + var integer: bool = ir_verify_integer(kind); + var floating: bool = ir_verify_float(kind); + var scalar: bool = kind >= 1 && kind <= 16; + var valid: bool = op <= 3 || op >= 24; + if (!ir_bytecode_known_sub(inst)) { + return ir_bytecode_fail(result, 1, 105, 5, result.index); + } + if (op == 4) { + valid = scalar; + } else if (op == 5) { + valid = false; + } else if (op == 6 || op == 13 || op == 15) { + valid = ir_bytecode_value_type(program, inst.ty); + } else if (op == 7 || op == 8) { + valid = integer || floating; + } else if (op == 9 || op == 17) { + valid = integer; + } else if (op == 10 || op == 11) { + valid = kind == 1 || integer || kind == 17 || (op == 10 && floating); + } else if (op == 12) { + valid = floating; + } else if (op == 14) { + valid = ir_verify_cast(inst.sub, program.types[inst.other].kind, kind); + } else if (op == 16) { + valid = scalar && inst.sub <= 1; + } else if (op == 18 || op == 23) { + valid = kind != 0; + } else if (op >= 19 && op <= 22) { + valid = ir_bytecode_value_type(program, inst.ty); + } + if (!valid) { + return ir_bytecode_fail(result, 5, 100, 5, result.index); + } + if (op == 28) { + if (program.functions[inst.a].has_body == 0 + || program.functions[inst.a].linkage != 0) { + return ir_bytecode_fail(result, 5, 102, 5, result.index); + } + } + if (op == 29) { + if (inst.sub != 0) { + return ir_bytecode_fail(result, 5, 103, 5, result.index); + } + var signature: u64 = 0; + if (inst.flags == 0) { + if (program.functions[inst.a].has_body == 0 + || program.functions[inst.a].linkage != 0) { + return ir_bytecode_fail(result, 5, 102, 5, result.index); + } + signature = program.functions[inst.a].signature; + } else { + signature = program.value_types[function.first_value_type + inst.a]; + } + if (!ir_bytecode_callable(program, signature, limits, result)) { + if (result.status != 0) { + return false; + } + return ir_bytecode_fail(result, 5, 101, 5, result.index); + } + } + return true; +} + +fun ir_bytecode_inventory(program: ptr, + limits: ptr, result: ptr) -> bool { + var global: u64 = 0; + var function_index: u64 = 0; + var block_index: u64 = 0; + var instruction_index: u64 = 0; + var kind: u64 = 0; + var function: ptr = null; + var block: ptr = null; + while (global < program.global_count) { + result.table = 8; + result.index = global; + if (!ir_bytecode_charge(result, limits, 1)) { + return false; + } + kind = program.types[program.globals[global].ty].kind; + // Aggregate storage is executable without materializing an aggregate + // value. Initializers, in contrast, must fit a scalar value record. + if (program.globals[global].initialized != 0 && (kind < 1 || kind > 16)) { + return ir_bytecode_fail(result, 5, 104, 8, global); + } + global += 1; + } + while (function_index < program.function_count) { + result.table = 3; + result.index = function_index; + if (!ir_bytecode_charge(result, limits, 1)) { + return false; + } + function = &program.functions[function_index]; + if (function.has_body != 0) { + if (function.linkage != 0 + || !ir_bytecode_callable(program, function.signature, limits, result)) { + if (result.status != 0) { + return false; + } + return ir_bytecode_fail(result, 5, 101, 3, function_index); + } + block_index = function.first_block; + while (block_index < function.first_block + function.block_count) { + if (!ir_bytecode_charge(result, limits, 1)) { + return false; + } + block = &program.blocks[block_index]; + instruction_index = block.first; + while (instruction_index < block.first + block.count) { + result.table = 5; + result.index = instruction_index; + if (!ir_bytecode_charge(result, limits, 1) + || !ir_bytecode_executable_instruction(program, function, + &program.instructions[instruction_index], limits, result)) { + return false; + } + instruction_index += 1; + } + block_index += 1; + } + } + function_index += 1; + } + result.table = 0; + result.index = 0; + return true; +} diff --git a/ir/bytecode_loader.wave b/ir/bytecode_loader.wave new file mode 100644 index 0000000..463cabb --- /dev/null +++ b/ir/bytecode_loader.wave @@ -0,0 +1,200 @@ +// SPDX-License-Identifier: MPL-2.0 +// Canonical little-endian decoding. Lengths are checked before allocation or reads. +fun ir_bytecode_read(data: ptr, at: u64) -> u64 { + var value: u64 = 0; + var i: u64 = 0; + while (i < 8) { + value = value | ((data[at + i] as u64) << (i * 8)); + i += 1; + } + return value; +} + +fun ir_bytecode_sizes(counts: ptr, limits: ptr, + result: ptr) -> bool { + var values: ptr = counts as ptr; + var total: u64 = 0; + var records: u64 = 0; + var table: u64 = 1; + while (table <= 16) { + var count: u64 = values[table - 1]; + var stride: u64 = ir_bytecode_native_stride(table); + if (count > limits.max_decoded_bytes / stride + || count * stride > limits.max_decoded_bytes - total) { + return ir_bytecode_fail(result, 2, 2, table, count); + } + total += count * stride; + if (table != 11) { + if (records > limits.max_records || count > limits.max_records - records) { + return ir_bytecode_fail(result, 2, 3, table, count); + } + records += count; + } + table += 1; + } + // A linear bound for CFG, SSA, source indexes and initialized type scratch. + var words: u64 = 256; + table = 1; + while (table <= 16) { + var factor: u64 = 32; + if (table == 4) { factor = 96; } + if (table == 6) { factor = 48; } + if (table == 7) { factor = 32; } + if (table == 15) { factor = 0; } + if (table == 11) { factor = 0; } + var count: u64 = values[table - 1]; + if (factor != 0 && count > (18446744073709551615 - words) / factor) { + return ir_bytecode_fail(result, 2, 4, table, count); + } + words += count * factor; + table += 1; + } + if (words > limits.max_workspace_bytes / 8 + || total > limits.max_workspace_bytes - words * 8) { + return ir_bytecode_fail(result, 2, 4, 0, words); + } + result.decoded_bytes = total; + result.scratch_words = words; + return true; +} + +export(c) fun whale_ir_bytecode_probe(data: ptr, count: u64, + limits: ptr, result: ptr) -> i32 { + if (result == null) { return 4; } + ir_bytecode_result_init(result); + if (limits == null || !ir_span_valid(data, count, 1)) { + ir_bytecode_fail(result, 4, 1, 0, 0); + return result.status as i32; + } + if (count > limits.max_input_bytes) { + ir_bytecode_fail(result, 2, 1, 0, count); + return result.status as i32; + } + if (count < 576) { + ir_bytecode_fail(result, 1, 1, 0, count); + return result.status as i32; + } + if (!ir_bytecode_charge(result, limits, 576)) { return result.status as i32; } + if (ir_bytecode_read(data, 0) != 18931688839137367 || ir_bytecode_read(data, 8) != 1 + || ir_bytecode_read(data, 16) != 1 || ir_bytecode_read(data, 24) != 1 + || ir_bytecode_read(data, 32) != count || ir_bytecode_read(data, 40) != 16 + || ir_bytecode_read(data, 48) != 0 || ir_bytecode_read(data, 56) != 576) { + ir_bytecode_fail(result, 1, 2, 0, 0); + return result.status as i32; + } + var counts: ptr = &result.counts as ptr; + var end: u64 = 576; + var table: u64 = 1; + while (table <= 16) { + var at: u64 = 64 + (table - 1) * 32; + var offset: u64 = ir_bytecode_read(data, at + 8); + var amount: u64 = ir_bytecode_read(data, at + 16); + var stride: u64 = ir_bytecode_stride(table); + if (ir_bytecode_read(data, at) != table || offset != end + || ir_bytecode_read(data, at + 24) != stride + || amount > (count - end) / stride) { + ir_bytecode_fail(result, 1, 3, table, 0); + return result.status as i32; + } + counts[table - 1] = amount; + end += amount * stride; + table += 1; + } + if (end != count) { + ir_bytecode_fail(result, 1, 4, 0, end); + return result.status as i32; + } + if (!ir_bytecode_sizes(&result.counts, limits, result)) { return result.status as i32; } + return 0; +} + +export(c) fun whale_ir_bytecode_load(data: ptr, count: u64, + program: ptr, scratch: ptr, capacity: u64, + limits: ptr, result: ptr) -> i32 { + var status: i32 = whale_ir_bytecode_probe(data, count, limits, result); + if (status != 0) { return status; } + if (program == null || !ir_span_valid(scratch as ptr, capacity, 8)) { + ir_bytecode_fail(result, 4, 1, 0, 0); + return result.status as i32; + } + if (capacity < result.scratch_words) { + ir_bytecode_fail(result, 2, 4, 0, capacity); + return result.status as i32; + } + var counts: ptr = &result.counts as ptr; + var table: u64 = 1; + while (table <= 16) { + if (ir_bytecode_count(program, table) != counts[table - 1] + || !ir_span_valid(ir_bytecode_data(program, table), counts[table - 1], + ir_bytecode_native_stride(table))) { + ir_bytecode_fail(result, 4, 2, table, 0); + return result.status as i32; + } + table += 1; + } + table = 1; + while (table <= 16) { + var offset: u64 = ir_bytecode_read(data, 64 + (table - 1) * 32 + 8); + var records: u64 = counts[table - 1]; + var i: u64 = 0; + if (table == 11) { + if (!ir_bytecode_charge(result, limits, records)) { return result.status as i32; } + while (i < records) { + program.text_bytes[i] = data[offset + i]; + i += 1; + } + } else { + while (i < records) { + result.table = table; + result.index = i; + var stride: u64 = ir_bytecode_stride(table); + if (!ir_bytecode_charge(result, limits, stride)) { return result.status as i32; } + var destination: ptr = ir_bytecode_data(program, table) as ptr; + var native_words: u64 = ir_bytecode_native_stride(table) / 8; + var word: u64 = 0; + while (word < native_words) { + destination[i * native_words + word] = 0; + word += 1; + } + if (table == 5) { + var inst: ptr = &program.instructions[i]; + var fields: ptr = inst as ptr; + word = 0; + var file_word: u64 = 0; + while (word < 21) { + if (word != 9 && word != 10 && word != 19 && word != 20) { + fields[word] = ir_bytecode_read(data, offset + i * stride + file_word * 8); + file_word += 1; + } + word += 1; + } + } else if (table == 8) { + var global: ptr = &program.globals[i]; + global.id = ir_bytecode_read(data, offset + i * stride); + global.ty = ir_bytecode_read(data, offset + i * stride + 8); + global.align = ir_bytecode_read(data, offset + i * stride + 16); + global.readonly = ir_bytecode_read(data, offset + i * stride + 24); + global.initialized = ir_bytecode_read(data, offset + i * stride + 32); + global.value.literal = ir_bytecode_read(data, offset + i * stride + 40); + global.value.low = ir_bytecode_read(data, offset + i * stride + 48); + global.value.high = ir_bytecode_read(data, offset + i * stride + 56); + if (global.initialized == 1) { + global.value.kind = 1; + global.value.ty = global.ty; + global.value.origin = 1; + } + } else { + word = 0; + while (word < native_words) { + destination[i * native_words + word] = + ir_bytecode_read(data, offset + i * stride + word * 8); + word += 1; + } + } + i += 1; + } + } + table += 1; + } + return ir_bytecode_verify_impl(program, scratch, capacity, limits, result); +} diff --git a/ir/bytecode_model.wave b/ir/bytecode_model.wave new file mode 100644 index 0000000..cd2b0c5 --- /dev/null +++ b/ir/bytecode_model.wave @@ -0,0 +1,149 @@ +// SPDX-License-Identifier: MPL-2.0 +// Portable file fields are encoded individually. These pointers are transport, +// never file contents or executable pointer authority. +struct IrBytecodeSite { + function: u64; + block: u64; + instruction: u64; + value: u64; +} + +struct IrBytecodeText { + first: u64; + count: u64; +} + +struct IrBytecodeFile { + id: u64; + text: u64; +} + +struct IrBytecodeCounts { + types: u64; + edges: u64; + functions: u64; + blocks: u64; + instructions: u64; + operands: u64; + value_types: u64; + globals: u64; + sites: u64; + texts: u64; + text_bytes: u64; + files: u64; + originals: u64; + mappings: u64; + value_ids: u64; + constant_globals: u64; +} + +struct IrBytecodeProgram { + types: ptr; + type_count: u64; + edges: ptr; + edge_count: u64; + functions: ptr; + function_count: u64; + blocks: ptr; + block_count: u64; + instructions: ptr; + instruction_count: u64; + operands: ptr; + operand_count: u64; + value_types: ptr; + value_type_count: u64; + globals: ptr; + global_count: u64; + sites: ptr; + site_count: u64; + texts: ptr; + text_count: u64; + text_bytes: ptr; + text_byte_count: u64; + files: ptr; + file_count: u64; + originals: ptr; + original_count: u64; + mappings: ptr; + mapping_count: u64; + value_ids: ptr; + value_id_count: u64; + constant_global_ids: ptr; + constant_global_count: u64; +} + +struct IrBytecodeLimits { + max_input_bytes: u64; + max_decoded_bytes: u64; + max_records: u64; + max_work: u64; + max_type_depth: u64; + max_workspace_bytes: u64; +} + +struct IrBytecodeResult { + status: u64; + code: u64; + table: u64; + index: u64; + work: u64; + decoded_bytes: u64; + scratch_words: u64; + counts: IrBytecodeCounts; +} + +fun ir_bytecode_fail(result: ptr, status: u64, + code: u64, table: u64, index: u64) -> bool { + result.status = status; + result.code = code; + result.table = table; + result.index = index; + return false; +} + +fun ir_bytecode_charge(result: ptr, limits: ptr, + amount: u64) -> bool { + if (result.work > limits.max_work || amount > limits.max_work - result.work) { + return ir_bytecode_fail(result, 3, 1, result.table, result.index); + } + result.work += amount; + return true; +} + +fun ir_bytecode_result_init(result: ptr) { + var words: ptr = result as ptr; + var i: u64 = 0; + while (i < 23) { + words[i] = 0; + i += 1; + } +} + +fun ir_bytecode_stride(table: u64) -> u64 { + if (table == 1) { return 40; } + if (table == 3) { return 88; } + if (table == 4 || table == 9) { return 32; } + if (table == 5) { return 136; } + if (table == 8) { return 64; } + if (table == 10 || table == 12) { return 16; } + if (table == 11) { return 1; } + if (table == 13) { return 56; } + if (table == 14) { return 40; } + return 8; +} + +fun ir_bytecode_native_stride(table: u64) -> u64 { + if (table == 5) { return 168; } + if (table == 8) { return 216; } + return ir_bytecode_stride(table); +} + +fun ir_bytecode_count(program: ptr, table: u64) -> u64 { + var words: ptr = program as ptr; + return words[(table - 1) * 2 + 1]; +} + +fun ir_bytecode_data(program: ptr, table: u64) -> ptr { + var words: ptr = program as ptr; + return words[(table - 1) * 2] as ptr; +} diff --git a/ir/bytecode_runtime.wave b/ir/bytecode_runtime.wave new file mode 100644 index 0000000..d87da30 --- /dev/null +++ b/ir/bytecode_runtime.wave @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: MPL-2.0 +// Bytecode admission precedes the existing tracked-memory execution engine. +// Disk records never supply runtime layout plans or executable authority. +export(c) fun whale_ir_bytecode_runtime_step(program: ptr, + driver: ptr, scratch: ptr, capacity: u64, + limits: ptr, admission: ptr) -> i32 { + if (program == null || driver == null || driver.result == null + || limits == null || admission == null) { + return 4; + } + if (driver.phase == 0) { + var status: i32 = whale_ir_bytecode_verify(program, scratch, capacity, limits, admission); + if (status != 0) { + ir_runtime_backend(driver); + return 4; + } + } + if (driver.types != program.types || driver.type_count != program.type_count + || driver.type_edges != program.edges || driver.type_edge_count != program.edge_count + || driver.functions != program.functions || driver.function_count != program.function_count + || driver.blocks != program.blocks || driver.block_count != program.block_count + || driver.instructions != program.instructions + || driver.instruction_count != program.instruction_count + || driver.operands != program.operands || driver.operand_count != program.operand_count + || driver.value_types != program.value_types + || driver.value_type_count != program.value_type_count + || driver.globals != program.globals || driver.global_count != program.global_count) { + ir_runtime_backend(driver); + return 4; + } + return whale_ir_runtime_step(driver); +} diff --git a/ir/bytecode_verify.wave b/ir/bytecode_verify.wave new file mode 100644 index 0000000..0cd2d12 --- /dev/null +++ b/ir/bytecode_verify.wave @@ -0,0 +1,337 @@ +// SPDX-License-Identifier: MPL-2.0 +// Complete admission precedes runtime effects. The exported query checks native +// spans and computes bounded initialized scratch before traversing any table. +fun ir_bytecode_verify_structure(context: ptr, + identities: ptr, identity_capacity: u64) -> bool { + var p: ptr = context.program; + var result: ptr = context.result; + var limits: ptr = context.limits; + var i: u64 = 0; + if (!ir_bytecode_charge(result, limits, p.value_type_count)) { return false; } + while (i < p.value_type_count) { + var definition: ptr = &context.definitions[i]; + definition.block = 18446744073709551615; + definition.position = 0; + definition.defined = 0; + definition.literal = 0; + definition.low = 0; + definition.high = 0; + i += 1; + } + var block_cursor: u64 = 0; + var value_cursor: u64 = 0; + var instruction_cursor: u64 = 0; + i = 0; + while (i < p.function_count) { + result.table = 3; + result.index = i; + if (!ir_bytecode_charge(result, limits, 1)) { return false; } + var function: ptr = &p.functions[i]; + if (function.id > 4294967295 || function.signature >= p.type_count + || p.types[function.signature].kind != 18 || function.has_body > 1 || function.linkage > 1 + || function.first_block != block_cursor || function.first_value_type != value_cursor + || function.block_count > p.block_count - block_cursor + || function.value_count > p.value_type_count - value_cursor + || function.first_parameter > p.operand_count + || function.parameter_count > p.operand_count - function.first_parameter) { + return ir_bytecode_fail(result, 1, 80, 3, i); + } + if (!ir_bytecode_unique(identities, identity_capacity, 1, function.id, 0, 0, context)) { return false; } + if (function.has_body == 0) { + if (function.block_count != 0 || function.value_count != 0 || function.parameter_count != 0 + || function.entry != 18446744073709551615 || function.linkage == 0) { + return ir_bytecode_fail(result, 1, 80, 3, i); + } + } else { + if (function.block_count == 0 || function.parameter_count >= p.types[function.signature].count + || function.parameter_count + 1 != p.types[function.signature].count + || !ir_bytecode_target(function, function.entry, context)) { + return ir_bytecode_fail(result, 1, 80, 3, i); + } + var parameter: u64 = 0; + while (parameter < function.parameter_count) { + if (!ir_bytecode_charge(result, limits, 1)) { return false; } + var slot: u64 = p.operands[function.first_parameter + parameter]; + if (slot >= function.value_count) { return ir_bytecode_fail(result, 1, 40, 3, i); } + var index: u64 = value_cursor + slot; + if (context.definitions[index].defined != 0) { return ir_bytecode_fail(result, 1, 81, 3, i); } + context.definitions[index].defined = 1; + if (!ir_bytecode_same(p, p.value_types[index], + p.edges[p.types[function.signature].first + parameter + 1], limits, result)) { return false; } + parameter += 1; + } + var b: u64 = 0; + while (b < function.block_count) { + result.table = 4; + result.index = block_cursor + b; + if (!ir_bytecode_charge(result, limits, 1)) { return false; } + var block: ptr = &p.blocks[block_cursor + b]; + if (block.id > 4294967295 || block.function != i || block.first != instruction_cursor + || block.count == 0 || block.count > p.instruction_count - instruction_cursor) { + return ir_bytecode_fail(result, 1, 82, 4, result.index); + } + if (!ir_bytecode_unique(identities, identity_capacity, 2, i, block.id, 0, context)) { return false; } + var position: u64 = 0; + while (position < block.count) { + result.table = 5; + result.index = instruction_cursor + position; + if (!ir_bytecode_charge(result, limits, 1)) { return false; } + var inst: ptr = &p.instructions[result.index]; + if (inst.op > 35 || inst.ty >= p.type_count || inst.other >= p.type_count + || (position + 1 == block.count && inst.op < 31) + || (position + 1 != block.count && inst.op >= 31)) { + return ir_bytecode_fail(result, 1, 83, 5, result.index); + } + var has_destination: bool = ir_bytecode_has_destination(inst); + if (has_destination) { + if (inst.dst >= function.value_count) { return ir_bytecode_fail(result, 1, 40, 5, result.index); } + var definition: ptr = &context.definitions[value_cursor + inst.dst]; + if (definition.defined != 0) { return ir_bytecode_fail(result, 1, 81, 5, result.index); } + definition.defined = 1; + definition.block = b; + definition.position = position; + if (inst.op == 3 || inst.op == 4) { + definition.literal = inst.literal; + definition.low = inst.low; + definition.high = inst.high; + } + } else if (inst.dst != 18446744073709551615) { + return ir_bytecode_fail(result, 1, 84, 5, result.index); + } + var site: ptr = &p.sites[result.index]; + var expected: u64 = 18446744073709551615; + if (has_destination) { expected = p.value_ids[value_cursor + inst.dst]; } + if (site.function != function.id || site.block != block.id + || site.instruction != position || site.value != expected) { + return ir_bytecode_fail(result, 1, 85, 9, result.index); + } + position += 1; + } + instruction_cursor += block.count; + b += 1; + } + } + var value: u64 = 0; + while (value < function.value_count) { + result.table = 15; + result.index = value_cursor + value; + if (!ir_bytecode_charge(result, limits, 1)) { return false; } + if (context.definitions[value_cursor + value].defined != 1 + || !ir_bytecode_unique(identities, identity_capacity, 3, i, + p.value_ids[value_cursor + value], 0, context)) { + if (result.status == 0) { ir_bytecode_fail(result, 1, 86, 15, result.index); } + return false; + } + value += 1; + } + block_cursor += function.block_count; + value_cursor += function.value_count; + i += 1; + } + if (block_cursor != p.block_count || value_cursor != p.value_type_count + || instruction_cursor != p.instruction_count) { + return ir_bytecode_fail(result, 1, 87, 0, 0); + } + i = 0; + while (i < p.global_count) { + result.table = 8; + result.index = i; + if (!ir_bytecode_charge(result, limits, 1)) { return false; } + var global: ptr = &p.globals[i]; + if (global.id > 4294967295 || global.ty >= p.type_count || global.readonly > 1 + || global.initialized > 1 || global.align > 4294967295 || !ir_power_two(global.align)) { + return ir_bytecode_fail(result, 1, 88, 8, i); + } + if (!ir_bytecode_unique(identities, identity_capacity, 4, global.id, 0, 0, context)) { return false; } + if (context.types[global.ty].storable == 0) { return ir_bytecode_fail(result, 1, 48, 8, i); } + if (global.initialized == 1) { + if (global.value.kind != 1 || global.value.ty != global.ty || global.value.origin != 1 + || global.value.flag != 0 || global.value.signature != 0 || global.value.target_kind != 0 + || global.value.target != 0 + || !ir_verify_literal(p.types[global.ty].kind, global.value.literal, + global.value.low, global.value.high)) { + return ir_bytecode_fail(result, 1, 89, 8, i); + } + } else { + var words: ptr = &global.value as ptr; + var word: u64 = 0; + while (word < 20) { + if (words[word] != 0) { return ir_bytecode_fail(result, 1, 89, 8, i); } + word += 1; + } + } + var pointer_words: ptr = &global.value.pointer as ptr; + var word: u64 = 0; + while (word < 10) { + if (pointer_words[word] != 0) { return ir_bytecode_fail(result, 1, 89, 8, i); } + word += 1; + } + i += 1; + } + i = 0; + while (i < p.constant_global_count) { + result.table = 16; + result.index = i; + if (p.constant_global_ids[i] > 4294967295 + || !ir_bytecode_unique(identities, identity_capacity, 4, + p.constant_global_ids[i], 0, 0, context)) { + if (result.status == 0) { ir_bytecode_fail(result, 1, 90, 16, i); } + return false; + } + i += 1; + } + return true; +} + +fun ir_bytecode_verify_sources(context: ptr) -> bool { + var p: ptr = context.program; + var result: ptr = context.result; + var scratch: ptr = context.scratch; + var files: ptr = ir_bytecode_take(scratch, p.file_count * 3, result) as ptr; + var blocks: ptr = ir_bytecode_take(scratch, p.block_count * 4, result) as ptr; + var global_count: u64 = p.global_count + p.constant_global_count; + var globals: ptr = ir_bytecode_take(scratch, global_count, result); + var total: u64 = p.file_count + p.original_count + p.block_count + global_count + p.mapping_count; + var capacity: u64 = 2; + while (capacity / 2 < total) { capacity *= 2; } + var table: ptr = ir_bytecode_take(scratch, capacity * 6, result) as ptr; + if (result.status != 0) { return false; } + var i: u64 = 0; + while (i < p.file_count) { + if (!ir_bytecode_charge(result, context.limits, 1)) { return false; } + if (p.files[i].id > 4294967295 || p.files[i].text >= p.text_count) { + return ir_bytecode_fail(result, 1, 91, 12, i); + } + var text: ptr = &p.texts[p.files[i].text]; + var available: u64 = context.limits.max_workspace_bytes + - result.decoded_bytes - result.scratch_words * 8; + if (context.owned_bytes > available || text.count > available - context.owned_bytes) { + return ir_bytecode_fail(result, 2, 6, 12, i); + } + context.owned_bytes += text.count; + if (!ir_bytecode_charge(result, context.limits, text.count)) { return false; } + files[i].id = p.files[i].id; + files[i].bytes = &p.text_bytes[text.first]; + files[i].length = text.count; + i += 1; + } + i = 0; + while (i < p.block_count) { + if (!ir_bytecode_charge(result, context.limits, 1)) { return false; } + blocks[i].function = p.functions[p.blocks[i].function].id; + blocks[i].block = p.blocks[i].id; + blocks[i].instructions = p.blocks[i].count - 1; + blocks[i].terminated = 1; + i += 1; + } + i = 0; + while (i < p.global_count) { + globals[i] = p.globals[i].id; + i += 1; + } + i = 0; + while (i < p.constant_global_count) { + globals[p.global_count + i] = p.constant_global_ids[i]; + i += 1; + } + i = 0; + while (i < p.original_count) { + if (!ir_bytecode_charge(result, context.limits, 1)) { return false; } + var node: ptr = &p.originals[i]; + if (node.file > 4294967295 || node.line > 4294967295 || node.column > 4294967295 + || node.end_line > 4294967295 || node.end_column > 4294967295) { + return ir_bytecode_fail(result, 1, 92, 13, i); + } + i += 1; + } + var source: IrSourceResult; + whale_ir_verify_sources(files, p.file_count, p.originals, p.original_count, + blocks, p.block_count, globals, global_count, p.mappings, p.mapping_count, + table, capacity, context.limits.max_work - result.work, &source); + if (!ir_bytecode_charge(result, context.limits, source.work)) { return false; } + if (source.status == 7) { return ir_bytecode_fail(result, 3, 1, 14, source.index); } + if (source.status != 0) { return ir_bytecode_fail(result, 1, 93, 14, source.index); } + return true; +} + +fun ir_bytecode_verify_impl(program: ptr, words: ptr, capacity: u64, + limits: ptr, result: ptr) -> i32 { + if (program == null || limits == null || !ir_span_valid(words as ptr, capacity, 8)) { + ir_bytecode_fail(result, 4, 1, 0, 0); + return result.status as i32; + } + var counts: ptr = &result.counts as ptr; + var table: u64 = 1; + while (table <= 16) { + var count: u64 = ir_bytecode_count(program, table); + if (!ir_span_valid(ir_bytecode_data(program, table), count, ir_bytecode_native_stride(table))) { + ir_bytecode_fail(result, 4, 2, table, 0); + return result.status as i32; + } + counts[table - 1] = count; + table += 1; + } + if (!ir_bytecode_sizes(&result.counts, limits, result)) { return result.status as i32; } + if (capacity < result.scratch_words) { + ir_bytecode_fail(result, 2, 4, 0, capacity); + return result.status as i32; + } + if (program.site_count != program.instruction_count || program.value_id_count != program.value_type_count) { + ir_bytecode_fail(result, 1, 5, 0, 0); + return result.status as i32; + } + var scratch: IrBytecodeScratch; + scratch.words = words; + scratch.capacity = capacity; + scratch.used = 0; + var context: IrBytecodeVerifier; + context.program = program; + context.owned_bytes = program.text_byte_count; + context.limits = limits; + context.result = result; + context.scratch = &scratch; + context.types = ir_bytecode_take(&scratch, program.type_count * 5, result) as ptr; + context.definitions = ir_bytecode_take(&scratch, program.value_type_count * 6, result) as ptr; + context.operand_capacity = program.operand_count + 3; + context.operands = ir_bytecode_take(&scratch, context.operand_capacity * 5, result) as ptr; + if (result.status != 0) { return result.status as i32; } + if (!ir_bytecode_verify_types(program, &scratch, limits, result) + || !ir_bytecode_layouts(&context)) { return result.status as i32; } + var base: u64 = scratch.used; + var total: u64 = program.function_count + program.block_count + program.value_type_count + + program.global_count + program.constant_global_count + program.operand_count; + var identity_capacity: u64 = 2; + while (identity_capacity / 2 < total) { identity_capacity *= 2; } + var identities: ptr = ir_bytecode_take(&scratch, + identity_capacity * 6, result) as ptr; + if (result.status != 0) { return result.status as i32; } + var i: u64 = 0; + while (i < identity_capacity) { + if (!ir_bytecode_charge(result, limits, 1)) { return result.status as i32; } + identities[i].kind = 0; + i += 1; + } + if (!ir_bytecode_verify_structure(&context, identities, identity_capacity)) { return result.status as i32; } + i = 0; + while (i < program.function_count) { + if (program.functions[i].has_body == 1 + && !ir_bytecode_function_flow(&context, i, identities, identity_capacity)) { + return result.status as i32; + } + i += 1; + } + scratch.used = base; + if (!ir_bytecode_verify_sources(&context) || !ir_bytecode_inventory(program, limits, result)) { + return result.status as i32; + } + result.table = 0; + result.index = 0; + return 0; +} + +export(c) fun whale_ir_bytecode_verify(program: ptr, words: ptr, capacity: u64, + limits: ptr, result: ptr) -> i32 { + if (result == null) { return 4; } + ir_bytecode_result_init(result); + return ir_bytecode_verify_impl(program, words, capacity, limits, result); +} diff --git a/ir/bytecode_verify_flow.wave b/ir/bytecode_verify_flow.wave new file mode 100644 index 0000000..c068227 --- /dev/null +++ b/ir/bytecode_verify_flow.wave @@ -0,0 +1,296 @@ +// SPDX-License-Identifier: MPL-2.0 +// All definition, predecessor and dominator facts are derived here, never read +// from the file. The shared Wave CFG and SSA cores consume only these facts. +fun ir_bytecode_unique(table: ptr, capacity: u64, kind: u64, + a: u64, b: u64, c: u64, context: ptr) -> bool { + var result: ptr = context.result; + var at: u64 = ir_source_slot(table, capacity, kind, a, b, c, + &result.work, context.limits.max_work); + if (at == capacity) { return ir_bytecode_fail(result, 3, 1, result.table, result.index); } + if (table[at].kind != 0) { return ir_bytecode_fail(result, 1, 60, result.table, result.index); } + ir_source_put(table, at, kind, a, b, c, 0, 0); + return true; +} + +fun ir_bytecode_has_destination(inst: ptr) -> bool { + var op: u64 = inst.op; + return op == 0 || (op >= 2 && op <= 19) || op == 21 || op == 24 + || op == 27 || op == 28 || (op == 29 && inst.dst != 18446744073709551615); +} + +fun ir_bytecode_target(function: ptr, target: u64, + context: ptr) -> bool { + if (target < function.first_block || target - function.first_block >= function.block_count) { + return ir_bytecode_fail(context.result, 1, 61, 5, context.result.index); + } + return true; +} + +fun ir_bytecode_successor(function: ptr, target: u64, block: u64, + edges: ptr, edge_count: ptr, seen: ptr, + context: ptr) -> bool { + if (!ir_bytecode_charge(context.result, context.limits, 1) + || !ir_bytecode_target(function, target, context)) { return false; } + var local: u64 = target - function.first_block; + if (seen[local] != block) { + seen[local] = block; + edges[edge_count[0]] = local; + edge_count[0] += 1; + } + return true; +} + +fun ir_bytecode_cfg_status(context: ptr, cfg: ptr) -> bool { + if (!ir_bytecode_charge(context.result, context.limits, cfg.work)) { return false; } + if (cfg.status == 3) { + return ir_bytecode_fail(context.result, 3, 1, 4, cfg.index); + } + if (cfg.status != 0) { + return ir_bytecode_fail(context.result, 1, 62, 4, cfg.index); + } + return true; +} + +fun ir_bytecode_function_flow(context: ptr, function_index: u64, + identities: ptr, identity_capacity: u64) -> bool { + var p: ptr = context.program; + var limits: ptr = context.limits; + var result: ptr = context.result; + var function: ptr = &p.functions[function_index]; + var saved: u64 = context.scratch.used; + var n: u64 = function.block_count; + var first_instruction: u64 = p.blocks[function.first_block].first; + var last_block: ptr = &p.blocks[function.first_block + n - 1]; + var instruction_count: u64 = last_block.first + last_block.count - first_instruction; + var edge_capacity: u64 = n * 2 + p.operand_count; + var successors: ptr = ir_bytecode_take(context.scratch, n * 2, result) as ptr; + var edges: ptr = ir_bytecode_take(context.scratch, edge_capacity, result); + var predecessor_blocks: ptr = ir_bytecode_take(context.scratch, n * 2, result) as ptr; + var predecessors: ptr = ir_bytecode_take(context.scratch, edge_capacity, result); + var seen: ptr = ir_bytecode_take(context.scratch, n, result); + var cursors: ptr = ir_bytecode_take(context.scratch, n, result); + var stack_block: ptr = ir_bytecode_take(context.scratch, n, result); + var stack_next: ptr = ir_bytecode_take(context.scratch, n, result); + var order: ptr = ir_bytecode_take(context.scratch, n, result); + var temporary: ptr = ir_bytecode_take(context.scratch, n, result); + var rank: ptr = ir_bytecode_take(context.scratch, n, result); + var idom: ptr = ir_bytecode_take(context.scratch, n, result); + var temporary_idom: ptr = ir_bytecode_take(context.scratch, n, result); + var heads: ptr = ir_bytecode_take(context.scratch, n, result); + var next: ptr = ir_bytecode_take(context.scratch, n, result); + var blocks: ptr = ir_bytecode_take(context.scratch, n * 9, result) as ptr; + var instructions: ptr = ir_bytecode_take(context.scratch, + instruction_count * 5, result) as ptr; + var use_capacity: u64 = instruction_count * 3 + p.operand_count; + var uses: ptr = ir_bytecode_take(context.scratch, + use_capacity * 6, result) as ptr; + var phi_capacity: u64 = 2; + while (phi_capacity / 2 < n) { phi_capacity *= 2; } + var phi_table: ptr = ir_bytecode_take(context.scratch, + phi_capacity * 2, result) as ptr; + if (result.status != 0) { return false; } + var b: u64 = 0; + while (b < n) { + if (!ir_bytecode_charge(result, limits, 1)) { return false; } + seen[b] = 18446744073709551615; + predecessor_blocks[b].count = 0; + heads[b] = 18446744073709551615; + next[b] = 18446744073709551615; + b += 1; + } + var edge_count: u64 = 0; + b = 0; + while (b < n) { + var block: ptr = &p.blocks[function.first_block + b]; + var terminal: ptr = &p.instructions[block.first + block.count - 1]; + result.index = block.first + block.count - 1; + successors[b].first = edge_count; + if (terminal.op == 31) { + if (!ir_bytecode_successor(function, terminal.a, b, edges, &edge_count, seen, context)) { return false; } + } else if (terminal.op == 32) { + if (!ir_bytecode_successor(function, terminal.b, b, edges, &edge_count, seen, context) + || !ir_bytecode_successor(function, terminal.c, b, edges, &edge_count, seen, context)) { return false; } + } else if (terminal.op == 33) { + if (terminal.first > p.operand_count + || terminal.count > (p.operand_count - terminal.first) / 3) { + return ir_bytecode_fail(result, 1, 41, 5, result.index); + } + if (!ir_bytecode_successor(function, terminal.b, b, edges, &edge_count, seen, context)) { return false; } + var i: u64 = 0; + var kind: u64 = p.types[terminal.ty].kind; + var literal: u64 = 1; + if (ir_verify_unsigned(kind)) { literal = 2; } + if (kind == 1) { literal = 3; } + while (i < terminal.count) { + var at: u64 = terminal.first + i * 3; + var low: u64 = p.operands[at]; + var high: u64 = p.operands[at + 1]; + if (!ir_verify_literal(kind, literal, low, high)) { + return ir_bytecode_fail(result, 1, 46, 5, result.index); + } + if (!ir_bytecode_unique(identities, identity_capacity, 8, result.index, + low, high, context)) { return false; } + if (!ir_bytecode_successor(function, p.operands[at + 2], b, + edges, &edge_count, seen, context)) { return false; } + i += 1; + } + } + successors[b].count = edge_count - successors[b].first; + var i: u64 = successors[b].first; + while (i < edge_count) { + if (!ir_bytecode_charge(result, limits, 1)) { return false; } + predecessor_blocks[edges[i]].count += 1; + i += 1; + } + b += 1; + } + var prefix: u64 = 0; + b = 0; + while (b < n) { + if (!ir_bytecode_charge(result, limits, 1)) { return false; } + predecessor_blocks[b].first = prefix; + cursors[b] = prefix; + prefix += predecessor_blocks[b].count; + b += 1; + } + b = 0; + while (b < n) { + var i: u64 = 0; + while (i < successors[b].count) { + if (!ir_bytecode_charge(result, limits, 1)) { return false; } + var target: u64 = edges[successors[b].first + i]; + predecessors[cursors[target]] = b; + cursors[target] += 1; + i += 1; + } + b += 1; + } + var cfg: IrCfgResult; + var entry: u64 = function.entry - function.first_block; + whale_ir_cfg_rpo(successors, n, edges, edge_count, entry, limits.max_work - result.work, + seen as ptr, n * 8, stack_block, stack_next, n, temporary, n, order, n, &cfg); + if (!ir_bytecode_cfg_status(context, &cfg)) { return false; } + var order_count: u64 = cfg.count; + whale_ir_cfg_idom(predecessor_blocks, n, predecessors, edge_count, order, order_count, + entry, limits.max_work - result.work, rank, n, temporary_idom, n, idom, n, &cfg); + if (!ir_bytecode_cfg_status(context, &cfg)) { return false; } + b = 0; + while (b < n) { + if (!ir_bytecode_charge(result, limits, 1)) { return false; } + blocks[b].reachable = 0; + blocks[b].start = 0; + blocks[b].end = 0; + if (idom[b] != 18446744073709551615) { + blocks[b].reachable = 1; + if (b != entry) { + next[b] = heads[idom[b]]; + heads[idom[b]] = b; + } + } + b += 1; + } + var depth: u64 = 1; + var clock: u64 = 1; + stack_block[0] = entry; + stack_next[0] = heads[entry]; + blocks[entry].start = clock; + while (depth != 0) { + if (!ir_bytecode_charge(result, limits, 1)) { return false; } + var top: u64 = depth - 1; + var child: u64 = stack_next[top]; + if (child == 18446744073709551615) { + clock += 1; + blocks[stack_block[top]].end = clock; + depth -= 1; + } else { + stack_next[top] = next[child]; + clock += 1; + blocks[child].start = clock; + stack_block[depth] = child; + stack_next[depth] = heads[child]; + depth += 1; + } + } + var use_count: u64 = 0; + b = 0; + while (b < n) { + var block: ptr = &p.blocks[function.first_block + b]; + blocks[b].id = block.id; + blocks[b].first = block.first - first_instruction; + blocks[b].count = block.count - 1; + blocks[b].pred_first = predecessor_blocks[b].first; + blocks[b].pred_count = predecessor_blocks[b].count; + blocks[b].terminator_use = 18446744073709551615; + var position: u64 = 0; + while (position < block.count) { + result.index = block.first + position; + var inst: ptr = &p.instructions[result.index]; + if (!ir_bytecode_charge(result, limits, 1) + || !ir_bytecode_instruction(context, function, inst)) { return false; } + var count: u64 = ir_bytecode_operands(context, function, inst); + if (result.status != 0) { return false; } + var item: ptr = &instructions[result.index - first_instruction]; + item.phi = 0; + if (inst.op == 15) { item.phi = 1; } + item.dst = inst.dst; + item.ty = inst.ty; + item.first = use_count; + item.count = count; + if (count > use_capacity - use_count) { return ir_bytecode_fail(result, 4, 3, 5, result.index); } + var i: u64 = 0; + while (i < count) { + if (!ir_bytecode_charge(result, limits, 1)) { return false; } + var slot: u64 = 0; + // Operand.value is the original identity; find the corresponding + // dense slot from the already validated instruction spelling. + if (inst.op == 15) { slot = p.operands[inst.first + i * 2]; } + else if (inst.op == 24) { + slot = inst.a; + if (i != 0) { slot = p.operands[inst.first + i - 1]; } + } else if (inst.op == 29) { + slot = inst.a; + if (inst.flags == 0) { slot = p.operands[inst.first + i]; } + else if (i != 0) { slot = p.operands[inst.first + i - 1]; } + } else if (inst.op == 20 || inst.op == 22) { + slot = inst.b; + if (i == 1) { slot = inst.a; } + } else { + slot = inst.a; + if (i == 1) { slot = inst.b; } + if (i == 2) { slot = inst.c; } + } + var definition: ptr = &context.definitions[function.first_value_type + slot]; + var usage: ptr = &uses[use_count]; + usage.value = p.value_ids[function.first_value_type + slot]; + usage.ty = p.value_types[function.first_value_type + slot]; + usage.pred = 18446744073709551615; + if (inst.op == 15) { + var predecessor: u64 = p.operands[inst.first + i * 2 + 1]; + if (!ir_bytecode_target(function, predecessor, context)) { return false; } + usage.pred = predecessor - function.first_block; + } + usage.def_block = definition.block; + usage.def_position = definition.position; + usage.defined = definition.defined; + use_count += 1; + i += 1; + } + if (position + 1 == block.count && count != 0) { + blocks[b].terminator_use = item.first; + } + position += 1; + } + b += 1; + } + var ssa: IrSsaResult; + whale_ir_verify_ssa(p.types, p.type_count, p.edges, p.edge_count, blocks, n, entry, + instructions, instruction_count, uses, use_count, predecessors, edge_count, + phi_table, phi_capacity, limits.max_work - result.work, &ssa); + if (!ir_bytecode_charge(result, limits, ssa.work)) { return false; } + if (ssa.status == 8) { return ir_bytecode_fail(result, 3, 1, 5, ssa.instruction + first_instruction); } + if (ssa.status != 0) { + return ir_bytecode_fail(result, 1, 70 + ssa.status, 5, ssa.instruction + first_instruction); + } + context.scratch.used = saved; + return true; +} diff --git a/ir/bytecode_verify_instructions.wave b/ir/bytecode_verify_instructions.wave new file mode 100644 index 0000000..e8d3134 --- /dev/null +++ b/ir/bytecode_verify_instructions.wave @@ -0,0 +1,303 @@ +// SPDX-License-Identifier: MPL-2.0 +// The bytecode uses runtime opcode numbers; verifier operations have a separate +// namespace. Every operand is validated before either core sees its index. +fun ir_bytecode_operand(context: ptr, function: ptr, + slot: u64, at: u64) -> bool { + var result: ptr = context.result; + if (slot >= function.value_count || at >= context.operand_capacity) { + return ir_bytecode_fail(result, 1, 40, 5, result.index); + } + var index: u64 = function.first_value_type + slot; + var operand: ptr = &context.operands[at]; + var definition: ptr = &context.definitions[index]; + operand.value = context.program.value_ids[index]; + operand.ty = context.program.value_types[index]; + operand.literal = definition.literal; + operand.low = definition.low; + operand.high = definition.high; + return true; +} + +fun ir_bytecode_operands(context: ptr, function: ptr, + inst: ptr) -> u64 { + var op: u64 = inst.op; + var count: u64 = 0; + if (op == 1 || op == 2 || op == 6 || (op >= 7 && op <= 16 && op != 15) || op == 17 + || op == 19 || op == 21 || op == 24 || op == 25 || op == 26 + || op == 30 || op == 32 || op == 33 || (op == 34 && inst.a != 18446744073709551615) + || (op == 29 && inst.flags == 1)) { + if (!ir_bytecode_operand(context, function, inst.a, count)) { return 0; } + count += 1; + } + if (op == 2 || op == 7 || (op >= 10 && op <= 13) || op == 17 || op == 25 || op == 26) { + if (!ir_bytecode_operand(context, function, inst.b, count)) { return 0; } + count += 1; + } + if (op == 13 || op == 25 || op == 26) { + if (!ir_bytecode_operand(context, function, inst.c, count)) { return 0; } + count += 1; + } + if (op == 20 || op == 22) { + if (!ir_bytecode_operand(context, function, inst.b, count)) { return 0; } + count += 1; + if (!ir_bytecode_operand(context, function, inst.a, count)) { return 0; } + count += 1; + } + if (op == 23) { + if (!ir_bytecode_operand(context, function, inst.a, count)) { return 0; } + count += 1; + } + if (op == 15 || op == 24 || op == 29) { + var stride: u64 = 1; + if (op == 15) { stride = 2; } + if (inst.first > context.program.operand_count + || inst.count > (context.program.operand_count - inst.first) / stride) { + ir_bytecode_fail(context.result, 1, 41, 5, context.result.index); + return 0; + } + var i: u64 = 0; + while (i < inst.count) { + if (!ir_bytecode_charge(context.result, context.limits, 1)) { return 0; } + if (!ir_bytecode_operand(context, function, + context.program.operands[inst.first + i * stride], count)) { return 0; } + count += 1; + i += 1; + } + } + return count; +} + +fun ir_bytecode_kind(context: ptr, kind: u64) -> u64 { + var i: u64 = 0; + while (i < context.program.type_count) { + if (!ir_bytecode_charge(context.result, context.limits, 1)) { return 0; } + if (context.program.types[i].kind == kind) { return i; } + i += 1; + } + ir_bytecode_fail(context.result, 1, 42, 5, context.result.index); + return 0; +} + +fun ir_bytecode_destination(context: ptr, function: ptr, + inst: ptr) -> bool { + var op: u64 = inst.op; + if (inst.dst == 18446744073709551615) { return true; } + var actual: u64 = context.program.value_types[function.first_value_type + inst.dst]; + var node: ptr = &context.program.types[actual]; + if (op == 0 || op == 18) { + if (node.kind != 17) { return ir_bytecode_fail(context.result, 1, 43, 5, context.result.index); } + return ir_bytecode_same(context.program, node.child, inst.ty, context.limits, context.result); + } + if (op == 2) { + if (node.kind == 8) { return true; } + } else if (op >= 10 && op <= 12) { + if (node.kind == 1) { return true; } + } else if (op == 17) { + if (node.kind != 21 || node.count != 2 + || context.program.types[context.program.edges[node.first + 1]].kind != 1) { + return ir_bytecode_fail(context.result, 1, 43, 5, context.result.index); + } + return ir_bytecode_same(context.program, context.program.edges[node.first], inst.ty, + context.limits, context.result); + } else { + return ir_bytecode_same(context.program, actual, inst.ty, context.limits, context.result); + } + return ir_bytecode_fail(context.result, 1, 43, 5, context.result.index); +} + +fun ir_bytecode_instruction(context: ptr, function: ptr, + inst: ptr) -> bool { + var program: ptr = context.program; + var limits: ptr = context.limits; + var result: ptr = context.result; + var op: u64 = inst.op; + if (op > 35 || inst.ty >= program.type_count || inst.other >= program.type_count + || inst.align > 4294967295 || (op != 29 && inst.flags != 0)) { + return ir_bytecode_fail(result, 1, 44, 5, result.index); + } + if (!ir_bytecode_destination(context, function, inst)) { return false; } + var count: u64 = ir_bytecode_operands(context, function, inst); + if (result.status != 0) { return false; } + var operation: IrVerifyInstruction; + operation.op = 0; + operation.sub = 0; + operation.ty = inst.ty; + operation.other = inst.other; + operation.dst = 0; + operation.align = inst.align; + if (op == 0) { + if (inst.global >= program.global_count) { return ir_bytecode_fail(result, 1, 45, 5, result.index); } + return ir_bytecode_same(program, inst.ty, program.globals[inst.global].ty, limits, result); + } + if (op == 3 || op == 4) { + if (!ir_verify_literal(program.types[inst.ty].kind, inst.literal, inst.low, inst.high)) { + return ir_bytecode_fail(result, 1, 46, 5, result.index); + } + return true; + } + if (op == 5) { return true; } + if (op == 1) { operation.op = 5; } + if (op == 2) { operation.op = 6; } + if (op == 6) { operation.op = 8; } + if (op == 7) { + if (inst.sub > 17) { return ir_bytecode_fail(result, 1, 47, 5, result.index); } + operation.op = 4; + if (inst.sub == 4 || inst.sub == 6) { operation.sub = 1; } + if (inst.sub == 3 || inst.sub == 5) { operation.sub = 2; } + if (inst.sub >= 7 && inst.sub <= 11) { operation.sub = 3; } + } + if (op == 8) { operation.op = 1; } + if (op == 9) { operation.op = 7; } + if (op == 10 || op == 11) { + if ((op == 10 && inst.sub > 15) || (op == 11 && inst.sub > 9)) { + return ir_bytecode_fail(result, 1, 47, 5, result.index); + } + operation.op = 9; + if (op == 10) { + if (inst.sub >= 2 && inst.sub <= 5) { operation.sub = 1; } + if (inst.sub >= 6 && inst.sub <= 9) { operation.sub = 2; } + if (inst.sub >= 10) { operation.sub = 3; } + } else { + if (inst.sub >= 2 && inst.sub <= 5) { operation.sub = 2; } + if (inst.sub >= 6) { operation.sub = 1; } + } + } + if (op == 12) { + if (inst.sub > 15) { return ir_bytecode_fail(result, 1, 47, 5, result.index); } + operation.op = 10; + } + if (op == 13) { operation.op = 11; } + if (op == 14) { + if (inst.sub > 12) { return ir_bytecode_fail(result, 1, 47, 5, result.index); } + operation.op = 2; + operation.sub = inst.sub; + operation.ty = inst.other; + operation.other = inst.ty; + } + if (op == 15) { + if (!ir_bytecode_storable(program, inst.ty, limits, result)) { return false; } + var i: u64 = 0; + while (i < count) { + if (!ir_bytecode_same(program, inst.ty, context.operands[i].ty, limits, result)) { return false; } + i += 1; + } + return true; + } + if (op == 16) { + operation.op = 12; + operation.sub = inst.sub; + } + if (op == 17) { + if (inst.sub > 5) { return ir_bytecode_fail(result, 1, 47, 5, result.index); } + operation.op = 3; + if (inst.sub < 3) { operation.sub = 1; } + } + if (op == 18) { operation.op = 14; } + if (op == 19) { operation.op = 15; } + if (op == 20) { operation.op = 16; } + if (op == 21) { operation.op = 17; } + if (op == 22) { operation.op = 18; } + if (op == 23) { operation.op = 13; } + if (op >= 18 && op <= 23 && context.types[inst.ty].storable == 0) { + return ir_bytecode_fail(result, 1, 48, 5, result.index); + } + if (op == 24) { operation.op = 19; } + if (op == 25 || op == 26) { + operation.op = op - 5; + operation.ty = ir_bytecode_kind(context, 9); + operation.other = ir_bytecode_kind(context, 12); + if (result.status != 0) { return false; } + } + if (op == 27 || op == 28) { + if (inst.signature >= program.type_count || program.types[inst.signature].kind != 18) { + return ir_bytecode_fail(result, 1, 49, 5, result.index); + } + if (!ir_bytecode_same(program, inst.ty, inst.signature, limits, result)) { return false; } + if (op == 28) { + if (inst.a >= program.function_count) { return ir_bytecode_fail(result, 1, 49, 5, result.index); } + return ir_bytecode_same(program, inst.signature, program.functions[inst.a].signature, limits, result); + } + return true; + } + var operand_start: u64 = 0; + if (op == 29) { + if (inst.flags > 1 || inst.sub > 1) { return ir_bytecode_fail(result, 1, 49, 5, result.index); } + operation.op = 28; + operation.sub = inst.sub; + operation.other = inst.ty; + if (inst.dst != 18446744073709551615) { operation.dst = 1; } + if (inst.flags == 0) { + if (inst.a >= program.function_count) { return ir_bytecode_fail(result, 1, 49, 5, result.index); } + operation.ty = program.functions[inst.a].signature; + } else { + operation.ty = context.operands[0].ty; + operand_start = 1; + count -= 1; + } + } + if (op == 30 || op == 32) { + if (program.types[context.operands[0].ty].kind != 1) { + return ir_bytecode_fail(result, 1, 50, 5, result.index); + } + } + if (op == 30 || op == 35) { + if (inst.global >= program.text_count) { return ir_bytecode_fail(result, 1, 51, 5, result.index); } + return true; + } + if (op == 31 || op == 32) { return true; } + if (op == 33) { + var kind: u64 = program.types[inst.ty].kind; + if ((!ir_verify_integer(kind) && kind != 1) + || !ir_bytecode_same(program, context.operands[0].ty, inst.ty, limits, result)) { + if (result.status == 0) { ir_bytecode_fail(result, 1, 52, 5, result.index); } + return false; + } + return true; + } + if (op == 34) { + var ret: u64 = program.edges[program.types[function.signature].first]; + if (!ir_bytecode_same(program, ret, inst.ty, limits, result)) { return false; } + if (program.types[ret].kind == 0) { + if (inst.a != 18446744073709551615) { return ir_bytecode_fail(result, 1, 53, 5, result.index); } + return true; + } + if (inst.a == 18446744073709551615) { return ir_bytecode_fail(result, 1, 53, 5, result.index); } + return ir_bytecode_same(program, ret, context.operands[0].ty, limits, result); + } + if (operation.op == 0) { return ir_bytecode_fail(result, 1, 54, 5, result.index); } + var semantic: IrVerifyResult; + ir_bytecode_semantic_init(&semantic); + var status: i32 = whale_ir_verify_semantics(program.types, program.type_count, + program.edges, program.edge_count, &operation, &context.operands[operand_start], count, + limits.max_work - result.work, &semantic); + if (!ir_bytecode_semantic(result, limits, &semantic, status == 0)) { return false; } + if (op == 14) { + operation.op = 30; + operation.ty = inst.other; + operation.other = inst.ty; + status = whale_ir_verify_semantics(program.types, program.type_count, program.edges, + program.edge_count, &operation, context.operands, count, + limits.max_work - result.work, &semantic); + if (!ir_bytecode_semantic(result, limits, &semantic, status == 0)) { return false; } + } + if (op == 24) { + var selected: u64 = program.types[context.operands[0].ty].child; + var i: u64 = 1; + while (i < count) { + if (!ir_bytecode_charge(result, limits, 1)) { return false; } + if (i == 1 || program.types[selected].kind == 19) { + if (i != 1) { selected = program.types[selected].child; } + if (context.types[selected].storable == 0) { + return ir_bytecode_fail(result, 1, 48, 5, result.index); + } + if (context.types[selected].size == 0) { + return ir_bytecode_fail(result, 5, 110, 5, result.index); + } + } else { + selected = program.edges[program.types[selected].first + context.operands[i].low]; + } + i += 1; + } + } + return true; +} diff --git a/ir/bytecode_verify_types.wave b/ir/bytecode_verify_types.wave new file mode 100644 index 0000000..8450bad --- /dev/null +++ b/ir/bytecode_verify_types.wave @@ -0,0 +1,298 @@ +// SPDX-License-Identifier: MPL-2.0 +// Type and text validation is shared by emission and hostile-file admission. +struct IrBytecodeScratch { + words: ptr; + capacity: u64; + used: u64; +} + +fun ir_bytecode_take(scratch: ptr, count: u64, + result: ptr) -> ptr { + if (scratch.used > scratch.capacity || count > scratch.capacity - scratch.used) { + ir_bytecode_fail(result, 4, 3, 0, count); + return null; + } + var data: ptr = &scratch.words[scratch.used]; + scratch.used += count; + return data; +} + +fun ir_bytecode_semantic(result: ptr, limits: ptr, + semantic: ptr, valid: bool) -> bool { + if (!ir_bytecode_charge(result, limits, semantic.work)) { return false; } + if (semantic.status == 8) { + return ir_bytecode_fail(result, 3, 1, result.table, result.index); + } + if (!valid || semantic.status != 0) { + return ir_bytecode_fail(result, 1, 10 + semantic.status, result.table, result.index); + } + return true; +} + +fun ir_bytecode_semantic_init(semantic: ptr) { + semantic.status = 0; + semantic.index = 0; + semantic.expected = 0; + semantic.actual = 0; + semantic.detail = 0; + semantic.work = 0; +} + +fun ir_bytecode_same(program: ptr, a: u64, b: u64, + limits: ptr, result: ptr) -> bool { + if (a >= program.type_count || b >= program.type_count) { + return ir_bytecode_fail(result, 1, 10, result.table, result.index); + } + var semantic: IrVerifyResult; + ir_bytecode_semantic_init(&semantic); + var valid: bool = ir_verify_equal(a, b, program.types, program.edges, + limits.max_type_depth, &semantic, limits.max_work - result.work); + return ir_bytecode_semantic(result, limits, &semantic, valid); +} + +fun ir_bytecode_storable(program: ptr, ty: u64, + limits: ptr, result: ptr) -> bool { + var semantic: IrVerifyResult; + ir_bytecode_semantic_init(&semantic); + var valid: bool = ir_verify_storable(ty, program.types, program.edges, + limits.max_type_depth, &semantic, limits.max_work - result.work); + return ir_bytecode_semantic(result, limits, &semantic, valid); +} + +fun ir_bytecode_value_type(program: ptr, ty: u64) -> bool { + var node: ptr = &program.types[ty]; + if (node.kind >= 1 && node.kind <= 18) { return true; } + return node.kind == 21 && node.count == 2 + && ir_verify_integer(program.types[program.edges[node.first]].kind) + && program.types[program.edges[node.first + 1]].kind == 1; +} + +fun ir_bytecode_utf8(data: ptr, count: u64, + limits: ptr, result: ptr) -> bool { + if (!ir_bytecode_charge(result, limits, count)) { return false; } + var i: u64 = 0; + while (i < count) { + var first: u64 = data[i] as u64; + var width: u64 = 1; + if (first >= 194 && first <= 223) { width = 2; } + else if (first >= 224 && first <= 239) { width = 3; } + else if (first >= 240 && first <= 244) { width = 4; } + else if (first >= 128) { + return ir_bytecode_fail(result, 1, 31, 11, i); + } + if (width > count - i) { return ir_bytecode_fail(result, 1, 31, 11, i); } + var j: u64 = 1; + while (j < width) { + var octet: u64 = data[i + j] as u64; + if (octet < 128 || octet > 191) { return ir_bytecode_fail(result, 1, 31, 11, i); } + j += 1; + } + if (width >= 3) { + var second: u64 = data[i + 1] as u64; + if ((first == 224 && second < 160) || (first == 237 && second >= 160) + || (first == 240 && second < 144) || (first == 244 && second >= 144)) { + return ir_bytecode_fail(result, 1, 31, 11, i); + } + } + i += width; + } + return true; +} + +fun ir_bytecode_verify_types(program: ptr, scratch: ptr, + limits: ptr, result: ptr) -> bool { + result.table = 1; + if (limits.max_type_depth == 0 || limits.max_type_depth > 1024) { + return ir_bytecode_fail(result, 1, 10, 1, 0); + } + var semantic: IrVerifyResult; + ir_bytecode_semantic_init(&semantic); + var valid: bool = ir_verify_graph_valid(program.types, program.type_count, program.edges, + program.edge_count, limits.max_work - result.work, &semantic); + if (!ir_bytecode_semantic(result, limits, &semantic, valid)) { return false; } + var depths: ptr = ir_bytecode_take(scratch, program.type_count, result); + if (result.status != 0) { return false; } + var i: u64 = 0; + while (i < program.type_count) { + result.index = i; + if (!ir_bytecode_charge(result, limits, 1)) { return false; } + var node: ptr = &program.types[i]; + var depth: u64 = 1; + if (node.kind <= 16) { + if (node.child != 0 || node.first != 0 || node.count != 0 || node.extra != 0) { + return ir_bytecode_fail(result, 1, 11, 1, i); + } + } else if (node.kind == 17 || node.kind == 19) { + if (node.first != 0 || node.extra != 0 || (node.kind == 17 && node.count != 0)) { + return ir_bytecode_fail(result, 1, 11, 1, i); + } + depth = depths[node.child] + 1; + } else { + if (node.child != 0 || (node.kind != 18 && node.extra != 0) + || (node.kind == 18 && (node.count == 0 || node.extra > 3))) { + return ir_bytecode_fail(result, 1, 11, 1, i); + } + var child: u64 = 0; + while (child < node.count) { + if (!ir_bytecode_charge(result, limits, 1)) { return false; } + var next: u64 = depths[program.edges[node.first + child]] + 1; + if (next > depth) { depth = next; } + child += 1; + } + } + if (depth > limits.max_type_depth) { return ir_bytecode_fail(result, 2, 5, 1, i); } + depths[i] = depth; + if (node.kind == 18) { + ir_bytecode_semantic_init(&semantic); + valid = ir_verify_signature(i, program.types, program.edges, limits.max_type_depth, + &semantic, limits.max_work - result.work); + if (!ir_bytecode_semantic(result, limits, &semantic, valid)) { return false; } + } + i += 1; + } + i = 0; + while (i < program.value_type_count) { + if (!ir_bytecode_charge(result, limits, 1)) { return false; } + if (program.value_types[i] >= program.type_count || program.value_ids[i] > 4294967295) { + return ir_bytecode_fail(result, 1, 10, 7, i); + } + i += 1; + } + if (!ir_bytecode_utf8(program.text_bytes, program.text_byte_count, limits, result)) { return false; } + var text_cursor: u64 = 0; + i = 0; + while (i < program.text_count) { + var text: ptr = &program.texts[i]; + if (text.first != text_cursor || text.first > program.text_byte_count || text.count > program.text_byte_count - text.first) { + return ir_bytecode_fail(result, 1, 30, 10, i); + } + if (!ir_bytecode_utf8(&program.text_bytes[text.first], text.count, limits, result)) { return false; } + text_cursor += text.count; + i += 1; + } + if (text_cursor != program.text_byte_count) { return ir_bytecode_fail(result, 1, 30, 10, i); } + return true; +} + +struct IrBytecodeType { + size: u64; + align: u64; + depth: u64; + expanded: u64; + storable: u64; +} + +struct IrBytecodeDefinition { + block: u64; + position: u64; + defined: u64; + literal: u64; + low: u64; + high: u64; +} + +struct IrBytecodeVerifier { + program: ptr; + limits: ptr; + result: ptr; + scratch: ptr; + types: ptr; + definitions: ptr; + operands: ptr; + operand_capacity: u64; + owned_bytes: u64; +} + +fun ir_bytecode_layouts(context: ptr) -> bool { + var program: ptr = context.program; + var limits: ptr = context.limits; + var result: ptr = context.result; + var total: u64 = 0; + var remaining: u64 = limits.max_workspace_bytes - result.decoded_bytes - result.scratch_words * 8; + if (context.owned_bytes > remaining) { return ir_bytecode_fail(result, 2, 6, 11, 0); } + remaining -= context.owned_bytes; + var i: u64 = 0; + while (i < program.type_count) { + if (!ir_bytecode_charge(result, limits, 1)) { return false; } + var node: ptr = &program.types[i]; + var info: ptr = &context.types[i]; + info.size = 0; + info.align = 1; + info.depth = 1; + info.expanded = 1; + info.storable = 0; + var width: u64 = ir_verify_width(node.kind); + if (node.kind >= 1 && node.kind <= 16) { + info.size = width / 8; + if (node.kind == 1 || width == 1) { info.size = 1; } + info.align = info.size; + info.storable = 1; + } else if (node.kind == 17 || node.kind == 19) { + var child: ptr = &context.types[node.child]; + info.depth = child.depth + 1; + info.expanded += child.expanded; + if (node.kind == 17) { + info.size = 8; + info.align = 8; + info.storable = 1; + } else if (child.storable == 1 + && (node.count == 0 || child.size <= 18446744073709551615 / node.count)) { + info.size = child.size * node.count; + info.align = child.align; + info.storable = 1; + } + } else if (node.kind >= 18) { + info.storable = 1; + var j: u64 = 0; + while (j < node.count) { + if (!ir_bytecode_charge(result, limits, 1)) { return false; } + var child: ptr = &context.types[program.edges[node.first + j]]; + if (child.expanded > remaining / 512 + || info.expanded > remaining / 512 - child.expanded) { + return ir_bytecode_fail(result, 2, 6, 1, i); + } + info.expanded += child.expanded; + if (child.depth + 1 > info.depth) { info.depth = child.depth + 1; } + if (node.kind != 18) { + if (child.storable == 0) { info.storable = 0; } + var aligned: u64 = 0; + if (!ir_align_up(info.size, child.align, &aligned) + || child.size > 18446744073709551615 - aligned) { + info.storable = 0; + } else { + info.size = aligned + child.size; + } + if (child.align > info.align) { info.align = child.align; } + } + j += 1; + } + if (node.kind == 18) { + info.size = 8; + info.align = 8; + } else { + var aligned: u64 = 0; + if (!ir_align_up(info.size, info.align, &aligned)) { info.storable = 0; } + info.size = aligned; + } + } + if (info.expanded > remaining / 512 || total > remaining / 512 - info.expanded) { + return ir_bytecode_fail(result, 2, 6, 1, i); + } + total += info.expanded; + i += 1; + } + i = 0; + while (i < program.function_count) { + if (!ir_bytecode_charge(result, limits, 1)) { return false; } + var signature: u64 = program.functions[i].signature; + if (signature >= program.type_count) { return ir_bytecode_fail(result, 1, 80, 3, i); } + var expanded: u64 = context.types[signature].expanded; + if (expanded > remaining / 512 || total > remaining / 512 - expanded) { + return ir_bytecode_fail(result, 2, 6, 3, i); + } + total += expanded; + i += 1; + } + context.owned_bytes += total * 512; + return true; +} diff --git a/ir/bytecode_writer.wave b/ir/bytecode_writer.wave new file mode 100644 index 0000000..2602e4c --- /dev/null +++ b/ir/bytecode_writer.wave @@ -0,0 +1,162 @@ +// SPDX-License-Identifier: MPL-2.0 +// Canonical little-endian emission has no allocation or host callbacks. All +// validation, capacity and work checks precede the first output byte. +fun ir_bytecode_put_word(output: ptr, offset: u64, word: u64) { + var byte_index: u64 = 0; + while (byte_index < 8) { + output[offset + byte_index] = (word >> (byte_index * 8)) as u8; + byte_index += 1; + } +} + +fun ir_bytecode_project_word(program: ptr, table: u64, + record: u64, field: u64) -> u64 { + if (table == 5) { + var native_field: u64 = field; + if (field >= 9) { + native_field += 2; + } + var instructions: ptr = program.instructions as ptr; + return instructions[record * 21 + native_field]; + } + if (table == 8) { + var global: ptr = &program.globals[record]; + if (field == 0) { + return global.id; + } + if (field == 1) { + return global.ty; + } + if (field == 2) { + return global.align; + } + if (field == 3) { + return global.readonly; + } + if (field == 4) { + return global.initialized; + } + if (field == 5) { + return global.value.literal; + } + if (field == 6) { + return global.value.low; + } + return global.value.high; + } + var data: ptr = ir_bytecode_data(program, table) as ptr; + return data[record * (ir_bytecode_stride(table) / 8) + field]; +} + +fun ir_bytecode_encoded_size(program: ptr, + limits: ptr, result: ptr, + required: ptr) -> bool { + var table: u64 = 1; + var count: u64 = 0; + var stride: u64 = 0; + var size: u64 = 576; + while (table <= 16) { + count = ir_bytecode_count(program, table); + stride = ir_bytecode_stride(table); + if (count > (18446744073709551615 - size) / stride) { + return ir_bytecode_fail(result, 1, 120, table, count); + } + size += count * stride; + if (size > limits.max_input_bytes) { + return ir_bytecode_fail(result, 1, 121, table, count); + } + table += 1; + } + required[0] = size; + return true; +} + +fun ir_bytecode_publish(program: ptr, output: ptr, + size: u64) { + // "WHALEBC\0", format 1, IR semantics 1, tracked64 layout profile 1. + ir_bytecode_put_word(output, 0, 18931688839137367); + ir_bytecode_put_word(output, 8, 1); + ir_bytecode_put_word(output, 16, 1); + ir_bytecode_put_word(output, 24, 1); + ir_bytecode_put_word(output, 32, size); + ir_bytecode_put_word(output, 40, 16); + ir_bytecode_put_word(output, 48, 0); + ir_bytecode_put_word(output, 56, 576); + var table: u64 = 1; + var offset: u64 = 576; + var count: u64 = 0; + var stride: u64 = 0; + var record: u64 = 0; + var field: u64 = 0; + var directory: u64 = 64; + while (table <= 16) { + count = ir_bytecode_count(program, table); + stride = ir_bytecode_stride(table); + ir_bytecode_put_word(output, directory, table); + ir_bytecode_put_word(output, directory + 8, offset); + ir_bytecode_put_word(output, directory + 16, count); + ir_bytecode_put_word(output, directory + 24, stride); + if (table == 11) { + record = 0; + while (record < count) { + output[offset + record] = program.text_bytes[record]; + record += 1; + } + } else { + record = 0; + while (record < count) { + field = 0; + while (field < stride / 8) { + ir_bytecode_put_word(output, offset + record * stride + field * 8, + ir_bytecode_project_word(program, table, record, field)); + field += 1; + } + record += 1; + } + } + offset += count * stride; + directory += 32; + table += 1; + } +} + +export(c) fun whale_ir_bytecode_write(program: ptr, output: ptr, + capacity: u64, required: ptr, scratch: ptr, scratch_capacity: u64, + limits: ptr, result: ptr) -> i32 { + if (result == null) { + return 4; + } + if (program == null || limits == null || required == null) { + ir_bytecode_result_init(result); + ir_bytecode_fail(result, 4, 3, 0, 0); + return 4; + } + required[0] = 0; + var status: i32 = whale_ir_bytecode_verify(program, scratch, scratch_capacity, + limits, result); + if (status != 0) { + return status; + } + if (!ir_bytecode_encoded_size(program, limits, result, required)) { + return result.status as i32; + } + if (output == null && capacity == 0) { + return 0; + } + if (capacity < required[0]) { + ir_bytecode_fail(result, 2, 122, 0, required[0]); + return 2; + } + if (!ir_span_valid(output, required[0], 1)) { + ir_bytecode_fail(result, 4, 3, 0, 0); + return 4; + } + // Admit the complete publish pass up front. After this charge, emission has + // no failure path and cannot leave a partially written rejected image. + var words: u64 = (required[0] - program.text_byte_count) / 8; + if (!ir_bytecode_charge(result, limits, words + program.text_byte_count)) { + return result.status as i32; + } + ir_bytecode_publish(program, output, required[0]); + return 0; +} diff --git a/ir/meson.build b/ir/meson.build index 7d888dc..20615c8 100644 --- a/ir/meson.build +++ b/ir/meson.build @@ -61,6 +61,15 @@ if wave_ir_directory == '' and wave_source != '' 'runtime_prepare.wave', 'runtime_execute.wave', 'runtime_driver.wave', + 'bytecode_model.wave', + 'bytecode_inventory.wave', + 'bytecode_loader.wave', + 'bytecode_verify_types.wave', + 'bytecode_verify_instructions.wave', + 'bytecode_verify_flow.wave', + 'bytecode_verify.wave', + 'bytecode_writer.wave', + 'bytecode_runtime.wave', 'entry.wave', 'src/wave_layout.rs', 'src/interpreter/integer.rs', @@ -70,6 +79,7 @@ if wave_ir_directory == '' and wave_source != '' 'src/fold_integer_wave.rs', 'src/constant_wave.rs', 'src/interpreter/runtime_wave.rs', + 'src/bytecode.rs', 'src/verifier/wave_constants.rs', 'src/source_wave.rs', 'src/interpreter/memory_wave.rs', diff --git a/ir/runtime_prepare.wave b/ir/runtime_prepare.wave index a09862d..616e763 100644 --- a/ir/runtime_prepare.wave +++ b/ir/runtime_prepare.wave @@ -593,7 +593,7 @@ fun ir_runtime_initialize(p: ptr) -> bool { } p.result.global = i; var global: ptr = &p.globals[i]; - if (!ir_runtime_call_value(p.types[global.ty].kind)) { + if (global.initialized != 0 && !ir_runtime_call_value(p.types[global.ty].kind)) { return ir_runtime_error(p, 17, 18446744073709551615, i, 0); } if (!ir_runtime_layout(p, global.ty)) { diff --git a/ir/src/bytecode.rs b/ir/src/bytecode.rs new file mode 100644 index 0000000..3cc8740 --- /dev/null +++ b/ir/src/bytecode.rs @@ -0,0 +1,1039 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Versioned Whale bytecode. Wave writes, loads, verifies and executes the format; +//! Rust owns initialized buffers and the existing typed memory adapter. +use crate::{ConstValue, FunctionId, InterpreterError, InterpreterOptions, Module, Type}; + +/// Resource ceilings apply to the entire image, including unreachable functions. +#[derive(Clone, Copy, Debug)] +#[repr(C)] +pub struct BytecodeLimits { + pub max_input_bytes: u64, + pub max_decoded_bytes: u64, + pub max_records: u64, + pub max_work: u64, + pub max_type_depth: u64, + pub max_workspace_bytes: u64, +} + +impl Default for BytecodeLimits { + fn default() -> Self { + Self { + max_input_bytes: 64 * 1024 * 1024, + max_decoded_bytes: 128 * 1024 * 1024, + max_records: 1_000_000, + max_work: 67_108_864, + max_type_depth: 128, + max_workspace_bytes: 256 * 1024 * 1024, + } + } +} + +#[derive(Debug)] +pub enum BytecodeError { + Unavailable, + Target, + Allocation, + Invalid { status: u64, code: u64, table: u64, index: u64 }, + Backend(&'static str), + Interpreter(InterpreterError), +} + +impl std::fmt::Display for BytecodeError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Unavailable => f.write_str("Wave bytecode is unavailable in this build"), + Self::Target => { + f.write_str("bytecode requires the whale-bytecode-v1 target and layout") + }, + Self::Allocation => f.write_str("unable to allocate bounded bytecode buffers"), + Self::Invalid { status, code, table, index } => { + write!(f, + "invalid bytecode (status {status}, code {code}, table {table}, record {index})") + }, + Self::Backend(reason) => f.write_str(reason), + Self::Interpreter(error) => error.fmt(f), + } + } +} + +impl std::error::Error for BytecodeError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Interpreter(error) => Some(error), + _ => None, + } + } +} + +impl From for BytecodeError { + fn from(error: InterpreterError) -> Self { + Self::Interpreter(error) + } +} + +type Result = std::result::Result; + +pub const fn available() -> bool { + cfg!(whale_wave_ir) +} + +#[derive(Clone, Debug)] +pub struct FunctionInfo { + pub id: FunctionId, + pub params: Vec, + pub ret: Type, + pub has_body: bool, +} + +#[derive(Clone, Debug)] +pub struct ImageInfo { + pub functions: Vec, + pub globals: usize, + pub instructions: usize, + pub decoded_bytes: u64, +} + +/// A typed value preserves callable origin without granting pointer authority. +#[derive(Clone, Debug)] +pub struct BytecodeValue { + value: crate::RuntimeValue<'static>, + #[cfg_attr(not(whale_wave_ir), allow(dead_code))] + origin: u64, +} + +impl BytecodeValue { + pub fn scalar(ty: Type, value: ConstValue) -> std::result::Result { + Ok(Self { value: crate::RuntimeValue::scalar(ty, value)?, origin: 0 }) + } + + pub fn raw_pointer(ty: Type, address: u64) -> std::result::Result { + Ok(Self { value: crate::RuntimeValue::raw_pointer(ty, address)?, origin: 0 }) + } + + pub fn null_function( + signature: crate::FunctionSignature, + ) -> std::result::Result { + Ok(Self { value: crate::RuntimeValue::null_function(signature)?, origin: 0 }) + } + + pub fn ty(&self) -> &Type { + self.value.ty() + } + + pub fn scalar_value(&self) -> Option<&ConstValue> { + self.value.scalar_value() + } + + pub fn pointer_address(&self) -> Option { + self.value.pointer_address() + } + + pub fn function_target(&self) -> Option { + self.value.function_target() + } +} + +#[derive(Clone, Debug)] +pub struct BytecodeRunResult { + pub value: Option, + pub steps: u64, +} + +/// A fully verified owned image. No disk-derived runtime layout plans are trusted. +pub struct BytecodeProgram { + #[cfg(whale_wave_ir)] + native: native::Owned<'static>, + #[cfg_attr(not(whale_wave_ir), allow(dead_code))] + limits: BytecodeLimits, + #[cfg_attr(not(whale_wave_ir), allow(dead_code))] + identity: u64, +} + +impl BytecodeProgram { + pub fn load(bytes: &[u8], limits: BytecodeLimits) -> Result { + #[cfg(whale_wave_ir)] + { + native::load(bytes, limits) + } + #[cfg(not(whale_wave_ir))] + { + let _ = (bytes, limits); + Err(BytecodeError::Unavailable) + } + } + + pub fn verify(&mut self) -> Result { + #[cfg(whale_wave_ir)] + { + self.native.verify(self.limits)?; + self.native.info() + } + #[cfg(not(whale_wave_ir))] + { + Err(BytecodeError::Unavailable) + } + } + + pub fn function(&self, id: FunctionId) -> Result> { + #[cfg(whale_wave_ir)] + { + self.native.function(id) + } + #[cfg(not(whale_wave_ir))] + { + let _ = id; + Err(BytecodeError::Unavailable) + } + } + + pub fn run( + &mut self, + function: FunctionId, + arguments: &[ConstValue], + options: InterpreterOptions, + ) -> Result { + #[cfg(whale_wave_ir)] + { + self.native.run(function, arguments, options, self.limits, self.identity) + } + #[cfg(not(whale_wave_ir))] + { + let _ = (function, arguments, options); + Err(BytecodeError::Unavailable) + } + } + + pub fn run_values( + &mut self, + function: FunctionId, + arguments: &[BytecodeValue], + options: InterpreterOptions, + ) -> Result { + #[cfg(whale_wave_ir)] + { + self.native.run_values(function, arguments, options, self.limits, self.identity) + } + #[cfg(not(whale_wave_ir))] + { + let _ = (function, arguments, options); + Err(BytecodeError::Unavailable) + } + } + + pub fn function_value(&self, function: FunctionId) -> Result { + #[cfg(whale_wave_ir)] + { + Ok(BytecodeValue { + value: self.native.runtime.callable_value(function)?, + origin: self.identity, + }) + } + #[cfg(not(whale_wave_ir))] + { + let _ = function; + Err(BytecodeError::Unavailable) + } + } +} + +pub fn compile(module: &Module, limits: BytecodeLimits) -> Result> { + #[cfg(whale_wave_ir)] + { + native::compile(module, limits) + } + #[cfg(not(whale_wave_ir))] + { + let _ = (module, limits); + Err(BytecodeError::Unavailable) + } +} + +pub fn verify_bytes(bytes: &[u8], limits: BytecodeLimits) -> Result { + BytecodeProgram::load(bytes, limits)?.verify() +} + +pub fn run( + bytes: &[u8], + function: FunctionId, + arguments: &[ConstValue], + options: InterpreterOptions, + limits: BytecodeLimits, +) -> Result { + BytecodeProgram::load(bytes, limits)?.run(function, arguments, options) +} + +#[cfg(whale_wave_ir)] +mod native { + use super::*; + + use crate::interpreter::runtime_wave::{ + self, Program, RawBlock, RawFunction, RawGlobal, RawInstruction, RawType, + }; + + use std::sync::atomic::{AtomicU64, Ordering}; + + const MISSING: u64 = u64::MAX; + + const BACKEND: &str = "invalid Wave bytecode transport"; + + static NEXT_IDENTITY: AtomicU64 = AtomicU64::new(1); + + macro_rules! wire { + ($name:ident { $($field:ident: $ty:ty),* $(,)? }) => { + #[repr(C)] + #[derive(Clone, Copy, Default)] + struct $name { $($field: $ty),* } + }; + } + + wire!(Site { function: u64, block: u64, instruction: u64, value: u64 }); + wire!(Text { first: u64, count: u64 }); + wire!(File { id: u64, text: u64 }); + wire!(Original { + id: u64, + has_span: u64, + file: u64, + line: u64, + column: u64, + end_line: u64, + end_column: u64 + }); + wire!(Mapping { kind: u64, function: u64, block: u64, index: u64, original: u64 }); + wire!(Counts { + types: u64, + edges: u64, + functions: u64, + blocks: u64, + instructions: u64, + operands: u64, + value_types: u64, + globals: u64, + sites: u64, + texts: u64, + text_bytes: u64, + files: u64, + originals: u64, + mappings: u64, + value_ids: u64, + constant_global_ids: u64 + }); + wire!(RawResult { + status: u64, + code: u64, + table: u64, + index: u64, + work: u64, + decoded_bytes: u64, + scratch_words: u64, + counts: Counts + }); + #[repr(C)] + struct RawProgram { + types: *mut RawType, + type_count: u64, + edges: *mut u64, + edge_count: u64, + functions: *mut RawFunction, + function_count: u64, + blocks: *mut RawBlock, + block_count: u64, + instructions: *mut RawInstruction, + instruction_count: u64, + operands: *mut u64, + operand_count: u64, + value_types: *mut u64, + value_type_count: u64, + globals: *mut RawGlobal, + global_count: u64, + sites: *mut Site, + site_count: u64, + texts: *mut Text, + text_count: u64, + text_bytes: *mut u8, + text_byte_count: u64, + files: *mut File, + file_count: u64, + originals: *mut Original, + original_count: u64, + mappings: *mut Mapping, + mapping_count: u64, + value_ids: *mut u64, + value_id_count: u64, + constant_global_ids: *mut u64, + constant_global_count: u64, + } + + unsafe extern "C" { + fn whale_ir_bytecode_probe( + data: *const u8, + count: u64, + limits: *const BytecodeLimits, + result: *mut RawResult, + ) -> i32; + + fn whale_ir_bytecode_load( + data: *const u8, + count: u64, + program: *mut RawProgram, + scratch: *mut u64, + capacity: u64, + limits: *const BytecodeLimits, + result: *mut RawResult, + ) -> i32; + + fn whale_ir_bytecode_verify( + program: *mut RawProgram, + scratch: *mut u64, + capacity: u64, + limits: *const BytecodeLimits, + result: *mut RawResult, + ) -> i32; + + fn whale_ir_bytecode_write( + program: *mut RawProgram, + output: *mut u8, + capacity: u64, + required: *mut u64, + scratch: *mut u64, + scratch_capacity: u64, + limits: *const BytecodeLimits, + result: *mut RawResult, + ) -> i32; + } + + fn buffer(count: u64) -> Result> { + let count = usize::try_from(count).map_err(|_| BytecodeError::Allocation)?; + let mut values = Vec::new(); + values.try_reserve_exact(count).map_err(|_| BytecodeError::Allocation)?; + values.resize_with(count, T::default); + Ok(values) + } + + fn check(status: i32, result: &RawResult, limits: BytecodeLimits) -> Result<()> { + if status < 0 + || status as u64 != result.status + || result.status > 5 + || result.work > limits.max_work + { + return Err(BytecodeError::Backend(BACKEND)); + } + if status != 0 { + return Err(BytecodeError::Invalid { + status: result.status, + code: result.code, + table: result.table, + index: result.index, + }); + } + Ok(()) + } + + pub(super) struct Owned<'a> { + pub(super) runtime: Program<'a>, + sites: Vec, + texts: Vec, + text_bytes: Vec, + files: Vec, + originals: Vec, + mappings: Vec, + constant_globals: Vec, + scratch: Vec, + decoded_bytes: u64, + } + + impl<'a> Owned<'a> { + fn empty(counts: Counts) -> Result { + let mut runtime = Program::new(None)?; + runtime.types = buffer(counts.types)?; + runtime.edges = buffer(counts.edges)?; + runtime.functions = buffer(counts.functions)?; + runtime.blocks = buffer(counts.blocks)?; + runtime.instructions = buffer(counts.instructions)?; + runtime.operands = buffer(counts.operands)?; + runtime.value_types = buffer(counts.value_types)?; + runtime.value_ids = buffer(counts.value_ids)?; + runtime.globals = buffer(counts.globals)?; + Ok(Self { + runtime, + sites: buffer(counts.sites)?, + texts: buffer(counts.texts)?, + text_bytes: buffer(counts.text_bytes)?, + files: buffer(counts.files)?, + originals: buffer(counts.originals)?, + mappings: buffer(counts.mappings)?, + constant_globals: buffer(counts.constant_global_ids)?, + scratch: Vec::new(), + decoded_bytes: 0, + }) + } + + fn packet(&mut self) -> RawProgram { + RawProgram { + types: self.runtime.types.as_mut_ptr(), + type_count: self.runtime.types.len() as u64, + edges: self.runtime.edges.as_mut_ptr(), + edge_count: self.runtime.edges.len() as u64, + functions: self.runtime.functions.as_mut_ptr(), + function_count: self.runtime.functions.len() as u64, + blocks: self.runtime.blocks.as_mut_ptr(), + block_count: self.runtime.blocks.len() as u64, + instructions: self.runtime.instructions.as_mut_ptr(), + instruction_count: self.runtime.instructions.len() as u64, + operands: self.runtime.operands.as_mut_ptr(), + operand_count: self.runtime.operands.len() as u64, + value_types: self.runtime.value_types.as_mut_ptr(), + value_type_count: self.runtime.value_types.len() as u64, + globals: self.runtime.globals.as_mut_ptr(), + global_count: self.runtime.globals.len() as u64, + sites: self.sites.as_mut_ptr(), + site_count: self.sites.len() as u64, + texts: self.texts.as_mut_ptr(), + text_count: self.texts.len() as u64, + text_bytes: self.text_bytes.as_mut_ptr(), + text_byte_count: self.text_bytes.len() as u64, + files: self.files.as_mut_ptr(), + file_count: self.files.len() as u64, + originals: self.originals.as_mut_ptr(), + original_count: self.originals.len() as u64, + mappings: self.mappings.as_mut_ptr(), + mapping_count: self.mappings.len() as u64, + value_ids: self.runtime.value_ids.as_mut_ptr(), + value_id_count: self.runtime.value_ids.len() as u64, + constant_global_ids: self.constant_globals.as_mut_ptr(), + constant_global_count: self.constant_globals.len() as u64, + } + } + + pub(super) fn verify(&mut self, limits: BytecodeLimits) -> Result<()> { + let mut packet = self.packet(); + let mut result = RawResult::default(); + // Native verification queries exact scratch before inspecting semantic records. + let status = unsafe { + whale_ir_bytecode_verify(&mut packet, std::ptr::null_mut(), 0, &limits, &mut result) + }; + if status != 2 || result.status != 2 { + return check(status, &result, limits); + } + self.scratch = Vec::new(); + self.scratch = buffer(result.scratch_words)?; + let status = unsafe { + whale_ir_bytecode_verify( + &mut packet, + self.scratch.as_mut_ptr(), + self.scratch.len() as u64, + &limits, + &mut result, + ) + }; + check(status, &result, limits)?; + self.decoded_bytes = result.decoded_bytes; + Ok(()) + } + + fn text(&self, index: u64) -> Result<&str> { + let span = self.texts.get(index as usize).ok_or(BytecodeError::Backend(BACKEND))?; + let first = usize::try_from(span.first).map_err(|_| BytecodeError::Backend(BACKEND))?; + let end = first + .checked_add( + usize::try_from(span.count).map_err(|_| BytecodeError::Backend(BACKEND))?, + ) + .ok_or(BytecodeError::Backend(BACKEND))?; + std::str::from_utf8( + self.text_bytes.get(first..end).ok_or(BytecodeError::Backend(BACKEND))?, + ) + .map_err(|_| BytecodeError::Backend(BACKEND)) + } + + fn materialize(&mut self) -> Result<()> { + self.runtime.materialize_types()?; + self.runtime.sites = self + .sites + .iter() + .map(|site| crate::ExecutionSite { + function: FunctionId(site.function as u32), + block: crate::BlockId(site.block as u32), + instruction: site.instruction as usize, + value: (site.value != MISSING).then_some(crate::ValueId(site.value as u32)), + }) + .collect(); + // Text indices also carry trap-reason identity; keep their exact order. + self.runtime.reasons = (0..self.texts.len()) + .map(|index| { + self.text(index as u64).map(|text| std::borrow::Cow::Owned(text.to_owned())) + }) + .collect::>>()?; + self.runtime.sources.files = self + .files + .iter() + .map(|file| { + Ok(crate::SourceFile { + id: file.id as u32, + name: self.text(file.text)?.to_owned(), + }) + }) + .collect::>>()?; + self.runtime.sources.originals = self + .originals + .iter() + .map(|raw| crate::OriginalNode { + id: raw.id, + span: (raw.has_span != 0).then_some(crate::SourceSpan { + file: raw.file as u32, + line: raw.line as u32, + column: raw.column as u32, + end_line: raw.end_line as u32, + end_column: raw.end_column as u32, + }), + }) + .collect(); + self.runtime.sources.mappings = self + .mappings + .iter() + .map(|raw| { + Ok(crate::SourceMapping { + original: raw.original, + target: match raw.kind { + 0 => crate::SourceTarget::Instruction { + function: FunctionId(raw.function as u32), + block: crate::BlockId(raw.block as u32), + index: raw.index as usize, + }, + 1 => crate::SourceTarget::Terminator { + function: FunctionId(raw.function as u32), + block: crate::BlockId(raw.block as u32), + }, + 2 => crate::SourceTarget::Global(crate::GlobalId(raw.function as u32)), + _ => return Err(BytecodeError::Backend(BACKEND)), + }, + }) + }) + .collect::>>()?; + Ok(()) + } + + pub(super) fn function(&self, id: FunctionId) -> Result> { + let Some(function) = self.runtime.function_record(id) else { + return Ok(None); + }; + let Type::FnPtr(signature) = self.runtime.type_model(function.signature)? else { + return Err(BytecodeError::Backend(BACKEND)); + }; + Ok(Some(FunctionInfo { + id, + params: signature.params, + ret: signature.ret, + has_body: function.has_body != 0, + })) + } + + pub(super) fn info(&self) -> Result { + Ok(ImageInfo { + functions: self + .runtime + .functions + .iter() + .map(|function| { + self.function(FunctionId(function.id as u32))? + .ok_or(BytecodeError::Backend(BACKEND)) + }) + .collect::>>()?, + globals: self.runtime.globals.len(), + instructions: self.runtime.instructions.len(), + decoded_bytes: self.decoded_bytes, + }) + } + + pub(super) fn run( + &mut self, + function: FunctionId, + arguments: &[ConstValue], + options: InterpreterOptions, + limits: BytecodeLimits, + identity: u64, + ) -> Result + where + 'a: 'static, + { + self.verify(limits)?; + let values = runtime_wave::scalar_arguments(&self.runtime, function, arguments)?; + let mut packet = self.packet(); + let mut admission_result = RawResult::default(); + let admission = runtime_wave::RuntimeAdmission { + program: (&mut packet as *mut RawProgram).cast(), + scratch: self.scratch.as_mut_ptr(), + capacity: self.scratch.len() as u64, + limits, + result: (&mut admission_result as *mut RawResult).cast(), + }; + let result = runtime_wave::execute( + &mut self.runtime, + function, + values, + false, + options, + Some(admission), + )?; + Ok(BytecodeRunResult { + value: result.value.map(|value| BytecodeValue { value, origin: identity }), + steps: result.steps, + }) + } + + pub(super) fn run_values( + &mut self, + function: FunctionId, + arguments: &[BytecodeValue], + options: InterpreterOptions, + limits: BytecodeLimits, + identity: u64, + ) -> Result + where + 'a: 'static, + { + argument_preflight(arguments, limits, self.decoded_bytes, self.scratch.len())?; + let inputs = arguments + .iter() + .map(|value| (&value.value, value.origin == identity)) + .collect::>(); + let original_types = self.runtime.types.len(); + let original_edges = self.runtime.edges.len(); + let original_decoded = self.decoded_bytes; + let original_scratch = self.scratch.len(); + let outcome = (|| -> Result> { + let ids = self.runtime.prepare_argument_types(&inputs)?; + self.verify(limits)?; + self.runtime.materialize_types()?; + let values = self.runtime.typed_arguments(&inputs, &ids)?; + let mut packet = self.packet(); + let mut admission_result = RawResult::default(); + let admission = runtime_wave::RuntimeAdmission { + program: (&mut packet as *mut RawProgram).cast(), + scratch: self.scratch.as_mut_ptr(), + capacity: self.scratch.len() as u64, + limits, + result: (&mut admission_result as *mut RawResult).cast(), + }; + runtime_wave::execute( + &mut self.runtime, + function, + values, + false, + options, + Some(admission), + ) + .map_err(BytecodeError::from) + })(); + self.runtime.rollback_argument_types(original_types, original_edges); + self.decoded_bytes = original_decoded; + self.scratch.truncate(original_scratch); + let result = outcome?; + Ok(BytecodeRunResult { + value: result.value.map(|value| BytecodeValue { value, origin: identity }), + steps: result.steps, + }) + } + } + + pub(super) fn load(bytes: &[u8], limits: BytecodeLimits) -> Result { + let mut result = RawResult::default(); + let status = unsafe { + whale_ir_bytecode_probe(bytes.as_ptr(), bytes.len() as u64, &limits, &mut result) + }; + check(status, &result, limits)?; + let mut native = Owned::empty(result.counts)?; + native.scratch = buffer(result.scratch_words)?; + let mut packet = native.packet(); + let status = unsafe { + whale_ir_bytecode_load( + bytes.as_ptr(), + bytes.len() as u64, + &mut packet, + native.scratch.as_mut_ptr(), + native.scratch.len() as u64, + &limits, + &mut result, + ) + }; + check(status, &result, limits)?; + native.decoded_bytes = result.decoded_bytes; + native.materialize()?; + let identity = NEXT_IDENTITY + .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1)) + .map_err(|_| BytecodeError::Backend("bytecode program identity exhausted"))?; + Ok(BytecodeProgram { native, limits, identity }) + } + + fn argument_preflight( + arguments: &[BytecodeValue], + limits: BytecodeLimits, + decoded: u64, + scratch_words: usize, + ) -> Result<()> { + let limited = || BytecodeError::Invalid { + status: 2, + code: 4, + table: 0, + index: limits.max_workspace_bytes, + }; + let available = limits + .max_workspace_bytes + .checked_sub(decoded) + .and_then(|n| n.checked_sub((scratch_words as u64).checked_mul(8)?)) + .ok_or_else(limited)?; + let nodes = (available / 1024).min(limits.max_records).min(limits.max_work / 16); + let ir_limits = crate::IrLimits { + max_nodes: usize::try_from(nodes) + .unwrap_or(usize::MAX) + .min(crate::IrLimits::default().max_nodes), + max_type_depth: usize::try_from(limits.max_type_depth) + .unwrap_or(usize::MAX) + .min(crate::limits::MAX_IR_NESTING), + ..Default::default() + }; + let mut budget = crate::limits::Budget::new(ir_limits).map_err(|_| limited())?; + budget.nodes(arguments.len()).map_err(|_| limited())?; + for value in arguments { + budget.ty(value.ty()).map_err(|_| limited())?; + } + Ok(()) + } + + /// Allocation arithmetic only: Wave still admits every semantic record. + /// Count annotated input nodes before making normalized tables or strings. + fn transport_preflight(module: &Module, limits: BytecodeLimits) -> Result { + let limited = || BytecodeError::Invalid { + status: 2, + code: 4, + table: 0, + index: limits.max_workspace_bytes, + }; + if limits.max_input_bytes < 576 || limits.max_workspace_bytes < 2048 || limits.max_work == 0 + { + return Err(limited()); + } + // A visited input node can contribute records, hash slots, initialized + // verification scratch and typed metadata. This conservative allowance + // includes Vec growth and the preflight worklist itself. + let nodes = limits + .max_records + .min(limits.max_workspace_bytes / 1024) + .min(limits.max_decoded_bytes / 256) + .min(limits.max_work / 16); + let node_limit = + usize::try_from(nodes).unwrap_or(usize::MAX).min(crate::IrLimits::default().max_nodes); + let type_depth = usize::try_from(limits.max_type_depth) + .unwrap_or(usize::MAX) + .min(crate::limits::MAX_IR_NESTING); + let ir_limits = crate::IrLimits { + max_nodes: node_limit, + max_type_depth: type_depth, + max_const_depth: type_depth, + max_input_bytes: usize::try_from( + limits.max_input_bytes.min(limits.max_workspace_bytes / 2).min(limits.max_work / 8), + ) + .unwrap_or(usize::MAX), + max_analysis_work: usize::try_from(limits.max_work).unwrap_or(usize::MAX), + ..Default::default() + }; + let visited = crate::limits::check_module_with_usage(module, ir_limits) + .map_err(|_| limited())? as u64; + let mut text_bytes = 0_u64; + let mut serialized_text = 0_u64; + let mut charge_text = |length: usize, serialized: bool| -> Result<()> { + text_bytes = text_bytes.checked_add(length as u64).ok_or_else(limited)?; + if serialized { + serialized_text = serialized_text.checked_add(length as u64).ok_or_else(limited)?; + if serialized_text.checked_add(576).is_none_or(|n| n > limits.max_input_bytes) { + return Err(limited()); + } + } + if text_bytes > limits.max_workspace_bytes / 2 || text_bytes > limits.max_work / 8 { + return Err(limited()); + } + Ok(()) + }; + // Names are not serialized, but error construction may retain them. + for global in &module.globals { + charge_text(global.name.len(), false)?; + } + for global in &module.global_storage { + charge_text(global.name.len(), false)?; + if let Some(name) = &global.link_name { + charge_text(name.len(), false)?; + } + } + for declaration in &module.declarations { + charge_text(declaration.name.len(), false)?; + if let Some(name) = &declaration.link_name { + charge_text(name.len(), false)?; + } + } + for file in &module.sources.files { + charge_text(file.name.len(), true)?; + } + for function in &module.functions { + charge_text(function.name.len(), false)?; + for parameter in &function.params { + charge_text(parameter.name.len(), false)?; + } + for block in &function.blocks { + charge_text(block.name.len(), false)?; + for instruction in &block.instructions { + match instruction { + crate::Instruction::TrapIf { reason, .. } => { + charge_text(reason.len(), true)? + }, + crate::Instruction::ConstDecl { name, .. } => { + charge_text(name.len(), false)? + }, + _ => {}, + } + } + if let Some(crate::Terminator::Trap { reason }) = &block.terminator { + charge_text(reason.len(), true)?; + } + } + } + let allocation_bytes = visited + .checked_mul(1024) + .and_then(|n| n.checked_add(2048)) + .and_then(|n| text_bytes.checked_mul(2).and_then(|text| n.checked_add(text))) + .ok_or_else(limited)?; + let decoded_bytes = visited + .checked_mul(256) + .and_then(|n| n.checked_add(serialized_text)) + .ok_or_else(limited)?; + let work = visited + .checked_mul(16) + .and_then(|n| text_bytes.checked_mul(8).and_then(|text| n.checked_add(text))) + .ok_or_else(limited)?; + if allocation_bytes > limits.max_workspace_bytes + || decoded_bytes > limits.max_decoded_bytes + || work > limits.max_work + { + return Err(limited()); + } + Ok(ir_limits) + } + + pub(super) fn compile(module: &Module, limits: BytecodeLimits) -> Result> { + if module.target != "whale-bytecode-v1" + || module.datalayout != crate::DataLayout::default_64bit_le() + { + return Err(BytecodeError::Target); + } + let ir_limits = transport_preflight(module, limits)?; + crate::verify_module_with_limits(module, ir_limits) + .map_err(|error| InterpreterError::Verification(Box::new(error)))?; + let mut runtime = Program::new(Some(module))?; + runtime.marshal()?; + let mut owned = Owned { + runtime, + sites: Vec::new(), + texts: Vec::new(), + text_bytes: Vec::new(), + files: Vec::new(), + originals: Vec::new(), + mappings: Vec::new(), + constant_globals: module.globals.iter().map(|global| u64::from(global.id.0)).collect(), + scratch: Vec::new(), + decoded_bytes: 0, + }; + owned.sites = owned + .runtime + .sites + .iter() + .map(|site| Site { + function: u64::from(site.function.0), + block: u64::from(site.block.0), + instruction: site.instruction as u64, + value: site.value.map_or(MISSING, |value| u64::from(value.0)), + }) + .collect(); + for reason in &owned.runtime.reasons { + owned + .texts + .push(Text { first: owned.text_bytes.len() as u64, count: reason.len() as u64 }); + owned.text_bytes.extend_from_slice(reason.as_bytes()); + } + for file in &module.sources.files { + owned.files.push(File { id: u64::from(file.id), text: owned.texts.len() as u64 }); + owned + .texts + .push(Text { first: owned.text_bytes.len() as u64, count: file.name.len() as u64 }); + owned.text_bytes.extend_from_slice(file.name.as_bytes()); + } + owned.originals = module + .sources + .originals + .iter() + .map(|node| { + let mut raw = Original { id: node.id, ..Original::default() }; + if let Some(span) = &node.span { + raw.has_span = 1; + raw.file = span.file.into(); + raw.line = span.line.into(); + raw.column = span.column.into(); + raw.end_line = span.end_line.into(); + raw.end_column = span.end_column.into(); + } + raw + }) + .collect(); + owned.mappings = module + .sources + .mappings + .iter() + .map(|mapping| { + let (kind, function, block, index) = match mapping.target { + crate::SourceTarget::Instruction { function, block, index } => { + (0, function.0 as u64, block.0 as u64, index as u64) + }, + crate::SourceTarget::Terminator { function, block } => { + (1, function.0 as u64, block.0 as u64, 0) + }, + crate::SourceTarget::Global(global) => (2, global.0 as u64, 0, 0), + }; + Mapping { kind, function, block, index, original: mapping.original } + }) + .collect(); + owned.verify(limits)?; + let mut packet = owned.packet(); + let mut result = RawResult::default(); + let mut required = 0; + let status = unsafe { + whale_ir_bytecode_write( + &mut packet, + std::ptr::null_mut(), + 0, + &mut required, + owned.scratch.as_mut_ptr(), + owned.scratch.len() as u64, + &limits, + &mut result, + ) + }; + check(status, &result, limits)?; + if required > limits.max_input_bytes { + return Err(BytecodeError::Backend(BACKEND)); + } + let mut output = buffer(required)?; + let status = unsafe { + whale_ir_bytecode_write( + &mut packet, + output.as_mut_ptr(), + output.len() as u64, + &mut required, + owned.scratch.as_mut_ptr(), + owned.scratch.len() as u64, + &limits, + &mut result, + ) + }; + check(status, &result, limits)?; + if required != output.len() as u64 { + return Err(BytecodeError::Backend(BACKEND)); + } + Ok(output) + } +} diff --git a/ir/src/interpreter/mod.rs b/ir/src/interpreter/mod.rs index 7694e58..cb4031a 100644 --- a/ir/src/interpreter/mod.rs +++ b/ir/src/interpreter/mod.rs @@ -9,7 +9,7 @@ mod scalar; mod memory; #[cfg(whale_wave_ir)] -mod runtime_wave; +pub(crate) mod runtime_wave; pub use memory::{MemoryLimits, MemoryResource, MemoryTrap}; @@ -874,9 +874,17 @@ impl SourceDetailBudget { } fn location(&mut self, module: &Module, target: SourceTarget) -> Option { - let original = module.sources.original(target)?; + self.location_metadata(&module.sources, target) + } + + fn location_metadata( + &mut self, + metadata: &SourceMetadata, + target: SourceTarget, + ) -> Option { + let original = metadata.original(target)?; let source = original.span.as_ref().and_then(|span| { - let file = module.sources.files.iter().find(|f| f.id == span.file)?; + let file = metadata.files.iter().find(|f| f.id == span.file)?; if file.name.len() > self.remaining { self.omitted += 1; return None; diff --git a/ir/src/interpreter/runtime_wave.rs b/ir/src/interpreter/runtime_wave.rs index b3de54b..e0bd8af 100644 --- a/ir/src/interpreter/runtime_wave.rs +++ b/ir/src/interpreter/runtime_wave.rs @@ -15,7 +15,7 @@ const ALLOCATION: &str = "unable to allocate Wave interpreter transport"; type Result = std::result::Result; -trait WireDefault { +pub(crate) trait WireDefault { fn wire_default() -> Self; } @@ -41,7 +41,7 @@ macro_rules! record { ($name:ident { $($field:ident: $ty:ty),* $(,)? }) => { #[repr(C)] #[derive(Clone, Copy)] - struct $name { $($field: $ty),* } + pub(crate) struct $name { $(pub(crate) $field: $ty),* } impl Default for $name { fn default() -> Self { Self { $($field: <$ty as WireDefault>::wire_default()),* } } @@ -257,6 +257,23 @@ record!(RawDriver { unsafe extern "C" { fn whale_ir_runtime_step(driver: *mut RawDriver) -> i32; + + fn whale_ir_bytecode_runtime_step( + program: *mut std::ffi::c_void, + driver: *mut RawDriver, + scratch: *mut u64, + capacity: u64, + limits: *const crate::bytecode::BytecodeLimits, + admission: *mut std::ffi::c_void, + ) -> i32; +} + +pub(crate) struct RuntimeAdmission { + pub(crate) program: *mut std::ffi::c_void, + pub(crate) scratch: *mut u64, + pub(crate) capacity: u64, + pub(crate) limits: crate::bytecode::BytecodeLimits, + pub(crate) result: *mut std::ffi::c_void, } fn backend(site: Option) -> InterpreterError { @@ -336,31 +353,34 @@ enum TypeView<'a> { Signature(&'a FunctionSignature), } -struct Program<'a> { - module: &'a Module, - types: Vec, +pub(crate) struct Program<'a> { + module: Option<&'a Module>, + pub(crate) sources: SourceMetadata, + pub(crate) types: Vec, type_views: Vec>, type_ids: HashMap<&'a Type, u64>, signature_ids: HashMap<&'a FunctionSignature, u64>, signature_arcs: HashMap>, cached_types: HashMap, - edges: Vec, - functions: Vec, - blocks: Vec, - instructions: Vec, - operands: Vec, - value_types: Vec, - globals: Vec, - sites: Vec, - reasons: Vec<&'a str>, + pub(crate) edges: Vec, + pub(crate) functions: Vec, + pub(crate) blocks: Vec, + pub(crate) instructions: Vec, + pub(crate) operands: Vec, + pub(crate) value_types: Vec, + pub(crate) value_ids: Vec, + pub(crate) globals: Vec, + pub(crate) sites: Vec, + pub(crate) reasons: Vec>, declaration_ids: HashMap, global_ids: HashMap, } impl<'a> Program<'a> { - fn new(module: &'a Module) -> Result { + pub(crate) fn new(module: Option<&'a Module>) -> Result { Ok(Self { module, + sources: SourceMetadata::default(), types: Vec::new(), type_views: Vec::new(), type_ids: HashMap::new(), @@ -373,6 +393,7 @@ impl<'a> Program<'a> { instructions: Vec::new(), operands: Vec::new(), value_types: Vec::new(), + value_ids: Vec::new(), globals: Vec::new(), sites: Vec::new(), reasons: Vec::new(), @@ -477,7 +498,10 @@ impl<'a> Program<'a> { Ok(id) } - fn type_model(&self, id: u64) -> Result { + pub(crate) fn type_model(&self, id: u64) -> Result { + if let Some(ty) = self.cached_types.get(&id) { + return Ok(ty.clone()); + } match self.type_views.get(usize::try_from(id).map_err(|_| backend(None))?) { Some(TypeView::Type(ty)) => Ok((*ty).clone()), Some(TypeView::Signature(signature)) => Ok(Type::FnPtr(Box::new((*signature).clone()))), @@ -496,6 +520,9 @@ impl<'a> Program<'a> { } fn type_ref(&self, id: u64) -> Result<&Type> { + if let Some(ty) = self.cached_types.get(&id) { + return Ok(ty); + } match self.type_views.get(id as usize) { Some(TypeView::Type(ty)) => Ok(ty), Some(TypeView::Signature(_)) => self.cached_types.get(&id).ok_or_else(|| backend(None)), @@ -507,10 +534,10 @@ impl<'a> Program<'a> { if let Some(signature) = self.signature_arcs.get(&id) { return Ok(signature.clone()); } - let Some(TypeView::Signature(signature)) = self.type_views.get(id as usize) else { - return Err(backend(None)); + let signature = match self.type_ref(id)? { + Type::FnPtr(signature) => Arc::new((**signature).clone()), + _ => return Err(backend(None)), }; - let signature = Arc::new((*signature).clone()); map_reserve(&mut self.signature_arcs, 1)?; self.signature_arcs.insert(id, signature.clone()); Ok(signature) @@ -534,11 +561,14 @@ impl<'a> Program<'a> { }, Value::FunctionPointer(pointer) => { raw.kind = 4; - raw.signature = self - .signature_ids - .get(&*pointer.signature) - .copied() - .ok_or_else(|| backend(None))?; + raw.signature = if self.types.get(ty as usize).is_some_and(|node| node.kind == 18) { + ty + } else { + self.signature_ids + .get(&*pointer.signature) + .copied() + .ok_or_else(|| backend(None))? + }; (raw.target_kind, raw.target) = match pointer.target { FunctionTarget::Null => (0, 0), FunctionTarget::Defined(id) => (1, u64::from(id.0)), @@ -575,7 +605,9 @@ impl<'a> Program<'a> { 1 if raw.origin == 1 => { let id = FunctionId(u32::try_from(raw.target).map_err(|_| backend(None))?); let index = *self.declaration_ids.get(&id).ok_or_else(|| backend(None))?; - if self.module.declarations[index as usize].signature != *signature { + if self.type_ref(self.functions[index as usize].signature)? + != self.type_ref(raw.signature)? + { return Err(backend(None)); } FunctionTarget::Defined(id) @@ -589,21 +621,22 @@ impl<'a> Program<'a> { } } - fn marshal(&mut self) -> Result<()> { - map_reserve(&mut self.declaration_ids, self.module.declarations.len())?; - for (index, declaration) in self.module.declarations.iter().enumerate() { + pub(crate) fn marshal(&mut self) -> Result<()> { + let module = self.module.ok_or_else(|| backend(None))?; + map_reserve(&mut self.declaration_ids, module.declarations.len())?; + for (index, declaration) in module.declarations.iter().enumerate() { self.declaration_ids.insert(declaration.id, index as u64); } - map_reserve(&mut self.global_ids, self.module.global_storage.len())?; - for (index, global) in self.module.global_storage.iter().enumerate() { + map_reserve(&mut self.global_ids, module.global_storage.len())?; + for (index, global) in module.global_storage.iter().enumerate() { self.global_ids.insert(global.id, index as u64); } let mut bodies = HashMap::new(); - map_reserve(&mut bodies, self.module.functions.len())?; - for function in &self.module.functions { + map_reserve(&mut bodies, module.functions.len())?; + for function in &module.functions { bodies.insert(function.id, function); } - for (index, declaration) in self.module.declarations.iter().enumerate() { + for (index, declaration) in module.declarations.iter().enumerate() { let signature = self.signature(&declaration.signature)?; let mut raw = RawFunction { id: u64::from(declaration.id.0), @@ -631,6 +664,7 @@ impl<'a> Program<'a> { slots.insert(param.id, slot); let type_id = self.ty(¶m.ty)?; push(&mut self.value_types, type_id)?; + push(&mut self.value_ids, u64::from(param.id.0))?; push(&mut self.operands, slot)?; } for block in &function.blocks { @@ -641,6 +675,7 @@ impl<'a> Program<'a> { let ty = annotations.get(&dst).ok_or_else(|| backend(None))?; let type_id = self.ty(ty)?; push(&mut self.value_types, type_id)?; + push(&mut self.value_ids, u64::from(dst.0))?; } } } @@ -694,7 +729,7 @@ impl<'a> Program<'a> { } push(&mut self.functions, raw)?; } - for global in &self.module.global_storage { + for global in &module.global_storage { let ty = self.ty(&global.ty)?; let mut native = RawGlobal { id: u64::from(global.id.0), @@ -919,7 +954,7 @@ impl<'a> Program<'a> { Instruction::TrapIf { cond, reason } => { raw.op = 30; raw.a = slot(cond)?; - raw.global = push(&mut self.reasons, reason)?; + raw.global = push(&mut self.reasons, std::borrow::Cow::Borrowed(reason))?; }, } Ok(raw) @@ -971,7 +1006,7 @@ impl<'a> Program<'a> { }, Terminator::Trap { reason } => { raw.op = 35; - raw.global = push(&mut self.reasons, reason)?; + raw.global = push(&mut self.reasons, std::borrow::Cow::Borrowed(reason))?; }, } Ok(raw) @@ -1140,7 +1175,219 @@ fn checked_code(op: &CheckedOp) -> u64 { } impl Program<'_> { - fn site(&self, index: u64, entry: FunctionId) -> Result { + pub(crate) fn callable_value(&self, function: FunctionId) -> Result> { + let body = + self.function_record(function).ok_or(InterpreterError::UnknownFunction(function))?; + let Type::FnPtr(signature) = self.type_model(body.signature)? else { + return Err(backend(None)); + }; + Ok(RuntimeValue { + ty: Type::FnPtr(signature.clone()), + value: Value::FunctionPointer(FunctionPointer { + signature: Arc::new(*signature), + target: FunctionTarget::Defined(function), + }), + callable_module: None, + }) + } + + fn append_argument_type(&mut self, ty: &Type) -> Result { + let mut node = RawType::default(); + node.kind = match ty { + Type::Void => 0, + Type::Bool => 1, + Type::I1 => 2, + Type::U1 => 3, + Type::I8 => 4, + Type::I16 => 5, + Type::I32 => 6, + Type::I64 => 7, + Type::I128 => 8, + Type::U8 => 9, + Type::U16 => 10, + Type::U32 => 11, + Type::U64 => 12, + Type::U128 => 13, + Type::F16 => 14, + Type::F32 => 15, + Type::F64 => 16, + Type::Ptr(child) => { + node.child = self.append_argument_type(child)?; + 17 + }, + Type::Array(child, count) => { + node.child = self.append_argument_type(child)?; + node.count = *count; + 19 + }, + Type::FnPtr(signature) => { + let mut children = Vec::new(); + push(&mut children, self.append_argument_type(&signature.ret)?)?; + for param in &signature.params { + push(&mut children, self.append_argument_type(param)?)?; + } + node.first = self.edges.len() as u64; + node.count = children.len() as u64; + node.extra = u64::from(signature.convention == CallingConvention::SysV64) + | (u64::from(signature.variadic) << 1); + reserve(&mut self.edges, children.len())?; + self.edges.extend(children); + 18 + }, + Type::Struct(fields) | Type::Tuple(fields) => { + let mut children = Vec::new(); + for field in fields { + push(&mut children, self.append_argument_type(field)?)?; + } + node.first = self.edges.len() as u64; + node.count = children.len() as u64; + reserve(&mut self.edges, children.len())?; + self.edges.extend(children); + if matches!(ty, Type::Struct(_)) { + 20 + } else { + 21 + } + }, + }; + push(&mut self.types, node) + } + + pub(crate) fn prepare_argument_types( + &mut self, + arguments: &[(&RuntimeValue<'_>, bool)], + ) -> Result> { + let mut ids = Vec::new(); + reserve(&mut ids, arguments.len())?; + for (value, _) in arguments { + ids.push(self.append_argument_type(value.ty())?); + } + Ok(ids) + } + + pub(crate) fn rollback_argument_types(&mut self, types: usize, edges: usize) { + self.types.truncate(types); + self.edges.truncate(edges); + self.cached_types.retain(|id, _| *id < types as u64); + self.signature_arcs.retain(|id, _| *id < types as u64); + } + + pub(crate) fn function_record(&self, id: FunctionId) -> Option<&RawFunction> { + let index = self.declaration_ids.get(&id)?; + self.functions.get(*index as usize) + } + + pub(crate) fn typed_arguments( + &mut self, + arguments: &[(&RuntimeValue<'_>, bool)], + ids: &[u64], + ) -> Result> { + if arguments.len() != ids.len() { + return Err(backend(None)); + } + let mut input = Vec::new(); + reserve(&mut input, arguments.len())?; + for ((value, origin), ty) in arguments.iter().zip(ids) { + input.push(self.value(&value.value, *ty, *origin)?); + } + Ok(input) + } + + /// Materialize verified structural type records for the typed memory adapter. + /// The loader has already bounded depth and expanded metadata size. + pub(crate) fn materialize_types(&mut self) -> Result<()> { + map_reserve(&mut self.cached_types, self.types.len())?; + map_reserve(&mut self.declaration_ids, self.functions.len())?; + for (index, function) in self.functions.iter().enumerate() { + self.declaration_ids.insert(FunctionId(function.id as u32), index as u64); + } + for (index, raw) in self.types.iter().enumerate() { + let child = |id: u64| self.cached_types.get(&id).cloned().ok_or_else(|| backend(None)); + let fields = || -> Result> { + let first = usize::try_from(raw.first).map_err(|_| backend(None))?; + let count = usize::try_from(raw.count).map_err(|_| backend(None))?; + let end = first.checked_add(count).ok_or_else(|| backend(None))?; + let mut fields = Vec::new(); + reserve(&mut fields, count)?; + for id in self.edges.get(first..end).ok_or_else(|| backend(None))? { + fields.push(child(*id)?); + } + Ok(fields) + }; + let ty = match raw.kind { + 0 => Type::Void, + 1 => Type::Bool, + 2 => Type::I1, + 3 => Type::U1, + 4 => Type::I8, + 5 => Type::I16, + 6 => Type::I32, + 7 => Type::I64, + 8 => Type::I128, + 9 => Type::U8, + 10 => Type::U16, + 11 => Type::U32, + 12 => Type::U64, + 13 => Type::U128, + 14 => Type::F16, + 15 => Type::F32, + 16 => Type::F64, + 17 => Type::Ptr(Box::new(child(raw.child)?)), + 18 => { + let mut parameters = fields()?; + if parameters.is_empty() { + return Err(backend(None)); + } + let ret = parameters.remove(0); + Type::FnPtr(Box::new(FunctionSignature { + params: parameters, + ret, + convention: if raw.extra & 1 == 0 { + CallingConvention::Whale + } else { + CallingConvention::SysV64 + }, + variadic: raw.extra & 2 != 0, + })) + }, + 19 => Type::Array(Box::new(child(raw.child)?), raw.count), + 20 => Type::Struct(fields()?), + 21 => Type::Tuple(fields()?), + _ => return Err(backend(None)), + }; + self.cached_types.insert(index as u64, ty); + } + Ok(()) + } + + fn execution_source( + &self, + site: ExecutionSite, + budget: &mut SourceDetailBudget, + ) -> Option { + if let Some(module) = self.module { + return execution_source(module, site, budget); + } + let block = self.blocks.iter().find(|block| { + block.id == u64::from(site.block.0) + && self + .functions + .get(block.function as usize) + .is_some_and(|f| f.id == u64::from(site.function.0)) + })?; + let target = if site.instruction as u64 + 1 == block.count { + SourceTarget::Terminator { function: site.function, block: site.block } + } else { + SourceTarget::Instruction { + function: site.function, + block: site.block, + index: site.instruction, + } + }; + budget.location_metadata(&self.sources, target) + } + + pub(crate) fn site(&self, index: u64, entry: FunctionId) -> Result { if index != MISSING { return self .sites @@ -1148,13 +1395,18 @@ impl Program<'_> { .copied() .ok_or_else(|| backend(None)); } - let body = self - .module + let function = self .functions .iter() - .find(|function| function.id == entry) + .find(|body| body.id == u64::from(entry.0)) .ok_or_else(|| backend(None))?; - Ok(ExecutionSite { function: entry, block: body.entry, instruction: 0, value: None }) + let block = self.blocks.get(function.entry as usize).ok_or_else(|| backend(None))?; + Ok(ExecutionSite { + function: entry, + block: BlockId(block.id as u32), + instruction: 0, + value: None, + }) } fn error( @@ -1165,10 +1417,9 @@ impl Program<'_> { ) -> Result { let count = |value| usize::try_from(value).map_err(|_| backend(None)); let function = |index: u64| { - self.module - .declarations + self.functions .get(count(index)?) - .map(|decl| decl.id) + .map(|decl| FunctionId(decl.id as u32)) .ok_or_else(|| backend(None)) }; let at = || self.site(raw.site, entry); @@ -1224,14 +1475,14 @@ impl Program<'_> { 12 => return trap(TrapReason::InvalidConversion), 13 => { let reason = self.reasons.get(count(raw.detail)?).ok_or_else(|| backend(None))?; - return trap(TrapReason::Explicit((*reason).to_owned())); + return trap(TrapReason::Explicit(reason.to_string())); }, 14 => return trap(TrapReason::NullFunction), 15 => return trap(TrapReason::InvalidFunctionPointer), 16 => return trap(TrapReason::FunctionSignatureMismatch), - 17 => InterpreterError::UnsupportedGlobal( - self.module.global_storage.get(count(raw.detail)?).ok_or_else(|| backend(None))?.id, - ), + 17 => InterpreterError::UnsupportedGlobal(GlobalId( + self.globals.get(count(raw.detail)?).ok_or_else(|| backend(None))?.id as u32, + )), 18 => { InterpreterError::Verification(Box::new(VerifyError::ResourceLimit(LimitError { resource: Resource::AnalysisWork, @@ -1249,11 +1500,34 @@ impl Program<'_> { frames: &[RawFrame], trace_limit: usize, ) -> InterpreterError { + let mut budget = SourceDetailBudget::new(); + let global = match &cause { + InterpreterError::GlobalMemory { global, .. } + | InterpreterError::GlobalMemoryLimit { global, .. } + | InterpreterError::UnsupportedGlobal(global) => Some(*global), + _ => None, + }; + if let Some(global) = global { + let metadata = self.module.map_or(&self.sources, |module| &module.sources); + if let Some(original) = budget.location_metadata(metadata, SourceTarget::Global(global)) + { + return InterpreterError::Diagnostic { + cause: Box::new(cause), + diagnostic: Box::new(RuntimeDiagnostic { + site: None, + global: Some(global), + original: Some(original), + calls: Vec::new(), + omitted_call_frames: 0, + omitted_source_details: budget.omitted, + }), + }; + } + } let Some(site) = cause.runtime_site() else { return cause; }; - let mut budget = SourceDetailBudget::new(); - let original = execution_source(self.module, site, &mut budget); + let original = self.execution_source(site, &mut budget); let caller_count = frames.len().saturating_sub(1); if original.is_none() && caller_count == 0 { return cause; @@ -1265,7 +1539,7 @@ impl Program<'_> { } for child in frames.iter().skip(1).rev().take(retained) { let Some(callee) = - self.module.declarations.get(child.function as usize).map(|decl| decl.id) + self.functions.get(child.function as usize).map(|decl| FunctionId(decl.id as u32)) else { return backend(Some(site)); }; @@ -1279,7 +1553,7 @@ impl Program<'_> { caller: call_site.function, callee, site: call_site, - original: execution_source(self.module, call_site, &mut budget), + original: self.execution_source(call_site, &mut budget), }); } calls.reverse(); @@ -1451,6 +1725,31 @@ fn grow(buffer: &mut Vec, requested: u64, maximum: usize) -> Resu Ok(true) } +pub(crate) fn scalar_arguments( + program: &Program<'_>, + function: FunctionId, + arguments: &[ConstValue], +) -> Result> { + let signature = program + .function_record(function) + .and_then(|body| program.types.get(body.signature as usize)); + let mut input = Vec::new(); + reserve(&mut input, arguments.len())?; + for (index, argument) in arguments.iter().enumerate() { + let (literal, low, high) = literal(argument); + let ty = signature + .and_then(|signature| { + (index as u64 + 1 < signature.count) + .then(|| program.edges.get(signature.first as usize + index + 1)) + .flatten() + .copied() + }) + .unwrap_or(MISSING); + input.push(RawValue { kind: 1, ty, literal, low, high, origin: 1, ..RawValue::default() }); + } + Ok(input) +} + pub(super) fn run<'module>( module: &'module Module, function: FunctionId, @@ -1459,7 +1758,7 @@ pub(super) fn run<'module>( ) -> Result> { verify_module_with_limits(module, options.ir_limits) .map_err(|error| InterpreterError::Verification(Box::new(error)))?; - let mut program = Program::new(module)?; + let mut program = Program::new(Some(module))?; program.marshal()?; let mut input = Vec::new(); reserve(&mut input, arguments.len())?; @@ -1480,6 +1779,32 @@ pub(super) fn run<'module>( } }, } + let result = execute( + &mut program, + function, + input, + matches!(arguments, Arguments::Scalars(_)), + options, + None, + )?; + Ok(RuntimeInterpreterResult { + value: result.value.map(|value| RuntimeValue { + callable_module: value.function_target().map(|_| module), + ty: value.ty, + value: value.value, + }), + steps: result.steps, + }) +} + +pub(crate) fn execute<'module>( + program: &mut Program<'module>, + function: FunctionId, + mut input: Vec, + scalar_arguments: bool, + options: InterpreterOptions, + admission: Option, +) -> Result> { let type_count = program.types.len(); let function_count = program.functions.len(); let instruction_count = program.instructions.len(); @@ -1529,7 +1854,7 @@ pub(super) fn run<'module>( global_values: global_values.as_mut_ptr(), arguments: input.as_mut_ptr(), argument_count: input.len() as u64, - scalar_arguments: u64::from(matches!(arguments, Arguments::Scalars(_))), + scalar_arguments: u64::from(scalar_arguments), entry_id: u64::from(function.0), storage: &mut storage, layout_nodes: layout_nodes.as_mut_ptr(), @@ -1563,7 +1888,19 @@ pub(super) fn run<'module>( loop { driver.memory_allocations = memory.allocation_count() as u64; // All spans are initialized, stable for this step, and exclusively borrowed. - let status = unsafe { whale_ir_runtime_step(&mut driver) }; + let status = unsafe { + match &admission { + Some(admission) => whale_ir_bytecode_runtime_step( + admission.program, + &mut driver, + admission.scratch, + admission.capacity, + &admission.limits, + admission.result, + ), + None => whale_ir_runtime_step(&mut driver), + } + }; if status != result.status as i32 || result.status > 4 || driver.steps < previous_steps @@ -1596,7 +1933,8 @@ pub(super) fn run<'module>( .. }) ) - .then_some(module); + .then_some(program.module) + .flatten(); Some(RuntimeValue { ty, value, callable_module }) }; return Ok(RuntimeInterpreterResult { value, steps: result.steps }); @@ -1610,13 +1948,13 @@ pub(super) fn run<'module>( let global = if result.global == MISSING { None } else { - Some( - module - .global_storage + Some(GlobalId( + program + .globals .get(result.global as usize) .ok_or_else(|| backend(None))? - .id, - ) + .id as u32, + )) }; let site = program.site(result.site, function).ok(); let cause = match (global, fault) { @@ -1822,7 +2160,7 @@ mod tests { ) .unwrap(); verify_module(&module).unwrap(); - let mut program = Program::new(&module).unwrap(); + let mut program = Program::new(Some(&module)).unwrap(); program.marshal().unwrap(); assert_eq!(program.functions[0].id, u64::from(u32::MAX)); assert_eq!(program.functions[0].value_count, 2); diff --git a/ir/src/lib.rs b/ir/src/lib.rs index 2b998e9..c7473a7 100644 --- a/ir/src/lib.rs +++ b/ir/src/lib.rs @@ -2,6 +2,8 @@ pub mod block; +pub mod bytecode; + pub mod builder; pub mod const_expr; diff --git a/ir/src/limits.rs b/ir/src/limits.rs index 068f666..94eb27c 100644 --- a/ir/src/limits.rs +++ b/ir/src/limits.rs @@ -162,6 +162,10 @@ impl Budget { } pub(crate) fn check_module(m: &Module, limits: IrLimits) -> Result<(), LimitError> { + check_module_with_usage(m, limits).map(|_| ()) +} + +pub(crate) fn check_module_with_usage(m: &Module, limits: IrLimits) -> Result { let mut b = Budget::new(limits)?; b.nodes(m.sources.files.len())?; b.nodes(m.sources.originals.len())?; @@ -258,7 +262,7 @@ pub(crate) fn check_module(m: &Module, limits: IrLimits) -> Result<(), LimitErro } } } - Ok(()) + Ok(limits.max_nodes - b.remaining) } /// Dispose of a rejected owned type without recursively dropping its tree. diff --git a/ir/src/lower_ast/o0.rs b/ir/src/lower_ast/o0.rs index 23d3d5e..9536532 100644 --- a/ir/src/lower_ast/o0.rs +++ b/ir/src/lower_ast/o0.rs @@ -41,7 +41,13 @@ pub fn lower_o0_with_limits( limits: super::AstLimits, ) -> Result { super::limits::inspect_program(program, limits).map_err(LowerError::ResourceLimit)?; - let selected = crate::Target::lookup(target).map_err(LowerError::Target)?; + let module_target = target; + let selected = if target == "whale-bytecode-v1" { + // Both built-in contracts use the same tracked 64-bit storage layout. + crate::Target::X86_64WhaleLinux + } else { + crate::Target::lookup(target).map_err(LowerError::Target)? + }; selected.validate_layout(datalayout).map_err(LowerError::Target)?; let target = selected; // Functions and globals have separate namespaces. Validate each before bodies. @@ -60,7 +66,7 @@ pub fn lower_o0_with_limits( } } } - let mut mb = ModuleBuilder::new(target.name(), datalayout); + let mut mb = ModuleBuilder::new(module_target, datalayout); mb.set_source_work_limit(limits.max_source_work); for d in &program.declarations { diff --git a/ir/src/lower_ast/wave_lower.rs b/ir/src/lower_ast/wave_lower.rs index db4de9f..d48bbb8 100644 --- a/ir/src/lower_ast/wave_lower.rs +++ b/ir/src/lower_ast/wave_lower.rs @@ -1808,7 +1808,13 @@ pub(super) fn lower( .ok_or(LowerError::ResourceLimit(AstLimitError::SourceWork))?, ..limits }; - let target = Target::lookup(target).map_err(LowerError::Target)?; + let module_target = target; + let target = if target == "whale-bytecode-v1" { + // Select the shared storage contract explicitly; retain the requested output target. + Target::X86_64WhaleLinux + } else { + Target::lookup(target).map_err(LowerError::Target)? + }; target.validate_layout(datalayout).map_err(LowerError::Target)?; let mut wire = Wire::new(); let root = wire.program(program)?; @@ -1822,7 +1828,9 @@ pub(super) fn lower( return Err(backend()); } let constants = evaluate_requests(&wire, &output)?; - materialize(&wire, &output, target, datalayout, constants) + let mut module = materialize(&wire, &output, target, datalayout, constants)?; + module.target = module_target.to_owned(); + Ok(module) } #[cfg(test)] diff --git a/ir/src/verifier.rs b/ir/src/verifier.rs index 45969e2..009aa66 100644 --- a/ir/src/verifier.rs +++ b/ir/src/verifier.rs @@ -254,6 +254,9 @@ pub fn verify_module_with_stats( m: &Module, limits: crate::IrLimits, ) -> Result { + if m.target == "whale-bytecode-v1" { + return verify_module_for_target_with_stats(m, &target_spec::whale_bytecode_v1(), limits); + } let target = crate::Target::lookup(&m.target).map_err(VerifyError::Target)?; target.validate_layout(m.datalayout).map_err(VerifyError::Target)?; verify_module_for_target_with_stats(m, &target.specification(), limits) diff --git a/ir/tests/bytecode_execution.rs b/ir/tests/bytecode_execution.rs new file mode 100644 index 0000000..e9e8b4e --- /dev/null +++ b/ir/tests/bytecode_execution.rs @@ -0,0 +1,360 @@ +use ir::{bytecode::*, *}; + +fn module(source: &str) -> Module { + parse_module(&source.replace("x86_64-whale-linux", "whale-bytecode-v1")).unwrap() +} + +fn compile_program(module: &Module) -> BytecodeProgram { + let bytes = compile(module, BytecodeLimits::default()).unwrap(); + let repeated = compile(module, BytecodeLimits::default()).unwrap(); + assert_eq!(bytes, repeated); + BytecodeProgram::load(&bytes, BytecodeLimits::default()).unwrap() +} + +#[test] +fn native_bytecode_execution_matches_calls_phi_pointer_and_float_fixtures() { + if !available() { + return; + } + let fixtures = [ + ( + include_str!("fixtures/interpreted-calls-v4.wir"), + vec![ + (0, vec![ConstValue::I(41)]), + (3, vec![]), + (5, vec![ConstValue::I(4)]), + (6, vec![ConstValue::U(4)]), + ], + ), + (include_str!("fixtures/tracked-memory-v4.wir"), vec![(0, vec![])]), + ( + include_str!("fixtures/runtime-storage-v6.wir"), + vec![(0, vec![]), (1, vec![]), (3, vec![]), (7, vec![])], + ), + ( + include_str!("fixtures/float-storage-v7.wir"), + vec![ + (0, vec![ConstValue::F(FloatBits::F16(0x7d55))]), + (1, vec![ConstValue::F(FloatBits::F32(0xff80_0123))]), + (2, vec![ConstValue::F(FloatBits::F64(0x7ff0_0000_0000_0123))]), + (3, vec![]), + ], + ), + ]; + for (fixture, cases) in fixtures { + let module = module(fixture); + let mut program = compile_program(&module); + for (id, arguments) in cases { + let reference = interpret(&module, FunctionId(id), &arguments).unwrap(); + for _ in 0..2 { + let result = + program.run(FunctionId(id), &arguments, InterpreterOptions::default()).unwrap(); + assert_eq!( + result.value.as_ref().and_then(BytecodeValue::scalar_value), + reference.value.as_ref() + ); + assert_eq!(result.steps, reference.steps); + } + } + } +} + +#[test] +fn bytecode_preserves_source_sites_call_trace_and_runtime_limits() { + if !available() { + return; + } + let module = module(include_str!("fixtures/runtime-diagnostics-v7.wir")); + let mut program = compile_program(&module); + let reference = interpret(&module, FunctionId(0), &[]).unwrap_err(); + let BytecodeError::Interpreter(actual) = + program.run(FunctionId(0), &[], InterpreterOptions::default()).unwrap_err() + else { + panic!("expected runtime trap") + }; + assert_eq!(actual.to_string(), reference.to_string()); + let BytecodeError::Interpreter(actual) = program + .run(FunctionId(0), &[], InterpreterOptions { max_steps: 0, ..Default::default() }) + .unwrap_err() + else { + panic!("expected step limit") + }; + assert!(matches!(actual.root_cause(), InterpreterError::StepLimit { limit: 0, .. })); +} + +#[test] +fn bytecode_preserves_sparse_parameter_and_definition_ids_and_return_bits() { + if !available() { + return; + } + let source = r#"module { + format_version 8 + semantics_version 1 + target "whale-bytecode-v1" + datalayout { ptr=64, endian=little } + declare @f2147483647 "sparse": whale (u128) -> u128, linkage internal + fn @f2147483647 "sparse"(%v2147483647 "argument": u128) -> u128, entry %b2147483647 { + %b2147483647 "entry": + %v4294967295: u128 = const u128 1 + %v42: u128 = add u128 %v2147483647, %v4294967295 + ret u128 %v42 + } + }"#; + let module = parse_module(source).unwrap(); + let mut program = compile_program(&module); + let info = program.function(FunctionId(2147483647)).unwrap().unwrap(); + assert_eq!(info.params, vec![Type::U128]); + let result = + program.run(info.id, &[ConstValue::U(u128::MAX)], InterpreterOptions::default()).unwrap(); + assert_eq!(result.value.unwrap().scalar_value(), Some(&ConstValue::U(0))); +} + +#[test] +fn bytecode_rejects_truncation_unknown_tables_bad_indices_and_limits_before_execution() { + if !available() { + return; + } + let module = module(include_str!("fixtures/runtime-diagnostics-v7.wir")); + let bytes = compile(&module, BytecodeLimits::default()).unwrap(); + for length in [0, 7, 63, 575, bytes.len() - 1] { + assert!(BytecodeProgram::load(&bytes[..length], BytecodeLimits::default()).is_err()); + } + for offset in [0, 8, 16, 24, 32, 40, 48, 56, 64, 88] { + let mut corrupt = bytes.clone(); + corrupt[offset] ^= 0x80; + assert!( + BytecodeProgram::load(&corrupt, BytecodeLimits::default()).is_err(), + "offset {offset}" + ); + } + for limits in [ + BytecodeLimits { max_input_bytes: bytes.len() as u64 - 1, ..Default::default() }, + BytecodeLimits { max_decoded_bytes: 0, ..Default::default() }, + BytecodeLimits { max_records: 0, ..Default::default() }, + BytecodeLimits { max_work: 0, ..Default::default() }, + BytecodeLimits { max_workspace_bytes: 0, ..Default::default() }, + ] { + assert!(BytecodeProgram::load(&bytes, limits).is_err()); + } +} + +#[test] +fn reference_build_reports_explicit_unavailability() { + if available() { + return; + } + assert!(matches!( + BytecodeProgram::load(&[], BytecodeLimits::default()), + Err(BytecodeError::Unavailable) + )); +} + +#[test] +fn bytecode_callable_origins_and_raw_addresses_preserve_authority() { + if !available() { + return; + } + let fixture = + include_str!("fixtures/interpreted-calls-v4.wir").trim().strip_suffix('}').unwrap(); + let text = format!( + r#"{fixture} + declare @f200 "apply": whale (fnptr i32>) -> i32, linkage internal + fn @f200 "apply"(%v0 "callback": fnptr i32>) -> i32, entry %b0 {{ + %b0 "entry": + %v1: i32 = const i32 41 + %v2: i32 = call whale i32 indirect %v0(%v1) + ret i32 %v2 + }} + }}"# + ); + let module = module(&text); + let bytes = compile(&module, BytecodeLimits::default()).unwrap(); + let mut first = BytecodeProgram::load(&bytes, BytecodeLimits::default()).unwrap(); + let mut second = BytecodeProgram::load(&bytes, BytecodeLimits::default()).unwrap(); + let callable = + first.run(FunctionId(7), &[], InterpreterOptions::default()).unwrap().value.unwrap(); + assert_eq!(callable.function_target(), Some(FunctionId(0))); + let result = first + .run_values(FunctionId(200), std::slice::from_ref(&callable), InterpreterOptions::default()) + .unwrap(); + assert_eq!(result.value.unwrap().scalar_value(), Some(&ConstValue::I(42))); + let error = + second.run_values(FunctionId(200), &[callable], InterpreterOptions::default()).unwrap_err(); + assert!(matches!( + error, + BytecodeError::Interpreter(InterpreterError::ArgumentType { index: 0, .. }) + )); + let raw = BytecodeValue::raw_pointer(Type::ptr_to(Type::U32), 0x1000).unwrap(); + let BytecodeError::Interpreter(error) = + first.run_values(FunctionId(1), &[raw], InterpreterOptions::default()).unwrap_err() + else { + panic!() + }; + assert!( + matches!(error.root_cause(), InterpreterError::Trap(trap) if trap.reason == TrapReason::Memory(MemoryTrap::MissingProvenance)) + ); +} + +#[test] +fn generated_streams_match_independent_integer_memory_and_branch_oracle() { + if !available() { + return; + } + let mut text = String::from("module { format_version 8 semantics_version 1 target \"whale-bytecode-v1\" datalayout {ptr=64,endian=little} "); + for id in 0..64 { + text.push_str(&format!( + "declare @f{id} \"generated{id}\": whale (u64, bool) -> u64, linkage internal " + )); + } + let mut random = 0x81e2_3945_6ad0_7c31_u64; + let mut seeds = Vec::new(); + for id in 0..64 { + random ^= random << 13; + random ^= random >> 7; + random ^= random << 17; + seeds.push(random); + text.push_str(&format!( + r#" + fn @f{id} "generated{id}"(%v0 "input": u64, %v1 "condition": bool) -> u64, entry %b0 {{ + %b0 "entry": + %v2: u64 = const u64 {random} + %v3: u64 = xor u64 %v0, %v2 + %v4: ptr = alloca u64, align 8 + volatile_store u64 %v3, ptr %v4, align 8 + %v5: u64 = volatile_load u64, ptr %v4, align 8 + cbr bool %v1, label %b1, label %b2 + %b1 "left": + %v6: u64 = add u64 %v5, %v2 + br label %b3 + %b2 "right": + %v7: u64 = mul u64 %v5, %v2 + br label %b3 + %b3 "join": + %v8: u64 = phi u64 [%v6, %b1], [%v7, %b2] + ret u64 %v8 + }} + "# + )); + } + text.push('}'); + let module = parse_module(&text).unwrap(); + let mut program = compile_program(&module); + for (id, salt) in seeds.iter().enumerate() { + for input in [0_u64, u64::MAX, salt.rotate_left(19)] { + for condition in [false, true] { + let expected = if condition { + (input ^ salt).wrapping_add(*salt) + } else { + (input ^ salt).wrapping_mul(*salt) + }; + let result = program + .run( + FunctionId(id as u32), + &[ConstValue::U(input.into()), ConstValue::Bool(condition)], + InterpreterOptions::default(), + ) + .unwrap(); + assert_eq!( + result.value.unwrap().scalar_value(), + Some(&ConstValue::U(expected.into())) + ); + assert_eq!(result.steps, 10); + } + } + } +} + +#[test] +fn empty_images_and_unused_declarations_are_valid_but_referenced_imports_are_rejected() { + if !available() { + return; + } + let empty = Module::new("whale-bytecode-v1", DataLayout::default_64bit_le()); + let mut program = compile_program(&empty); + assert!(program.verify().unwrap().functions.is_empty()); + let text = r#"module { + format_version 8 + semantics_version 1 + target "whale-bytecode-v1" + datalayout { ptr=64, endian=little } + declare @f0 "entry": whale () -> u32, linkage internal + declare @f1 "external": whale () -> u32, linkage external, link_name "external" + fn @f0 "entry"() -> u32, entry %b0 { + %b0 "entry": + %v0: u32 = const u32 42 + ret u32 %v0 + } + }"#; + let module = parse_module(text).unwrap(); + let mut program = compile_program(&module); + let result = program.run(FunctionId(0), &[], InterpreterOptions::default()).unwrap(); + assert_eq!(result.value.unwrap().scalar_value(), Some(&ConstValue::U(42))); + let called = parse_module(&text.replace("const u32 42", "call whale u32 @f1()")).unwrap(); + assert!(matches!( + compile(&called, BytecodeLimits::default()), + Err(BytecodeError::Invalid { status: 5, .. }) + )); +} + +#[test] +fn compile_budget_preflight_precedes_semantic_verification_and_packet_copies() { + if !available() { + return; + } + let mut module = Module::new("whale-bytecode-v1", DataLayout::default_64bit_le()); + module.sources.files.push(SourceFile { id: 0, name: "x".repeat(64 * 1024) }); + module.sources.files.push(SourceFile { id: 0, name: "duplicate".into() }); + for limits in [ + BytecodeLimits { max_workspace_bytes: 0, ..Default::default() }, + BytecodeLimits { max_workspace_bytes: 2048, ..Default::default() }, + BytecodeLimits { max_decoded_bytes: 0, ..Default::default() }, + BytecodeLimits { max_input_bytes: 575, ..Default::default() }, + BytecodeLimits { max_work: 1, ..Default::default() }, + ] { + assert!(matches!( + compile(&module, limits), + Err(BytecodeError::Invalid { status: 2, code: 4, .. }) + )); + } +} + +#[test] +fn typed_argument_admission_is_bounded_and_does_not_mutate_the_verified_packet() { + if !available() { + return; + } + let module = parse_module( + r#"module { + format_version 8 + semantics_version 1 + target "whale-bytecode-v1" + datalayout { ptr=64, endian=little } + declare @f0 "ignore": whale (ptr) -> void, linkage internal + fn @f0 "ignore"(%v0 "pointer": ptr) -> void, entry %b0 { + %b0 "entry": + ret void + } + }"#, + ) + .unwrap(); + let bytes = compile(&module, BytecodeLimits::default()).unwrap(); + let limits = BytecodeLimits { max_workspace_bytes: 64 * 1024, ..Default::default() }; + let mut program = BytecodeProgram::load(&bytes, limits).unwrap(); + let initial_bytes = program.verify().unwrap().decoded_bytes; + let oversized = + BytecodeValue::raw_pointer(Type::ptr_to(Type::Struct(vec![Type::U8; 256])), 1).unwrap(); + assert!(matches!( + program.run_values(FunctionId(0), &[oversized], InterpreterOptions::default()), + Err(BytecodeError::Invalid { status: 2, .. }) + )); + assert_eq!(program.verify().unwrap().decoded_bytes, initial_bytes); + for _ in 0..16 { + let value = BytecodeValue::raw_pointer(Type::ptr_to(Type::U8), 1).unwrap(); + assert!(program + .run_values(FunctionId(0), &[value], InterpreterOptions::default()) + .unwrap() + .value + .is_none()); + assert_eq!(program.verify().unwrap().decoded_bytes, initial_bytes); + } +} diff --git a/ir/tests/bytecode_output_ceiling.rs b/ir/tests/bytecode_output_ceiling.rs new file mode 100644 index 0000000..73ba1ef --- /dev/null +++ b/ir/tests/bytecode_output_ceiling.rs @@ -0,0 +1,17 @@ +use ir::{bytecode::*, *}; + +#[test] +fn exact_encoded_byte_ceiling_accepts_the_same_valid_output() { + if !available() { + return; + } + let mut builder = ModuleBuilder::new("whale-bytecode-v1", DataLayout::default_64bit_le()); + let mut function = builder.begin_function("answer", vec![], Type::U32); + let value = function.const_uint(Type::U32, 42); + function.ret(Some(value)); + function.finish(); + let module = builder.finish(); + let bytes = compile(&module, BytecodeLimits::default()).unwrap(); + let exact = BytecodeLimits { max_input_bytes: bytes.len() as u64, ..Default::default() }; + assert_eq!(compile(&module, exact).unwrap(), bytes); +} diff --git a/ir/tests/fixtures/bytecode/constant_source.wbc b/ir/tests/fixtures/bytecode/constant_source.wbc new file mode 100644 index 0000000000000000000000000000000000000000..5ce8a3484ca1cc276de2c8a5d9cdc310a2dce835 GIT binary patch literal 1360 zcmb`Hu};H45JZmvfe->HRZ5G>qM%NBfRIuIi4IDnRB0j?A;||&@JW0EC7Whp8D|M#{5yfo)Dh?h4N>@FZrp@KKtUo#nTVn zx%i)ie;~d#eyse3aHK_1w^aU87>#ER=A0yW*|Wf&b3*3J>4ph``-$n#eRDgyT;6q@ zpZmB6I+m7pe@pE6a%1{j-Rq40Pmjs=9x^BA;rpAZqx1NDPVVV^QN1s3*DK%mhy6F; TIUnu=G2b)sQ(^_oSS{@{PZ8tItgb0 literal 0 HcmV?d00001 diff --git a/ir/tests/fixtures/bytecode/invalid_block_count.wbc b/ir/tests/fixtures/bytecode/invalid_block_count.wbc new file mode 100644 index 0000000000000000000000000000000000000000..17b7069aeaea3a98b74f6c4dd883eb8a745d03bf GIT binary patch literal 1216 zcmb`GI|>3Z7=+{d{lF6}R*NUFTou8>-Yo?$VCfM&lBGwn^cGs|e1ZcZ2&NhSe`YfO zCfUPowcoBcp%$v;cyCtysd%8Mf9t6w54nVrg@@_8;v2%J@um9gS4hZwnfR9QD4x8l z`fcHvjZ~B0F`oV5!Hf9|`FcWl@-y}O!khUy&q0J|j$wqyKZ@{6^~VuDSASwWxqLS{ zyaUMtJaq~==ai28lx`LgxSyJQ-kaOerTVVp{@nM{vTOhRXRiOXUYNn>GCIty;d0y@du-Pq3hA1UsquRrR}i zdO7S?`|WxYYM~mA_h!XUr2|F%+fOZf$Yqo*Jj~yf-Vi=bFU2!oAtUR{q_>1e>EvC- zw}odWQcZrxbmm6~FVT!9PWi}B`DPJ=_fwP4ee-sFDc*gYpYz-UJNC~z^PFGng*AA-$zg7U`(GMn U`+G?)=fVCFbkc|G^s!ESZ_30V`~Uy| literal 0 HcmV?d00001 diff --git a/ir/tests/fixtures/bytecode/invalid_count_overflow.wbc b/ir/tests/fixtures/bytecode/invalid_count_overflow.wbc new file mode 100644 index 0000000000000000000000000000000000000000..ba0b66e7acf7399bef406622683e8a22f02a71b0 GIT binary patch literal 1216 zcmb`GI|>3Z7=+{d{lF6}R*NUFTou8>-Yo?$VCfM&lBGwn^cGs|e1ZcZ2&NhSe`YfO zCfUPowcoBcp%$v;cyCtysd%8Mf9t7VTDgRhg@@_8;v2%J@um8T4~2xxmx*r)kK)O@ zs^1o#*+@0{9pl*_9=w>pkgq3%CqGlaFT9zb^BhEY<`_nJ{G$lJRDT@dbM+_2lgoFL z!#j{Xz*DD?b57~VPw8e6f%~b+=e@ZdU8?Uo?$3R^1H1Omf9CpM>xCJ7E~CTT8m{NR UHQC=wa=8ybzmpQ3$H$!L-ug8t?*IS* literal 0 HcmV?d00001 diff --git a/ir/tests/fixtures/bytecode/invalid_cross_function_target.wbc b/ir/tests/fixtures/bytecode/invalid_cross_function_target.wbc new file mode 100644 index 0000000000000000000000000000000000000000..d2e1f7b8810c39c7fddf11b9ca6f192d6e061074 GIT binary patch literal 2248 zcmd7SxlIH?5CzcTz7JvGGQwJe05BI2(i->>03IR-OhVaECJaI#12FbKgOXYUi-Z{G zZ`J>Gc5mO$uI_HHZ@QIk@l_nQ7yje$V7mHM&t8vU5{#^S%MW(ac5BhSmwXTL%QuUV z-G|=@4&k?AzXmshFCpmFr=RDC{CGGJCf_u;6U3AC@$Uxb62-R9y$0_b_8YwTg9d*Y z|6zll#D7%yI=?#ZLF8Q-hr5aP(iDU+_n7XaA#lIY^6~4#y`zKXXNzz7>6|kgig(V{ zuP^6}*B{9Kt*yZ_VD z(b!)9%Ram}+OK_o_dLWcyT5Y{1m)xYtNWpz`p{ez@fE#m^&K(?zW$G%(m>_qukrPr ZdM@$!R(yTOE+SMPU*jKBN5ATd{{&`qRQ3P> literal 0 HcmV?d00001 diff --git a/ir/tests/fixtures/bytecode/invalid_destination.wbc b/ir/tests/fixtures/bytecode/invalid_destination.wbc new file mode 100644 index 0000000000000000000000000000000000000000..82d57f247b78d273ab89bc30b7422dd9421774ba GIT binary patch literal 1216 zcmbW0I|>3p5JboS|AQx3j22H|xGI8yxf=>zz|bRjBtws4=q)tZdV&SRh?^8$Ro&Ij zjECK7zg=%aEmWW5y;<>7=|EBc_EXCqav5a{5A%1WH-t~qOYzJrWMscgdP{hePTo~~ zTX<%WYVtd#GantiSbw3uo)DevwqHV5YgFV7}4n;Mf9ckaYWC>PfRD5-%Sqh zK=y!6okGqz3Z7=+{d{lF6}R*NUFTou8>-Yo?$VCfM&lBGwn^cGs|e1ZcZ2yQd{^T@;` z9(Jq!cD)I;P<@W~X2nmX14aGY4=;PjMaUK&=I=^x2%n~x;#sedk^N=TTf(Ds`mW;J z!ZQnLroUr4>!X7g%NNS^gy{5V;`_pzc2#mp-%o SeWaKB@bf#V(RFg{6W<%6PawGf literal 0 HcmV?d00001 diff --git a/ir/tests/fixtures/bytecode/invalid_duplicate_ssa_id.wbc b/ir/tests/fixtures/bytecode/invalid_duplicate_ssa_id.wbc new file mode 100644 index 0000000000000000000000000000000000000000..ffc936f17813b0d2701c75f09ec9c8e0fb206544 GIT binary patch literal 2248 zcmd7SxlIH?5CzcTz7JvGGQwJe05BI2(i->>03IR-OhVaECJaI#12FbKgOXYUi-Z{G zZ`J>Gc5mO$uI_HHZ@QIk@l_nQ7yje$V7mHM&t8vU5{#^S%MW(ac5BhSmwXTL%QuUV z-G|=@4&k?AzXmshFCpmFr=RDC{CGGJCf_u;6U3AC@$Uxb62-R9y$0_b_8YwTg9d*Y z|6zll#D7%yI=?#ZLF8Q-hr5aP(iDU+_n7XaA#lIY^6~4#y`zKXXNzz7>6|kgig(V{ zuP^6}*B{$LXQ%5&Bt;!~FVrG%1&r|G-m8^V|INA;N(C1k%sd`ox|Pu@-a zw(!Cr)#P`KXFfc5HGh<^Cxj=zP`@v{o1gm}BzX21CV2d#1iw^&oZw6KC&rV@cay_A zkUYRs=a75O>B!INW(k4&smbTPxgA}u?>hdU`*;U)BiwKF&*j3Dxw*ML-a0n+?3p5JboS|AQx3j22H|I4XjHxf=>zz|bRjBtws4=q)tZdV&SRf;dUhUDaK^ z)3b-&YQJ4?LM@cX@!l-+Q}IBof9r`Q54nVrg@@_8;v2%J@rCmAixM(lCcY&+ipTG& zd|P;?kz)Ki#?v1jyjXoyT~7#)f2Mq2c(Z!$bCBSfW0>HnA0_yu^5X=bD?c$FU%ne3 z-ht!+p12CR=PDikRk~S1;Pu4#^WNACZO{>ep7)sjp$B;fw)W3|hVEBfSfS5lbeLPh X^)DTh{XN8&efa&I0y@du-Pq3hA1UvcsTDtyp z_Z)Vs{dTdEgI&;Ib#i}?%rdaCf`XTtlcH}i9zg9y(Y!w8Rm6ycY`#}PgkJ~5tLzMCB0 zf#d<6K2T)aMy8v?&BTUwSWFI*Z3p5JboS|AQx3j22H|xGI8yxf=>zz|bRjBtws4=q)tZdV&SRAUH|UT~*V) zJ-vtBYQJ4?LM>Fs@!qWRQ}IAi|JD;r9&!mK3lGzG#W#dc<4fhauaJ=bGVv|pQ9Sjo z%D07QE>cYWj`7?N4_?e)$k!9XQ$JI_FT9zbc@82xeGDT!{!xTqDnE|!x$+a^smpg$ zhdq!yz!RsCIj3~gPw8e6f%}PHI_#U<(WUaPaq_$zmqCDkB>gly#Z38DC__L literal 0 HcmV?d00001 diff --git a/ir/tests/fixtures/bytecode/invalid_header.wbc b/ir/tests/fixtures/bytecode/invalid_header.wbc new file mode 100644 index 0000000000000000000000000000000000000000..2bd8647c9fd32a94feffeb89aa7792fa76ecd2fc GIT binary patch literal 1216 zcmb`GyA8rH07T9I{}B^JR1p(U1`rYjJ(Nf+K*zo=8TqMn2mDn%Dzb-CM$zG^7yMo64dKi5qj=`4WF%imZwXJ*>AQ(< z3olHhG5sCWnI9dzTE0@QCq$>e5Z@QxEzf=q5<2S`CUo+nguWC%PUxlhiRtw6-Slt| zWDn?!bI3mDeDvphvxLF(jOpjTc^qGkcOU2HIqrcS`}aR{|F7eP1$jN~o-ZJ| literal 0 HcmV?d00001 diff --git a/ir/tests/fixtures/bytecode/invalid_layout.wbc b/ir/tests/fixtures/bytecode/invalid_layout.wbc new file mode 100644 index 0000000000000000000000000000000000000000..ba8da2158c3dc0afdc0e51e6c280123f135194c9 GIT binary patch literal 1216 zcmb`GxeWp_6hzH^AEJU4(TWNP4G4*V96}@-AfyCJBBT^Tx`1Hk5sYM6NNh6u|IGaH z+TO!%wcoBcp%$tKtgC)BtCy*2AWDFqTJlgz$egF?yW$(dm+?pSnHMD_uMpo7p2U-P zQ@<^|Fi17|9pjk~4_?h5qDr z;T}jH;Hh)SKIe4g=XA4#!2Q(ZbKl&KF4uP*=jT4|fgStzKXd)B^}-CkE~CTT8m@oq VG1=csaybv*zq1mZ$HzL+eE`k$Ap8IT literal 0 HcmV?d00001 diff --git a/ir/tests/fixtures/bytecode/invalid_length.wbc b/ir/tests/fixtures/bytecode/invalid_length.wbc new file mode 100644 index 0000000000000000000000000000000000000000..8abee84e75873965b1821b2a6230628eb3f53a39 GIT binary patch literal 1216 zcmb`GI|>3Z7=+{d{lF6}R*NUFjEZ1kuchDxEIoopvh*mH-a-rK6C4OZFwN}$&rIgu zWOuh&Y}dUV`#^K+iP1kW7(1do4^;OFWO6MU)u$ar#jZ*p!n zKfLT&;GA>03IR-OhVaECJaI#12FbKgOXYU3kKu- zt@^*t?(O^8)!ps&O}El5zKX;4!hakdOjp0^+3OKZf{}G^`N2-wZY{d^lJ6mY`DPKa z`|umVA^cYC*WhOGB?P_t^z;0X9}fq@T%-=U2x)h`cM~a5vFjnt~AK9@CvP1nw7FK7M_;cXZJFZ1F8WopWYG@y@yW z_2r!L`olYCynBrA5e@vvht`*P{@>!*p49zmo!0(ZdCpoy{PtnbBl4x`v3)GN|I^aZ z*k1q3KD;;DuYG^_Jj5-#zjF-)<>PigsvrN?s17t&MSMl?T78Gifv^9grwmeg`D=WA ar=CkZz7=2Jv5N@R$JhAB)X}fH;y(dAq*Uwx literal 0 HcmV?d00001 diff --git a/ir/tests/fixtures/bytecode/invalid_opcode.wbc b/ir/tests/fixtures/bytecode/invalid_opcode.wbc new file mode 100644 index 0000000000000000000000000000000000000000..f2153b5e1c4a73d1596a6e32951de791c21bf24a GIT binary patch literal 1216 zcmb`FxeWp_6hzH^AEJU4(TWNP4G4*V96}@-AfyCJBBT^Tx`1Hk1&m~w04JmW-;BT4 z>%(rf->x^I7OLg?Xjc8HI1=mMernl6DWh!RY5uNwL;5m)RGd)bC60mghbP3C=l&2~K{L;7j$#30|r{G0t4Rn>oA# z*#n$9r`&VS$NZdcmN0mpn)$ppkK@br-N*m)9Pi+4!1IQGE*Iv^?K{u--&$t-d&xQZ OAAWz_mveHQ6W<3*`ypBY literal 0 HcmV?d00001 diff --git a/ir/tests/fixtures/bytecode/invalid_phi_duplicate_edge.wbc b/ir/tests/fixtures/bytecode/invalid_phi_duplicate_edge.wbc new file mode 100644 index 0000000000000000000000000000000000000000..68b4d0fb3a18dbba9305aeabcae85c81b41d4814 GIT binary patch literal 2248 zcmd7SxlIH?5CzcTz7JvGGQwJe05BI2(i->>03IR-OhVaECJaI#12FbKgOXYUi-Z{G zZ`J>Gc5mO$uI_HHZ@QIk@l_nQ7yje$V7mHM&t8vU5{#^S%MW(ac5BhSmwXTL%QuUV z-G|=@4&k?AzXmshFCpmFr=RDC{CGGJCf_u;6U3AC@$Uxb62-R9y$0_b_8YwTg9d*Y z|6zll#D7%yI=?#ZLF8Q-hr5aP(iDU+_n7XaA#lIY^6~4#y`zKXXNzz7>6|kgig(V{ zuP^6}*B{$LXQ%5&Bt;;LE}4OCv<8eiY3 Y=Ms-^#n*T2B0}}?HU2Sm^sBD;Pd?04?EnA( literal 0 HcmV?d00001 diff --git a/ir/tests/fixtures/bytecode/invalid_phi_missing_edge.wbc b/ir/tests/fixtures/bytecode/invalid_phi_missing_edge.wbc new file mode 100644 index 0000000000000000000000000000000000000000..2cba851a623f49f1402d38ab6fb004c289fe3f44 GIT binary patch literal 2248 zcmd7SIZgvX5Cza--xm>(Vi7su0E7mFuCBd(RJc(smoseUyBU@yj=j zkUa{&73{8(M*FqzW%nTt%C{_D7GcfvSNB63>O=RUBEF(`t-eFffv^9g=QL1x`D=WA ar(Q}tz7=2Jv8xEx$Jh9$)X}fH;=cer>{RUl literal 0 HcmV?d00001 diff --git a/ir/tests/fixtures/bytecode/invalid_phi_nonpredecessor.wbc b/ir/tests/fixtures/bytecode/invalid_phi_nonpredecessor.wbc new file mode 100644 index 0000000000000000000000000000000000000000..c747f4ea37c8e9b8435b2d02221613b477f26c9c GIT binary patch literal 2248 zcmd7SxlIH?5CzcTz7JvGGQwJe05BI2(i->>03IR-OhVaECJaI#12FbKgOXYUi-Z{G zZ`J>Gc5mO$uI_HHZ@QIk@l_nQ7yje$V7mHM&t8vU5{#^S%MW(ac5BhSmwXTL%QuUV z-G|=@4&k?AzXmshFCpmFr=RDC{CGGJCf_u;6U3AC@$Uxb62-R9y$0_b_8YwTg9d*Y z|6zll#D7%yI=?#ZLF8Q-hr5aP(iDU+_n7XaA#lIY^6~4#y`zKXXNzz7>6|kgig(V{ zuP^6}*B{$LXQ%5&Bt;>03IR-OhVaECJaI#12FbKgOXYUi-Z{G zZ`J>Gc5mO$uI_HHZ@QIk@l_nQ7yje$V7mHM&t8vU5{#^S%MW(ac5BhSmwXTL%QuUV z-G|=@4&k?AzXmshFCpmFr=RDC{CGGJCf_u;6U3AC@$Uxb62-R9y$0_b_8YwTg9d*Y z|6zll#D7%yI=?#ZLF8Q-hr5aP(iDU+_n7XaA#lIY^6~4#y`zKXXNzz7>6|kgig(V{ zuP^6}*B{$LXQ%5&Bt;>03IR-OhVaECJaI#12FbKgOXYUi-Z{G zZ`J>Gc5mO$uI_HHZ@QIk@l_nQ7yje$V7mHM&t8vU5{#^S%MW(ac5BhSmwXTL%QuUV z-G|=@4&k?AzXmshFCpmFr=RDC{CGGJCf_u;6U3AC@$Uxb62-R9y$0_b_8YwTg9d*Y z|6zll#D7%yI=?#ZLF8Q-hr5aP(iDU+_n7XaA#lIY^6~4#y`zKXXNzz7>6|kgig(V{ zuP^6}*B{$LXQ%5&Bt;;LE}g)1+Ajj!+2 YbBV{d;_Ewh5uy6{8vmF&`c+r_CqA@P?EnA( literal 0 HcmV?d00001 diff --git a/ir/tests/fixtures/bytecode/invalid_return_slot.wbc b/ir/tests/fixtures/bytecode/invalid_return_slot.wbc new file mode 100644 index 0000000000000000000000000000000000000000..5fe7e1838f97fb7afd66267b377b630fc66d993c GIT binary patch literal 1216 zcmb`GI|>3Z7=+{d{lF6}R*NUFTou8>-Yo?$VCfM&lBGwn^cGs|e1ZcZ2&NhSe`YfO zCfUPowcoBcp%$v;cyCtysd%8Mf9t6w54nVrg@@_8;v2%J@um9gS4hZwnfR9QD4x8l z`fcHvjZ~B0F`oV5!Hf9|`FcWl@-y}O!khUy&q0J|j$wqyKZ@{6^~VuDSASwWxqLS{ zyaUMtJaq~==ai28lx`LgxSyJQ-kaOerTVVp{@lkquxtPPXRiOXUYNn>GCIty;rf>? UlmD$Gm;3PZJ1NO|e2j_i4Jbk=^8f$< literal 0 HcmV?d00001 diff --git a/ir/tests/fixtures/bytecode/invalid_return_type.wbc b/ir/tests/fixtures/bytecode/invalid_return_type.wbc new file mode 100644 index 0000000000000000000000000000000000000000..7b14e1e1e1f6c0b61b25e3ff2d254110d31a4daa GIT binary patch literal 1216 zcmcJOxeWp_6hzH^AEJU4(TWNP7Z4HwIU6F;03jt%5+S7!(gg%N4~da1ivTC1KZpNc z+k4op_S^L))Izl!@6C#zN(YMix1U<}kjp4rc$mK{y&-&>UW#YGLPqAxq_>1e>GZpb zZwt?Cq?-O6)7c*#yjZ?at|vsNe!yjh;}97J^H7)EsRqlmr~KaS|R_=)NC<-6&_ zJCHq~Q>Tz~PWkAc^35U!&r{Q%_vUeYDc*hDpXYc7cI}`4%>BRC3k&#MCWpBZ%m@9_ UqW%{$C->p!cT!{5$uTFsH_8+s`~Uy| literal 0 HcmV?d00001 diff --git a/ir/tests/fixtures/bytecode/invalid_semantics.wbc b/ir/tests/fixtures/bytecode/invalid_semantics.wbc new file mode 100644 index 0000000000000000000000000000000000000000..36e7d9834f00151722dc142f5d1072cebb8f6146 GIT binary patch literal 1216 zcmb`GISN8C7=+`#FL;87)x#55Mn$l&*HZ8TmL9<)S$Y&pZ=uDT&tf11!PgA`ESZ?Z z!)~?Tt~a3;s;@3&el#m$DjtY3;$xOQlrpm3)BIiO4dKi5qj=VfGSXK_ZwXJ*>AQ(< z3ok6Bnf{LHtd9;}EgzNZ3DM~<#P@}F%X6NCgw8&O37z~Xp)bXc6M89rVmiJ2ZhCkJ zvIlhL9CFS%AN@JsEMf3GGyS|bkK@bn?&JPE$2+iV|NhV1|LeT4fbYxXFgL>eZ+&L_ S`$#YM;pcZ&qwD0@C%zBO{2=@Q literal 0 HcmV?d00001 diff --git a/ir/tests/fixtures/bytecode/invalid_signature.wbc b/ir/tests/fixtures/bytecode/invalid_signature.wbc new file mode 100644 index 0000000000000000000000000000000000000000..5f2c8e6557fc4337d6f84eeb628ea0c174a8a8ba GIT binary patch literal 1216 zcmbu8I|>3Z7=+{d{lF6}R*NUFTou8>-Yo?$VCfM&lBGwn^cGs|e1ZcZh-rrZpP9_R zN%pW??YHYqsD)}d-kVi_Djq26-+F4vLoT6Y;bHo&_=fOle5pSB6%sOECcY&+iYM=? zep`5EBh}=0jAws%@M8W#zMc@C{7n76@MeC_a}eQ~V;JG_k0Sh1{c(iP)t?woF5gWK z??CbZPn|-}Ii({%rJF?r?x!aIrR8>XslMyDKlkwt?Aky7nd^V87iRFej1F^axIT6+ UX8XG&m;3PZJ1N0=e9VdN4H{V}@Bjb+ literal 0 HcmV?d00001 diff --git a/ir/tests/fixtures/bytecode/invalid_site.wbc b/ir/tests/fixtures/bytecode/invalid_site.wbc new file mode 100644 index 0000000000000000000000000000000000000000..eb6131903ed963f053b8945c1bf8ace950d2e827 GIT binary patch literal 1216 zcmb`GISK+n6hzy7U+@Hj(clRTM@29&cS6An70y@du-Pq3hA1Uo5yE&cy= z_Z)Vs{dT?WdMKj}~6pNa1aZ3Z7=+{d{lF6}R*NUFTou8>-Yo?$VCfM&lBGwn^cGs|e1ZcZ2&NhSe`YfO zCfUPowcoBcp%$v;cyCtysd%8Mf9t6w54nVrg@@_8;v2%J@um9gS4hZwnfR9QD4x8l z`fcHvjZ~B0F`oV5!Hf9|`FcWl@-y}O!khUy&q0J|j$wqyKZ@{6^~VuDSASwWxqLS{ zyaUMtJaq~==ai28lx`LgxSyJQ-kaOerTVVp{@lkquxtPPXRiOXUYNn>GCIty;rf@B T$^KrF%YFFyos{T2KIR19>JTW9 literal 0 HcmV?d00001 diff --git a/ir/tests/fixtures/bytecode/invalid_stride.wbc b/ir/tests/fixtures/bytecode/invalid_stride.wbc new file mode 100644 index 0000000000000000000000000000000000000000..f50c772fdd88a0822ec35f6d7e58938383a844f7 GIT binary patch literal 1216 zcmb`GISK+n6hzy7U+@Hjk$3{bQ4tKxolx)sh91Eq8F~~$Z=u1|8?c~h1Sk3YU$45_ z?)JD}A9kBH(sdP$S|K{n1hps?j;b}a2L)^>sLUY#31+u?PdQ0^roxGdo zZPg14sVBc#3rXpK0D#y_=u&97J^XF^uT=M-hFc`8c94G@qDGF29=` z-huGye(6({b53#Or?^=Ja6diyyf?SQrRL6Yf9~TQ*tJ*xGv|NpmuB#NnH=UeaQ>~& Uu)nwDavy$vXC=ChkA1>@06a_}+W-In literal 0 HcmV?d00001 diff --git a/ir/tests/fixtures/bytecode/invalid_table_count.wbc b/ir/tests/fixtures/bytecode/invalid_table_count.wbc new file mode 100644 index 0000000000000000000000000000000000000000..aaac257181051dc348842949036966498594d89d GIT binary patch literal 1216 zcmb`GI|{-;7=+jN`+0(36+D4uR0IoqEd?)N=@C4VrAM*!7FuLJ!GUEFOf&rR*x6(^ z`|WbKS*=4Ql#k=RUh)&^KvDhnGs_-w8D$F(^S7nfgiq5C;#sedk^N=T8^WV>`mW-e z!ZQnLroUx6>!X7g%NNRZgy{5V;=96|<;UWC5uJVXBRcs(L|=#>M)X|#$aH#nZ+f@~ zvIlhL6!M)@KKfI>X~f`pX8O5r9>Z;G!7pT=+1=e$Hh?iY!#33uYj zJF8z89yv%g`3>VaA09lJKasB`geN~zzb(AT56?V1;;-VF2lwcTzga&1UJgH1zn{a$ z>JN-3m-i-z??CbZPhEt}xkyKTk#3YDa6dKq%-8Mciu$f&f9_+?wzkiI=K5dji5dJ} hMu)LAT>sKzvcH$)vJanMszm4U`8|D~)cZrqQEzu8BOU+% literal 0 HcmV?d00001 diff --git a/ir/tests/fixtures/bytecode/invalid_trailing.wbc b/ir/tests/fixtures/bytecode/invalid_trailing.wbc new file mode 100644 index 0000000000000000000000000000000000000000..6ec390107fe74ed596a102edc824457149182b63 GIT binary patch literal 1217 zcmb`GI|>3Z7=+{d{lF6}R*NUFTou8>-Yo?$VCfM&lBGwn^cGs|e1ZcZ2&NhSe`YfO zCfUPowcoBcp%$v;cyCtysd%8Mf9t6w54nVrg@@_8;v2%J@um9gS4hZwnfR9QD4x8l z`fcHvjZ~B0F`oV5!Hf9|`FcWl@-y}O!khUy&q0J|j$wqyKZ@{6^~VuDSASwWxqLS{ zyaUMtJaq~==ai28lx`LgxSyJQ-kaOerTVVp{@lkquxtPPXRiOXUYNn>GCIty;rf@B U$^KrF%YFFyos{T2KITLh-s(pn`v3p{ literal 0 HcmV?d00001 diff --git a/ir/tests/fixtures/bytecode/invalid_truncated.wbc b/ir/tests/fixtures/bytecode/invalid_truncated.wbc new file mode 100644 index 0000000000000000000000000000000000000000..fc2316845443ab588777f3f5dfa8edaef34cf1ac GIT binary patch literal 1215 zcmb`GI|>3Z7=+{d{lF6}R*NUFTou8>-Yo?$VCfM&lBGwn^cGs|e1ZcZ2&NhSe`YfO zCfUPowcoBcp%$v;cyCtysd%8Mf9t6w54nVrg@@_8;v2%J@um9gS4hZwnfR9QD4x8l z`fcHvjZ~B0F`oV5!Hf9|`FcWl@-y}O!khUy&q0J|j$wqyKZ@{6^~VuDSASwWxqLS{ zyaUMtJaq~==ai28lx`LgxSyJQ-kaOerTVVp{@lkquxtPPXRiOXUYNn>GCIty;rf@B U$^KrF%YFFyos{T2KIW9}4X9Bd`v3p{ literal 0 HcmV?d00001 diff --git a/ir/tests/fixtures/bytecode/invalid_type_cycle.wbc b/ir/tests/fixtures/bytecode/invalid_type_cycle.wbc new file mode 100644 index 0000000000000000000000000000000000000000..0b5bb2595b747a7d5d578797ca35a334cec99abf GIT binary patch literal 1216 zcmb`GI|>3Z7=+{d{kp+owRi%{RS_)g-BR!ZmL9<)S$Y&pZ=uD`CpZv-V4C6oXD0J+ zl0EEJ`|WxYYN1+=_h!|fiU*4Nx1L(^kV`08c$mH`z9D=XU#ic3g@nwPiEjyy;>o+J z-xi+PNHzH#Tz~PU*-`>1Gju`>Dz2y}2D-s_#1P&wacDyY|n2=K5djg&BM$Nlll7E;apmT}gHqZi8;%5|i0=4a}6r8mp-J$n((KKc<(eh}dc^@kCjt3NW%T;7{G z+ymJIoI0h`ltG;NDf=X1@H{o=%zg7XzEt0RoS)~o2X^eA|IGcr)^iK^z6^(%HQfKw VW46DS%;h}%`<*n=IXU);?+xs9AqoHh literal 0 HcmV?d00001 diff --git a/ir/tests/fixtures/bytecode/invalid_utf8.wbc b/ir/tests/fixtures/bytecode/invalid_utf8.wbc new file mode 100644 index 0000000000000000000000000000000000000000..d7df7fad5e30777d859486f89040e62d195f3551 GIT binary patch literal 1234 zcmb`GISK+n6hzy7U+@Hj(clRTM@29&*HG{RhK7b7$|K{dTPl-DxqZIZu+|TlJH^tT7Bka60*NUd_}ks zPu@}es&L03)#TTVXFfc*H-9EyLkLfPqJC3&lArmUXG{D=JbrX-@mI^o-^t;}>UVSa zRQ;auvP-@%cVE=ko#Q3%RNyyZ`_I literal 0 HcmV?d00001 diff --git a/ir/tests/fixtures/bytecode/invalid_version.wbc b/ir/tests/fixtures/bytecode/invalid_version.wbc new file mode 100644 index 0000000000000000000000000000000000000000..e82d1fb6e585ff8f4bf1529fa3acc4b2e8e1e4fd GIT binary patch literal 1216 zcmb`FxeWqA6hnvmK12m8q7@Yo4j?1~ayCSw0YXZkBtl9dqzeevFR?Tl0w%HkxBWfW z>99HOx4X~`^=cSC+jV2EJ`iO^~!{~xyy|Hqh+$cm+X`G O@cX+c(RqCA6Wtfi1R(qX literal 0 HcmV?d00001 diff --git a/ir/tests/fixtures/bytecode/phi_diamond.wbc b/ir/tests/fixtures/bytecode/phi_diamond.wbc new file mode 100644 index 0000000000000000000000000000000000000000..45322b96383df5e74b4ca9315599a4dc6869bd16 GIT binary patch literal 2248 zcmd7SxlIH?5CzcTz7JvGGQwJe05BI2(i->>03IR-OhVaECJaI#12FbKgOXYUi-Z{G zZ`J>Gc5mO$uI_HHZ@QIk@l_nQ7yje$V7mHM&t8vU5{#^S%MW(ac5BhSmwXTL%QuUV z-G|=@4&k?AzXmshFCpmFr=RDC{CGGJCf_u;6U3AC@$Uxb62-R9y$0_b_8YwTg9d*Y z|6zll#D7%yI=?#ZLF8Q-hr5aP(iDU+_n7XaA#lIY^6~4#y`zKXXNzz7>6|kgig(V{ zuP^6}*B{$LXQ%5&Bt;3Z7=+{d{lF6}R*NUFTou8>-Yo?$VCfM&lBGwn^cGs|e1ZcZ2&NhSe`YfO zCfUPowcoBcp%$v;cyCtysd%8Mf9t6w54nVrg@@_8;v2%J@um9gS4hZwnfR9QD4x8l z`fcHvjZ~B0F`oV5!Hf9|`FcWl@-y}O!khUy&q0J|j$wqyKZ@{6^~VuDSASwWxqLS{ zyaUMtJaq~==ai28lx`LgxSyJQ-kaOerTVVp{@lkquxtPPXRiOXUYNn>GCIty;rf@B U$^KrF%YFFyos{T2KITOC2FXky`v3p{ literal 0 HcmV?d00001 diff --git a/meson.build b/meson.build index c81d073..1a6112b 100644 --- a/meson.build +++ b/meson.build @@ -20,6 +20,9 @@ endforeach if get_option('socket-cli') selected_features += ['socket-cli'] endif +if get_option('native-linker') + selected_features += ['native-linker'] +endif cargo_host_target = get_option('cargo-host-target') if meson.is_cross_build() and cargo_host_target == '' diff --git a/meson.options b/meson.options index 9033647..ecf2a7b 100644 --- a/meson.options +++ b/meson.options @@ -9,6 +9,8 @@ option('asm-loongarch64', type: 'boolean', value: true, description: 'Include the LoongArch64 assembler output module') option('socket-cli', type: 'boolean', value: false, description: 'Include experimental AST JSON lowering commands') +option('native-linker', type: 'boolean', value: true, + description: 'Include static Linux AMD64 executable linking') option('asmobj-dir', type: 'string', value: '', description: 'Absolute directory of the complete prebuilt Wave asmobj module for the executable host') option('wave-ir-dir', type: 'string', value: '', diff --git a/src/backends/bytecode.rs b/src/backends/bytecode.rs new file mode 100644 index 0000000..eba5c56 --- /dev/null +++ b/src/backends/bytecode.rs @@ -0,0 +1,30 @@ +//! Explicit built-in bytecode composition; the compiler itself executes in Wave. +use backend_api::{Artifact, Backend, CheckedModule, Requirement, Support}; + +use diagnostic::Diagnostic; + +use target_spec::TargetSpec; + +pub(crate) struct Bytecode { + pub limits: ir::bytecode::BytecodeLimits, +} + +impl Backend for Bytecode { + fn target_id(&self) -> &str { + "whale-bytecode-v1" + } + + fn support(&self, _requirement: Requirement<'_>, _target: &TargetSpec) -> Support { + // Wave performs the complete executable-subset and import check before + // serializing any bytes, including unreachable instructions. + Support::Direct + } + + fn emit(&self, module: &CheckedModule<'_>) -> Result, Vec> { + ir::bytecode::compile(module.module(), self.limits) + .map(|bytes| vec![Artifact { name: "program.wbc".into(), bytes }]) + .map_err(|error| { + vec![Diagnostic::new("bytecode", "compile", "bytecode.compile", error.to_string())] + }) + } +} diff --git a/src/backends/mod.rs b/src/backends/mod.rs new file mode 100644 index 0000000..469e602 --- /dev/null +++ b/src/backends/mod.rs @@ -0,0 +1 @@ +pub(crate) mod bytecode; diff --git a/src/builtins.rs b/src/builtins.rs index 9b540a8..05d8cf1 100644 --- a/src/builtins.rs +++ b/src/builtins.rs @@ -1,9 +1,19 @@ //! Built-in composition belongs to the application, not the extension APIs. pub fn registry() -> toolchain::Registry { + registry_with_bytecode_limits(ir::bytecode::BytecodeLimits::default()) +} + +pub(crate) fn registry_with_bytecode_limits( + limits: ir::bytecode::BytecodeLimits, +) -> toolchain::Registry { let mut registry = toolchain::Registry::new(); registry .register_target(ir::Target::X86_64WhaleLinux.specification()) .expect("valid built-in target"); + registry.register_target(target_spec::whale_bytecode_v1()).expect("valid bytecode target"); + registry + .register_backend(crate::backends::bytecode::Bytecode { limits }) + .expect("unique bytecode backend"); #[cfg(feature = "asm-amd64")] registry.register_assembler(amd64::AMD64).expect("unique built-in assembler"); #[cfg(feature = "asm-aarch64")] diff --git a/src/cli.rs b/src/cli.rs index 1013d5e..9c5b2ec 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -23,8 +23,15 @@ pub fn run() { "--version" | "-V" => println!("whale {}", env!("CARGO_PKG_VERSION")), "asm" => commands::asm::run(args.collect()), "object" => commands::object::run(args.collect()), + #[cfg(feature = "native-linker")] "link" => commands::linker::run(args.collect()), + #[cfg(not(feature = "native-linker"))] + "link" => { + eprintln!("Error: native linker is not included; enable feature 'native-linker'."); + std::process::exit(2); + }, "ir" => commands::ir::run(args.collect()), + "bytecode" => commands::bytecode::run(args.collect()), "disasm" => commands::reverse::disasm(args.collect()), "reverse" => commands::reverse::reverse(args.collect()), _ => { @@ -40,17 +47,24 @@ fn print_help() { println!(" whale asm --amd64|--aarch64|--riscv64|--loongarch64 -o "); println!(" whale asm --arch ID -o "); println!(" whale object -o "); + #[cfg(feature = "native-linker")] println!(" whale link ... -o [--entry NAME]"); println!(" whale ir [options]"); + println!(" whale bytecode verify|run [options]"); println!(" whale disasm [--amd64] [--json]"); println!(" whale reverse inspect|cfg|xrefs [options]"); println!(" whale --version | -V"); println!(); println!("Commands:"); - println!(" asm Assemble AMD64/AArch64/RV64I/LoongArch64 source into an ELF64 object"); + println!( + " asm Selected assemblers: {}", + crate::builtins::registry().assembler_ids().collect::>().join(", ") + ); println!(" object Wrap raw bytes in an AMD64 ELF64 object"); + #[cfg(feature = "native-linker")] println!(" link Static Linux AMD64 executable linking"); println!(" disasm Disassembly entry point (core currently unavailable)"); println!(" reverse ELF inspection; CFG/xrefs core currently unavailable"); - println!(" ir IR tools (verify/print/run; socket-cli enables AST lower)"); + println!(" ir IR verify/print/fold/run/emit; socket-cli enables AST lower"); + println!(" bytecode Versioned Whale bytecode verification and tracked execution"); } diff --git a/src/commands/bytecode.rs b/src/commands/bytecode.rs new file mode 100644 index 0000000..f3bb208 --- /dev/null +++ b/src/commands/bytecode.rs @@ -0,0 +1,167 @@ +//! File and CLI boundaries for the Wave bytecode compiler and verified VM. +use std::{fs, io::Read, process}; + +use ir::bytecode::{BytecodeLimits, BytecodeProgram}; + +use super::report::println; + +fn fail(message: impl std::fmt::Display) -> ! { + eprintln!("Error: {message}"); + process::exit(1); +} + +pub(super) fn emit(module: &ir::Module, input: &str, output: &str, maximum: Option) { + let mut limits = BytecodeLimits::default(); + if let Some(maximum) = maximum { + limits.max_input_bytes = limits.max_input_bytes.min(maximum as u64); + } + let artifacts = crate::builtins::registry_with_bytecode_limits(limits) + .compile(module, ir::IrLimits::default()) + .unwrap_or_else(|errors| { + fail(errors.iter().map(|error| error.message.as_str()).collect::>().join("; ")) + }); + let [artifact]: [_; 1] = + artifacts.try_into().unwrap_or_else(|_| fail("invalid bytecode artifact count")); + let limit = maximum.unwrap_or(64 * 1024 * 1024); + if artifact.bytes.len() > limit { + fail(format!("bytecode output exceeds {limit} bytes")); + } + super::output::publish(input.as_ref(), output.as_ref(), &artifact.bytes) + .unwrap_or_else(|error| fail(format!("failed to write {output}: {error}"))); + println!("Wrote bytecode to {output}"); +} + +pub fn run(arguments: Vec) { + if arguments.is_empty() || arguments.iter().any(|argument| argument == "--help") { + println!("Usage: whale bytecode verify [limits]"); + println!( + " whale bytecode run --function @fN [--arg ...] [limits]" + ); + println!("Limits: --max-input , --max-decoded , --max-work , --max-workspace "); + println!("Run limits: --max-steps , --max-memory "); + println!("Only verified v1 images execute. External runtime imports are unsupported."); + return; + } + let command = arguments[0].as_str(); + if !matches!(command, "verify" | "run") { + fail(format!("unsupported bytecode command: {command}")); + } + let mut limits = BytecodeLimits::default(); + let mut options = ir::InterpreterOptions::default(); + let mut input = None; + let mut function = None; + let mut literals = Vec::new(); + let mut seen = std::collections::BTreeSet::new(); + let mut arguments = arguments.iter().skip(1); + while let Some(argument) = arguments.next() { + match argument.as_str() { + "--arg" if command == "run" => { + literals.push(arguments.next().unwrap_or_else(|| fail("--arg requires a literal"))); + }, + "--function" if command == "run" => { + if function.is_some() { + fail("duplicate --function option"); + } + let value = arguments.next().unwrap_or_else(|| fail("--function requires @fN")); + let id = value + .strip_prefix("@f") + .filter(|id| !id.is_empty() && id.bytes().all(|byte| byte.is_ascii_digit())) + .and_then(|id| id.parse::().ok()) + .unwrap_or_else(|| fail("--function requires @fN with a u32 ID")); + function = Some(ir::FunctionId(id)); + }, + "--max-input" | "--max-decoded" | "--max-work" | "--max-workspace" | "--max-steps" + | "--max-memory" => { + if command != "run" && matches!(argument.as_str(), "--max-steps" | "--max-memory") { + fail(format!("{argument} is only valid for run")); + } + if !seen.insert(argument) { + fail(format!("duplicate {argument} option")); + } + let value = arguments + .next() + .unwrap_or_else(|| fail(format!("{argument} requires a count"))); + let count = value + .parse::() + .ok() + .filter(|_| { + !value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit()) + }) + .unwrap_or_else(|| fail(format!("{argument} requires a decimal u64 count"))); + match argument.as_str() { + "--max-input" => limits.max_input_bytes = count, + "--max-decoded" => limits.max_decoded_bytes = count, + "--max-work" => { + limits.max_work = count; + options.ir_limits.max_analysis_work = usize::try_from(count) + .unwrap_or_else(|_| fail("--max-work exceeds host count range")); + }, + "--max-workspace" => limits.max_workspace_bytes = count, + "--max-steps" => options.max_steps = count, + "--max-memory" => options.memory_limits.max_bytes = count, + _ => unreachable!(), + } + }, + value if !value.starts_with('-') && input.is_none() => input = Some(argument), + _ => fail(format!("unexpected argument: {argument}")), + } + } + if command == "run" && function.is_none() { + fail("run requires --function @fN"); + } + let input = input.unwrap_or_else(|| fail("missing input file")); + let mut bytes = Vec::new(); + fs::File::open(input) + .and_then(|file| { + file.take(limits.max_input_bytes.saturating_add(1)).read_to_end(&mut bytes) + }) + .unwrap_or_else(|error| fail(format!("failed to read {input}: {error}"))); + if bytes.len() as u64 > limits.max_input_bytes { + fail("bytecode input byte limit exceeded"); + } + let mut program = BytecodeProgram::load(&bytes, limits) + .unwrap_or_else(|error| fail(format!("{input}: {error}"))); + if command == "verify" { + println!("Verified bytecode {input}"); + return; + } + execute(&mut program, function.expect("required function"), &literals, options); +} + +fn execute( + program: &mut BytecodeProgram, + function: ir::FunctionId, + literals: &[&String], + options: ir::InterpreterOptions, +) { + let info = program + .function(function) + .unwrap_or_else(|error| fail(error)) + .unwrap_or_else(|| fail(format!("no body for @f{}", function.0))); + if !info.has_body { + fail(format!("no body for @f{}", function.0)); + } + if info.params.len() != literals.len() { + fail(format!("expected {} arguments, got {}", info.params.len(), literals.len())); + } + let arguments = info + .params + .iter() + .zip(literals) + .enumerate() + .map(|(index, (ty, literal))| { + super::ir::scalar_argument(ty, literal).unwrap_or_else(|| { + fail(format!("argument {index} requires an exact {ty} scalar literal")) + }) + }) + .collect::>(); + let result = program.run(function, &arguments, options).unwrap_or_else(|error| fail(error)); + match result.value.as_ref().map(|value| value.scalar_value()) { + Some(Some(ir::ConstValue::I(value))) => println!("{} {value}", info.ret), + Some(Some(ir::ConstValue::U(value))) => println!("{} {value}", info.ret), + Some(Some(ir::ConstValue::Bool(value))) => println!("bool {value}"), + Some(Some(ir::ConstValue::F(value))) => println!("{} {value}", info.ret), + None => println!("void"), + Some(None) => fail("CLI output requires a scalar or void result"), + } +} diff --git a/src/commands/ir.rs b/src/commands/ir.rs index 0232ee9..609c7db 100644 --- a/src/commands/ir.rs +++ b/src/commands/ir.rs @@ -27,7 +27,7 @@ pub fn run(args: Vec) { return; } let command = &args[0]; - if !matches!(command.as_str(), "lower" | "verify" | "print" | "run") { + if !matches!(command.as_str(), "lower" | "verify" | "print" | "run" | "emit" | "fold") { fail(format!("unsupported IR command: {command}")); } #[cfg(not(feature = "socket-cli"))] @@ -43,14 +43,13 @@ pub fn run(args: Vec) { let mut max_output = None; let mut input = None; let mut output = None; - #[cfg(feature = "socket-cli")] let mut target = None; #[cfg(feature = "socket-cli")] let mut do_verify = true; let mut args = args.iter().skip(1); while let Some(arg) = args.next() { match arg.as_str() { - "--max-output" if matches!(command.as_str(), "lower" | "print") => { + "--max-output" if matches!(command.as_str(), "lower" | "print" | "emit" | "fold") => { if max_output.is_some() { fail("duplicate --max-output option"); } @@ -64,7 +63,7 @@ pub fn run(args: Vec) { .unwrap_or_else(|| fail("--max-output requires a decimal byte count")), ); }, - "-o" if matches!(command.as_str(), "lower" | "print") => { + "-o" if matches!(command.as_str(), "lower" | "print" | "emit" | "fold") => { if output.is_some() { fail("duplicate -o option"); } @@ -115,8 +114,7 @@ pub fn run(args: Vec) { .unwrap_or_else(|| fail("--max-memory requires a decimal u64 byte count")), ); }, - #[cfg(feature = "socket-cli")] - "--target" if command == "lower" => { + "--target" if matches!(command.as_str(), "lower" | "emit") => { if target.is_some() { fail("duplicate --target option"); } @@ -131,12 +129,25 @@ pub fn run(args: Vec) { if command == "run" && function.is_none() { fail("run requires --function @fN"); } + if command == "emit" { + let selected = target.map(String::as_str).unwrap_or("whale-bytecode-v1"); + if crate::builtins::registry().backend(selected).is_none() { + fail(format!( + "unsupported IR emission target {selected:?}; available: whale-bytecode-v1" + )); + } + if output.is_none() { + fail("emit requires -o "); + } + } let input = input.unwrap_or_else(|| fail("missing input file")); #[cfg(feature = "socket-cli")] let lower_target = if command == "lower" { Some( - ir::Target::lookup(target.map(String::as_str).unwrap_or("x86_64-whale-linux")) - .unwrap_or_else(|e| fail(e)), + target_spec::TargetSpec::lookup_builtin( + target.map(String::as_str).unwrap_or("x86_64-whale-linux"), + ) + .unwrap_or_else(|e| fail(e)), ) } else { None @@ -151,13 +162,13 @@ pub fn run(args: Vec) { Ok(source) })() .unwrap_or_else(|e| fail(format!("failed to read {input}: {e}"))); - let module = if command == "lower" { + let mut module = if command == "lower" { #[cfg(feature = "socket-cli")] { let target = lower_target.expect("lower target checked before reading input"); let program = interchange::decode(&source) .unwrap_or_else(|e| fail(format!("Failed to parse socket JSON: {e}"))); - let module = lower_o0(&program, target.name(), target.data_layout()) + let module = lower_o0(&program, &target.id, target.storage.data) .unwrap_or_else(|e| fail(format!("lower_o0 failed: {e}"))); if do_verify { ir::verify_module(&module) @@ -170,6 +181,23 @@ pub fn run(args: Vec) { } else { parse_module(&source).unwrap_or_else(|e| fail(format!("{input}:{e}"))) }; + if command == "fold" { + ir::pass::run_pass( + &mut module, + &mut ir::pass::IntegerConstantFold::default(), + &mut ir::pass::AnalysisState::default(), + ) + .unwrap_or_else(|error| fail(error)); + } + if command == "emit" { + let target = target.map(String::as_str).unwrap_or("whale-bytecode-v1"); + if target != module.target { + fail(format!("input target {:?} differs from --target {target:?}", module.target)); + } + let output = output.unwrap_or_else(|| fail("emit requires -o ")); + super::bytecode::emit(&module, input, output, max_output); + return; + } if command == "verify" { stdout(format!("Verified IR {input}\n")); return; @@ -220,11 +248,13 @@ fn print_help() { "Usage: whale ir [options]", "\n", " verify Read and verify format 3/4/5/6/7/8 typed IR", "\n", " print [-o ] [--max-output ]", "\n", + " fold [-o ] [--max-output ]", "\n", + " emit --target whale-bytecode-v1 -o [--max-output ]", "\n", " run --function @fN [--arg ...] [--max-steps ] [--max-memory ]", "\n", " Execute integer/bool/float values, control flow and tracked stack memory; default 1000000 steps, 64 MiB storage.", "\n", " lower [-o ] [--max-output ] (requires socket-cli)", "\n", " Canonical output streams within a 64 MiB default limit; failed file writes preserve existing output.", "\n", - " lower options: --target x86_64-whale-linux, --no-verify", "\n", + " lower options: --target x86_64-whale-linux|whale-bytecode-v1, --no-verify", "\n", " AST envelope: reads format_version 2/3/4/5, writes 5; semantics_version: 1, features: [], program: AST", "\n", " Typed IR reads format_version 3/4/5/6/7/8, writes 8; semantics_version 1. Legacy undef is invalid.", "\n", " Integer literals are decimal; floats use exact-width 0x storage bits.", "\n", @@ -271,7 +301,7 @@ fn execute( } } -fn scalar_argument(ty: &ir::Type, literal: &str) -> Option { +pub(super) fn scalar_argument(ty: &ir::Type, literal: &str) -> Option { let decimal = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()); match ty { ir::Type::F16 => ir::FloatBits::parse(16, literal).ok().map(ir::ConstValue::F), diff --git a/src/commands/mod.rs b/src/commands/mod.rs index d663360..9dd0025 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -4,8 +4,11 @@ mod debug; mod input; +#[cfg(feature = "native-linker")] pub mod linker; +pub mod bytecode; + pub mod object; mod output; diff --git a/src/commands/output.rs b/src/commands/output.rs index 5b79457..cacae43 100644 --- a/src/commands/output.rs +++ b/src/commands/output.rs @@ -50,6 +50,7 @@ pub(super) fn publish_with( /// Publish an artifact while protecting every input, including hard/symlink aliases. /// Executables receive an explicit 0755 mode on Unix; no input or previous mode /// can propagate setuid/setgid bits into a newly linked artifact. +#[cfg(feature = "native-linker")] pub(super) fn publish_many( inputs: &[&Path], output: &Path, diff --git a/src/lib.rs b/src/lib.rs index e89438d..229aff8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3,3 +3,5 @@ pub mod cli; pub mod commands; pub mod builtins; + +mod backends; diff --git a/target-spec/src/extension.rs b/target-spec/src/extension.rs index 769bada..c1f18d1 100644 --- a/target-spec/src/extension.rs +++ b/target-spec/src/extension.rs @@ -58,7 +58,30 @@ pub struct TargetSpec { pub memory: MemoryModel, } +/// The built-in versioned bytecode target has tracked 64-bit little-endian storage. +/// It does not describe a native machine or promise a native object encoder. +pub fn whale_bytecode_v1() -> TargetSpec { + TargetSpec { + id: "whale-bytecode-v1".into(), + output: OutputKind::Bytecode("whale-bytecode-v1".into()), + storage: StorageLayout { + data: DataLayout { ptr_bits: 64, endian: crate::Endian::Little }, + scalar_align: [1, 2, 4, 8, 16], + pointer_align: 8, + large_array: Some((16, 16)), + }, + memory: MemoryModel::Tracked, + } +} + impl TargetSpec { + pub fn lookup_builtin(id: &str) -> Result { + if id == "whale-bytecode-v1" { + return Ok(whale_bytecode_v1()); + } + Target::lookup(id).map(Target::specification) + } + pub fn validate(&self) -> Result<(), String> { if self.id.is_empty() || self.id.chars().any(|c| c.is_control() || c.is_whitespace()) { return Err( diff --git a/target-spec/src/lib.rs b/target-spec/src/lib.rs index 635e5bd..ceb3814 100644 --- a/target-spec/src/lib.rs +++ b/target-spec/src/lib.rs @@ -198,4 +198,4 @@ impl std::error::Error for TargetError {} pub mod extension; -pub use extension::{MemoryModel, OutputKind, StorageLayout, TargetSpec}; +pub use extension::{whale_bytecode_v1, MemoryModel, OutputKind, StorageLayout, TargetSpec}; diff --git a/tests/bytecode_cli.rs b/tests/bytecode_cli.rs new file mode 100644 index 0000000..b025dfb --- /dev/null +++ b/tests/bytecode_cli.rs @@ -0,0 +1,142 @@ +use std::{fs, process::Command}; + +fn whale() -> Command { + Command::new(env!("CARGO_BIN_EXE_whale")) +} + +fn source(target: &str) -> String { + format!( + concat!( + "module {{\n format_version 8\n semantics_version 1\n target \"{}\"\n", + " datalayout {{ ptr=64, endian=little }}\n", + " declare @f0 \"answer\": whale (i32) -> i32, linkage internal\n", + " fn @f0 \"answer\"(%v7 \"argument\": i32) -> i32, entry %b9 {{\n %b9 \"entry\":\n", + " %v11: i32 = const i32 2\n %v30: i32 = add i32 %v7, %v11\n", + " ret i32 %v30\n }}\n}}\n" + ), + target + ) +} + +#[test] +fn bytecode_argument_errors_precede_file_access() { + for arguments in [ + vec!["bytecode", "run", "missing.wbc"], + vec!["bytecode", "run", "missing.wbc", "--function", "@f-1"], + vec!["bytecode", "verify", "missing.wbc", "--max-work", "-1"], + vec!["bytecode", "verify", "missing.wbc", "--max-work", "1", "--max-work", "2"], + vec!["bytecode", "verify", "missing.wbc", "--arg", "1"], + vec!["ir", "emit", "missing.wir", "--target", "missing", "-o", "missing.wbc"], + ] { + let result = whale().args(arguments).output().unwrap(); + assert!(!result.status.success()); + assert!(!String::from_utf8_lossy(&result.stderr).contains("failed to read")); + } +} + +#[test] +fn bytecode_compile_verify_run_and_limits_preserve_files() { + if !ir::bytecode::available() { + return; + } + let directory = tempfile::tempdir().unwrap(); + let input = directory.path().join("answer.wir"); + let output = directory.path().join("answer.wbc"); + fs::write(&input, source("whale-bytecode-v1")).unwrap(); + let emit = || { + whale() + .args(["ir", "emit"]) + .arg(&input) + .args(["--target", "whale-bytecode-v1", "-o"]) + .arg(&output) + .output() + .unwrap() + }; + let result = emit(); + assert!(result.status.success(), "{}", String::from_utf8_lossy(&result.stderr)); + let bytes = fs::read(&output).unwrap(); + assert!(emit().status.success()); + assert_eq!(fs::read(&output).unwrap(), bytes); + let verified = whale().args(["bytecode", "verify"]).arg(&output).output().unwrap(); + assert!(verified.status.success(), "{verified:?}"); + let run = whale() + .args(["bytecode", "run"]) + .arg(&output) + .args(["--function", "@f0", "--arg", "40"]) + .output() + .unwrap(); + assert!(run.status.success(), "{run:?}"); + assert_eq!(run.stdout, b"i32 42\n"); + let constant_input = directory.path().join("fold.wir"); + let folded = directory.path().join("folded.wir"); + fs::write( + &constant_input, + source("whale-bytecode-v1") + .replace("whale (i32)", "whale ()") + .replace("%v7 \"argument\": i32", "") + .replace("%v11: i32 = const", "%v7: i32 = const i32 40\n %v11: i32 = const"), + ) + .unwrap(); + let fold = + whale().args(["ir", "fold"]).arg(&constant_input).arg("-o").arg(&folded).output().unwrap(); + assert!(fold.status.success(), "{fold:?}"); + let folded_source = fs::read_to_string(&folded).unwrap(); + assert!(folded_source.contains("const i32 42")); + assert!(!folded_source.contains("add i32")); + let external = fs::read_to_string(&constant_input).unwrap() + .replace("declare @f0", "declare @f1 \"foreign\": sysv64 () -> i32, linkage external, link_name \"foreign\"\n declare @f0") + .replace("%v7: i32 = const i32 40", "%v7: i32 = call sysv64 i32 @f1()"); + fs::write(&constant_input, external).unwrap(); + let rejected = + whale().args(["ir", "emit"]).arg(&constant_input).arg("-o").arg(&output).output().unwrap(); + assert!(!rejected.status.success()); + assert_eq!(fs::read(&output).unwrap(), bytes); + for option in ["--max-steps", "--max-work", "--max-workspace", "--max-decoded", "--max-input"] { + let run = whale() + .args(["bytecode", "run"]) + .arg(&output) + .args(["--function", "@f0", "--arg", "40", option, "0"]) + .output() + .unwrap(); + assert!(!run.status.success(), "{option}"); + assert_eq!(fs::read(&output).unwrap(), bytes); + } + let limited = whale() + .args(["ir", "emit"]) + .arg(&input) + .arg("-o") + .arg(&output) + .args(["--max-output", "1"]) + .output() + .unwrap(); + assert!(!limited.status.success()); + assert_eq!(fs::read(&output).unwrap(), bytes); + let original = fs::read(&input).unwrap(); + let same = whale().args(["ir", "emit"]).arg(&input).arg("-o").arg(&input).output().unwrap(); + assert!(!same.status.success()); + assert_eq!(fs::read(&input).unwrap(), original); + let mut damaged = bytes.clone(); + damaged[0] ^= 1; + fs::write(&output, &damaged).unwrap(); + let run = whale() + .args(["bytecode", "run"]) + .arg(&output) + .args(["--function", "@f0", "--arg", "40"]) + .output() + .unwrap(); + assert!(!run.status.success()); + assert_eq!(fs::read(&output).unwrap(), damaged); +} + +#[test] +fn emission_never_relabels_a_native_module() { + let directory = tempfile::tempdir().unwrap(); + let input = directory.path().join("native.wir"); + let output = directory.path().join("keep.wbc"); + fs::write(&input, source("x86_64-whale-linux")).unwrap(); + fs::write(&output, b"previous").unwrap(); + let result = whale().args(["ir", "emit"]).arg(&input).arg("-o").arg(&output).output().unwrap(); + assert!(!result.status.success()); + assert!(String::from_utf8_lossy(&result.stderr).contains("differs from --target")); + assert_eq!(fs::read(output).unwrap(), b"previous"); +} diff --git a/tests/command_status.rs b/tests/command_status.rs index 91021ef..22ad2cc 100644 --- a/tests/command_status.rs +++ b/tests/command_status.rs @@ -5,7 +5,8 @@ fn invalid_link_arguments_report_failure() { let output = Command::new(env!("CARGO_BIN_EXE_whale")).args(["link", "missing.o"]).output().unwrap(); assert!(!output.status.success()); - assert!(String::from_utf8_lossy(&output.stderr).contains("missing output")); + let expected = if cfg!(feature = "native-linker") { "missing output" } else { "not included" }; + assert!(String::from_utf8_lossy(&output.stderr).contains(expected)); } #[test] diff --git a/tests/module_selection.rs b/tests/module_selection.rs index 94e7430..de54c34 100644 --- a/tests/module_selection.rs +++ b/tests/module_selection.rs @@ -18,4 +18,28 @@ fn registry_contains_exactly_the_selected_assemblers() { expected.sort_unstable(); assert_eq!(registry.assembler_ids().collect::>(), expected); assert!(registry.target("x86_64-whale-linux").is_some()); + let bytecode = registry.target("whale-bytecode-v1").expect("built-in bytecode target"); + assert_eq!(bytecode.memory, target_spec::MemoryModel::Tracked); + assert!(matches!(bytecode.output, target_spec::OutputKind::Bytecode(_))); + assert!(registry.backend("whale-bytecode-v1").is_some()); +} + +#[test] +fn help_reports_selected_components_and_disabled_linking() { + let help = + std::process::Command::new(env!("CARGO_BIN_EXE_whale")).arg("--help").output().unwrap(); + assert!(help.status.success()); + let text = String::from_utf8(help.stdout).unwrap(); + let expected = whale::builtins::registry().assembler_ids().collect::>().join(", "); + assert!(text.contains(&format!("Selected assemblers: {expected}"))); + assert_eq!(text.contains("whale link "), cfg!(feature = "native-linker")); + assert!(text.contains("bytecode verify|run")); + if !cfg!(feature = "native-linker") { + let result = std::process::Command::new(env!("CARGO_BIN_EXE_whale")) + .args(["link", "missing.o", "-o", "keep"]) + .output() + .unwrap(); + assert_eq!(result.status.code(), Some(2)); + assert!(String::from_utf8_lossy(&result.stderr).contains("not included")); + } } diff --git a/tests/multi_isa.rs b/tests/multi_isa.rs index 75b31e2..626cbe9 100644 --- a/tests/multi_isa.rs +++ b/tests/multi_isa.rs @@ -189,9 +189,13 @@ fn elf_identity_symbol_relocations_and_sparse_bss_are_preserved() { .unwrap(); assert_eq!(ext[4] >> 4, 1); assert_eq!(u16_at(ext, 6), 0); - let mut linker = linker::Linker::new(linker::core::linker::OutputFormat::ELF64Executable); - linker.add_object(object); - assert!(linker.link().unwrap_err().contains("unsupported object target")); + #[cfg(feature = "native-linker")] + { + let mut linker = + linker::Linker::new(linker::core::linker::OutputFormat::ELF64Executable); + linker.add_object(object); + assert!(linker.link().unwrap_err().contains("unsupported object target")); + } } } diff --git a/tests/static_link_cli.rs b/tests/static_link_cli.rs index 0fd7f89..fdec507 100644 --- a/tests/static_link_cli.rs +++ b/tests/static_link_cli.rs @@ -1,4 +1,4 @@ -#![cfg(feature = "asm-amd64")] +#![cfg(all(feature = "asm-amd64", feature = "native-linker"))] use std::{fs, path::Path, process::Command}; diff --git a/tools/build_wave_ir.py b/tools/build_wave_ir.py index d55bf7f..e2cf01c 100644 --- a/tools/build_wave_ir.py +++ b/tools/build_wave_ir.py @@ -56,6 +56,15 @@ 'runtime_prepare.wave', 'runtime_execute.wave', 'runtime_driver.wave', + 'bytecode_model.wave', + 'bytecode_inventory.wave', + 'bytecode_loader.wave', + 'bytecode_verify_types.wave', + 'bytecode_verify_instructions.wave', + 'bytecode_verify_flow.wave', + 'bytecode_verify.wave', + 'bytecode_writer.wave', + 'bytecode_runtime.wave', 'entry.wave', ) ABI_SOURCES = ( @@ -67,6 +76,7 @@ 'ir/src/fold_integer_wave.rs', 'ir/src/constant_wave.rs', 'ir/src/interpreter/runtime_wave.rs', + 'ir/src/bytecode.rs', 'ir/src/verifier/wave_constants.rs', 'ir/src/source_wave.rs', 'ir/src/interpreter/memory_wave.rs', diff --git a/tools/check_product_graph.py b/tools/check_product_graph.py index c66a387..b14e396 100644 --- a/tools/check_product_graph.py +++ b/tools/check_product_graph.py @@ -23,7 +23,7 @@ def package_names(tree): return names -def check_product(root, selected): +def check_product(root, selected, native_linker=False): unknown = set(selected) - ISAS if unknown: raise ValueError(f"unknown ISA selection: {sorted(unknown)}") @@ -32,12 +32,18 @@ def check_product(root, selected): "--locked", "--offline", "-e", "normal,build", "--prefix", "none", "--format", "{p}", ] - if selected: - command += ["--features", ",".join(f"asm-{isa}" for isa in sorted(selected))] + features = [f"asm-{isa}" for isa in sorted(selected)] + if native_linker: + features.append("native-linker") + if features: + command += ["--features", ",".join(features)] result = subprocess.run(command, cwd=root, capture_output=True, text=True, check=False) if result.returncode: raise ValueError(f"cargo tree failed ({result.returncode}): {result.stderr.strip()}") - actual = package_names(result.stdout) & ISAS + packages = package_names(result.stdout) + if ("linker" in packages) != native_linker: + raise ValueError("native linker selection differs from product dependencies") + actual = packages & ISAS if actual != set(selected): raise ValueError(f"selected ISA crates {sorted(selected)}, product contains {sorted(actual)}") return actual @@ -47,10 +53,11 @@ def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--root", type=Path, default=ROOT) parser.add_argument("--isa", choices=sorted(ISAS), action="append", default=[]) + parser.add_argument("--native-linker", action="store_true") args = parser.parse_args() try: selected = set(args.isa) - actual = check_product(args.root, selected) + actual = check_product(args.root, selected, args.native_linker) print(f"product ISA crates: {', '.join(sorted(actual)) or '(none)'}") except ValueError as error: parser.exit(1, f"product graph: {error}\n") diff --git a/tools/check_wave_bytecode.py b/tools/check_wave_bytecode.py new file mode 100644 index 0000000..0a9e810 --- /dev/null +++ b/tools/check_wave_bytecode.py @@ -0,0 +1,286 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Independent little-endian fixtures and bounded hostile-bytecode admission.""" +import argparse +import ctypes as C +import json +from pathlib import Path +import random +import struct + +U = C.c_uint64 +MISSING = (1 << 64) - 1 +FIELDS = ('types edges functions blocks instructions operands value_types globals ' + 'sites texts text_bytes files originals mappings value_ids constant_globals').split() +STRIDES = [40, 8, 88, 32, 136, 8, 8, 64, 32, 16, 1, 16, 56, 40, 8, 8] +NATIVE_STRIDES = STRIDES.copy() +NATIVE_STRIDES[4] = 168 +NATIVE_STRIDES[7] = 216 +HEADER = 576 + + +class Program(C.Structure): + _fields_ = [(field + suffix, kind) for field in FIELDS + for suffix, kind in (('_data', C.c_void_p), ('_count', U))] + + +class Limits(C.Structure): + _fields_ = [(field, U) for field in + 'max_input_bytes max_decoded_bytes max_records max_work max_type_depth max_workspace_bytes'.split()] + + def __init__(self, **changes): + defaults = dict(max_input_bytes=64 << 20, max_decoded_bytes=64 << 20, + max_records=1_000_000, max_work=64 << 20, + max_type_depth=128, max_workspace_bytes=128 << 20) + defaults.update(changes) + super().__init__(**defaults) + + +class Result(C.Structure): + _fields_ = [(field, U) for field in + 'status code table index work decoded_bytes scratch_words'.split()] + [('counts', U * 16)] + + +def words(*values): + return struct.pack('<' + 'Q' * len(values), *[value & MISSING for value in values]) + + +def instruction(op, **fields): + names = 'op sub ty other dst a b c align first count low high literal signature flags global'.split() + values = dict.fromkeys(names, 0) + values.update(op=op, dst=MISSING) + values.update(fields) + return words(*(values[name] for name in names)) + + +def image(tables): + """Construct file bytes from explicit portable records, without native writer.""" + assert len(tables) == 16 + directory, payload = bytearray(), bytearray() + for kind, (data, stride) in enumerate(zip(tables, STRIDES), 1): + assert len(data) % stride == 0 + directory += words(kind, HEADER + len(payload), len(data) // stride, stride) + payload += data + return b'WHALEBC\0' + words(1, 1, 1, HEADER + len(payload), 16, 0, HEADER) + directory + payload + + +def simple_tables(value=42): + tables = [b''] * 16 + tables[0] = words(0, 0, 0, 0, 0) + words(7, 0, 0, 0, 0) + words(1, 0, 0, 0, 0) + words(18, 0, 0, 1, 0) + tables[1] = words(1) + tables[2] = words(7, 3, 0, 0, 1, 0, 0, 1, 0, 1, 0) + tables[3] = words(11, 0, 0, 2) + tables[4] = instruction(4, ty=1, dst=0, low=value, literal=1) + instruction(34, ty=1, a=0) + tables[6] = words(1) + tables[8] = words(7, 11, 0, 99) + words(7, 11, 1, MISSING) + tables[14] = words(99) + return tables + + +def diamond_tables(): + tables = simple_tables() + tables[0] = tables[0][:-40] + words(18, 0, 0, 2, 0) + tables[1] = words(1, 2) + tables[2] = words(7, 3, 0, 0, 4, 0, 1, 4, 0, 1, 0) + tables[3] = words(10, 0, 0, 1) + words(11, 0, 1, 2) + words(12, 0, 3, 2) + words(13, 0, 5, 2) + tables[4] = (instruction(32, a=0, b=1, c=2) + + instruction(4, ty=1, dst=1, low=11, literal=1) + instruction(31, a=3) + + instruction(4, ty=1, dst=2, low=22, literal=1) + instruction(31, a=3) + + instruction(15, ty=1, dst=3, first=1, count=2) + instruction(34, ty=1, a=3)) + tables[5] = words(0, 1, 1, 2, 2) + tables[6] = words(2, 1, 1, 1) + tables[8] = (words(7, 10, 0, MISSING) + words(7, 11, 0, 107) + words(7, 11, 1, MISSING) + + words(7, 12, 0, 109) + words(7, 12, 1, MISSING) + + words(7, 13, 0, 300) + words(7, 13, 1, MISSING)) + tables[14] = words(100, 107, 109, 300) + return tables + + +def scale_tables(count): + tables = simple_tables() + tables[2] = words(7, 3, 0, 0, 1, 0, 0, count, 0, 1, 0) + tables[3] = words(11, 0, 0, count + 1) + tables[4] = b''.join(instruction(4, ty=1, dst=i, low=i, literal=1) + for i in range(count)) + instruction(34, ty=1, a=count - 1) + tables[6] = words(*([1] * count)) + tables[8] = b''.join(words(7, 11, i, 99 + i * 3) for i in range(count)) + words(7, 11, count, MISSING) + tables[14] = words(*(99 + i * 3 for i in range(count))) + return tables + + +def parse_directory(data): + """Independent structural oracle; does not inspect any native output.""" + assert len(data) >= HEADER and data[:8] == b'WHALEBC\0' + assert struct.unpack_from('<7Q', data, 8) == (1, 1, 1, len(data), 16, 0, HEADER) + tables, offset = [], HEADER + for kind, stride in enumerate(STRIDES, 1): + actual, start, count, width = struct.unpack_from('<4Q', data, 64 + (kind - 1) * 32) + assert (actual, start, width) == (kind, offset, stride) + end = start + count * stride + assert end <= len(data) + tables.append(data[start:end]) + offset = end + assert offset == len(data) + return tables + + +def replace_word(data, table, record, field, value): + result = bytearray(data) + offset = struct.unpack_from(' 0, vars_result(result) + scratch = (U64 * result.scratch_words)() + status = self.verify( + c.byref(packet), scratch, len(scratch), c.byref(limits), c.byref(result) + ) + assert status == result.status == 0, vars_result(result) + return scratch + + def publish(self, packet, scratch, limits, capacity, *, query=False): + output = None if query else (c.c_uint8 * capacity)(*([0xA5] * capacity)) + required = U64(MISSING) + result = Result() + status = self.write( + c.byref(packet), + output, + capacity, + c.byref(required), + scratch, + len(scratch), + c.byref(limits), + c.byref(result), + ) + assert status == result.status and result.work <= limits.max_work, vars_result(result) + return status, required.value, bytes(output) if output is not None else None, result + + +def vars_result(result): + return { + name: getattr(result, name) + for name in ["status", "code", "table", "index", "work", "decoded_bytes", "scratch_words"] + } + + +def golden_cases(native, output_dir): + cases = [ + ("signed64", fixture()), + ("signed128-min", fixture(8, 1, 0, 1 << 63)), + ("unsigned128", fixture(13, 2, 0xFEDCBA9876543210, 0x0123456789ABCDEF)), + ("bool", fixture(1, 3, 1)), + ("f16-nan", fixture(14, 4, 0x7D55)), + ("f32-negative-zero", fixture(15, 5, 0x80000000)), + ("f64-nan", fixture(16, 6, 0xFFF8000000001234)), + ("sparse-parameter", fixture(parameter=True)), + ("initialized-global", global_fixture(True)), + ("uninitialized-aggregate-global", global_fixture(False)), + ("unused-import", import_fixture()), + ] + hashes = {} + for name, tables in cases: + packet, keep = native.packet(tables) + limits = Limits() + scratch = native.admitted(packet, limits) + expected = expected_image(tables) + status, required, _, query = native.publish(packet, scratch, limits, 0, query=True) + assert status == 0 and required == len(expected), (name, vars_result(query)) + status, required, actual, result = native.publish(packet, scratch, limits, required) + assert status == 0 and required == len(expected), (name, vars_result(result)) + assert actual == expected, name + assert keep # Keep all borrowed native arrays alive through both calls. + hashes[name] = hashlib.sha256(expected).hexdigest() + if output_dir: + output_dir.mkdir(parents=True, exist_ok=True) + (output_dir / (name + ".wbc")).write_bytes(actual) + # Deliberately unaligned UTF-8 table: later source records must remain LE. + text_end = struct.unpack_from(" Date: Sat, 31 Oct 2026 14:58:26 +0900 Subject: [PATCH 8/8] build: make Wave products explicit, reproducible and independently checked Require selected Wave source modules by default, isolate explicit Rust references, and check the identities of linked modules. Bound retained and temporary bytecode metadata before allocation and reclaim rejected argument transport completely. Embed portable source/compiler/module provenance, validate standalone packages, and remap build paths. Cover native modules with bounded replayable local conformance and provide real CLI benchmarks and concise contribution guidance. Update workflow definitions for native and explicitly labelled reference paths. References #368, #369, #370, #371. Signed-off-by: LunaStev --- .github/workflows/asmobj.yml | 100 ++- .github/workflows/coverage.yml | 13 +- .github/workflows/fuzz.yml | 28 +- .github/workflows/maintenance.yml | 11 + .github/workflows/quality.yml | 48 +- .github/workflows/release.yml | 45 +- .github/workflows/rust.yml | 43 +- .gitignore | 2 + BUILDING.md | 97 +-- CONTRIBUTING.md | 18 +- Cargo.toml | 4 + README.md | 81 ++- assembler/Cargo.toml | 4 + assembler/aarch64/Cargo.toml | 4 + assembler/aarch64/entry.wave | 5 + assembler/aarch64/src/lib.rs | 39 +- assembler/aarch64/src/wave.rs | 2 +- assembler/amd64/Cargo.toml | 4 + assembler/amd64/build.rs | 1 + assembler/amd64/encoder.wave | 5 + assembler/amd64/meson.build | 1 + assembler/amd64/src/lib.rs | 31 + assembler/asmobj/entry.wave | 5 + assembler/asmobj/meson.build | 2 +- assembler/build.rs | 1 + assembler/build_support.rs | 7 +- assembler/lexer.wave | 5 + assembler/loongarch64/Cargo.toml | 4 + assembler/loongarch64/entry.wave | 5 + assembler/loongarch64/src/lib.rs | 41 +- assembler/meson.build | 1 + assembler/riscv64/Cargo.toml | 4 + assembler/riscv64/entry.wave | 5 + assembler/riscv64/src/encoder.rs | 2 +- assembler/riscv64/src/lib.rs | 39 +- assembler/riscv64/src/parser.rs | 2 +- assembler/riscv64/src/wave.rs | 16 +- assembler/src/fixed.rs | 32 +- assembler/src/fixed_wave.rs | 2 + assembler/src/lib.rs | 31 + build.rs | 117 ++++ examples/fuzz_boundaries.rs | 76 ++- fuzz/README.md | 25 +- fuzz/corpus/bytecode/empty.wbc | Bin 0 -> 576 bytes .../bytecode/invalid_count_overflow.wbc | Bin 0 -> 1216 bytes .../bytecode/invalid_phi_duplicate_edge.wbc | Bin 0 -> 2248 bytes fuzz/corpus/bytecode/phi_diamond.wbc | Bin 0 -> 2248 bytes fuzz/corpus/bytecode/return42.wbc | Bin 0 -> 1216 bytes fuzz/support.rs | 30 +- ir/Cargo.toml | 1 + ir/build.rs | 10 +- ir/bytecode_loader.wave | 47 +- ir/bytecode_model.wave | 3 +- ir/bytecode_verify.wave | 7 +- ir/bytecode_verify_types.wave | 131 +++- ir/entry.wave | 5 + ir/examples/bytecode_workspace_probe.rs | 127 ++++ ir/meson.build | 3 + ir/src/bytecode.rs | 73 ++- ir/src/function.rs | 82 +-- ir/src/global_storage.rs | 111 ++-- ir/src/interpreter/runtime_wave.rs | 53 +- ir/src/lib.rs | 31 + ir/src/verifier/wave_semantics.rs | 55 +- ir/tests/public_semantic_boundaries.rs | 58 ++ meson.build | 15 + meson.options | 2 + src/build_info.rs | 57 ++ src/cli.rs | 8 +- src/lib.rs | 2 + tests/build_info.rs | 44 ++ tests/cli_arguments.rs | 2 +- tests/cli_io.rs | 32 +- tests/fuzz_corpus.rs | 3 + toolchain/Cargo.toml | 4 + toolchain/src/assembly_object.rs | 31 + tools/BENCHMARKS.md | 48 +- tools/RELEASING.md | 92 ++- tools/benchmark_cli.py | 610 ++++++++++++++++++ tools/build_wave_assembler.py | 2 + tools/build_wave_ir.py | 3 + tools/check_wave_bytecode.py | 87 ++- tools/check_wave_bytecode_writer.py | 208 +++++- tools/check_wave_module_selection.py | 83 +++ tools/fuzz_checkpoint.py | 65 ++ tools/fuzz_smoke.py | 4 +- tools/meson_cargo.py | 70 +- tools/release.py | 152 ++++- tools/test_benchmark_cli.py | 206 ++++++ tools/test_build_wave_assembler.py | 15 +- tools/test_build_wave_ir.py | 10 +- tools/test_bytecode_writer_replay.py | 75 +++ tools/test_fuzz_checkpoint.py | 71 ++ tools/test_meson_build.py | 39 +- tools/test_release.py | 58 +- 95 files changed, 3520 insertions(+), 413 deletions(-) create mode 100644 build.rs create mode 100644 fuzz/corpus/bytecode/empty.wbc create mode 100644 fuzz/corpus/bytecode/invalid_count_overflow.wbc create mode 100644 fuzz/corpus/bytecode/invalid_phi_duplicate_edge.wbc create mode 100644 fuzz/corpus/bytecode/phi_diamond.wbc create mode 100644 fuzz/corpus/bytecode/return42.wbc create mode 100644 ir/examples/bytecode_workspace_probe.rs create mode 100644 ir/tests/public_semantic_boundaries.rs create mode 100644 src/build_info.rs create mode 100644 tests/build_info.rs create mode 100755 tools/benchmark_cli.py create mode 100644 tools/check_wave_module_selection.py create mode 100644 tools/fuzz_checkpoint.py create mode 100644 tools/test_benchmark_cli.py create mode 100644 tools/test_bytecode_writer_replay.py create mode 100644 tools/test_fuzz_checkpoint.py diff --git a/.github/workflows/asmobj.yml b/.github/workflows/asmobj.yml index 19698f9..a03365e 100644 --- a/.github/workflows/asmobj.yml +++ b/.github/workflows/asmobj.yml @@ -1,4 +1,4 @@ -name: Build complete Wave asmobj module +name: Build complete Wave source modules on: workflow_call: @@ -12,17 +12,21 @@ on: artifact_name: description: Exact archive artifact published by this prerequisite job value: ${{ jobs.archives.outputs.artifact_name }} + wave_artifact_name: + description: Linux AMD64 IR and assembler modules from the same source + value: ${{ jobs.archives.outputs.wave_artifact_name }} permissions: contents: read jobs: archives: - name: Wave asmobj archives and Linux conformance + name: Wave modules / native Linux AMD64 and cross-object conformance runs-on: ubuntu-24.04 timeout-minutes: 40 outputs: artifact_name: asmobj-${{ github.run_id }}-${{ github.run_attempt }} + wave_artifact_name: wave-modules-${{ github.run_id }}-${{ github.run_attempt }} env: CARGO_INCREMENTAL: '0' CARGO_BUILD_JOBS: '2' @@ -106,6 +110,20 @@ jobs: "tools/check_wave_ir_$component.py" \ --library "$RUNNER_TEMP/wave-ir-o$optimization.so" --cases "$ir_cases" done + for component in admission writer; do + checker=tools/check_wave_bytecode.py + bytecode_cases=100000 + extra_arguments=(--scale 32768) + if [ "$component" = writer ]; then + checker=tools/check_wave_bytecode_writer.py + bytecode_cases=10000 + extra_arguments=() + fi + python3 tools/ci.py run --name "bytecode-$component-o$optimization" --timeout 195 -- \ + timeout 180s python3 tools/fuzz_limits.py --memory-mib 512 -- "$ir_python" \ + "$checker" --library "$RUNNER_TEMP/wave-ir-o$optimization.so" \ + --cases "$bytecode_cases" "${extra_arguments[@]}" --artifacts ".ci-artifacts/bytecode-$component-o$optimization" + done WHALE_WAVE_IR_DIR="$RUNNER_TEMP/wave-ir-o$optimization" \ cargo test -p ir --all-features --locked --offline done @@ -160,6 +178,55 @@ jobs: tools/check_wave_amd64_cli.py --binary target/debug/whale \ --output-dir ".ci-artifacts/amd64-o$optimization" --cases 2000 done + - name: Compare Wave bytecode with the explicit Rust IR reference + run: | + env -u WHALE_WAVE_IR_DIR -u WHALE_WAVE_ASSEMBLER_DIR -u WHALE_WAVE_AMD64_DIR \ + -u WHALE_WAVE_AARCH64_DIR -u WHALE_WAVE_RISCV64_DIR -u WHALE_WAVE_LOONGARCH64_DIR \ + WHALE_ASMOBJ_DIR="$GITHUB_WORKSPACE/.ci-asmobj/x86_64-unknown-linux-gnu" \ + cargo build -p whale --locked --offline --features rust-reference,socket-cli \ + --target-dir "$RUNNER_TEMP/rust-reference-target" + for optimization in 0 2; do + WHALE_ASMOBJ_DIR="$GITHUB_WORKSPACE/.ci-asmobj/x86_64-unknown-linux-gnu" \ + WHALE_WAVE_IR_DIR="$RUNNER_TEMP/wave-ir-o$optimization" \ + WHALE_WAVE_ASSEMBLER_DIR="$RUNNER_TEMP/assembler-common-o$optimization" \ + WHALE_WAVE_AMD64_DIR="$RUNNER_TEMP/assembler-amd64-o$optimization" \ + WHALE_WAVE_AARCH64_DIR="$RUNNER_TEMP/assembler-aarch64-o$optimization" \ + WHALE_WAVE_RISCV64_DIR="$RUNNER_TEMP/assembler-riscv64-o$optimization" \ + WHALE_WAVE_LOONGARCH64_DIR="$RUNNER_TEMP/assembler-loongarch64-o$optimization" \ + cargo build -p whale --locked --offline --features socket-cli + python3 tools/ci.py run --name "bytecode-reference-o$optimization" --timeout 180 -- \ + python3 tools/check_wave_bytecode_cli.py --binary target/debug/whale \ + --reference "$RUNNER_TEMP/rust-reference-target/debug/whale" \ + --artifacts ".ci-artifacts/bytecode-reference-o$optimization" + done + - name: Stage Linux AMD64 Wave modules under one artifact root + run: | + mkdir -p .ci-wave/ir + cp -R "$RUNNER_TEMP/wave-ir-o2/." .ci-wave/ir/ + for module in common amd64 aarch64 riscv64 loongarch64; do + mkdir -p ".ci-wave/$module" + cp -R "$RUNNER_TEMP/assembler-$module-o2/." ".ci-wave/$module/" + done + - name: Prove selected native implementation identities and allocation ceilings + run: | + export WHALE_ASMOBJ_DIR="$GITHUB_WORKSPACE/.ci-asmobj/x86_64-unknown-linux-gnu" + export WHALE_WAVE_IR_DIR="$GITHUB_WORKSPACE/.ci-wave/ir" + export WHALE_WAVE_ASSEMBLER_DIR="$GITHUB_WORKSPACE/.ci-wave/common" + export WHALE_WAVE_AMD64_DIR="$GITHUB_WORKSPACE/.ci-wave/amd64" + export WHALE_WAVE_AARCH64_DIR="$GITHUB_WORKSPACE/.ci-wave/aarch64" + export WHALE_WAVE_RISCV64_DIR="$GITHUB_WORKSPACE/.ci-wave/riscv64" + export WHALE_WAVE_LOONGARCH64_DIR="$GITHUB_WORKSPACE/.ci-wave/loongarch64" + cargo test --workspace --no-default-features --features socket-cli --locked --offline \ + selected_implementation_has_its_own_compiled_identity + cargo test --workspace --all-features --locked --offline \ + selected_implementation_has_its_own_compiled_identity + cargo build -p ir --example bytecode_workspace_probe --all-features --locked --offline + timeout 180s python3 tools/fuzz_limits.py --memory-mib 512 -- \ + target/debug/examples/bytecode_workspace_probe + python3 tools/ci.py run --name wave-selection-guards --timeout 300 -- \ + python3 tools/check_wave_module_selection.py \ + --ir-dir "$WHALE_WAVE_IR_DIR" --assembler-dir "$WHALE_WAVE_ASSEMBLER_DIR" \ + --target-dir "$RUNNER_TEMP/wave-selection-target" - name: Reproduce the pinned typed HIR fixture run: | python3 tools/check_wave_hir_fixture.py --wave-source .asmobj-bootstrap-source \ @@ -180,13 +247,19 @@ jobs: "$RUNNER_TEMP/whale-meson-install/usr/local/bin/whale" --version - name: Verify isolated minimal and single-ISA Meson products run: | - meson setup "$RUNNER_TEMP/whale-minimal" \ + meson setup "$RUNNER_TEMP/whale-minimal" -Dnative-linker=false \ -Dasmobj-dir="$GITHUB_WORKSPACE/.ci-asmobj/x86_64-unknown-linux-gnu" \ + -Dwave-ir-dir="$GITHUB_WORKSPACE/.ci-wave/ir" \ + -Dwave-assembler-dir="$GITHUB_WORKSPACE/.ci-wave/common" \ + -Dwave-aarch64-dir="$GITHUB_WORKSPACE/.ci-wave/aarch64" \ -Dasm-amd64=false -Dasm-aarch64=false -Dasm-riscv64=false -Dasm-loongarch64=false meson compile -C "$RUNNER_TEMP/whale-minimal" meson test -C "$RUNNER_TEMP/whale-minimal" --print-errorlogs meson setup "$RUNNER_TEMP/whale-aarch64-output" \ -Dasmobj-dir="$GITHUB_WORKSPACE/.ci-asmobj/x86_64-unknown-linux-gnu" \ + -Dwave-ir-dir="$GITHUB_WORKSPACE/.ci-wave/ir" \ + -Dwave-assembler-dir="$GITHUB_WORKSPACE/.ci-wave/common" \ + -Dwave-aarch64-dir="$GITHUB_WORKSPACE/.ci-wave/aarch64" \ -Dasm-amd64=false -Dasm-riscv64=false -Dasm-loongarch64=false meson compile -C "$RUNNER_TEMP/whale-aarch64-output" meson test -C "$RUNNER_TEMP/whale-aarch64-output" --print-errorlogs @@ -201,15 +274,32 @@ jobs: EOF meson setup "$RUNNER_TEMP/whale-cross" --cross-file "$RUNNER_TEMP/aarch64-cross.ini" \ -Dcargo-host-target=aarch64-unknown-linux-gnu \ - -Dasmobj-dir="$GITHUB_WORKSPACE/.ci-asmobj/aarch64-unknown-linux-gnu" + -Dasmobj-dir="$GITHUB_WORKSPACE/.ci-asmobj/aarch64-unknown-linux-gnu" -Drust-reference=true meson introspect --tests "$RUNNER_TEMP/whale-cross" | \ python3 -c 'import json,sys; assert {t["name"] for t in json.load(sys.stdin)} == {"build-helper"}' meson setup "$RUNNER_TEMP/whale-cross-runner" --cross-file "$RUNNER_TEMP/aarch64-cross.ini" \ -Dcargo-host-target=aarch64-unknown-linux-gnu \ - -Dasmobj-dir="$GITHUB_WORKSPACE/.ci-asmobj/aarch64-unknown-linux-gnu" \ + -Dasmobj-dir="$GITHUB_WORKSPACE/.ci-asmobj/aarch64-unknown-linux-gnu" -Drust-reference=true \ '-Dhost-runner=["/bin/true"]' meson introspect --tests "$RUNNER_TEMP/whale-cross-runner" | \ python3 -c 'import json,sys; tests={t["name"]:t for t in json.load(sys.stdin)}; assert set(tests)=={"build-helper","cli-smoke"}; assert "--runner-arg=/bin/true" in tests["cli-smoke"]["cmd"]' + - name: Retain native conformance logs, bytecode originals and replay manifests + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: wave-conformance-${{ github.run_id }}-${{ github.run_attempt }} + path: .ci-artifacts/ + include-hidden-files: true + if-no-files-found: warn + retention-days: 14 + - name: Retain selected Linux AMD64 modules and provenance + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: wave-modules-${{ github.run_id }}-${{ github.run_attempt }} + path: .ci-wave/ + include-hidden-files: true + if-no-files-found: error + retention-days: 7 - name: Retain independent AMD64 oracle evidence if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index e1d68eb..30de2b4 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -26,11 +26,17 @@ jobs: workspace: needs: asmobj - name: Workspace coverage + name: Rust adapter coverage with actual Wave modules runs-on: ubuntu-24.04 timeout-minutes: 30 env: WHALE_ASMOBJ_DIR: ${{ github.workspace }}/.ci-asmobj/x86_64-unknown-linux-gnu + WHALE_WAVE_IR_DIR: ${{ github.workspace }}/.ci-wave/ir + WHALE_WAVE_ASSEMBLER_DIR: ${{ github.workspace }}/.ci-wave/common + WHALE_WAVE_AMD64_DIR: ${{ github.workspace }}/.ci-wave/amd64 + WHALE_WAVE_AARCH64_DIR: ${{ github.workspace }}/.ci-wave/aarch64 + WHALE_WAVE_RISCV64_DIR: ${{ github.workspace }}/.ci-wave/riscv64 + WHALE_WAVE_LOONGARCH64_DIR: ${{ github.workspace }}/.ci-wave/loongarch64 steps: - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 with: @@ -40,6 +46,11 @@ jobs: with: name: ${{ needs.asmobj.outputs.artifact_name }} path: .ci-asmobj + - name: Download selected Linux AMD64 Wave modules + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: ${{ needs.asmobj.outputs.wave_artifact_name }} + path: .ci-wave - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: '3.13' diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml index 7a44cf4..878b391 100644 --- a/.github/workflows/fuzz.yml +++ b/.github/workflows/fuzz.yml @@ -17,16 +17,28 @@ concurrency: cancel-in-progress: true jobs: + asmobj: + name: Build validated Linux Wave modules + uses: ./.github/workflows/asmobj.yml + mutation: + needs: asmobj name: ${{ matrix.target }} / bounded mutation runs-on: ubuntu-24.04 timeout-minutes: 15 strategy: fail-fast: false matrix: - target: [assembler, object] + target: [assembler, object, ir, ast, bytecode] env: RUSTUP_TOOLCHAIN: stable + WHALE_ASMOBJ_DIR: ${{ github.workspace }}/.ci-asmobj/x86_64-unknown-linux-gnu + WHALE_WAVE_IR_DIR: ${{ github.workspace }}/.ci-wave/ir + WHALE_WAVE_ASSEMBLER_DIR: ${{ github.workspace }}/.ci-wave/common + WHALE_WAVE_AMD64_DIR: ${{ github.workspace }}/.ci-wave/amd64 + WHALE_WAVE_AARCH64_DIR: ${{ github.workspace }}/.ci-wave/aarch64 + WHALE_WAVE_RISCV64_DIR: ${{ github.workspace }}/.ci-wave/riscv64 + WHALE_WAVE_LOONGARCH64_DIR: ${{ github.workspace }}/.ci-wave/loongarch64 WHALE_FUZZ_ARTIFACT_DIR: .ci-artifacts/fuzz CASES: ${{ github.event_name == 'schedule' && '50000' || '512' }} SEED: '1464353100' @@ -34,19 +46,29 @@ jobs: - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 with: persist-credentials: false + - name: Download complete Wave asmobj module + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: ${{ needs.asmobj.outputs.artifact_name }} + path: .ci-asmobj + - name: Download selected Linux AMD64 Wave modules + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: ${{ needs.asmobj.outputs.wave_artifact_name }} + path: .ci-wave - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: '3.13' - run: rustup toolchain install stable --profile minimal - name: Build real library boundary targets - run: python tools/ci.py run --name fuzz-build --timeout 300 -- cargo build --all-features --locked --example fuzz_boundaries + run: python tools/ci.py run --name fuzz-build --timeout 300 -- cargo build --features socket-cli --locked --example fuzz_boundaries - name: Execute nonempty corpus and bounded mutations run: python tools/ci.py run --name fuzz-${{ matrix.target }} --timeout 330 -- python tools/fuzz_smoke.py --binary target/debug/examples/fuzz_boundaries --target ${{ matrix.target }} --cases "$CASES" --seed "$SEED" --timeout 300 --memory-mib 512 - name: Retain logs, original failures, minimized inputs and replay commands if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: - name: fuzz-${{ matrix.target }}-${{ github.run_id }} + name: fuzz-${{ matrix.target }}-${{ github.run_id }}-${{ github.run_attempt }} path: .ci-artifacts/ include-hidden-files: true if-no-files-found: error diff --git a/.github/workflows/maintenance.yml b/.github/workflows/maintenance.yml index 5566390..6baa922 100644 --- a/.github/workflows/maintenance.yml +++ b/.github/workflows/maintenance.yml @@ -58,6 +58,12 @@ jobs: timeout-minutes: 25 env: WHALE_ASMOBJ_DIR: ${{ github.workspace }}/.ci-asmobj/x86_64-unknown-linux-gnu + WHALE_WAVE_IR_DIR: ${{ github.workspace }}/.ci-wave/ir + WHALE_WAVE_ASSEMBLER_DIR: ${{ github.workspace }}/.ci-wave/common + WHALE_WAVE_AMD64_DIR: ${{ github.workspace }}/.ci-wave/amd64 + WHALE_WAVE_AARCH64_DIR: ${{ github.workspace }}/.ci-wave/aarch64 + WHALE_WAVE_RISCV64_DIR: ${{ github.workspace }}/.ci-wave/riscv64 + WHALE_WAVE_LOONGARCH64_DIR: ${{ github.workspace }}/.ci-wave/loongarch64 RUSTUP_TOOLCHAIN: beta steps: - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 @@ -68,6 +74,11 @@ jobs: with: name: ${{ needs.asmobj.outputs.artifact_name }} path: .ci-asmobj + - name: Download selected Linux AMD64 Wave modules + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: ${{ needs.asmobj.outputs.wave_artifact_name }} + path: .ci-wave - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: '3.13' diff --git a/.github/workflows/quality.yml b/.github/workflows/quality.yml index 0024002..0427a70 100644 --- a/.github/workflows/quality.yml +++ b/.github/workflows/quality.yml @@ -59,6 +59,12 @@ jobs: features: [default, all] env: WHALE_ASMOBJ_DIR: ${{ github.workspace }}/.ci-asmobj/x86_64-unknown-linux-gnu + WHALE_WAVE_IR_DIR: ${{ github.workspace }}/.ci-wave/ir + WHALE_WAVE_ASSEMBLER_DIR: ${{ github.workspace }}/.ci-wave/common + WHALE_WAVE_AMD64_DIR: ${{ github.workspace }}/.ci-wave/amd64 + WHALE_WAVE_AARCH64_DIR: ${{ github.workspace }}/.ci-wave/aarch64 + WHALE_WAVE_RISCV64_DIR: ${{ github.workspace }}/.ci-wave/riscv64 + WHALE_WAVE_LOONGARCH64_DIR: ${{ github.workspace }}/.ci-wave/loongarch64 FEATURE_FLAGS: ${{ matrix.features == 'all' && '--all-features' || '' }} steps: - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 @@ -69,6 +75,11 @@ jobs: with: name: ${{ needs.asmobj.outputs.artifact_name }} path: .ci-asmobj + - name: Download selected Linux AMD64 Wave modules + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: ${{ needs.asmobj.outputs.wave_artifact_name }} + path: .ci-wave - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: '3.13' @@ -96,12 +107,20 @@ jobs: matrix: include: - { name: none, flags: '', graph_flags: '' } + - { name: bytecode-only, flags: '--features socket-cli', graph_flags: '' } + - { name: all-isa-no-linker, flags: '--features builtin-assemblers,socket-cli', graph_flags: '--isa amd64 --isa aarch64 --isa riscv64 --isa loongarch64' } - { name: amd64, flags: '--features asm-amd64', graph_flags: '--isa amd64' } - { name: aarch64, flags: '--features asm-aarch64', graph_flags: '--isa aarch64' } - { name: riscv64, flags: '--features asm-riscv64', graph_flags: '--isa riscv64' } - { name: loongarch64, flags: '--features asm-loongarch64', graph_flags: '--isa loongarch64' } env: WHALE_ASMOBJ_DIR: ${{ github.workspace }}/.ci-asmobj/x86_64-unknown-linux-gnu + WHALE_WAVE_IR_DIR: ${{ github.workspace }}/.ci-wave/ir + WHALE_WAVE_ASSEMBLER_DIR: ${{ github.workspace }}/.ci-wave/common + WHALE_WAVE_AMD64_DIR: ${{ github.workspace }}/.ci-wave/amd64 + WHALE_WAVE_AARCH64_DIR: ${{ github.workspace }}/.ci-wave/aarch64 + WHALE_WAVE_RISCV64_DIR: ${{ github.workspace }}/.ci-wave/riscv64 + WHALE_WAVE_LOONGARCH64_DIR: ${{ github.workspace }}/.ci-wave/loongarch64 steps: - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 with: @@ -111,6 +130,11 @@ jobs: with: name: ${{ needs.asmobj.outputs.artifact_name }} path: .ci-asmobj + - name: Download selected Linux AMD64 Wave modules + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: ${{ needs.asmobj.outputs.wave_artifact_name }} + path: .ci-wave - run: rustup toolchain install stable --profile minimal - name: Check selected assembler registration and integration run: python tools/ci.py run --name reduced-isa -- cargo test -p whale --no-default-features ${{ matrix.flags }} --locked @@ -133,6 +157,12 @@ jobs: timeout-minutes: 15 env: WHALE_ASMOBJ_DIR: ${{ github.workspace }}/.ci-asmobj/x86_64-unknown-linux-gnu + WHALE_WAVE_IR_DIR: ${{ github.workspace }}/.ci-wave/ir + WHALE_WAVE_ASSEMBLER_DIR: ${{ github.workspace }}/.ci-wave/common + WHALE_WAVE_AMD64_DIR: ${{ github.workspace }}/.ci-wave/amd64 + WHALE_WAVE_AARCH64_DIR: ${{ github.workspace }}/.ci-wave/aarch64 + WHALE_WAVE_RISCV64_DIR: ${{ github.workspace }}/.ci-wave/riscv64 + WHALE_WAVE_LOONGARCH64_DIR: ${{ github.workspace }}/.ci-wave/loongarch64 RUSTDOCFLAGS: -D warnings steps: - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 @@ -143,6 +173,11 @@ jobs: with: name: ${{ needs.asmobj.outputs.artifact_name }} path: .ci-asmobj + - name: Download selected Linux AMD64 Wave modules + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: ${{ needs.asmobj.outputs.wave_artifact_name }} + path: .ci-wave - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: '3.13' @@ -198,6 +233,12 @@ jobs: timeout-minutes: 20 env: WHALE_ASMOBJ_DIR: ${{ github.workspace }}/.ci-asmobj/x86_64-unknown-linux-gnu + WHALE_WAVE_IR_DIR: ${{ github.workspace }}/.ci-wave/ir + WHALE_WAVE_ASSEMBLER_DIR: ${{ github.workspace }}/.ci-wave/common + WHALE_WAVE_AMD64_DIR: ${{ github.workspace }}/.ci-wave/amd64 + WHALE_WAVE_AARCH64_DIR: ${{ github.workspace }}/.ci-wave/aarch64 + WHALE_WAVE_RISCV64_DIR: ${{ github.workspace }}/.ci-wave/riscv64 + WHALE_WAVE_LOONGARCH64_DIR: ${{ github.workspace }}/.ci-wave/loongarch64 WHALE_FUZZ_ARTIFACT_DIR: .ci-artifacts/fuzz steps: - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 @@ -208,6 +249,11 @@ jobs: with: name: ${{ needs.asmobj.outputs.artifact_name }} path: .ci-asmobj + - name: Download selected Linux AMD64 Wave modules + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: ${{ needs.asmobj.outputs.wave_artifact_name }} + path: .ci-wave - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: '3.13' @@ -217,7 +263,7 @@ jobs: - name: Build real library boundary targets run: python tools/ci.py run --name fuzz-build --timeout 300 -- cargo build --workspace --all-features --examples --locked - name: Bounded assembler, object, IR and AST mutation targets - run: python tools/ci.py run --name boundary-fuzz --timeout 240 -- python tools/fuzz_smoke.py --binary target/debug/examples/fuzz_boundaries --cases 512 --seed 1464353100 --timeout 45 + run: python tools/ci.py run --name boundary-fuzz --timeout 300 -- python tools/fuzz_smoke.py --binary target/debug/examples/fuzz_boundaries --cases 512 --seed 1464353100 --timeout 45 - name: Versioned schema and decoder agreement run: python tools/ci.py run --name schema-agreement --timeout 90 -- python tools/schema_agreement.py --binary target/debug/examples/schema_probe - name: Independent tracked-memory operation model diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d9a1905..d913516 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -44,6 +44,12 @@ jobs: version: ${{ steps.identity.outputs.version }} env: WHALE_ASMOBJ_DIR: ${{ github.workspace }}/.ci-asmobj/x86_64-unknown-linux-gnu + WHALE_WAVE_IR_DIR: ${{ github.workspace }}/.ci-wave/ir + WHALE_WAVE_ASSEMBLER_DIR: ${{ github.workspace }}/.ci-wave/common + WHALE_WAVE_AMD64_DIR: ${{ github.workspace }}/.ci-wave/amd64 + WHALE_WAVE_AARCH64_DIR: ${{ github.workspace }}/.ci-wave/aarch64 + WHALE_WAVE_RISCV64_DIR: ${{ github.workspace }}/.ci-wave/riscv64 + WHALE_WAVE_LOONGARCH64_DIR: ${{ github.workspace }}/.ci-wave/loongarch64 steps: - name: Check input syntax before checkout env: @@ -65,6 +71,11 @@ jobs: - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: '3.13' + - name: Download native Wave source modules + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: ${{ needs.asmobj.outputs.wave_artifact_name }} + path: .ci-wave - name: Validate exact commit, Cargo version and existing tag id: identity env: @@ -95,21 +106,33 @@ jobs: - os: ubuntu-24.04 host: x86_64-unknown-linux-gnu binary: target/release/whale + features: socket-cli + package_flags: --require-wave - os: ubuntu-24.04-arm host: aarch64-unknown-linux-gnu binary: target/release/whale + features: socket-cli,rust-reference + package_flags: '' - os: macos-15-intel host: x86_64-apple-darwin binary: target/release/whale + features: socket-cli,rust-reference + package_flags: '' - os: macos-15 host: aarch64-apple-darwin binary: target/release/whale + features: socket-cli,rust-reference + package_flags: '' - os: windows-2025 host: x86_64-pc-windows-msvc binary: target/release/whale.exe + features: socket-cli,rust-reference + package_flags: '' - os: windows-11-arm host: aarch64-pc-windows-msvc binary: target/release/whale.exe + features: socket-cli,rust-reference + package_flags: '' env: WHALE_ASMOBJ_DIR: ${{ github.workspace }}/.ci-asmobj/${{ matrix.host }} SOURCE: ${{ needs.source.outputs.source }} @@ -125,18 +148,34 @@ jobs: with: name: ${{ needs.asmobj.outputs.artifact_name }} path: .ci-asmobj + - name: Download validated native Wave source modules + if: matrix.host == 'x86_64-unknown-linux-gnu' + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: ${{ needs.asmobj.outputs.wave_artifact_name }} + path: .ci-wave + - name: Select the native Wave product + if: matrix.host == 'x86_64-unknown-linux-gnu' + shell: bash + run: | + echo "WHALE_WAVE_IR_DIR=$GITHUB_WORKSPACE/.ci-wave/ir" >> "$GITHUB_ENV" + echo "WHALE_WAVE_ASSEMBLER_DIR=$GITHUB_WORKSPACE/.ci-wave/common" >> "$GITHUB_ENV" + for module in AMD64 AARCH64 RISCV64 LOONGARCH64; do + directory=$(echo "$module" | tr '[:upper:]' '[:lower:]') + echo "WHALE_WAVE_${module}_DIR=$GITHUB_WORKSPACE/.ci-wave/$directory" >> "$GITHUB_ENV" + done - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: '3.13' - run: rustup toolchain install stable-${{ matrix.host }} --profile minimal - run: python tools/ci.py host --expected ${{ matrix.host }} - - run: python tools/ci.py run --name build -- cargo build --release --workspace --all-features --locked + - run: python tools/ci.py run --name build -- cargo build --release --workspace --features ${{ matrix.features }} --locked - name: Test each native package producer run: python -m unittest discover -s tools -p test_release.py -v - name: Create deterministic native archive - run: python tools/release.py package --binary ${{ matrix.binary }} --directory dist --target ${{ matrix.host }} --version ${{ env.VERSION }} --source ${{ env.SOURCE }} --socket-cli + run: python tools/release.py package --binary ${{ matrix.binary }} --directory dist --target ${{ matrix.host }} --version ${{ env.VERSION }} --source ${{ env.SOURCE }} --socket-cli ${{ matrix.package_flags }} - name: Execute the extracted binary outside the checkout - run: python tools/release.py validate --directory dist --target ${{ matrix.host }} --version ${{ env.VERSION }} --source ${{ env.SOURCE }} + run: python tools/release.py validate --directory dist --target ${{ matrix.host }} --version ${{ env.VERSION }} --source ${{ env.SOURCE }} ${{ matrix.package_flags }} - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: release-${{ github.run_id }}-${{ matrix.host }} diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index caf313f..fdd0955 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -26,7 +26,7 @@ jobs: native: needs: asmobj - name: Native ${{ matrix.platform }} / ${{ matrix.features }} + name: ${{ matrix.platform == 'linux-x64' && 'Wave native' || 'Rust reference' }} / ${{ matrix.platform }} / ${{ matrix.features }} runs-on: ${{ matrix.os }} timeout-minutes: 30 strategy: @@ -62,7 +62,7 @@ jobs: env: WHALE_ASMOBJ_DIR: ${{ github.workspace }}/.ci-asmobj/${{ matrix.host }} RUSTUP_TOOLCHAIN: stable-${{ matrix.host }} - FEATURE_FLAGS: ${{ matrix.features == 'all' && '--all-features' || '' }} + FEATURE_FLAGS: ${{ matrix.features == 'all' && '--all-features' || (matrix.platform != 'linux-x64' && '--features rust-reference' || '') }} steps: - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 with: @@ -72,9 +72,24 @@ jobs: with: name: ${{ needs.asmobj.outputs.artifact_name }} path: .ci-asmobj + - name: Download selected Linux AMD64 Wave modules + if: matrix.platform == 'linux-x64' + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: ${{ needs.asmobj.outputs.wave_artifact_name }} + path: .ci-wave - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: '3.13' + - name: Select the validated Wave native host + if: matrix.platform == 'linux-x64' + shell: bash + run: | + for module in IR ASSEMBLER AMD64 AARCH64 RISCV64 LOONGARCH64; do + directory="${module,,}" + if [ "$module" = ASSEMBLER ]; then directory=common; fi + echo "WHALE_WAVE_${module}_DIR=$GITHUB_WORKSPACE/.ci-wave/$directory" >> "$GITHUB_ENV" + done - name: Install native Rust toolchain run: rustup toolchain install stable-${{ matrix.host }} --profile minimal - name: Verify native compiler identity @@ -114,6 +129,12 @@ jobs: features: [default, all] env: WHALE_ASMOBJ_DIR: ${{ github.workspace }}/.ci-asmobj/x86_64-unknown-linux-gnu + WHALE_WAVE_IR_DIR: ${{ github.workspace }}/.ci-wave/ir + WHALE_WAVE_ASSEMBLER_DIR: ${{ github.workspace }}/.ci-wave/common + WHALE_WAVE_AMD64_DIR: ${{ github.workspace }}/.ci-wave/amd64 + WHALE_WAVE_AARCH64_DIR: ${{ github.workspace }}/.ci-wave/aarch64 + WHALE_WAVE_RISCV64_DIR: ${{ github.workspace }}/.ci-wave/riscv64 + WHALE_WAVE_LOONGARCH64_DIR: ${{ github.workspace }}/.ci-wave/loongarch64 RUSTUP_TOOLCHAIN: '1.86.0' FEATURE_FLAGS: ${{ matrix.features == 'all' && '--all-features' || '' }} steps: @@ -125,6 +146,11 @@ jobs: with: name: ${{ needs.asmobj.outputs.artifact_name }} path: .ci-asmobj + - name: Download selected Linux AMD64 Wave modules + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: ${{ needs.asmobj.outputs.wave_artifact_name }} + path: .ci-wave - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: '3.13' @@ -153,6 +179,12 @@ jobs: timeout-minutes: 25 env: WHALE_ASMOBJ_DIR: ${{ github.workspace }}/.ci-asmobj/x86_64-unknown-linux-gnu + WHALE_WAVE_IR_DIR: ${{ github.workspace }}/.ci-wave/ir + WHALE_WAVE_ASSEMBLER_DIR: ${{ github.workspace }}/.ci-wave/common + WHALE_WAVE_AMD64_DIR: ${{ github.workspace }}/.ci-wave/amd64 + WHALE_WAVE_AARCH64_DIR: ${{ github.workspace }}/.ci-wave/aarch64 + WHALE_WAVE_RISCV64_DIR: ${{ github.workspace }}/.ci-wave/riscv64 + WHALE_WAVE_LOONGARCH64_DIR: ${{ github.workspace }}/.ci-wave/loongarch64 steps: - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 with: @@ -162,6 +194,11 @@ jobs: with: name: ${{ needs.asmobj.outputs.artifact_name }} path: .ci-asmobj + - name: Download selected Linux AMD64 Wave modules + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: ${{ needs.asmobj.outputs.wave_artifact_name }} + path: .ci-wave - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: '3.13' @@ -181,7 +218,7 @@ jobs: riscv: needs: asmobj - name: RISC-V Linux host / QEMU smoke + name: Rust reference RISC-V host / QEMU smoke runs-on: ubuntu-24.04 timeout-minutes: 25 env: diff --git a/.gitignore b/.gitignore index b575e76..52f98a6 100644 --- a/.gitignore +++ b/.gitignore @@ -5,5 +5,7 @@ target/ *.swp .ci-artifacts/ +.ci-asmobj/ +.ci-wave/ __pycache__/ /docs/ diff --git a/BUILDING.md b/BUILDING.md index 56cafce..2f29fd7 100644 --- a/BUILDING.md +++ b/BUILDING.md @@ -1,10 +1,9 @@ # Building Whale with Meson -Meson configures the product, compiles the Wave `asmobj` and IR sources, then -builds Rust components with Cargo. `assembler/asmobj/` is entirely Wave. IR model, -text, verification, numeric semantics, passes and execution run in Wave when -its archive is selected; -Rust supplies typed transport and retained reference implementations. +Meson builds the Wave IR, shared assembler, selected ISA modules and `asmobj`, +then uses Cargo for Rust data transport, files, object formats and CLI components. +IR and assembler production algorithms run in Wave. Rust references require the +explicit `rust-reference` feature and are for comparison tests. Generated files and Cargo outputs stay in the selected build directory. ## Build, test and install @@ -14,6 +13,7 @@ and a native linker. Building `asmobj` also requires LLVM 21 development libraries, `ar`, and installed Rust **1.89.0** for the pinned Wave compiler. The initial executable host for the linked module is **Linux x86_64 GNU**. Whale's Rust MSRV and the Wave bootstrap's Rust version are separate requirements. +`whale build-info --json` reports linked module identities and build fingerprints. Provide a Wave Git repository containing commit `e0952ed65d07e14c6ed0aa64f3c9a5532dd7533b`. The helper reads that commit with @@ -31,6 +31,7 @@ meson setup /tmp/whale-build \ -Dwave-rust-toolchain=1.89 meson compile -C /tmp/whale-build meson test -C /tmp/whale-build --print-errorlogs +/tmp/whale-build/whale build-info --json DESTDIR=/tmp/whale-install meson install -C /tmp/whale-build /tmp/whale-install/usr/local/bin/whale --version ``` @@ -52,54 +53,62 @@ source list and artifact metadata. A compiler/std cache can be shared through `wave-bootstrap-dir`; cache identities and hashes are validated before reuse. Do not use the source tree's `target/` as a Meson build directory. -## Reuse a built module +## Reuse built modules or run Cargo checks -Build the complete module directly when an existing archive is preferable: +The helpers read the pinned Wave commit without changing its checkout: + +| Helper | Module | +| --- | --- | +| `tools/build_asmobj.py` | Assembly-to-object mapping | +| `tools/build_wave_ir.py` | IR, passes, interpreter and bytecode | +| `tools/build_wave_assembler.py --module common` | Shared assembler | +| `tools/build_wave_assembler.py --module amd64` | Selected ISA; also `aarch64`, `riscv64`, `loongarch64` | + +Each accepts `--wave-source`, `--out-dir`, `--bootstrap-dir` and +`--rust-toolchain` as in this example: ```sh -LLVM_SYS_211_PREFIX=/usr/lib64/llvm21 python3 tools/build_asmobj.py \ - --wave-source /absolute/path/to/Wave --out-dir /tmp/whale-asmobj \ - --bootstrap-dir /tmp/whale-bootstrap --rust-toolchain 1.89 -meson setup /tmp/whale-prebuilt -Dasmobj-dir=/tmp/whale-asmobj -meson compile -C /tmp/whale-prebuilt -meson test -C /tmp/whale-prebuilt --print-errorlogs +python3 tools/build_wave_ir.py --wave-source /absolute/path/to/Wave \ + --out-dir /tmp/whale-ir --bootstrap-dir /tmp/whale-bootstrap --rust-toolchain 1.89 ``` -Meson requires either `wave-source` or `asmobj-dir`; `asmobj` is part of the -product. Explicit archive metadata is checked before linking. The helper records -the pinned compiler, std, Rust/LLVM bootstrap requirements, ABI, source and archive -hashes. Changing the Rust/Wave boundary requires rebuilding the archive. Failed -compilation or archiving preserves the previous complete publication. Ambient environment -variables cannot select a different module for a Meson product. -Source builds also compile Wave IR parsing, printing, verification, numeric -semantics, constant evaluation, verified passes and execution. -With a prebuilt `asmobj`, pass `-Dwave-ir-dir=/absolute/path/to/built-wave-ir` -to use them. Ordinary Cargo keeps the Rust reference during the IR migration. -The Wave numeric core uses two 64-bit words for 128-bit integers and exact -IEEE rounding; it does not depend on host floating-point arithmetic. - -Source builds also compile the shared Wave assembler and selected ISA modules. -Prebuilt builds select them with `-Dwave-assembler-dir=...` and -`-Dwave-ARCH-dir=...` for each selected ISA; unselected archives are not linked. -For focused Cargo tests, `tools/build_wave_assembler.py --module common|amd64|aarch64|riscv64|loongarch64` -produces the corresponding archive. Set `WHALE_WAVE_ASSEMBLER_DIR` and -the corresponding `WHALE_WAVE_ARCH_DIR` explicitly; Cargo does not invoke Wave. - -For work confined to Rust components, ordinary Cargo builds remain available: +Prebuilt Meson products require `-Dasmobj-dir=...`, `-Dwave-ir-dir=...`, +`-Dwave-assembler-dir=...` and `-Dwave-ARCH-dir=...` for every selected ISA. +Unselected ISA archives are not linked. Meson requires all selected modules; +ambient environment variables cannot replace its explicit selections. + +For direct native Cargo checks, select those same archives explicitly: ```sh -cargo build --workspace --locked -cargo test -p ir --all-features --locked -# Include the complete Wave module for assembly-to-object integration tests. -export WHALE_ASMOBJ_DIR=/tmp/whale-asmobj +export WHALE_ASMOBJ_DIR=/path/to/asmobj +export WHALE_WAVE_IR_DIR=/path/to/ir +export WHALE_WAVE_ASSEMBLER_DIR=/path/to/common +export WHALE_WAVE_AMD64_DIR=/path/to/amd64 +export WHALE_WAVE_AARCH64_DIR=/path/to/aarch64 +export WHALE_WAVE_RISCV64_DIR=/path/to/riscv64 +export WHALE_WAVE_LOONGARCH64_DIR=/path/to/loongarch64 cargo test --workspace --all-features --locked ``` -Cargo never bootstraps or downloads Wave automatically. A build without the -module can inspect objects and use Rust IR APIs; assembly-to-object commands -return an explicit unavailable error. There is no Rust implementation of the -`asmobj` policies selected in its place. A linked executable needs no `wavec` -at runtime. +Source, ABI, archive and pinned compiler/std fingerprints are checked before +linking; rebuild the affected archive after changing its boundary or Wave source. +Failed compilation or archiving preserves the previous complete publication. +Cargo never bootstraps or downloads Wave automatically. A linked executable +needs no `wavec` at runtime. The numeric core uses two 64-bit words for 128-bit +integers and exact IEEE rounding without host floating-point arithmetic. + +For deliberate Rust reference checks, omit the `WHALE_WAVE_*` variables and use +`cargo test --workspace --all-features --locked`, or select `--features rust-reference` +on the component being tested. For a reference CLI: + +```sh +cargo build --no-default-features \ + --features asm-amd64,socket-cli,native-linker,rust-reference +``` + +Supplying a Wave archive selects Wave even with `rust-reference` enabled. +Missing production archives fail with setup instructions. `asmobj` has no Rust +implementation; reference CLI assembly-to-object checks still need its archive. ## Select assembler outputs and host machines @@ -107,7 +116,7 @@ Architecture selection controls generated code independently of the machine running Whale. For an AArch64-only product: ```sh -meson setup /tmp/whale-aarch64 -Dasmobj-dir=/tmp/whale-asmobj \ +meson setup /tmp/whale-aarch64 -Dwave-source=/absolute/path/to/Wave \ -Dasm-amd64=false -Dasm-riscv64=false -Dasm-loongarch64=false meson compile -C /tmp/whale-aarch64 ``` diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 199c8f4..70dcd23 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -9,9 +9,10 @@ and review comments should be in English. Follow the Use [BUILDING.md](BUILDING.md) for Meson, the pinned Wave compiler, dependencies and installation. Rust's MSRV is **1.86.0**; CI uses Python **3.13**. -Rust component tests can run without Wave. The complete product and -assembly-to-object tests require the built Wave `asmobj` archive. A linked -executable does not need the Wave compiler at runtime. +Use Meson for the native product and its tests. Direct Cargo checks need the +Wave archives listed in BUILDING.md, or explicit `rust-reference` for reference +tests. `asmobj` always requires Wave. A linked executable needs no Wave compiler +at runtime. ## 2. Repository structure and module boundaries @@ -30,7 +31,7 @@ executable does not need the Wave compiler at runtime. Split source files by role. Shared modules must not import a concrete ISA. `asmobj` contains only Wave sources; its Rust data boundary lives in `toolchain/src/assembly_object.rs`. Object serialization belongs to `object`. -IR reference algorithms remain available for comparison during the Wave migration. +Rust reference algorithms are selected explicitly with `rust-reference` for comparison tests. Keep Wave blocks readable with four-space indentation and one statement per line. ### Adding an assembler or IR target @@ -76,11 +77,10 @@ existing authorship and attribution. ## 5. Local verification -For assembly-to-object and CLI checks, first build `asmobj` as described in -[BUILDING.md](BUILDING.md), then supply its archive explicitly: +For native checks, select all required Wave archives as described in +[BUILDING.md](BUILDING.md#reuse-built-modules-or-run-cargo-checks): ```sh -export WHALE_ASMOBJ_DIR=/absolute/path/to/built-asmobj python3 tools/format-rust.py --check python3 -m unittest discover -s tools -p 'test_*.py' -v python3 tools/check_module_layers.py @@ -92,8 +92,8 @@ cargo build --workspace --all-features --locked python3 tools/ci_smoke.py --binary target/debug/whale --socket enabled ``` -On Windows use `target/debug/whale.exe`. For Rust-only work, start with a focused -command such as `cargo test -p ir --all-features --locked` without the archive. +For a reference-only check, omit Wave archive variables and use a focused +command such as `cargo test -p ir --features rust-reference,socket --locked`. See the [Rust](.github/workflows/rust.yml) and [quality](.github/workflows/quality.yml) workflows for MSRV, host, default-feature and optimized checks. diff --git a/Cargo.toml b/Cargo.toml index da1bf23..c1ee33d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -33,6 +33,7 @@ asm-riscv64 = ["dep:riscv64"] asm-loongarch64 = ["dep:loongarch64"] socket-cli = ["ir/socket"] native-linker = ["dep:linker"] +rust-reference = ["assembler/rust-reference", "ir/rust-reference", "toolchain/rust-reference", "amd64?/rust-reference", "aarch64?/rust-reference", "riscv64?/rust-reference", "loongarch64?/rust-reference"] [dependencies] assembler = { path = "assembler" } @@ -53,6 +54,9 @@ serde = { version = "1", features = ["derive"] } same-file = "1" tempfile = "3" +[build-dependencies] +serde_json = "1" + [[example]] name = "benchmark_probe" required-features = ["asm-amd64"] diff --git a/README.md b/README.md index 6e11348..2371666 100644 --- a/README.md +++ b/README.md @@ -8,8 +8,8 @@ Whale brings together an intermediate representation, assembler, object-file library, and linker infrastructure. Developed within the [Wave ecosystem](https://github.com/wavefnd/Wave), its components are intended to serve language implementations and compiler tooling through separately owned source -modules. Most components are Rust; the complete assembly-to-object `asmobj` -module is Wave. +modules. IR algorithms, assembler algorithms and the assembly-to-object `asmobj` +module are Wave. Rust owns typed data boundaries, files, object formats and the CLI. Whale is in active, early development. APIs and IR formats are evolving; the current capabilities are listed below. @@ -38,17 +38,17 @@ native compilation pipeline are still being developed. | Component | Available today | Status | | --- | --- | --- | | Assembler | AMD64 plus initial AArch64, RV64I and LoongArch64 integer subsets; sections, symbols, ELF64 and initial AMD64/AArch64 COFF and Mach-O output | Object emission requires the complete Wave `asmobj` module; initial linked host Linux x86_64 GNU | -| IR | Typed IR construction, text parsing/printing, bounded verification, integer/control-flow, tracked stack-memory and bounded Whale-call interpretation, and scalar AST JSON lowering | Experimental | +| IR | Wave text parsing/printing, bounded verification, constants, integer folding, tracked interpretation, AST JSON lowering and versioned Whale bytecode | Experimental | | Object library | Object model, bounded ELF64 reading and ELF64/COFF/Mach-O relocatable serialization | Available | | Object CLI | Wrap raw input bytes in an ELF64 object with a `.text` section | Limited | | Reverse | Bounded ELF/raw image inspection and typed result records | Inspection available; decoder and CFG/xrefs unavailable | | Linker | Static Linux AMD64 ELF executables from objects and ordinary archives, checked relocations and explicit entry | Initial subset | -The IR target selector accepts only `x86_64-whale-linux`; unknown targets fail -with the supported choice, including with `--no-verify`. Its output data layout -is 64-bit little endian on every build host. Library lowering and verification +The IR target selector accepts `x86_64-whale-linux` and `whale-bytecode-v1`; +unknown targets fail even with `--no-verify`. Both use a checked 64-bit +little-endian data layout on every build host. Library lowering and verification reject target/layout mismatches. The IR layout API computes checked sizes, -field offsets, array strides, and natural/allocation alignments for this target. +field offsets, array strides, and natural/allocation alignments for these targets. It does not implement aggregate ABI passing or native code generation. BSS reservations retain a logical `zero_fill` count instead of allocating their @@ -89,8 +89,8 @@ subsets, source syntax, relocation types and examples. ## Getting started -Use Meson for the complete product build. It builds the Wave `asmobj` module -and the Rust components in dependency order. See [BUILDING.md](BUILDING.md) for +Use Meson for the complete product build. It builds the Wave IR, shared +assembler, selected ISA and `asmobj` modules, then the Rust components. See [BUILDING.md](BUILDING.md) for LLVM 21, the pinned Wave compiler, Rust toolchains and archive reuse. On the initial Linux x86_64 GNU host: @@ -105,23 +105,14 @@ meson setup /tmp/whale-build --buildtype=release \ meson compile -C /tmp/whale-build meson test -C /tmp/whale-build --print-errorlogs /tmp/whale-build/whale --version +/tmp/whale-build/whale build-info --json ``` -Rust components require **Rust 1.86.0 or newer**. Cargo remains available for -Rust development. To run the `cargo run` assembly examples below, first build -and select the complete Wave module: - -```sh -python3 tools/build_asmobj.py --wave-source /absolute/path/to/Wave \ - --out-dir /tmp/whale-asmobj -export WHALE_ASMOBJ_DIR=/tmp/whale-asmobj -cargo build --release --locked -``` - -Without that module, Cargo still builds the Rust components and IR commands; -assembly-to-object commands return an explicit unavailable error. The executable -is written to `target/release/whale` on Linux. Enable experimental AST JSON -lowering with `-Dsocket-cli=true` in Meson or `--features socket-cli` in Cargo. +Rust components require **Rust 1.86.0 or newer**. For direct Cargo development, +select the Wave archives listed in [BUILDING.md](BUILDING.md#reuse-built-modules-or-run-cargo-checks). +Rust reference algorithms require explicit `rust-reference`; Meson products use Wave. +Enable AST JSON lowering with `-Dsocket-cli=true` in Meson or `--features socket-cli` +in Cargo. Linked products need no Wave compiler at runtime. ## Usage @@ -191,13 +182,13 @@ preserving the previous archive on an archiver failure. ### Execute scalar integer IR -Save this format 7 module as `answer.wir`: +Save this format 8 module as `answer.wir`: ```text module { - format_version 7 + format_version 8 semantics_version 1 - target "x86_64-whale-linux" + target "whale-bytecode-v1" datalayout { ptr=64, endian=little } declare @f7 "answer": whale () -> i32, linkage internal @@ -215,7 +206,23 @@ module { cargo run --locked -- ir run answer.wir --function @f7 ``` -The output is `i32 42`. The default build verifies the whole module and runs +The output is `i32 42`. Compile the same module to portable Whale bytecode: + +```sh +whale ir emit answer.wir -o answer.wbc +whale bytecode verify answer.wbc +whale bytecode run answer.wbc --function @f7 +whale ir fold answer.wir -o folded.wir +``` + +Wave writes, verifies, loads and executes [bytecode v1](ir/BYTECODE.md). +Compilation checks every body, including unreachable code, before publishing. +The format preserves scalar bits, SSA IDs and source sites; runtime pointer +capabilities and layout plans are reconstructed. External runtime imports and +aggregate values passed by value are unsupported. Folding is an explicit pass; +ordinary O0 lowering keeps its operations. + +The interpreter verifies the whole module and runs one explicit Whale-convention function with integer/bool/float parameters and scalar or void return. Use repeated `--arg` decimal integer literals (`true`/`false` for Bool, exact-width hexadecimal storage bits for floats) @@ -223,7 +230,7 @@ and `--max-steps` to set the instruction/terminator budget (default 1,000,000). Zero division/remainder and explicit traps return structured errors; unused executed operations still trap. Loops evaluate phi inputs simultaneously. -This oracle supports integer constants, arithmetic, comparisons, bit casts, +The Wave interpreter supports integer constants, arithmetic, comparisons, bit casts, checked pairs, select and control flow. It also supports bit-exact f16/f32/f64 constants, mov/phi/select and tracked stack allocations, integer/Bool/float/data-pointer storage, typed GEP, byte copies and fills, with initialization and capability checks. @@ -742,13 +749,18 @@ The checked-in fixture is [symbol-metadata.asm](tests/fixtures/symbol-metadata.a ## Release packages -Native Linux, macOS and Windows x64/ARM64 packaging, extracted-binary checks and -exact checksum manifests are documented in [the release guide](tools/RELEASING.md). -The manual workflow validates one tagged source commit across every package; -draft creation is opt-in and runs only after all checks pass. +Complete Wave product packages are initially validated on Linux x86_64 GNU. +[The release guide](tools/RELEASING.md) describes provenance, extracted-binary +checks and checksum manifests. Reference packages for other hosts must identify +their selected implementation; cross-produced Wave objects do not establish +native execution support. Draft creation is opt-in after checks pass. ## Development +[CLI and library benchmarks](tools/BENCHMARKS.md) record verified outputs, timings +and peak RSS. Further compiler/backend work remains tracked in +[#232](https://github.com/wavefnd/Whale/issues/232). + | Path | Responsibility | | --- | --- | | [assembler/](assembler/) | Assembly parsing and instruction encoding | @@ -861,8 +873,7 @@ artifact targets Linux AMD64 regardless of the machine running Whale. ## Reverse image inspection The reusable [reverse module](reverse/README.md) provides bounded AMD64 ELF/raw -image inspection and typed result records. Inspection works in ordinary Cargo -builds: +image inspection and typed result records. In a configured product: ```sh cargo run --locked -- reverse inspect app --json diff --git a/assembler/Cargo.toml b/assembler/Cargo.toml index b47943b..80deb6f 100644 --- a/assembler/Cargo.toml +++ b/assembler/Cargo.toml @@ -4,6 +4,10 @@ version = "0.1.0" edition = "2021" rust-version.workspace = true +[features] +default = [] +rust-reference = [] + [dependencies] target-spec = { path = "../target-spec" } diagnostic = { path = "../diagnostic" } diff --git a/assembler/aarch64/Cargo.toml b/assembler/aarch64/Cargo.toml index 73ce25a..baadf05 100644 --- a/assembler/aarch64/Cargo.toml +++ b/assembler/aarch64/Cargo.toml @@ -4,6 +4,10 @@ version = "0.1.0" edition = "2021" rust-version.workspace = true +[features] +default = [] +rust-reference = ["assembler/rust-reference"] + [dependencies] assembler = { path = ".." } target-spec = { path = "../../target-spec" } diff --git a/assembler/aarch64/entry.wave b/assembler/aarch64/entry.wave index 0cd09c1..c5d0de3 100644 --- a/assembler/aarch64/entry.wave +++ b/assembler/aarch64/entry.wave @@ -41,3 +41,8 @@ export(c) fun whale_aarch64_assemble(packet: ptr, result: ptr u64 { + return 6289348675458121985; +} diff --git a/assembler/aarch64/src/lib.rs b/assembler/aarch64/src/lib.rs index 076e035..d99ef4b 100644 --- a/assembler/aarch64/src/lib.rs +++ b/assembler/aarch64/src/lib.rs @@ -5,16 +5,16 @@ use assembler::{ AsmError, AssemblerOutput, AssemblyLimits, }; -#[cfg(any(not(whale_wave_aarch64), test))] +#[cfg(any(not(whale_wave_aarch64), all(test, feature = "rust-reference")))] mod encoder; -#[cfg(any(not(whale_wave_aarch64), test))] +#[cfg(any(not(whale_wave_aarch64), all(test, feature = "rust-reference")))] mod encoding; -#[cfg(any(not(whale_wave_aarch64), test))] +#[cfg(any(not(whale_wave_aarch64), all(test, feature = "rust-reference")))] mod parser; -#[cfg(any(not(whale_wave_aarch64), test))] +#[cfg(any(not(whale_wave_aarch64), all(test, feature = "rust-reference")))] mod tables; #[cfg(whale_wave_aarch64)] @@ -82,3 +82,34 @@ impl FixedIsa for AArch64 { } } } + +/// The implementation actually selected by this owning module. +pub fn module_identity() -> &'static str { + #[cfg(whale_wave_aarch64)] + { + unsafe extern "C" { + fn whale_aarch64_module_identity() -> u64; + } + // This no-argument stamp is exported by this module's guarded archive. + if unsafe { whale_aarch64_module_identity() } == 6289348675458121985 { + "wave" + } else { + "invalid-wave" + } + } + #[cfg(not(whale_wave_aarch64))] + { + "rust-reference" + } +} + +#[cfg(test)] +mod implementation_identity_tests { + #[test] + fn selected_implementation_has_its_own_compiled_identity() { + assert_eq!( + super::module_identity(), + if cfg!(whale_wave_aarch64) { "wave" } else { "rust-reference" } + ); + } +} diff --git a/assembler/aarch64/src/wave.rs b/assembler/aarch64/src/wave.rs index 0562143..3fa46f5 100644 --- a/assembler/aarch64/src/wave.rs +++ b/assembler/aarch64/src/wave.rs @@ -65,7 +65,7 @@ pub(super) fn encode( native::encode(instruction, context, whale_aarch64_encode, render) } -#[cfg(test)] +#[cfg(all(test, feature = "rust-reference"))] mod tests { use super::*; diff --git a/assembler/amd64/Cargo.toml b/assembler/amd64/Cargo.toml index 839f60b..df5d2d4 100644 --- a/assembler/amd64/Cargo.toml +++ b/assembler/amd64/Cargo.toml @@ -4,6 +4,10 @@ version = "0.1.0" edition = "2021" rust-version.workspace = true +[features] +default = [] +rust-reference = ["assembler/rust-reference"] + [dependencies] assembler = { path = ".." } diff --git a/assembler/amd64/build.rs b/assembler/amd64/build.rs index 636e1a5..5a9abc8 100644 --- a/assembler/amd64/build.rs +++ b/assembler/amd64/build.rs @@ -42,5 +42,6 @@ const ABI_SOURCES: &[&str] = &[ "assembler/amd64/src/encoding/modrm.rs", "assembler/amd64/src/encoding/rex.rs", "assembler/amd64/src/encoding/sib.rs", + "assembler/amd64/src/lib.rs", ]; include!("../build_support.rs"); diff --git a/assembler/amd64/encoder.wave b/assembler/amd64/encoder.wave index 68dc329..d4bac1b 100644 --- a/assembler/amd64/encoder.wave +++ b/assembler/amd64/encoder.wave @@ -384,3 +384,8 @@ export(c) fun whale_amd64_condition(name: ptr, output: ptr) -> i32 } return 1; } + +// Distinct compiled identity used by product composition checks. +export(c) fun whale_amd64_module_identity() -> u64 { + return 6289348675458125057; +} diff --git a/assembler/amd64/meson.build b/assembler/amd64/meson.build index dfb376d..e054f9f 100644 --- a/assembler/amd64/meson.build +++ b/assembler/amd64/meson.build @@ -19,6 +19,7 @@ if wave_amd64_directory == '' and wave_source != '' output: [archive_name, 'wave-amd64.meta', 'provenance.json'], command: [python, files('../../tools/build_wave_assembler.py'), arguments], depend_files: files( + 'src/lib.rs', '../model.wave', '../declarations.wave', '../ast_model.wave', diff --git a/assembler/amd64/src/lib.rs b/assembler/amd64/src/lib.rs index 088f892..d0f9452 100644 --- a/assembler/amd64/src/lib.rs +++ b/assembler/amd64/src/lib.rs @@ -329,3 +329,34 @@ _start: } } } + +/// The implementation actually selected by this owning module. +pub fn module_identity() -> &'static str { + #[cfg(whale_wave_amd64)] + { + unsafe extern "C" { + fn whale_amd64_module_identity() -> u64; + } + // This no-argument stamp is exported by this module's guarded archive. + if unsafe { whale_amd64_module_identity() } == 6289348675458125057 { + "wave" + } else { + "invalid-wave" + } + } + #[cfg(not(whale_wave_amd64))] + { + "rust-reference" + } +} + +#[cfg(test)] +mod implementation_identity_tests { + #[test] + fn selected_implementation_has_its_own_compiled_identity() { + assert_eq!( + super::module_identity(), + if cfg!(whale_wave_amd64) { "wave" } else { "rust-reference" } + ); + } +} diff --git a/assembler/asmobj/entry.wave b/assembler/asmobj/entry.wave index e8441b8..57de4ce 100644 --- a/assembler/asmobj/entry.wave +++ b/assembler/asmobj/entry.wave @@ -138,3 +138,8 @@ export(c) fun whale_asmobj(target: ptr, sections: ptr u64 { + return 6289348675458125569; +} diff --git a/assembler/asmobj/meson.build b/assembler/asmobj/meson.build index 9fc8988..b03b55d 100644 --- a/assembler/asmobj/meson.build +++ b/assembler/asmobj/meson.build @@ -33,7 +33,7 @@ else error('-Dasmobj-dir must be absolute.') endif archive_name = host_machine.system() == 'windows' ? 'whale_asmobj.lib' : 'libwhale_asmobj.a' - foreach artifact : [archive_name, 'asmobj.meta'] + foreach artifact : [archive_name, 'asmobj.meta', 'provenance.json'] if not fs.is_file(asmobj_directory / artifact) error('Missing asmobj module artifact: ' + (asmobj_directory / artifact)) endif diff --git a/assembler/build.rs b/assembler/build.rs index 90fa289..54c14c0 100644 --- a/assembler/build.rs +++ b/assembler/build.rs @@ -31,5 +31,6 @@ const ABI_SOURCES: &[&str] = &[ "assembler/src/tokens_wave.rs", "assembler/src/fixed.rs", "assembler/src/fixed_wave.rs", + "assembler/src/lib.rs", ]; include!("build_support.rs"); diff --git a/assembler/build_support.rs b/assembler/build_support.rs index 1ea1241..4609fc4 100644 --- a/assembler/build_support.rs +++ b/assembler/build_support.rs @@ -34,7 +34,12 @@ fn hash_file(path: &std::path::Path, maximum: Option) -> String { fn main() { println!("cargo:rustc-check-cfg=cfg({CFG})"); println!("cargo:rerun-if-env-changed={ENV}"); - let Some(directory) = env::var_os(ENV) else { return }; + println!("cargo:rerun-if-env-changed=CARGO_FEATURE_RUST_REFERENCE"); + let Some(directory) = env::var_os(ENV) else { + assert!(env::var_os("CARGO_FEATURE_RUST_REFERENCE").is_some(), + "{CFG} requires its Wave module; build with Meson or select rust-reference explicitly for comparison"); + return; + }; if CFG != "whale_wave_assembler" { assert!( env::var_os("WHALE_WAVE_ASSEMBLER_DIR").is_some(), diff --git a/assembler/lexer.wave b/assembler/lexer.wave index 52eef86..7be4a22 100644 --- a/assembler/lexer.wave +++ b/assembler/lexer.wave @@ -423,3 +423,8 @@ export(c) fun whale_asm_lex(source: ptr, length: u64, max_tokens: u64, } return 0; } + +// Distinct compiled identity used by product composition checks. +export(c) fun whale_assembler_module_identity() -> u64 { + return 6289348675458126593; +} diff --git a/assembler/loongarch64/Cargo.toml b/assembler/loongarch64/Cargo.toml index 5c93332..e018d6b 100644 --- a/assembler/loongarch64/Cargo.toml +++ b/assembler/loongarch64/Cargo.toml @@ -4,6 +4,10 @@ version = "0.1.0" edition = "2021" rust-version.workspace = true +[features] +default = [] +rust-reference = ["assembler/rust-reference"] + [dependencies] assembler = { path = ".." } target-spec = { path = "../../target-spec" } diff --git a/assembler/loongarch64/entry.wave b/assembler/loongarch64/entry.wave index 410fbce..e61e811 100644 --- a/assembler/loongarch64/entry.wave +++ b/assembler/loongarch64/entry.wave @@ -26,3 +26,8 @@ export(c) fun whale_loongarch64_assemble(packet: ptr, } return 0; } + +// Distinct compiled identity used by product composition checks. +export(c) fun whale_loongarch64_module_identity() -> u64 { + return 6289348675458842881; +} diff --git a/assembler/loongarch64/src/lib.rs b/assembler/loongarch64/src/lib.rs index 89c5801..6cb96c9 100644 --- a/assembler/loongarch64/src/lib.rs +++ b/assembler/loongarch64/src/lib.rs @@ -8,7 +8,7 @@ use assembler::{ #[cfg(not(whale_wave_loongarch64))] mod encoder; -#[cfg(all(test, whale_wave_loongarch64))] +#[cfg(all(test, whale_wave_loongarch64, feature = "rust-reference"))] #[path = "encoder.rs"] mod reference_encoder; @@ -18,13 +18,13 @@ mod wave; #[cfg(not(whale_wave_loongarch64))] use assembler::fixed; -#[cfg(any(test, not(whale_wave_loongarch64)))] +#[cfg(any(all(test, feature = "rust-reference"), not(whale_wave_loongarch64)))] mod encoding; -#[cfg(any(test, not(whale_wave_loongarch64)))] +#[cfg(any(all(test, feature = "rust-reference"), not(whale_wave_loongarch64)))] mod parser; -#[cfg(any(test, not(whale_wave_loongarch64)))] +#[cfg(any(all(test, feature = "rust-reference"), not(whale_wave_loongarch64)))] mod tables; pub struct LoongArch64; @@ -86,7 +86,7 @@ impl FixedIsa for LoongArch64 { } } -#[cfg(all(test, whale_wave_loongarch64))] +#[cfg(all(test, whale_wave_loongarch64, feature = "rust-reference"))] mod wave_tests { use super::*; @@ -192,3 +192,34 @@ mod wave_tests { } } } + +/// The implementation actually selected by this owning module. +pub fn module_identity() -> &'static str { + #[cfg(whale_wave_loongarch64)] + { + unsafe extern "C" { + fn whale_loongarch64_module_identity() -> u64; + } + // This no-argument stamp is exported by this module's guarded archive. + if unsafe { whale_loongarch64_module_identity() } == 6289348675458842881 { + "wave" + } else { + "invalid-wave" + } + } + #[cfg(not(whale_wave_loongarch64))] + { + "rust-reference" + } +} + +#[cfg(test)] +mod implementation_identity_tests { + #[test] + fn selected_implementation_has_its_own_compiled_identity() { + assert_eq!( + super::module_identity(), + if cfg!(whale_wave_loongarch64) { "wave" } else { "rust-reference" } + ); + } +} diff --git a/assembler/meson.build b/assembler/meson.build index 9aa4670..9e82762 100644 --- a/assembler/meson.build +++ b/assembler/meson.build @@ -21,6 +21,7 @@ if wave_assembler_directory == '' and wave_source != '' output: [archive_name, 'wave-assembler.meta', 'provenance.json'], command: [python, files('../tools/build_wave_assembler.py'), arguments], depend_files: files( + 'src/lib.rs', 'model.wave', 'unicode.wave', 'numeric.wave', diff --git a/assembler/riscv64/Cargo.toml b/assembler/riscv64/Cargo.toml index 744e831..4a6bb51 100644 --- a/assembler/riscv64/Cargo.toml +++ b/assembler/riscv64/Cargo.toml @@ -4,6 +4,10 @@ version = "0.1.0" edition = "2021" rust-version.workspace = true +[features] +default = [] +rust-reference = ["assembler/rust-reference"] + [dependencies] assembler = { path = ".." } target-spec = { path = "../../target-spec" } diff --git a/assembler/riscv64/entry.wave b/assembler/riscv64/entry.wave index 8c300b2..6124387 100644 --- a/assembler/riscv64/entry.wave +++ b/assembler/riscv64/entry.wave @@ -62,3 +62,8 @@ export(c) fun whale_riscv64_entry(packet: ptr, result: ptr u64 { + return 6289348675459241473; +} diff --git a/assembler/riscv64/src/encoder.rs b/assembler/riscv64/src/encoder.rs index 34a3fdd..c847b7b 100644 --- a/assembler/riscv64/src/encoder.rs +++ b/assembler/riscv64/src/encoder.rs @@ -5,7 +5,7 @@ use assembler::{ AsmError, }; -#[cfg(any(test, not(whale_wave_riscv64)))] +#[cfg(any(all(test, feature = "rust-reference"), not(whale_wave_riscv64)))] #[path = "encoder_reference.rs"] pub(crate) mod reference; diff --git a/assembler/riscv64/src/lib.rs b/assembler/riscv64/src/lib.rs index 7e41a38..5bcd79f 100644 --- a/assembler/riscv64/src/lib.rs +++ b/assembler/riscv64/src/lib.rs @@ -7,13 +7,13 @@ use assembler::{ mod encoder; -#[cfg(any(test, not(whale_wave_riscv64)))] +#[cfg(any(all(test, feature = "rust-reference"), not(whale_wave_riscv64)))] mod encoding; -#[cfg(any(test, not(whale_wave_riscv64)))] +#[cfg(any(all(test, feature = "rust-reference"), not(whale_wave_riscv64)))] mod parser; -#[cfg(any(test, not(whale_wave_riscv64)))] +#[cfg(any(all(test, feature = "rust-reference"), not(whale_wave_riscv64)))] mod tables; #[cfg(whale_wave_riscv64)] @@ -67,7 +67,7 @@ impl FixedIsa for RiscV64 { } } -#[cfg(all(test, whale_wave_riscv64))] +#[cfg(all(test, whale_wave_riscv64, feature = "rust-reference"))] mod wave_tests { use super::*; @@ -173,3 +173,34 @@ mod wave_tests { } } } + +/// The implementation actually selected by this owning module. +pub fn module_identity() -> &'static str { + #[cfg(whale_wave_riscv64)] + { + unsafe extern "C" { + fn whale_riscv64_module_identity() -> u64; + } + // This no-argument stamp is exported by this module's guarded archive. + if unsafe { whale_riscv64_module_identity() } == 6289348675459241473 { + "wave" + } else { + "invalid-wave" + } + } + #[cfg(not(whale_wave_riscv64))] + { + "rust-reference" + } +} + +#[cfg(test)] +mod implementation_identity_tests { + #[test] + fn selected_implementation_has_its_own_compiled_identity() { + assert_eq!( + super::module_identity(), + if cfg!(whale_wave_riscv64) { "wave" } else { "rust-reference" } + ); + } +} diff --git a/assembler/riscv64/src/parser.rs b/assembler/riscv64/src/parser.rs index 5c61892..e10f756 100644 --- a/assembler/riscv64/src/parser.rs +++ b/assembler/riscv64/src/parser.rs @@ -3,7 +3,7 @@ #[cfg(test)] use assembler::AsmError; -#[cfg(any(test, not(whale_wave_riscv64)))] +#[cfg(any(all(test, feature = "rust-reference"), not(whale_wave_riscv64)))] #[path = "parser_reference.rs"] pub(crate) mod reference; diff --git a/assembler/riscv64/src/wave.rs b/assembler/riscv64/src/wave.rs index cd4e05e..b458bca 100644 --- a/assembler/riscv64/src/wave.rs +++ b/assembler/riscv64/src/wave.rs @@ -4,7 +4,7 @@ use assembler::fixed::{native, Context, Instruction}; use assembler::{AsmError, AssemblerOutput, AssemblyLimits}; -#[cfg(test)] +#[cfg(all(test, feature = "rust-reference"))] use native::FixedText; use native::{FixedContext, FixedInput, FixedInstruction, FixedResult}; @@ -18,10 +18,10 @@ unsafe extern "C" { result: *mut FixedResult, ) -> i32; - #[cfg(test)] + #[cfg(all(test, feature = "rust-reference"))] fn whale_riscv64_operand(mode: u64, text: *const FixedText, result: *mut FixedResult) -> i32; - #[cfg(test)] + #[cfg(all(test, feature = "rust-reference"))] fn whale_riscv64_branch( jump: u64, f3: u64, @@ -59,7 +59,7 @@ pub(crate) fn encode( native::encode(instruction, context, whale_riscv64_instruction, render) } -#[cfg(test)] +#[cfg(all(test, feature = "rust-reference"))] fn operand(mode: u64, text: &str) -> Result<(u64, u64), AsmError> { let text_record = FixedText::new(text); let mut result = FixedResult::new(); @@ -68,7 +68,7 @@ fn operand(mode: u64, text: &str) -> Result<(u64, u64), AsmError> { Ok((result.word, result.detail)) } -#[cfg(test)] +#[cfg(all(test, feature = "rust-reference"))] pub(crate) fn reg(text: &str) -> Result { let (word, detail) = operand(0, text)?; if word >= 32 || detail != 0 { @@ -77,7 +77,7 @@ pub(crate) fn reg(text: &str) -> Result { Ok(word as u32) } -#[cfg(test)] +#[cfg(all(test, feature = "rust-reference"))] pub(crate) fn memory(text: &str) -> Result<(u32, u32), AsmError> { let (word, detail) = operand(1, text)?; if word >= 32 || detail >= 4096 { @@ -86,7 +86,7 @@ pub(crate) fn memory(text: &str) -> Result<(u32, u32), AsmError> { Ok((word as u32, detail as u32)) } -#[cfg(test)] +#[cfg(all(test, feature = "rust-reference"))] pub(crate) fn fence_mask(text: &str) -> Result { let (word, detail) = operand(2, text)?; if word >= 16 || detail != 0 { @@ -95,7 +95,7 @@ pub(crate) fn fence_mask(text: &str) -> Result { Ok(word as u32) } -#[cfg(test)] +#[cfg(all(test, feature = "rust-reference"))] pub(crate) fn branch( jump: bool, f3: u32, diff --git a/assembler/src/fixed.rs b/assembler/src/fixed.rs index 408b837..eaac743 100644 --- a/assembler/src/fixed.rs +++ b/assembler/src/fixed.rs @@ -49,6 +49,7 @@ pub struct Context<'a> { } #[doc(hidden)] +#[cfg(feature = "rust-reference")] #[path = "fixed_reference.rs"] pub mod reference; @@ -66,6 +67,7 @@ impl Context<'_> { } #[doc(hidden)] + #[cfg(feature = "rust-reference")] pub fn pc_relative_reference(&mut self, operand: &str, code: u32) -> Result { reference::pc_relative(self, operand, code) } @@ -129,5 +131,33 @@ pub fn assemble( if let Some(output) = isa.native_assemble(name, source, limits) { return output; } - reference::assemble(isa, name, source, limits) + #[cfg(not(whale_wave_assembler))] + return reference::assemble(isa, name, source, limits); + #[cfg(whale_wave_assembler)] + Err(AsmError::Backend("selected ISA has no Wave source driver")) +} + +#[cfg(all(test, whale_wave_assembler))] +mod driver_selection_tests { + use super::*; + + struct Missing; + + impl FixedIsa for Missing { + fn id(&self) -> &'static str { + "missing" + } + + fn encode(&self, _: &Instruction, _: &mut Context<'_>) -> Result { + panic!("a missing native driver cannot invoke Rust encoding") + } + } + + #[test] + fn missing_wave_driver_never_uses_the_reference_parser() { + assert!(matches!( + assemble(&Missing, "input.s", "nop", &AssemblyLimits::default()), + Err(AsmError::Backend("selected ISA has no Wave source driver")) + )); + } } diff --git a/assembler/src/fixed_wave.rs b/assembler/src/fixed_wave.rs index bca7448..bf02985 100644 --- a/assembler/src/fixed_wave.rs +++ b/assembler/src/fixed_wave.rs @@ -1031,6 +1031,7 @@ mod tests { } #[test] + #[cfg(feature = "rust-reference")] fn public_context_relative_transport_matches_reference_and_appends_only_native_relocations() { let span = SourceSpan { start: 0, end: 1, line: 1, column: 1 }; let symbols = BTreeMap::from([ @@ -1072,6 +1073,7 @@ mod tests { } #[test] + #[cfg(feature = "rust-reference")] fn common_numeric_and_operand_facades_match_explicit_rust_reference() { for text in [ "0", diff --git a/assembler/src/lib.rs b/assembler/src/lib.rs index d2b156f..218b05e 100644 --- a/assembler/src/lib.rs +++ b/assembler/src/lib.rs @@ -21,3 +21,34 @@ pub mod extension; pub mod fixed; pub use target_spec::{Machine, ObjectTarget}; + +/// The implementation actually selected by this owning module. +pub fn module_identity() -> &'static str { + #[cfg(whale_wave_assembler)] + { + unsafe extern "C" { + fn whale_assembler_module_identity() -> u64; + } + // This no-argument stamp is exported by this module's guarded archive. + if unsafe { whale_assembler_module_identity() } == 6289348675458126593 { + "wave" + } else { + "invalid-wave" + } + } + #[cfg(not(whale_wave_assembler))] + { + "rust-reference" + } +} + +#[cfg(test)] +mod implementation_identity_tests { + #[test] + fn selected_implementation_has_its_own_compiled_identity() { + assert_eq!( + super::module_identity(), + if cfg!(whale_wave_assembler) { "wave" } else { "rust-reference" } + ); + } +} diff --git a/build.rs b/build.rs new file mode 100644 index 0000000..b56963d --- /dev/null +++ b/build.rs @@ -0,0 +1,117 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Embed portable provenance. Running Whale never needs Git, Cargo or Wave. +use std::{env, fs, io::Read, path::Path, process::Command}; + +use serde_json::{json, Map, Value}; + +fn git(root: &Path, arguments: &[&str]) -> Option { + let output = Command::new("git") + .env("GIT_OPTIONAL_LOCKS", "0") + .args(arguments) + .current_dir(root) + .output() + .ok()?; + output.status.success().then(|| String::from_utf8_lossy(&output.stdout).trim().to_owned()) +} + +fn provenance(directory: &Path) -> Value { + let path = directory.join("provenance.json"); + println!("cargo:rerun-if-changed={}", path.display()); + let mut bytes = Vec::new(); + fs::File::open(&path) + .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display())) + .take(16385) + .read_to_end(&mut bytes) + .expect("cannot read module provenance"); + assert!(bytes.len() <= 16384, "oversized module provenance"); + let original: Value = serde_json::from_slice(&bytes).expect("invalid module provenance"); + let mut portable = Map::new(); + // Exclude the bootstrap cache path: it is not part of the built product. + for key in [ + "wave_revision", + "target", + "opt_level", + "source_sha256", + "abi_sha256", + "archive_sha256", + "compiler_sha256", + "std_sha256", + "bootstrap_rust_version", + "required_llvm_major", + ] { + let value = original.get(key).unwrap_or_else(|| panic!("missing provenance {key}")); + portable.insert(key.into(), value.clone()); + } + Value::Object(portable) +} + +fn main() { + let root = std::path::PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap()); + println!("cargo:rerun-if-env-changed=WHALE_SOURCE_REVISION"); + println!("cargo:rerun-if-env-changed=RUSTC"); + // Follow the actual worktree's refs and index, including linked worktrees. + let branch = git(&root, &["symbolic-ref", "-q", "HEAD"]); + for name in + [Some("HEAD"), Some("index"), Some("packed-refs"), branch.as_deref()].into_iter().flatten() + { + if let Some(path) = git(&root, &["rev-parse", "--git-path", name]) { + let path = root.join(path); + if path.exists() { + println!("cargo:rerun-if-changed={}", path.display()); + } + } + } + if let Some(files) = git(&root, &["ls-files", "-z"]) { + for path in files.split('\0').filter(|path| !path.is_empty()) { + println!("cargo:rerun-if-changed={}", root.join(path).display()); + } + } + let supplied = env::var("WHALE_SOURCE_REVISION").ok(); + if let Some(revision) = &supplied { + assert!( + revision.len() == 40 + && revision + .bytes() + .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()), + "WHALE_SOURCE_REVISION requires a full lowercase Git commit SHA" + ); + } + let commit = + supplied.or_else(|| git(&root, &["rev-parse", "HEAD"])).unwrap_or_else(|| "unknown".into()); + let dirty = git(&root, &["status", "--porcelain", "--untracked-files=normal"]) + .is_some_and(|status| !status.is_empty()); + let compiler = Command::new(env::var_os("RUSTC").unwrap_or_else(|| "rustc".into())) + .arg("-Vv") + .output() + .expect("cannot query the Rust compiler"); + assert!(compiler.status.success(), "cannot query the Rust compiler"); + let mut modules = Map::new(); + for (id, variable, feature) in [ + ("ir", "WHALE_WAVE_IR_DIR", None), + ("assembler", "WHALE_WAVE_ASSEMBLER_DIR", None), + ("asmobj", "WHALE_ASMOBJ_DIR", None), + ("amd64", "WHALE_WAVE_AMD64_DIR", Some("CARGO_FEATURE_ASM_AMD64")), + ("aarch64", "WHALE_WAVE_AARCH64_DIR", Some("CARGO_FEATURE_ASM_AARCH64")), + ("riscv64", "WHALE_WAVE_RISCV64_DIR", Some("CARGO_FEATURE_ASM_RISCV64")), + ("loongarch64", "WHALE_WAVE_LOONGARCH64_DIR", Some("CARGO_FEATURE_ASM_LOONGARCH64")), + ] { + println!("cargo:rerun-if-env-changed={variable}"); + if feature.is_some_and(|feature| env::var_os(feature).is_none()) { + continue; + } + if let Some(directory) = env::var_os(variable) { + modules.insert(id.into(), provenance(Path::new(&directory))); + } + } + let record = json!({ + "schema_version": 1, + "source_commit": commit, + "source_dirty": dirty, + "host_target": env::var("TARGET").unwrap(), + "rustc": String::from_utf8(compiler.stdout).expect("invalid rustc version").trim(), + "reference_feature": env::var_os("CARGO_FEATURE_RUST_REFERENCE").is_some(), + "wave_modules": modules, + }); + let path = std::path::PathBuf::from(env::var_os("OUT_DIR").unwrap()).join("build-info.json"); + fs::write(path, serde_json::to_vec(&record).unwrap()).expect("cannot publish build provenance"); +} diff --git a/examples/fuzz_boundaries.rs b/examples/fuzz_boundaries.rs index d266301..1285dc7 100644 --- a/examples/fuzz_boundaries.rs +++ b/examples/fuzz_boundaries.rs @@ -8,12 +8,14 @@ use std::{ fn main() { let mut args = std::env::args().skip(1); - let target = fuzz::Target::parse(&args.next().expect("target: assembler|object|ir|ast")) - .expect("unknown target"); + let target = + fuzz::Target::parse(&args.next().expect("target: assembler|object|ir|ast|bytecode")) + .expect("unknown target"); let mode = args.next().expect("cases count or --replay"); if mode == "--replay" { let path = args.next().expect("replay path"); let bytes = fuzz::read_bounded(std::path::Path::new(&path)); + checkpoint(target, &bytes, 0, None, &PathBuf::from(&path)); fuzz::check(target, &bytes); println!("replay passed"); return; @@ -24,7 +26,8 @@ fn main() { let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("fuzz/corpus"); let seeds = fuzz::seeds(&corpus, target); let mut seed_accepted = 0; - for (_, bytes) in &seeds { + for (path, bytes) in &seeds { + checkpoint(target, bytes, seed, None, path); seed_accepted += usize::from(fuzz::check(target, bytes)); } assert!(seed_accepted > 0, "corpus needs a valid seed"); @@ -33,6 +36,7 @@ fn main() { for case in 0..cases { let (path, bytes) = &seeds[rng.index(seeds.len())]; let input = if case % 8 == 0 { bytes.clone() } else { fuzz::mutate(bytes, &mut rng) }; + checkpoint(target, &input, seed, Some(case), path); match catch_unwind(AssertUnwindSafe(|| fuzz::check(target, &input))) { Ok(valid) => accepted += usize::from(valid), Err(_) => { @@ -46,8 +50,17 @@ fn main() { // Retain evidence before minimization: the process may hit its // independent time/memory limit while reducing a failing input. std::fs::write(&original, &input).unwrap(); - std::fs::write(directory.join(format!("{}-{seed}-{case}.replay", target.name())), - format!("origin={}\nreplay: cargo run --locked --all-features --example fuzz_boundaries -- {} --replay {}\n",path.display(),target.name(),original.display())).unwrap(); + let replay = serde_json::json!({ + "origin": path, + "replay": [std::env::current_exe().unwrap().to_str().expect("UTF-8 replay path"), + target.name(), "--replay", + original.to_str().expect("UTF-8 replay path")], + }); + std::fs::write( + directory.join(format!("{}-{seed}-{case}.replay", target.name())), + serde_json::to_vec_pretty(&replay).unwrap(), + ) + .unwrap(); let attempts = std::cell::Cell::new(0usize); let started = std::time::Instant::now(); let minimal = fuzz::minimize(input, |b| { @@ -55,10 +68,16 @@ fn main() { return false; } attempts.set(attempts.get() + 1); + checkpoint(target, b, seed, Some(case), path); catch_unwind(AssertUnwindSafe(|| fuzz::check(target, b))).is_err() }); std::fs::write(&crash, minimal).unwrap(); - eprintln!("seed={} case={case} origin={} replay: cargo run --locked --features socket-cli --example fuzz_boundaries -- {} --replay {}",seed,path.display(),target.name(),crash.display()); + eprintln!( + "seed={seed} case={case} origin={} original={} minimized={}", + path.display(), + original.display(), + crash.display() + ); std::process::exit(1); }, } @@ -70,3 +89,48 @@ fn main() { fuzz::MAX_INPUT ); } + +// A native abort or timeout cannot reach catch_unwind. Publish the original and +// literal replay arguments before entering any native-backed library boundary. +fn checkpoint( + target: fuzz::Target, + bytes: &[u8], + seed: u64, + case: Option, + origin: &std::path::Path, +) { + assert!(bytes.len() <= fuzz::MAX_INPUT); + let directory = std::env::var_os("WHALE_FUZZ_ARTIFACT_DIR") + .map(PathBuf::from) + .unwrap_or_else(|| std::env::temp_dir().join("whale-fuzz")); + std::fs::create_dir_all(&directory).unwrap(); + let directory = directory.canonicalize().unwrap(); + use std::io::Write; + + static PREVIOUS: std::sync::Mutex> = std::sync::Mutex::new(None); + let mut previous = PREVIOUS.lock().unwrap(); + let mut file = tempfile::Builder::new() + .prefix(&format!("{}.current-", target.name())) + .tempfile_in(&directory) + .unwrap(); + file.write_all(bytes).unwrap(); + let (file, original) = file.keep().unwrap(); + drop(file); + let record = serde_json::json!({ + "target": target.name(), "seed": seed, "case": case, "origin": origin, + "bytes": bytes.len(), "input": original, "ir_wave": ir::IR_WAVE_ENABLED, + "replay": [std::env::current_exe().unwrap().to_str().expect("UTF-8 replay path"), + target.name(), "--replay", + original.to_str().expect("UTF-8 replay path")], + }); + let metadata = directory.join(format!("{}.current.json", target.name())); + let temporary = directory.join(format!("{}.current.json.tmp", target.name())); + std::fs::write(&temporary, serde_json::to_vec_pretty(&record).unwrap()).unwrap(); + if let Err(error) = std::fs::rename(temporary, metadata) { + let _ = std::fs::remove_file(&original); + panic!("unable to publish replay manifest: {error}"); + } + if let Some(path) = previous.replace(original) { + std::fs::remove_file(path).unwrap(); + } +} diff --git a/fuzz/README.md b/fuzz/README.md index acadb4c..2a71573 100644 --- a/fuzz/README.md +++ b/fuzz/README.md @@ -1,16 +1,18 @@ # Bounded validation campaigns -These opt-in mutation targets use the project's Rust APIs directly. They do not -require libFuzzer, an external assembler, network access or a native backend. +These mutation targets call the project APIs. With the selected Wave archives, +IR/AST/assembler/bytecode algorithms execute in Wave; Rust owns the harness. +Build the archives as described in [CONTRIBUTING.md](../CONTRIBUTING.md). +Missing Wave modules fail explicitly; `rust-reference` is a separate comparison build. A fixed seed and case count make each campaign reproducible; the normal Rust suite also exercises every retained seed and small deterministic mutations. ```sh -cargo build --locked --all-features --examples +cargo build --locked --features socket-cli --examples python3 tools/fuzz_smoke.py --binary target/debug/examples/fuzz_boundaries --cases 512 --seed 1464353100 ``` -Each target is independently visible (`assembler`, `object`, `ir`, `ast`). The runner +Targets are independently selected: `assembler`, `object`, `ir`, `ast`, `bytecode`. The runner rejects an empty corpus or a corpus with no valid seed. Arguments cap runs at 100,000 mutations; the Python wrapper bounds each process to 60 seconds by default, with a Linux RLIMIT_AS ceiling of 512 MiB (`--memory-mib`). Inputs and seed/replay reads are capped at 8192 bytes. Assembler output @@ -26,7 +28,10 @@ Seed cases retain malformed syntax, numeric overflow, huge reservations, sparse IR identities, unknown versions, nested aggregates, strict JSON and exact-width float/call inputs. Mutations are byte insertion/deletion/repetition/bit flips and boundary-token injection. Library rejections are expected outcomes; a panic is -a failure. The original failing bytes and replay command are saved before at +a failure. Before every native call, one immutable current input and an atomic +JSON replay manifest are published; SIGSEGV, abort and timeout evidence therefore +survives outside Rust panic handling. On panic, the original failing bytes and +replay command are saved before at most 256 deletion-minimization attempts or five seconds of reduction. Both the original and minimized bytes are written under `WHALE_FUZZ_ARTIFACT_DIR` (default `/tmp/whale-fuzz` for direct runs, or @@ -34,7 +39,7 @@ original and minimized bytes are written under exact replay command: ```sh -cargo run --locked --features socket-cli --example fuzz_boundaries -- ir --replay /path/to/ir-SEED-CASE.crash +target/debug/examples/fuzz_boundaries ir --replay /path/to/ir-SEED-CASE.original ``` The byte/token model for tracked memory is independent of production access and @@ -102,7 +107,11 @@ relocations/tables, sparse BSS and conceptual NOBITS offsets beyond EOF. The reader bounds sections, symbols, relocations, payload, copied/inspected strings and work; BSS stays sparse. -CI runs all four targets on pull requests. `fuzz.yml` also gives assembler and -object separate jobs, with weekly scheduled campaigns of 50,000 cases each, +Bytecode inputs use the bounded Wave loader/verifier with 64 KiB decoded bytes, +4096 records, depth 32, 131072 work and 4 MiB workspace. Independent O0/O2 bytecode +checkers also retain original inputs and literal replay argument arrays. + +CI runs all five targets on pull requests. `fuzz.yml` gives them separate jobs, +with weekly scheduled campaigns of 50,000 cases each, 300-second process deadlines and 512 MiB address-space limits. Logs, originals, minimized inputs and exact replay commands are retained as artifacts. diff --git a/fuzz/corpus/bytecode/empty.wbc b/fuzz/corpus/bytecode/empty.wbc new file mode 100644 index 0000000000000000000000000000000000000000..b9ada89ddd8d1d904d708f3bd3aeecc96ce2e983 GIT binary patch literal 576 zcmaiwISzm@3_oSS{@{PZ8tItgb0 literal 0 HcmV?d00001 diff --git a/fuzz/corpus/bytecode/invalid_count_overflow.wbc b/fuzz/corpus/bytecode/invalid_count_overflow.wbc new file mode 100644 index 0000000000000000000000000000000000000000..ba0b66e7acf7399bef406622683e8a22f02a71b0 GIT binary patch literal 1216 zcmb`GI|>3Z7=+{d{lF6}R*NUFTou8>-Yo?$VCfM&lBGwn^cGs|e1ZcZ2&NhSe`YfO zCfUPowcoBcp%$v;cyCtysd%8Mf9t7VTDgRhg@@_8;v2%J@um8T4~2xxmx*r)kK)O@ zs^1o#*+@0{9pl*_9=w>pkgq3%CqGlaFT9zb^BhEY<`_nJ{G$lJRDT@dbM+_2lgoFL z!#j{Xz*DD?b57~VPw8e6f%~b+=e@ZdU8?Uo?$3R^1H1Omf9CpM>xCJ7E~CTT8m{NR UHQC=wa=8ybzmpQ3$H$!L-ug8t?*IS* literal 0 HcmV?d00001 diff --git a/fuzz/corpus/bytecode/invalid_phi_duplicate_edge.wbc b/fuzz/corpus/bytecode/invalid_phi_duplicate_edge.wbc new file mode 100644 index 0000000000000000000000000000000000000000..68b4d0fb3a18dbba9305aeabcae85c81b41d4814 GIT binary patch literal 2248 zcmd7SxlIH?5CzcTz7JvGGQwJe05BI2(i->>03IR-OhVaECJaI#12FbKgOXYUi-Z{G zZ`J>Gc5mO$uI_HHZ@QIk@l_nQ7yje$V7mHM&t8vU5{#^S%MW(ac5BhSmwXTL%QuUV z-G|=@4&k?AzXmshFCpmFr=RDC{CGGJCf_u;6U3AC@$Uxb62-R9y$0_b_8YwTg9d*Y z|6zll#D7%yI=?#ZLF8Q-hr5aP(iDU+_n7XaA#lIY^6~4#y`zKXXNzz7>6|kgig(V{ zuP^6}*B{$LXQ%5&Bt;;LE}4OCv<8eiY3 Y=Ms-^#n*T2B0}}?HU2Sm^sBD;Pd?04?EnA( literal 0 HcmV?d00001 diff --git a/fuzz/corpus/bytecode/phi_diamond.wbc b/fuzz/corpus/bytecode/phi_diamond.wbc new file mode 100644 index 0000000000000000000000000000000000000000..45322b96383df5e74b4ca9315599a4dc6869bd16 GIT binary patch literal 2248 zcmd7SxlIH?5CzcTz7JvGGQwJe05BI2(i->>03IR-OhVaECJaI#12FbKgOXYUi-Z{G zZ`J>Gc5mO$uI_HHZ@QIk@l_nQ7yje$V7mHM&t8vU5{#^S%MW(ac5BhSmwXTL%QuUV z-G|=@4&k?AzXmshFCpmFr=RDC{CGGJCf_u;6U3AC@$Uxb62-R9y$0_b_8YwTg9d*Y z|6zll#D7%yI=?#ZLF8Q-hr5aP(iDU+_n7XaA#lIY^6~4#y`zKXXNzz7>6|kgig(V{ zuP^6}*B{$LXQ%5&Bt;3Z7=+{d{lF6}R*NUFTou8>-Yo?$VCfM&lBGwn^cGs|e1ZcZ2&NhSe`YfO zCfUPowcoBcp%$v;cyCtysd%8Mf9t6w54nVrg@@_8;v2%J@um9gS4hZwnfR9QD4x8l z`fcHvjZ~B0F`oV5!Hf9|`FcWl@-y}O!khUy&q0J|j$wqyKZ@{6^~VuDSASwWxqLS{ zyaUMtJaq~==ai28lx`LgxSyJQ-kaOerTVVp{@lkquxtPPXRiOXUYNn>GCIty;rf@B U$^KrF%YFFyos{T2KITOC2FXky`v3p{ literal 0 HcmV?d00001 diff --git a/fuzz/support.rs b/fuzz/support.rs index 86749aa..567e8e9 100644 --- a/fuzz/support.rs +++ b/fuzz/support.rs @@ -10,6 +10,7 @@ pub enum Target { Ir, Ast, Object, + Bytecode, } impl Target { @@ -19,6 +20,7 @@ impl Target { "ir" => Some(Self::Ir), "ast" => Some(Self::Ast), "object" => Some(Self::Object), + "bytecode" => Some(Self::Bytecode), _ => None, } } @@ -29,6 +31,7 @@ impl Target { Self::Ir => "ir", Self::Ast => "ast", Self::Object => "object", + Self::Bytecode => "bytecode", } } } @@ -53,11 +56,36 @@ pub fn check(target: Target, bytes: &[u8]) -> bool { if matches!(target, Target::Object) { return check_object(bytes); } + if matches!(target, Target::Bytecode) { + let limits = ir::bytecode::BytecodeLimits { + max_input_bytes: MAX_INPUT as u64, + max_decoded_bytes: 65536, + max_records: 4096, + max_work: 131072, + max_type_depth: 32, + max_workspace_bytes: 4 * 1024 * 1024, + }; + return match ir::bytecode::verify_bytes(bytes, limits) { + Ok(info) => { + assert!(info.decoded_bytes <= limits.max_decoded_bytes); + true + }, + Err(ir::bytecode::BytecodeError::Backend(reason)) => { + panic!("bytecode transport: {reason}") + }, + Err(ir::bytecode::BytecodeError::Unavailable) => { + panic!("bytecode requires the Wave IR module") + }, + Err(_) => false, + }; + } let Ok(source) = std::str::from_utf8(bytes) else { return false; }; match target { - Target::Object => unreachable!("binary target handled before UTF-8 conversion"), + Target::Object | Target::Bytecode => { + unreachable!("binary target handled before UTF-8 conversion") + }, #[cfg(not(feature = "asm-amd64"))] Target::Assembler => false, #[cfg(feature = "asm-amd64")] diff --git a/ir/Cargo.toml b/ir/Cargo.toml index 884faed..540a7df 100644 --- a/ir/Cargo.toml +++ b/ir/Cargo.toml @@ -6,6 +6,7 @@ rust-version.workspace = true [features] default = [] +rust-reference = [] socket = ["dep:serde", "dep:serde_json"] [dependencies] diff --git a/ir/build.rs b/ir/build.rs index 9131468..14b2e81 100644 --- a/ir/build.rs +++ b/ir/build.rs @@ -91,6 +91,9 @@ const ABI_SOURCES: &[&str] = &[ "src/printer_wave.rs", "src/verifier/wave_cfg.rs", "src/verifier/wave_shape.rs", + "src/lib.rs", + "src/function.rs", + "src/global_storage.rs", ]; fn update(hash: u64, bytes: &[u8]) -> u64 { @@ -123,7 +126,12 @@ fn hash_file(path: &std::path::Path, maximum: Option) -> String { fn main() { println!("cargo:rustc-check-cfg=cfg(whale_wave_ir)"); println!("cargo:rerun-if-env-changed=WHALE_WAVE_IR_DIR"); - let Some(directory) = env::var_os("WHALE_WAVE_IR_DIR") else { return }; + println!("cargo:rerun-if-env-changed=CARGO_FEATURE_RUST_REFERENCE"); + let Some(directory) = env::var_os("WHALE_WAVE_IR_DIR") else { + assert!(env::var_os("CARGO_FEATURE_RUST_REFERENCE").is_some(), + "IR requires its Wave module; build with Meson or select rust-reference explicitly for comparison"); + return; + }; let directory = PathBuf::from(directory).canonicalize().expect("WHALE_WAVE_IR_DIR must exist"); let target = env::var("TARGET").expect("Cargo target required"); let archive = directory.join(if target.contains("msvc") { diff --git a/ir/bytecode_loader.wave b/ir/bytecode_loader.wave index 463cabb..621620d 100644 --- a/ir/bytecode_loader.wave +++ b/ir/bytecode_loader.wave @@ -55,6 +55,9 @@ fun ir_bytecode_sizes(counts: ptr, limits: ptr, count: u64, export(c) fun whale_ir_bytecode_load(data: ptr, count: u64, program: ptr, scratch: ptr, capacity: u64, limits: ptr, result: ptr) -> i32 { - var status: i32 = whale_ir_bytecode_probe(data, count, limits, result); + // Reuse loop storage at O0; file-controlled iterations must not grow the stack. + var status: i32; + var counts: ptr; + var table: u64; + var offset: u64; + var records: u64; + var i: u64; + var stride: u64; + var destination: ptr; + var native_words: u64; + var word: u64; + var inst: ptr; + var fields: ptr; + var file_word: u64; + var global: ptr; + + status = whale_ir_bytecode_probe(data, count, limits, result); if (status != 0) { return status; } if (program == null || !ir_span_valid(scratch as ptr, capacity, 8)) { ir_bytecode_fail(result, 4, 1, 0, 0); @@ -121,8 +140,8 @@ export(c) fun whale_ir_bytecode_load(data: ptr, count: u64, ir_bytecode_fail(result, 2, 4, 0, capacity); return result.status as i32; } - var counts: ptr = &result.counts as ptr; - var table: u64 = 1; + counts = &result.counts as ptr; + table = 1; while (table <= 16) { if (ir_bytecode_count(program, table) != counts[table - 1] || !ir_span_valid(ir_bytecode_data(program, table), counts[table - 1], @@ -134,9 +153,9 @@ export(c) fun whale_ir_bytecode_load(data: ptr, count: u64, } table = 1; while (table <= 16) { - var offset: u64 = ir_bytecode_read(data, 64 + (table - 1) * 32 + 8); - var records: u64 = counts[table - 1]; - var i: u64 = 0; + offset = ir_bytecode_read(data, 64 + (table - 1) * 32 + 8); + records = counts[table - 1]; + i = 0; if (table == 11) { if (!ir_bytecode_charge(result, limits, records)) { return result.status as i32; } while (i < records) { @@ -147,20 +166,20 @@ export(c) fun whale_ir_bytecode_load(data: ptr, count: u64, while (i < records) { result.table = table; result.index = i; - var stride: u64 = ir_bytecode_stride(table); + stride = ir_bytecode_stride(table); if (!ir_bytecode_charge(result, limits, stride)) { return result.status as i32; } - var destination: ptr = ir_bytecode_data(program, table) as ptr; - var native_words: u64 = ir_bytecode_native_stride(table) / 8; - var word: u64 = 0; + destination = ir_bytecode_data(program, table) as ptr; + native_words = ir_bytecode_native_stride(table) / 8; + word = 0; while (word < native_words) { destination[i * native_words + word] = 0; word += 1; } if (table == 5) { - var inst: ptr = &program.instructions[i]; - var fields: ptr = inst as ptr; + inst = &program.instructions[i]; + fields = inst as ptr; word = 0; - var file_word: u64 = 0; + file_word = 0; while (word < 21) { if (word != 9 && word != 10 && word != 19 && word != 20) { fields[word] = ir_bytecode_read(data, offset + i * stride + file_word * 8); @@ -169,7 +188,7 @@ export(c) fun whale_ir_bytecode_load(data: ptr, count: u64, word += 1; } } else if (table == 8) { - var global: ptr = &program.globals[i]; + global = &program.globals[i]; global.id = ir_bytecode_read(data, offset + i * stride); global.ty = ir_bytecode_read(data, offset + i * stride + 8); global.align = ir_bytecode_read(data, offset + i * stride + 16); diff --git a/ir/bytecode_model.wave b/ir/bytecode_model.wave index cd2b0c5..2f597fa 100644 --- a/ir/bytecode_model.wave +++ b/ir/bytecode_model.wave @@ -89,6 +89,7 @@ struct IrBytecodeResult { work: u64; decoded_bytes: u64; scratch_words: u64; + estimated_workspace_bytes: u64; counts: IrBytecodeCounts; } @@ -113,7 +114,7 @@ fun ir_bytecode_charge(result: ptr, limits: ptr) { var words: ptr = result as ptr; var i: u64 = 0; - while (i < 23) { + while (i < 24) { words[i] = 0; i += 1; } diff --git a/ir/bytecode_verify.wave b/ir/bytecode_verify.wave index 0cd2d12..a1ddece 100644 --- a/ir/bytecode_verify.wave +++ b/ir/bytecode_verify.wave @@ -286,7 +286,7 @@ fun ir_bytecode_verify_impl(program: ptr, words: ptr, ca scratch.used = 0; var context: IrBytecodeVerifier; context.program = program; - context.owned_bytes = program.text_byte_count; + context.owned_bytes = 0; context.limits = limits; context.result = result; context.scratch = &scratch; @@ -295,7 +295,8 @@ fun ir_bytecode_verify_impl(program: ptr, words: ptr, ca context.operand_capacity = program.operand_count + 3; context.operands = ir_bytecode_take(&scratch, context.operand_capacity * 5, result) as ptr; if (result.status != 0) { return result.status as i32; } - if (!ir_bytecode_verify_types(program, &scratch, limits, result) + if (!ir_bytecode_metadata(&context) + || !ir_bytecode_verify_types(program, &scratch, limits, result) || !ir_bytecode_layouts(&context)) { return result.status as i32; } var base: u64 = scratch.used; var total: u64 = program.function_count + program.block_count + program.value_type_count @@ -324,6 +325,8 @@ fun ir_bytecode_verify_impl(program: ptr, words: ptr, ca if (!ir_bytecode_verify_sources(&context) || !ir_bytecode_inventory(program, limits, result)) { return result.status as i32; } + result.estimated_workspace_bytes = result.decoded_bytes + result.scratch_words * 8 + + context.owned_bytes; result.table = 0; result.index = 0; return 0; diff --git a/ir/bytecode_verify_types.wave b/ir/bytecode_verify_types.wave index 8450bad..1ace6b7 100644 --- a/ir/bytecode_verify_types.wave +++ b/ir/bytecode_verify_types.wave @@ -69,11 +69,19 @@ fun ir_bytecode_value_type(program: ptr, ty: u64) -> bool { fun ir_bytecode_utf8(data: ptr, count: u64, limits: ptr, result: ptr) -> bool { + // Reuse loop storage at O0; file-controlled iterations must not grow the stack. + var i: u64; + var first: u64; + var width: u64; + var j: u64; + var octet: u64; + var second: u64; + if (!ir_bytecode_charge(result, limits, count)) { return false; } - var i: u64 = 0; + i = 0; while (i < count) { - var first: u64 = data[i] as u64; - var width: u64 = 1; + first = data[i] as u64; + width = 1; if (first >= 194 && first <= 223) { width = 2; } else if (first >= 224 && first <= 239) { width = 3; } else if (first >= 240 && first <= 244) { width = 4; } @@ -81,14 +89,14 @@ fun ir_bytecode_utf8(data: ptr, count: u64, return ir_bytecode_fail(result, 1, 31, 11, i); } if (width > count - i) { return ir_bytecode_fail(result, 1, 31, 11, i); } - var j: u64 = 1; + j = 1; while (j < width) { - var octet: u64 = data[i + j] as u64; + octet = data[i + j] as u64; if (octet < 128 || octet > 191) { return ir_bytecode_fail(result, 1, 31, 11, i); } j += 1; } if (width >= 3) { - var second: u64 = data[i + 1] as u64; + second = data[i + 1] as u64; if ((first == 224 && second < 160) || (first == 237 && second >= 160) || (first == 240 && second < 144) || (first == 244 && second >= 144)) { return ir_bytecode_fail(result, 1, 31, 11, i); @@ -101,23 +109,35 @@ fun ir_bytecode_utf8(data: ptr, count: u64, fun ir_bytecode_verify_types(program: ptr, scratch: ptr, limits: ptr, result: ptr) -> bool { + // Reuse loop storage at O0; file-controlled iterations must not grow the stack. + var semantic: IrVerifyResult; + var valid: bool; + var depths: ptr; + var i: u64; + var node: ptr; + var depth: u64; + var child: u64; + var next: u64; + var text_cursor: u64; + var text: ptr; + result.table = 1; if (limits.max_type_depth == 0 || limits.max_type_depth > 1024) { return ir_bytecode_fail(result, 1, 10, 1, 0); } - var semantic: IrVerifyResult; + ir_bytecode_semantic_init(&semantic); - var valid: bool = ir_verify_graph_valid(program.types, program.type_count, program.edges, + valid = ir_verify_graph_valid(program.types, program.type_count, program.edges, program.edge_count, limits.max_work - result.work, &semantic); if (!ir_bytecode_semantic(result, limits, &semantic, valid)) { return false; } - var depths: ptr = ir_bytecode_take(scratch, program.type_count, result); + depths = ir_bytecode_take(scratch, program.type_count, result); if (result.status != 0) { return false; } - var i: u64 = 0; + i = 0; while (i < program.type_count) { result.index = i; if (!ir_bytecode_charge(result, limits, 1)) { return false; } - var node: ptr = &program.types[i]; - var depth: u64 = 1; + node = &program.types[i]; + depth = 1; if (node.kind <= 16) { if (node.child != 0 || node.first != 0 || node.count != 0 || node.extra != 0) { return ir_bytecode_fail(result, 1, 11, 1, i); @@ -132,10 +152,10 @@ fun ir_bytecode_verify_types(program: ptr, scratch: ptr 3))) { return ir_bytecode_fail(result, 1, 11, 1, i); } - var child: u64 = 0; + child = 0; while (child < node.count) { if (!ir_bytecode_charge(result, limits, 1)) { return false; } - var next: u64 = depths[program.edges[node.first + child]] + 1; + next = depths[program.edges[node.first + child]] + 1; if (next > depth) { depth = next; } child += 1; } @@ -159,10 +179,10 @@ fun ir_bytecode_verify_types(program: ptr, scratch: ptr = &program.texts[i]; + text = &program.texts[i]; if (text.first != text_cursor || text.first > program.text_byte_count || text.count > program.text_byte_count - text.first) { return ir_bytecode_fail(result, 1, 30, 10, i); } @@ -203,32 +223,79 @@ struct IrBytecodeVerifier { owned_bytes: u64; } +fun ir_bytecode_owned(context: ptr, amount: u64) -> bool { + var available: u64 = context.limits.max_workspace_bytes + - context.result.decoded_bytes - context.result.scratch_words * 8; + if (context.owned_bytes > available || amount > available - context.owned_bytes) { + return ir_bytecode_fail(context.result, 2, 6, context.result.table, context.result.index); + } + context.owned_bytes += amount; + return true; +} + +fun ir_bytecode_metadata(context: ptr) -> bool { + if (!ir_bytecode_owned(context, context.program.text_byte_count)) { return false; } + var table: u64 = 9; + while (table <= 16) { + var allowance: u64 = 0; + if (table == 9) { allowance = 64; } + if (table == 10) { allowance = 32; } + if (table == 12 || table == 13 || table == 14) { allowance = 96; } + if (table == 16) { allowance = 16; } + var count: u64 = ir_bytecode_count(context.program, table); + if (allowance != 0) { + if (count > context.limits.max_workspace_bytes / allowance) { + return ir_bytecode_fail(context.result, 2, 6, table, count); + } + if (!ir_bytecode_owned(context, count * allowance)) { return false; } + } + table += 1; + } + return true; +} + fun ir_bytecode_layouts(context: ptr) -> bool { - var program: ptr = context.program; - var limits: ptr = context.limits; - var result: ptr = context.result; - var total: u64 = 0; - var remaining: u64 = limits.max_workspace_bytes - result.decoded_bytes - result.scratch_words * 8; + // Reuse loop storage at O0; file-controlled iterations must not grow the stack. + var program: ptr; + var limits: ptr; + var result: ptr; + var total: u64; + var remaining: u64; + var i: u64; + var node: ptr; + var info: ptr; + var width: u64; + var child: ptr; + var j: u64; + var aligned: u64; + var signature: u64; + var expanded: u64; + + program = context.program; + limits = context.limits; + result = context.result; + total = 0; + remaining = limits.max_workspace_bytes - result.decoded_bytes - result.scratch_words * 8; if (context.owned_bytes > remaining) { return ir_bytecode_fail(result, 2, 6, 11, 0); } remaining -= context.owned_bytes; - var i: u64 = 0; + i = 0; while (i < program.type_count) { if (!ir_bytecode_charge(result, limits, 1)) { return false; } - var node: ptr = &program.types[i]; - var info: ptr = &context.types[i]; + node = &program.types[i]; + info = &context.types[i]; info.size = 0; info.align = 1; info.depth = 1; info.expanded = 1; info.storable = 0; - var width: u64 = ir_verify_width(node.kind); + width = ir_verify_width(node.kind); if (node.kind >= 1 && node.kind <= 16) { info.size = width / 8; if (node.kind == 1 || width == 1) { info.size = 1; } info.align = info.size; info.storable = 1; } else if (node.kind == 17 || node.kind == 19) { - var child: ptr = &context.types[node.child]; + child = &context.types[node.child]; info.depth = child.depth + 1; info.expanded += child.expanded; if (node.kind == 17) { @@ -243,10 +310,10 @@ fun ir_bytecode_layouts(context: ptr) -> bool { } } else if (node.kind >= 18) { info.storable = 1; - var j: u64 = 0; + j = 0; while (j < node.count) { if (!ir_bytecode_charge(result, limits, 1)) { return false; } - var child: ptr = &context.types[program.edges[node.first + j]]; + child = &context.types[program.edges[node.first + j]]; if (child.expanded > remaining / 512 || info.expanded > remaining / 512 - child.expanded) { return ir_bytecode_fail(result, 2, 6, 1, i); @@ -255,7 +322,7 @@ fun ir_bytecode_layouts(context: ptr) -> bool { if (child.depth + 1 > info.depth) { info.depth = child.depth + 1; } if (node.kind != 18) { if (child.storable == 0) { info.storable = 0; } - var aligned: u64 = 0; + aligned = 0; if (!ir_align_up(info.size, child.align, &aligned) || child.size > 18446744073709551615 - aligned) { info.storable = 0; @@ -270,7 +337,7 @@ fun ir_bytecode_layouts(context: ptr) -> bool { info.size = 8; info.align = 8; } else { - var aligned: u64 = 0; + aligned = 0; if (!ir_align_up(info.size, info.align, &aligned)) { info.storable = 0; } info.size = aligned; } @@ -284,9 +351,9 @@ fun ir_bytecode_layouts(context: ptr) -> bool { i = 0; while (i < program.function_count) { if (!ir_bytecode_charge(result, limits, 1)) { return false; } - var signature: u64 = program.functions[i].signature; + signature = program.functions[i].signature; if (signature >= program.type_count) { return ir_bytecode_fail(result, 1, 80, 3, i); } - var expanded: u64 = context.types[signature].expanded; + expanded = context.types[signature].expanded; if (expanded > remaining / 512 || total > remaining / 512 - expanded) { return ir_bytecode_fail(result, 2, 6, 3, i); } diff --git a/ir/entry.wave b/ir/entry.wave index 6330716..2b65df3 100644 --- a/ir/entry.wave +++ b/ir/entry.wave @@ -61,3 +61,8 @@ export(c) fun whale_ir_layout(storage: ptr, nodes: ptr, n result.index = root; return 0; } + +// Distinct compiled identity used by product composition checks. +export(c) fun whale_ir_module_identity() -> u64 { + return 6289348675458650625; +} diff --git a/ir/examples/bytecode_workspace_probe.rs b/ir/examples/bytecode_workspace_probe.rs new file mode 100644 index 0000000..4c154b1 --- /dev/null +++ b/ir/examples/bytecode_workspace_probe.rs @@ -0,0 +1,127 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Count live allocation requests around admission, including rejected arguments. +use ir::{bytecode::*, *}; + +use std::alloc::{GlobalAlloc, Layout, System}; + +use std::sync::atomic::{AtomicUsize, Ordering}; + +struct Counted; + +static LIVE: AtomicUsize = AtomicUsize::new(0); + +static PEAK: AtomicUsize = AtomicUsize::new(0); + +fn allocated(bytes: usize) { + let live = LIVE.fetch_add(bytes, Ordering::SeqCst) + bytes; + PEAK.fetch_max(live, Ordering::SeqCst); +} + +unsafe impl GlobalAlloc for Counted { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + // Forward the identical allocation request to the system allocator. + let pointer = unsafe { System.alloc(layout) }; + if !pointer.is_null() { + allocated(layout.size()); + } + pointer + } + + unsafe fn dealloc(&self, pointer: *mut u8, layout: Layout) { + LIVE.fetch_sub(layout.size(), Ordering::SeqCst); + // The pointer and layout are the original allocation's pair. + unsafe { + System.dealloc(pointer, layout); + } + } + + unsafe fn realloc(&self, pointer: *mut u8, layout: Layout, size: usize) -> *mut u8 { + // Preserve the system allocator's failure and ownership contract. + let next = unsafe { System.realloc(pointer, layout, size) }; + if !next.is_null() { + LIVE.fetch_sub(layout.size(), Ordering::SeqCst); + allocated(size); + } + next + } +} + +#[global_allocator] +static ALLOCATOR: Counted = Counted; + +fn image(shared_text: bool) -> Vec { + let expected = FunctionSignature::whale(vec![], Type::U64); + let mut builder = ModuleBuilder::new("whale-bytecode-v1", DataLayout::default_64bit_le()); + let mut function = builder.begin_function( + "entry", + vec![("callback".into(), Type::FnPtr(Box::new(expected)))], + Type::Void, + ); + function.ret(None); + function.finish(); + let mut module = builder.finish(); + module.functions[0].blocks[0].terminator = Some(Terminator::Trap { + reason: if shared_text { "x".repeat(2 * 1024 * 1024) } else { "probe".into() }, + }); + if shared_text { + module.sources.files.push(SourceFile { id: 0, name: "x".into() }); + module.sources.originals.push(OriginalNode { + id: 0, + span: Some(SourceSpan { file: 0, line: 1, column: 1, end_line: 1, end_column: 2 }), + }); + module.sources.mappings.push(SourceMapping { + target: SourceTarget::Terminator { + function: FunctionId(0), + block: module.functions[0].entry, + }, + original: 0, + }); + } + let mut bytes = compile(&module, BytecodeLimits::default()).unwrap(); + if shared_text { + // V1 permits a filename to reference an existing reason text. This + // independent wire mutation reproduces retained-string amplification. + let entry = 64 + 11 * 32; + let offset = u64::from_le_bytes(bytes[entry + 8..entry + 16].try_into().unwrap()) as usize; + assert_eq!(u64::from_le_bytes(bytes[entry + 16..entry + 24].try_into().unwrap()), 1); + bytes[offset + 8..offset + 16].copy_from_slice(&0_u64.to_le_bytes()); + } + bytes +} + +fn measure(shared_text: bool) { + let bytes = image(shared_text); + let argument = + BytecodeValue::null_function(FunctionSignature::whale(vec![Type::U64; 5000], Type::U64)) + .unwrap(); + let arguments = [argument]; + let limits = BytecodeLimits { max_workspace_bytes: 8 * 1024 * 1024, ..Default::default() }; + let baseline = LIVE.load(Ordering::SeqCst); + PEAK.store(baseline, Ordering::SeqCst); + let mut program = BytecodeProgram::load(&bytes, limits).unwrap(); + let loaded = LIVE.load(Ordering::SeqCst) - baseline; + let result = program.run_values(FunctionId(0), &arguments, InterpreterOptions::default()); + assert!(result.is_err()); + if shared_text { + assert!(matches!(result, Err(BytecodeError::Invalid { status: 2, .. }))); + } + let peak = PEAK.load(Ordering::SeqCst) - baseline; + drop(result); + let retained = LIVE.load(Ordering::SeqCst) - baseline; + assert!( + peak <= limits.max_workspace_bytes as usize, + "workspace {} < peak {peak}", + limits.max_workspace_bytes + ); + assert_eq!(retained, loaded, "rejected temporary types or scratch retained capacity"); + println!( + "shared_text={shared_text} limit={} loaded={loaded} peak={peak} retained={retained}", + limits.max_workspace_bytes + ); +} + +fn main() { + assert!(available(), "the workspace probe requires the actual Wave module"); + measure(true); + measure(false); +} diff --git a/ir/meson.build b/ir/meson.build index 20615c8..1930e87 100644 --- a/ir/meson.build +++ b/ir/meson.build @@ -19,6 +19,7 @@ if wave_ir_directory == '' and wave_source != '' output: [archive_name, 'wave-ir.meta', 'provenance.json'], command: [python, files('../tools/build_wave_ir.py'), arguments], depend_files: files( + 'src/lib.rs', 'model.wave', 'layout.wave', 'lexer.wave', @@ -103,6 +104,8 @@ if wave_ir_directory == '' and wave_source != '' 'src/printer_wave.rs', 'src/verifier/wave_cfg.rs', 'src/verifier/wave_shape.rs', + 'src/function.rs', + 'src/global_storage.rs', '../tools/build_wave_ir.py', '../tools/wave_bootstrap.py', ), diff --git a/ir/src/bytecode.rs b/ir/src/bytecode.rs index 3cc8740..37672d4 100644 --- a/ir/src/bytecode.rs +++ b/ir/src/bytecode.rs @@ -325,6 +325,7 @@ mod native { work: u64, decoded_bytes: u64, scratch_words: u64, + estimated_workspace_bytes: u64, counts: Counts }); #[repr(C)] @@ -417,6 +418,20 @@ mod native { { return Err(BytecodeError::Backend(BACKEND)); } + if status == 0 + && (result.estimated_workspace_bytes > limits.max_workspace_bytes + || result + .decoded_bytes + .checked_add( + result + .scratch_words + .checked_mul(8) + .ok_or(BytecodeError::Backend(BACKEND))?, + ) + .is_none_or(|base| base > result.estimated_workspace_bytes)) + { + return Err(BytecodeError::Backend(BACKEND)); + } if status != 0 { return Err(BytecodeError::Invalid { status: result.status, @@ -439,6 +454,7 @@ mod native { constant_globals: Vec, scratch: Vec, decoded_bytes: u64, + estimated_workspace_bytes: u64, } impl<'a> Owned<'a> { @@ -464,6 +480,7 @@ mod native { constant_globals: buffer(counts.constant_global_ids)?, scratch: Vec::new(), decoded_bytes: 0, + estimated_workspace_bytes: 0, }) } @@ -514,6 +531,29 @@ mod native { if status != 2 || result.status != 2 { return check(status, &result, limits); } + if result.scratch_words == 0 { + return check(status, &result, limits); + } + let previous_base = self + .decoded_bytes + .checked_add( + (self.scratch.len() as u64).checked_mul(8).ok_or(BytecodeError::Allocation)?, + ) + .ok_or(BytecodeError::Allocation)?; + let retained = self.estimated_workspace_bytes.saturating_sub(previous_base); + let preview = result + .estimated_workspace_bytes + .checked_add(retained) + .and_then(|n| n.checked_add(self.runtime.argument_spare_bytes())) + .ok_or(BytecodeError::Allocation)?; + if preview > limits.max_workspace_bytes { + return Err(BytecodeError::Invalid { + status: 2, + code: 4, + table: 0, + index: preview, + }); + } self.scratch = Vec::new(); self.scratch = buffer(result.scratch_words)?; let status = unsafe { @@ -527,6 +567,7 @@ mod native { }; check(status, &result, limits)?; self.decoded_bytes = result.decoded_bytes; + self.estimated_workspace_bytes = result.estimated_workspace_bytes; Ok(()) } @@ -690,15 +731,16 @@ mod native { where 'a: 'static, { - argument_preflight(arguments, limits, self.decoded_bytes, self.scratch.len())?; + argument_preflight(arguments, limits, self.estimated_workspace_bytes)?; let inputs = arguments .iter() .map(|value| (&value.value, value.origin == identity)) .collect::>(); - let original_types = self.runtime.types.len(); - let original_edges = self.runtime.edges.len(); + let checkpoint = self.runtime.argument_checkpoint(); + let original_estimate = self.estimated_workspace_bytes; let original_decoded = self.decoded_bytes; let original_scratch = self.scratch.len(); + let original_scratch_capacity = self.scratch.capacity(); let outcome = (|| -> Result> { let ids = self.runtime.prepare_argument_types(&inputs)?; self.verify(limits)?; @@ -723,9 +765,11 @@ mod native { ) .map_err(BytecodeError::from) })(); - self.runtime.rollback_argument_types(original_types, original_edges); + self.runtime.rollback_argument_types(checkpoint); self.decoded_bytes = original_decoded; + self.estimated_workspace_bytes = original_estimate; self.scratch.truncate(original_scratch); + self.scratch.shrink_to(original_scratch_capacity); let result = outcome?; Ok(BytecodeRunResult { value: result.value.map(|value| BytecodeValue { value, origin: identity }), @@ -756,7 +800,10 @@ mod native { }; check(status, &result, limits)?; native.decoded_bytes = result.decoded_bytes; + native.estimated_workspace_bytes = result.estimated_workspace_bytes; native.materialize()?; + // try_update is unavailable on our Rust 1.86 MSRV. + #[allow(deprecated)] let identity = NEXT_IDENTITY .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1)) .map_err(|_| BytecodeError::Backend("bytecode program identity exhausted"))?; @@ -766,8 +813,7 @@ mod native { fn argument_preflight( arguments: &[BytecodeValue], limits: BytecodeLimits, - decoded: u64, - scratch_words: usize, + estimated_workspace: u64, ) -> Result<()> { let limited = || BytecodeError::Invalid { status: 2, @@ -775,11 +821,8 @@ mod native { table: 0, index: limits.max_workspace_bytes, }; - let available = limits - .max_workspace_bytes - .checked_sub(decoded) - .and_then(|n| n.checked_sub((scratch_words as u64).checked_mul(8)?)) - .ok_or_else(limited)?; + let available = + limits.max_workspace_bytes.checked_sub(estimated_workspace).ok_or_else(limited)?; let nodes = (available / 1024).min(limits.max_records).min(limits.max_work / 16); let ir_limits = crate::IrLimits { max_nodes: usize::try_from(nodes) @@ -938,6 +981,7 @@ mod native { constant_globals: module.globals.iter().map(|global| u64::from(global.id.0)).collect(), scratch: Vec::new(), decoded_bytes: 0, + estimated_workspace_bytes: 0, }; owned.sites = owned .runtime @@ -1017,6 +1061,13 @@ mod native { if required > limits.max_input_bytes { return Err(BytecodeError::Backend(BACKEND)); } + if owned + .estimated_workspace_bytes + .checked_add(required) + .is_none_or(|peak| peak > limits.max_workspace_bytes) + { + return Err(BytecodeError::Invalid { status: 2, code: 4, table: 0, index: required }); + } let mut output = buffer(required)?; let status = unsafe { whale_ir_bytecode_write( diff --git a/ir/src/function.rs b/ir/src/function.rs index 8dd8c3b..1bc3011 100644 --- a/ir/src/function.rs +++ b/ir/src/function.rs @@ -112,6 +112,7 @@ pub enum CallError { ForbiddenFunctionPointerCast, } +#[cfg(any(not(whale_wave_ir), feature = "socket"))] pub(crate) fn validate_signature(sig: &FunctionSignature) -> Result<(), CallError> { validate_signature_with_limits(sig, crate::IrLimits::default()) } @@ -120,46 +121,53 @@ pub fn validate_signature_with_limits( sig: &FunctionSignature, limits: crate::IrLimits, ) -> Result<(), CallError> { - crate::limits::Budget::new(limits) - .and_then(|mut b| b.signature(sig)) - .map_err(CallError::ResourceLimit)?; - let invalid = || { - CallError::InvalidSignature( - "void parameters, malformed types and variadic calls are unsupported".into(), - ) - }; - let mut signatures = vec![sig]; - while let Some(sig) = signatures.pop() { - if sig.variadic { - return Err(invalid()); - } - if sig.convention == CallingConvention::SysV64 - && sig - .params - .iter() - .chain(std::iter::once(&sig.ret)) - .any(|t| matches!(t, Type::Array(..) | Type::Struct(..) | Type::Tuple(..))) - { - return Err(CallError::InvalidSignature( - "SysV64 aggregate signatures are unsupported".into(), - )); - } - let mut types: Vec<_> = sig.params.iter().collect(); - if sig.ret != Type::Void { - types.push(&sig.ret); - } - while let Some(ty) = types.pop() { - match ty { - Type::Void => return Err(invalid()), - Type::FnPtr(sig) => signatures.push(sig), - Type::Ptr(t) if **t == Type::Void => {}, - Type::Ptr(t) | Type::Array(t, _) => types.push(t), - Type::Struct(ts) | Type::Tuple(ts) => types.extend(ts), - _ => {}, + #[cfg(whale_wave_ir)] + { + crate::verifier::wave_semantics::validate_signature_boundary(sig, limits) + } + #[cfg(not(whale_wave_ir))] + { + crate::limits::Budget::new(limits) + .and_then(|mut b| b.signature(sig)) + .map_err(CallError::ResourceLimit)?; + let invalid = || { + CallError::InvalidSignature( + "void parameters, malformed types and variadic calls are unsupported".into(), + ) + }; + let mut signatures = vec![sig]; + while let Some(sig) = signatures.pop() { + if sig.variadic { + return Err(invalid()); + } + if sig.convention == CallingConvention::SysV64 + && sig + .params + .iter() + .chain(std::iter::once(&sig.ret)) + .any(|t| matches!(t, Type::Array(..) | Type::Struct(..) | Type::Tuple(..))) + { + return Err(CallError::InvalidSignature( + "SysV64 aggregate signatures are unsupported".into(), + )); + } + let mut types: Vec<_> = sig.params.iter().collect(); + if sig.ret != Type::Void { + types.push(&sig.ret); + } + while let Some(ty) = types.pop() { + match ty { + Type::Void => return Err(invalid()), + Type::FnPtr(sig) => signatures.push(sig), + Type::Ptr(t) if **t == Type::Void => {}, + Type::Ptr(t) | Type::Array(t, _) => types.push(t), + Type::Struct(ts) | Type::Tuple(ts) => types.extend(ts), + _ => {}, + } } } + Ok(()) } - Ok(()) } #[cfg(any(not(whale_wave_ir), test))] diff --git a/ir/src/global_storage.rs b/ir/src/global_storage.rs index 92b50f3..e741d5e 100644 --- a/ir/src/global_storage.rs +++ b/ir/src/global_storage.rs @@ -43,58 +43,67 @@ impl GlobalStorage { } pub fn validate_with_limits(&self, limits: IrLimits) -> Result<(), GlobalStorageError> { - crate::limits::Budget::new(limits) - .and_then(|mut b| b.ty(&self.ty)) - .map_err(GlobalStorageError::ResourceLimit)?; - if !matches!( - self.ty, - Type::Bool - | Type::I1 - | Type::U1 - | Type::I8 - | Type::U8 - | Type::I16 - | Type::U16 - | Type::I32 - | Type::U32 - | Type::I64 - | Type::U64 - | Type::I128 - | Type::U128 - | Type::F16 - | Type::F32 - | Type::F64 - | Type::Ptr(_) - | Type::FnPtr(_) - ) { - return Err(GlobalStorageError::InvalidType); + #[cfg(whale_wave_ir)] + { + crate::verifier::wave_semantics::validate_global_boundary(self, limits) } - crate::function::validate_signature_with_limits( - &crate::FunctionSignature::whale(vec![self.ty.clone()], Type::Void), - limits, - ) - .map_err(|error| match error { - crate::CallError::ResourceLimit(error) => GlobalStorageError::ResourceLimit(error), - _ => GlobalStorageError::InvalidType, - })?; - if !self.align.is_power_of_two() { - return Err(GlobalStorageError::InvalidAlignment); - } - match &self.init { - GlobalStorageInit::Value(value) - if !crate::constant::valid_constant(&self.ty, value) => - { - return Err(GlobalStorageError::InvalidInitializer) - }, - GlobalStorageInit::Uninitialized if self.readonly => { - return Err(GlobalStorageError::ReadOnlyUninitialized) - }, - _ => {}, - } - match (&self.linkage, &self.link_name) { - (Linkage::Internal, None) => Ok(()), - (Linkage::External, Some(name)) if !name.is_empty() && !name.contains('\0') => Ok(()), - _ => Err(GlobalStorageError::InvalidLinkName), + #[cfg(not(whale_wave_ir))] + { + crate::limits::Budget::new(limits) + .and_then(|mut b| b.ty(&self.ty)) + .map_err(GlobalStorageError::ResourceLimit)?; + if !matches!( + self.ty, + Type::Bool + | Type::I1 + | Type::U1 + | Type::I8 + | Type::U8 + | Type::I16 + | Type::U16 + | Type::I32 + | Type::U32 + | Type::I64 + | Type::U64 + | Type::I128 + | Type::U128 + | Type::F16 + | Type::F32 + | Type::F64 + | Type::Ptr(_) + | Type::FnPtr(_) + ) { + return Err(GlobalStorageError::InvalidType); + } + crate::function::validate_signature_with_limits( + &crate::FunctionSignature::whale(vec![self.ty.clone()], Type::Void), + limits, + ) + .map_err(|error| match error { + crate::CallError::ResourceLimit(error) => GlobalStorageError::ResourceLimit(error), + _ => GlobalStorageError::InvalidType, + })?; + if !self.align.is_power_of_two() { + return Err(GlobalStorageError::InvalidAlignment); + } + match &self.init { + GlobalStorageInit::Value(value) + if !crate::constant::valid_constant(&self.ty, value) => + { + return Err(GlobalStorageError::InvalidInitializer) + }, + GlobalStorageInit::Uninitialized if self.readonly => { + return Err(GlobalStorageError::ReadOnlyUninitialized) + }, + _ => {}, + } + match (&self.linkage, &self.link_name) { + (Linkage::Internal, None) => Ok(()), + (Linkage::External, Some(name)) if !name.is_empty() && !name.contains('\0') => { + Ok(()) + }, + _ => Err(GlobalStorageError::InvalidLinkName), + } } } } diff --git a/ir/src/interpreter/runtime_wave.rs b/ir/src/interpreter/runtime_wave.rs index e0bd8af..619351a 100644 --- a/ir/src/interpreter/runtime_wave.rs +++ b/ir/src/interpreter/runtime_wave.rs @@ -353,6 +353,15 @@ enum TypeView<'a> { Signature(&'a FunctionSignature), } +pub(crate) struct ArgumentCheckpoint { + types: usize, + edges: usize, + type_capacity: usize, + edge_capacity: usize, + cache_capacity: usize, + signature_capacity: usize, +} + pub(crate) struct Program<'a> { module: Option<&'a Module>, pub(crate) sources: SourceMetadata, @@ -1265,11 +1274,31 @@ impl Program<'_> { Ok(ids) } - pub(crate) fn rollback_argument_types(&mut self, types: usize, edges: usize) { - self.types.truncate(types); - self.edges.truncate(edges); - self.cached_types.retain(|id, _| *id < types as u64); - self.signature_arcs.retain(|id, _| *id < types as u64); + pub(crate) fn argument_checkpoint(&self) -> ArgumentCheckpoint { + ArgumentCheckpoint { + types: self.types.len(), + edges: self.edges.len(), + type_capacity: self.types.capacity(), + edge_capacity: self.edges.capacity(), + cache_capacity: self.cached_types.capacity(), + signature_capacity: self.signature_arcs.capacity(), + } + } + + pub(crate) fn argument_spare_bytes(&self) -> u64 { + ((self.types.capacity() - self.types.len()) as u64) * 40 + + ((self.edges.capacity() - self.edges.len()) as u64) * 8 + } + + pub(crate) fn rollback_argument_types(&mut self, checkpoint: ArgumentCheckpoint) { + self.types.truncate(checkpoint.types); + self.edges.truncate(checkpoint.edges); + self.cached_types.retain(|id, _| *id < checkpoint.types as u64); + self.signature_arcs.retain(|id, _| *id < checkpoint.types as u64); + self.types.shrink_to(checkpoint.type_capacity); + self.edges.shrink_to(checkpoint.edge_capacity); + self.cached_types.shrink_to(checkpoint.cache_capacity); + self.signature_arcs.shrink_to(checkpoint.signature_capacity); } pub(crate) fn function_record(&self, id: FunctionId) -> Option<&RawFunction> { @@ -1296,12 +1325,18 @@ impl Program<'_> { /// Materialize verified structural type records for the typed memory adapter. /// The loader has already bounded depth and expanded metadata size. pub(crate) fn materialize_types(&mut self) -> Result<()> { - map_reserve(&mut self.cached_types, self.types.len())?; - map_reserve(&mut self.declaration_ids, self.functions.len())?; - for (index, function) in self.functions.iter().enumerate() { - self.declaration_ids.insert(FunctionId(function.id as u32), index as u64); + let missing = self.types.len().saturating_sub(self.cached_types.len()); + map_reserve(&mut self.cached_types, missing)?; + if self.declaration_ids.is_empty() { + map_reserve(&mut self.declaration_ids, self.functions.len())?; + for (index, function) in self.functions.iter().enumerate() { + self.declaration_ids.insert(FunctionId(function.id as u32), index as u64); + } } for (index, raw) in self.types.iter().enumerate() { + if self.cached_types.contains_key(&(index as u64)) { + continue; + } let child = |id: u64| self.cached_types.get(&id).cloned().ok_or_else(|| backend(None)); let fields = || -> Result> { let first = usize::try_from(raw.first).map_err(|_| backend(None))?; diff --git a/ir/src/lib.rs b/ir/src/lib.rs index c7473a7..e90e92b 100644 --- a/ir/src/lib.rs +++ b/ir/src/lib.rs @@ -413,3 +413,34 @@ pub use parser::{ }; mod diagnostic; + +/// The implementation actually selected by this owning module. +pub fn module_identity() -> &'static str { + #[cfg(whale_wave_ir)] + { + unsafe extern "C" { + fn whale_ir_module_identity() -> u64; + } + // This no-argument stamp is exported by this module's guarded archive. + if unsafe { whale_ir_module_identity() } == 6289348675458650625 { + "wave" + } else { + "invalid-wave" + } + } + #[cfg(not(whale_wave_ir))] + { + "rust-reference" + } +} + +#[cfg(test)] +mod implementation_identity_tests { + #[test] + fn selected_implementation_has_its_own_compiled_identity() { + assert_eq!( + super::module_identity(), + if cfg!(whale_wave_ir) { "wave" } else { "rust-reference" } + ); + } +} diff --git a/ir/src/verifier/wave_semantics.rs b/ir/src/verifier/wave_semantics.rs index c63812c..d66bee0 100644 --- a/ir/src/verifier/wave_semantics.rs +++ b/ir/src/verifier/wave_semantics.rs @@ -584,7 +584,7 @@ pub(super) fn return_value( } } -pub(super) fn global_storage( +fn global_storage_policy( global: &crate::GlobalStorage, budget: &AnalysisBudget, ) -> Result<(), VerifyError> { @@ -621,7 +621,58 @@ pub(super) fn global_storage( 24 => crate::GlobalStorageError::ReadOnlyUninitialized, _ => return Err(resource_error(budget)), }; - Err(VerifyError::GlobalStorage { name: global.name.clone(), global: global.id, reason }) + Err(VerifyError::GlobalStorage { name: String::new(), global: global.id, reason }) +} + +fn boundary_budget(limits: crate::IrLimits) -> AnalysisBudget { + AnalysisBudget { + limit: limits.max_analysis_work, + work: std::cell::Cell::new(0), + queries: std::cell::Cell::new(0), + } +} + +pub(super) fn global_storage( + global: &crate::GlobalStorage, + budget: &AnalysisBudget, +) -> Result<(), VerifyError> { + global_storage_policy(global, budget).map_err(|error| match error { + VerifyError::GlobalStorage { global: id, reason, .. } => { + VerifyError::GlobalStorage { name: global.name.clone(), global: id, reason } + }, + other => other, + }) +} + +pub(crate) fn validate_global_boundary( + global: &crate::GlobalStorage, + limits: crate::IrLimits, +) -> Result<(), crate::GlobalStorageError> { + crate::limits::Budget::new(limits) + .and_then(|mut budget| budget.ty(&global.ty)) + .map_err(crate::GlobalStorageError::ResourceLimit)?; + global_storage_policy(global, &boundary_budget(limits)).map_err(|error| match error { + VerifyError::GlobalStorage { reason, .. } => reason, + VerifyError::ResourceLimit(limit) => crate::GlobalStorageError::ResourceLimit(limit), + _ => crate::GlobalStorageError::ResourceLimit(crate::LimitError { + resource: crate::Resource::AnalysisWork, + limit: limits.max_analysis_work, + }), + }) +} + +pub(crate) fn validate_signature_boundary( + sig: &crate::FunctionSignature, + limits: crate::IrLimits, +) -> Result<(), CallError> { + signature(sig, limits, &boundary_budget(limits)).map_err(|error| match error { + VerifyError::Call { reason, .. } => reason, + VerifyError::ResourceLimit(limit) => CallError::ResourceLimit(limit), + _ => CallError::ResourceLimit(crate::LimitError { + resource: crate::Resource::AnalysisWork, + limit: limits.max_analysis_work, + }), + }) } fn signature_error(status: u64, detail: u64) -> CallError { diff --git a/ir/tests/public_semantic_boundaries.rs b/ir/tests/public_semantic_boundaries.rs new file mode 100644 index 0000000..bdb1263 --- /dev/null +++ b/ir/tests/public_semantic_boundaries.rs @@ -0,0 +1,58 @@ +use ir::*; + +#[test] +fn public_signature_and_global_policy_preserve_existing_diagnostics() { + let valid = FunctionSignature::whale(vec![Type::U64], Type::Void); + validate_signature_with_limits(&valid, IrLimits::default()).unwrap(); + let invalid = FunctionSignature::whale(vec![Type::Void], Type::Void); + assert!(matches!( + validate_signature_with_limits(&invalid, IrLimits::default()), + Err(CallError::InvalidSignature(_)) + )); + let mut global = GlobalStorage::internal( + "value", + Type::U8, + GlobalStorageInit::Value(ConstValue::U(42)), + false, + 1, + ); + global.validate_with_limits(IrLimits::default()).unwrap(); + global.align = 3; + assert_eq!( + global.validate_with_limits(IrLimits::default()), + Err(GlobalStorageError::InvalidAlignment) + ); + global.align = 1; + global.init = GlobalStorageInit::Value(ConstValue::U(256)); + assert_eq!( + global.validate_with_limits(IrLimits::default()), + Err(GlobalStorageError::InvalidInitializer) + ); +} + +#[test] +fn wave_public_boundaries_apply_the_native_analysis_work_ceiling() { + if !IR_WAVE_ENABLED { + return; + } + let limits = IrLimits { max_analysis_work: 0, ..Default::default() }; + let signature = FunctionSignature::whale(vec![], Type::Void); + assert!(matches!( + validate_signature_with_limits(&signature, limits), + Err(CallError::ResourceLimit(LimitError { resource: Resource::AnalysisWork, limit: 0 })) + )); + let global = GlobalStorage::internal( + "value", + Type::U8, + GlobalStorageInit::Value(ConstValue::U(42)), + false, + 1, + ); + assert_eq!( + global.validate_with_limits(limits), + Err(GlobalStorageError::ResourceLimit(LimitError { + resource: Resource::AnalysisWork, + limit: 0 + })) + ); +} diff --git a/meson.build b/meson.build index 1a6112b..cbded86 100644 --- a/meson.build +++ b/meson.build @@ -23,6 +23,9 @@ endif if get_option('native-linker') selected_features += ['native-linker'] endif +if get_option('rust-reference') + selected_features += ['rust-reference'] +endif cargo_host_target = get_option('cargo-host-target') if meson.is_cross_build() and cargo_host_target == '' @@ -32,6 +35,17 @@ endif # asmobj is one complete Wave source module. Cargo only links it through the # data transport in toolchain; there is no Rust implementation or fallback. wave_source = get_option('wave-source') +if not get_option('rust-reference') and wave_source == '' + required_modules = ['asmobj-dir', 'wave-ir-dir', 'wave-assembler-dir'] + foreach arch : assembler_outputs + required_modules += ['wave-' + arch + '-dir'] + endforeach + foreach module : required_modules + if get_option(module) == '' + error('The default Wave product requires -Dwave-source=/absolute/Wave or every selected prebuilt module; missing -D' + module + '. Rust reference builds require explicit -Drust-reference=true.') + endif + endforeach +endif wave_cache = get_option('wave-bootstrap-dir') if wave_cache == '' wave_cache = meson.project_build_root() / 'wave-bootstrap' @@ -154,5 +168,6 @@ summary({ 'Assembler output modules': assembler_outputs, 'Complete Wave module': 'assembler/asmobj', 'Wave IR sources': wave_ir_directory == '' ? 'Rust compatibility path' : wave_ir_directory, + 'Rust reference algorithms allowed': get_option('rust-reference'), 'Cargo offline': get_option('cargo-offline'), }, section: 'Whale source modules') diff --git a/meson.options b/meson.options index ecf2a7b..d5ae65d 100644 --- a/meson.options +++ b/meson.options @@ -11,6 +11,8 @@ option('socket-cli', type: 'boolean', value: false, description: 'Include experimental AST JSON lowering commands') option('native-linker', type: 'boolean', value: true, description: 'Include static Linux AMD64 executable linking') +option('rust-reference', type: 'boolean', value: false, + description: 'Explicitly allow Rust reference algorithms for comparison builds') option('asmobj-dir', type: 'string', value: '', description: 'Absolute directory of the complete prebuilt Wave asmobj module for the executable host') option('wave-ir-dir', type: 'string', value: '', diff --git a/src/build_info.rs b/src/build_info.rs new file mode 100644 index 0000000..f6ebaa7 --- /dev/null +++ b/src/build_info.rs @@ -0,0 +1,57 @@ +//! Embedded build provenance and stamps returned by the linked source modules. +use serde_json::{json, Value}; + +pub fn value() -> Result { + let mut value: Value = + serde_json::from_str(include_str!(concat!(env!("OUT_DIR"), "/build-info.json"))) + .map_err(|_| "invalid embedded build provenance")?; + let mut modules = serde_json::Map::new(); + modules.insert("ir".into(), json!(ir::module_identity())); + modules.insert("assembler".into(), json!(assembler::module_identity())); + modules.insert("asmobj".into(), json!(toolchain::assembly_object::module_identity())); + #[cfg(feature = "asm-amd64")] + modules.insert("amd64".into(), json!(amd64::module_identity())); + #[cfg(feature = "asm-aarch64")] + modules.insert("aarch64".into(), json!(aarch64::module_identity())); + #[cfg(feature = "asm-riscv64")] + modules.insert("riscv64".into(), json!(riscv64::module_identity())); + #[cfg(feature = "asm-loongarch64")] + modules.insert("loongarch64".into(), json!(loongarch64::module_identity())); + if modules.values().any(|module| module == "invalid-wave") { + return Err("linked Wave module identity mismatch"); + } + let mode = if modules.values().all(|module| module == "wave") { + "wave" + } else if modules.get("ir").is_some_and(|module| module == "rust-reference") { + "rust-reference" + } else { + "mixed" + }; + value["product_mode"] = json!(mode); + value["implementations"] = Value::Object(modules); + value["version"] = json!(env!("CARGO_PKG_VERSION")); + value["ir_format_version"] = json!(ir::IR_FORMAT_VERSION); + value["semantics_version"] = json!(ir::SEMANTICS_VERSION); + value["bytecode_format_version"] = json!(1); + value["assemblers"] = json!(crate::builtins::registry().assembler_ids().collect::>()); + value["native_linker"] = json!(cfg!(feature = "native-linker")); + value["socket_cli"] = json!(cfg!(feature = "socket-cli")); + Ok(value) +} + +pub(crate) fn run(arguments: Vec) { + if !arguments.is_empty() && arguments != ["--json"] { + eprintln!("Usage: whale build-info [--json]"); + std::process::exit(2); + } + let value = value().unwrap_or_else(|error| { + eprintln!("Error: {error}"); + std::process::exit(1); + }); + let output = if arguments.is_empty() { + serde_json::to_string_pretty(&value).expect("serializable provenance") + } else { + value.to_string() + }; + crate::commands::report::println!("{output}"); +} diff --git a/src/cli.rs b/src/cli.rs index 9c5b2ec..25182e3 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -21,6 +21,7 @@ pub fn run() { match cmd.as_str() { "--help" | "-h" => print_help(), "--version" | "-V" => println!("whale {}", env!("CARGO_PKG_VERSION")), + "build-info" => crate::build_info::run(args.collect()), "asm" => commands::asm::run(args.collect()), "object" => commands::object::run(args.collect()), #[cfg(feature = "native-linker")] @@ -54,6 +55,7 @@ fn print_help() { println!(" whale disasm [--amd64] [--json]"); println!(" whale reverse inspect|cfg|xrefs [options]"); println!(" whale --version | -V"); + println!(" whale build-info [--json]"); println!(); println!("Commands:"); println!( @@ -66,5 +68,9 @@ fn print_help() { println!(" disasm Disassembly entry point (core currently unavailable)"); println!(" reverse ELF inspection; CFG/xrefs core currently unavailable"); println!(" ir IR verify/print/fold/run/emit; socket-cli enables AST lower"); - println!(" bytecode Versioned Whale bytecode verification and tracked execution"); + if ir::bytecode::available() { + println!(" bytecode Versioned Whale bytecode verification and tracked execution"); + } else { + println!(" bytecode Unavailable: this reference build does not link Wave IR"); + } } diff --git a/src/lib.rs b/src/lib.rs index 229aff8..fca8be3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,3 +5,5 @@ pub mod commands; pub mod builtins; mod backends; + +pub mod build_info; diff --git a/tests/build_info.rs b/tests/build_info.rs new file mode 100644 index 0000000..4855f03 --- /dev/null +++ b/tests/build_info.rs @@ -0,0 +1,44 @@ +use std::process::Command; + +#[test] +fn embedded_identity_matches_the_selected_modules_and_has_no_build_paths() { + let result = + Command::new(env!("CARGO_BIN_EXE_whale")).args(["build-info", "--json"]).output().unwrap(); + assert!(result.status.success(), "{result:?}"); + let value: serde_json::Value = serde_json::from_slice(&result.stdout).unwrap(); + assert_eq!(value["schema_version"], 1); + assert_eq!(value["version"], env!("CARGO_PKG_VERSION")); + assert_eq!(value["semantics_version"], ir::SEMANTICS_VERSION); + assert_eq!(value["implementations"]["ir"], ir::module_identity()); + assert_eq!(value["implementations"]["assembler"], assembler::module_identity()); + assert_eq!(value["implementations"]["asmobj"], toolchain::assembly_object::module_identity()); + let selected = + whale::builtins::registry().assembler_ids().map(str::to_owned).collect::>(); + assert_eq!(value["assemblers"], serde_json::json!(selected)); + assert_eq!(value["native_linker"], cfg!(feature = "native-linker")); + let serialized = String::from_utf8(result.stdout).unwrap(); + assert!(!serialized.contains(env!("CARGO_MANIFEST_DIR"))); + assert!(!serialized.contains("bootstrap_provenance")); + for module in value["wave_modules"].as_object().unwrap().values() { + for key in + ["source_sha256", "abi_sha256", "archive_sha256", "compiler_sha256", "std_sha256"] + { + let digest = module[key].as_str().unwrap(); + assert_eq!(digest.len(), 64); + assert!(digest.bytes().all(|byte| byte.is_ascii_hexdigit())); + } + } +} + +#[test] +fn build_info_rejects_unknown_options_and_help_names_unavailable_bytecode() { + let result = Command::new(env!("CARGO_BIN_EXE_whale")) + .args(["build-info", "--unknown"]) + .output() + .unwrap(); + assert_eq!(result.status.code(), Some(2)); + let help = Command::new(env!("CARGO_BIN_EXE_whale")).arg("--help").output().unwrap(); + let help = String::from_utf8(help.stdout).unwrap(); + assert!(help.contains("build-info [--json]")); + assert_eq!(help.contains("bytecode Unavailable:"), !ir::bytecode::available()); +} diff --git a/tests/cli_arguments.rs b/tests/cli_arguments.rs index 80cdbe4..c7d9838 100644 --- a/tests/cli_arguments.rs +++ b/tests/cli_arguments.rs @@ -134,7 +134,7 @@ fn help_describes_available_commands_and_object_options() { let text = String::from_utf8(result.stdout).unwrap(); assert!(text.contains("whale asm --amd64")); assert!(text.contains("raw bytes")); - assert!(text.contains("Static Linux AMD64")); + assert_eq!(text.contains("Static Linux AMD64"), cfg!(feature = "native-linker")); assert!(text.contains("run")); for flag in ["--aarch64", "--riscv64", "--loongarch64"] { assert!(text.contains(flag)); diff --git a/tests/cli_io.rs b/tests/cli_io.rs index c9e8d9b..40c8484 100644 --- a/tests/cli_io.rs +++ b/tests/cli_io.rs @@ -214,9 +214,15 @@ fn closed_artifact_stdout_preserves_completed_output_without_panicking() { .arg("-o") .arg(&executable), ); - assert!(result.status.success(), "{result:?}"); - assert!(result.stderr.is_empty(), "{result:?}"); - assert!(fs::read(executable).unwrap().starts_with(b"\x7fELF")); + if cfg!(feature = "native-linker") { + assert!(result.status.success(), "{result:?}"); + assert!(result.stderr.is_empty(), "{result:?}"); + assert!(fs::read(executable).unwrap().starts_with(b"\x7fELF")); + } else { + assert_eq!(result.status.code(), Some(2), "{result:?}"); + assert!(String::from_utf8_lossy(&result.stderr).contains("native linker is not included")); + assert!(!executable.exists()); + } } #[cfg(unix)] @@ -230,8 +236,15 @@ fn closed_help_stdout_and_real_command_failures_keep_their_exit_policy() { vec!["link", "--help"], ] { let result = closed_stdout(Command::new(env!("CARGO_BIN_EXE_whale")).args(&arguments)); - assert!(result.status.success(), "{arguments:?}: {result:?}"); - assert!(result.stderr.is_empty(), "{result:?}"); + if arguments[0] == "link" && !cfg!(feature = "native-linker") { + assert_eq!(result.status.code(), Some(2), "{result:?}"); + assert!( + String::from_utf8_lossy(&result.stderr).contains("native linker is not included") + ); + } else { + assert!(result.status.success(), "{arguments:?}: {result:?}"); + assert!(result.stderr.is_empty(), "{result:?}"); + } } let directory = tempfile::tempdir().unwrap(); let input = directory.path().join("invalid"); @@ -264,9 +277,14 @@ fn ordinary_artifact_stdout_failures_are_diagnostics() { .stdout(full) .output() .unwrap(); - assert_eq!(result.status.code(), Some(1)); let diagnostic = String::from_utf8_lossy(&result.stderr); - assert!(diagnostic.contains("failed to write stdout"), "{diagnostic}"); + if command == "link" && !cfg!(feature = "native-linker") { + assert_eq!(result.status.code(), Some(2), "{result:?}"); + assert!(diagnostic.contains("native linker is not included"), "{diagnostic}"); + } else { + assert_eq!(result.status.code(), Some(1), "{result:?}"); + assert!(diagnostic.contains("failed to write stdout"), "{diagnostic}"); + } assert!(!diagnostic.contains("panicked"), "{diagnostic}"); } } diff --git a/tests/fuzz_corpus.rs b/tests/fuzz_corpus.rs index 57afcce..0e6cac0 100644 --- a/tests/fuzz_corpus.rs +++ b/tests/fuzz_corpus.rs @@ -5,6 +5,9 @@ mod fuzz; fn deterministic_seed_and_mutation_smoke_is_bounded() { let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fuzz/corpus"); let mut targets = vec![fuzz::Target::Ir, fuzz::Target::Object]; + if ir::bytecode::available() { + targets.push(fuzz::Target::Bytecode); + } if cfg!(feature = "asm-amd64") { targets.push(fuzz::Target::Assembler); } diff --git a/toolchain/Cargo.toml b/toolchain/Cargo.toml index 149eed0..5e39762 100644 --- a/toolchain/Cargo.toml +++ b/toolchain/Cargo.toml @@ -4,6 +4,10 @@ version = "0.1.0" edition = "2021" rust-version.workspace = true +[features] +default = [] +rust-reference = ["assembler/rust-reference", "ir/rust-reference"] + [dependencies] assembler = { path = "../assembler" } backend-api = { path = "../backend-api" } diff --git a/toolchain/src/assembly_object.rs b/toolchain/src/assembly_object.rs index 533449c..79f2cb0 100644 --- a/toolchain/src/assembly_object.rs +++ b/toolchain/src/assembly_object.rs @@ -414,3 +414,34 @@ mod native { Ok(object) } } + +/// The implementation actually selected by this owning module. +pub fn module_identity() -> &'static str { + #[cfg(whale_asmobj)] + { + unsafe extern "C" { + fn whale_asmobj_module_identity() -> u64; + } + // This no-argument stamp is exported by this module's guarded archive. + if unsafe { whale_asmobj_module_identity() } == 6289348675458125569 { + "wave" + } else { + "invalid-wave" + } + } + #[cfg(not(whale_asmobj))] + { + "unavailable" + } +} + +#[cfg(test)] +mod implementation_identity_tests { + #[test] + fn selected_implementation_has_its_own_compiled_identity() { + assert_eq!( + super::module_identity(), + if cfg!(whale_asmobj) { "wave" } else { "unavailable" } + ); + } +} diff --git a/tools/BENCHMARKS.md b/tools/BENCHMARKS.md index cdaef9d..e2c146f 100644 --- a/tools/BENCHMARKS.md +++ b/tools/BENCHMARKS.md @@ -1,8 +1,54 @@ # Assembly and IR performance measurements +## Actual Wave CLI pipelines + +Select the native Wave archives from [BUILDING.md](../BUILDING.md#reuse-built-modules-or-run-cargo-checks), then run on an otherwise idle Linux host: + +```sh +python3 tools/benchmark_cli.py --output /tmp/whale-bench/cli.json --runs 3 --warmups 1 +``` + +This builds a release CLI with `socket-cli` and all four ISAs, locked/offline +with two Cargo jobs. Repeat `--isa amd64`, `--isa aarch64`, etc. to measure a +selected product; selections must match its `build-info` architecture list. +The driver requires Wave identities for every selected module and `socket-cli`. +Missing, reference or mixed implementations fail the run. `--skip-build --cli PATH` +measures an existing product; its hash is recorded, without claiming that the +harness built it from the reported revision or profile. + +Each size runs these real commands in separate processes: + +| Commands | Correctness gate outside the timed process | +| --- | --- | +| `asm --arch ID` for each selected ISA | ELF machine and exact independently specified instruction bytes | +| `ir verify`, `bytecode verify` | Successful verification of the retained input | +| `ir lower` | All unused O0 loads remain in order; execution returns `i32 42` | +| `ir fold` | Constant values and SSA IDs match; execution returns 42 and a second fold is identical | +| `ir emit` | Canonical bytecode tables, literal bits, instructions and SSA IDs; deterministic output and result 42 | +| `bytecode run` | Exact `i32 42` result | + +The fixed defaults are 64 and 32,768 operations. Assembly adds zero repeatedly. +IR folding/compilation use dependent i32 add-zero chains. Lowering uses flat +unused scalar-parameter references, which fit existing AST limits and deliberately +retain O0 loads. These are scalar pipeline workloads, not a claim about all IR +or ISA performance. + +Reports retain every measured sample, medians, process wall time, peak RSS, +commands, input/output SHA256, source revision/dirty state, executable/driver +hashes, host/toolchains, build flags, complete `build-info --json` and selected +archive fingerprints. GNU +`time` RSS covers the timed CLI process; validation subprocesses are excluded. +Outputs are removed before each sample. A failed command, changed input, wrong +result or nondeterministic output preserves the previous report. +`--compare PREVIOUS.json` requires matching workloads, environment and verified +results, then reports median time/RSS ratios without timing pass/fail thresholds. + +## Public library phases + Issue #76 is measured with real public library calls and CLI processes. The harness currently requires Linux, Python 3.13+, GNU `/usr/bin/time`, and the Rust -toolchain. It needs no external assembler, linker, release credentials or network. +toolchain. Select native Wave archives as above; it needs no external assembler, release +credentials or network. Ordinary Cargo builds do not run benchmarks. Run from the repository root on an otherwise idle host; CPU contention and frequency changes affect short samples. diff --git a/tools/RELEASING.md b/tools/RELEASING.md index bded4a1..74e1eca 100644 --- a/tools/RELEASING.md +++ b/tools/RELEASING.md @@ -1,67 +1,57 @@ -# Native release packages +# Standalone packages -Python 3.13+ and the standard library are sufficient for the release tools. -The six supported package hosts are the Linux, macOS and Windows x64/ARM64 -hosts already exercised in native CI. RISC-V host emulation does not qualify -as native release validation. These packages generate AMD64 ELF objects, -independently of the host CPU/OS; they do not add native executable linking. +The validated full Wave product runs on **Linux x86_64 GNU**. Other native +package jobs explicitly build Rust reference products; their manifests identify +that mode. Cross-produced Wave objects do not establish another executable host. -Build a native binary, then package and validate it (replace the full commit -with the actual source SHA; the version must equal Cargo.toml): +Build a clean revision with Meson, then package it with Python 3.13+: ```sh -cargo build --release --workspace --all-features --locked -python tools/release.py package --binary target/release/whale --directory dist --version 0.1.0 --source FULL_40_DIGIT_COMMIT --target x86_64-unknown-linux-gnu --socket-cli -python tools/release.py validate --directory dist --version 0.1.0 --source FULL_40_DIGIT_COMMIT --target x86_64-unknown-linux-gnu +meson setup /tmp/whale-release --buildtype=release -Dsocket-cli=true \ + -Dwave-source=/absolute/Wave -Dwave-rust-toolchain=1.89 +meson compile -C /tmp/whale-release +python3 tools/release.py package --binary /tmp/whale-release/whale \ + --directory /tmp/whale-dist --version 0.1.0 --source FULL_40_DIGIT_COMMIT \ + --target x86_64-unknown-linux-gnu --socket-cli --require-wave +python3 tools/release.py validate --directory /tmp/whale-dist --version 0.1.0 \ + --source FULL_40_DIGIT_COMMIT --target x86_64-unknown-linux-gnu --require-wave ``` -Use the native `.exe` on Windows. Omit `--socket-cli` for a default-feature -binary. The manifest's feature declaration is checked before archive -publication and again against the extracted binary. Archives include exactly the binary, LICENSE, README.md and -manifest.json under a versioned root directory. The manifest records version, -host target, source SHA, feature availability and binary SHA256. Packaging -checks executable header architecture, actual CLI version and socket-cli availability; missing binaries, -version/target mismatches and existing output names fail. Identical inputs give -identical archive bytes with normalized metadata, entry order and timestamps. -The caller must provide a binary built from the stated commit; the workflow -enforces that provenance through exact-SHA native builds. +Omit `--socket-cli` for the default selection. `whale build-info --json` reports +actual linked module stamps, selected architectures, source revision and dirty +state, Rust version, IR/bytecode semantics and portable Wave compiler/source/ABI/ +archive hashes. Source exports without Git can supply `WHALE_SOURCE_REVISION`. +`--require-wave` rejects reference/mixed products, dirty sources and unvalidated +hosts. End users need only the extracted binary, with no compiler or checkout. -Validation checks members and metadata before extracting into a temporary -directory. It rejects paths, links, duplicates, missing files, non-executable -binaries, oversized contents and checksum mismatches. With an empty PATH and -outside the checkout, the extracted binary runs help/version, creates an object -with independently specified instruction bytes, rejects malformed assembly -without overwriting output, and confirms socket-cli availability. +Archives contain exactly the binary, LICENSE, README.md and manifest.json. +Manifest format 2 embeds the binary's provenance and SHA256; format 1 remains +readable. The producer checks target/version/source/features against the binary. +Metadata, entry order and timestamps are fixed, so equivalent inputs produce +identical archive bytes. Publication is atomic and never overwrites an earlier +artifact. Failed creation or validation preserves it. -After collecting the exact six archives in one directory: +Validation rejects unsafe members, links, duplicate names, missing files, +invalid permissions, excessive sizes and checksum/provenance mismatches before +extraction. In a fresh directory with empty PATH and no Wave/LLVM environment, +it checks selected assembler bytes, failed-output preservation and bytecode +emit/verify/run. Disabling all assemblers is supported. -```sh -python tools/release.py checksums --directory dist --version 0.1.0 --source FULL_40_DIGIT_COMMIT -python tools/release.py verify --directory dist --version 0.1.0 --source FULL_40_DIGIT_COMMIT -``` - -For local single-host checks, supply one `--target`; repeat it for an explicit -subset. Empty/duplicated targets and unexpected, missing or stale-version files -fail. SHA256SUMS is sorted and checked byte-for-byte, so duplicate manifest -entries and tampering fail. Files are published atomically without replacement. - -The **Manual release** workflow runs only on workflow_dispatch. It requires a -full source SHA, matching Cargo version and an existing `vVERSION` tag pointing -to that exact commit. It checks source, builds and executes all six native -packages, then verifies the exact aggregate archive set and checksums. Every -producer and validation job must succeed. Only the final job has contents:write. -`publish_draft` defaults to false; when selected it creates a new draft and -refuses to overwrite an existing release. Implementing this tooling does not -dispatch the workflow, create a tag or publish a release. - -Focused local regressions (synthetic packages require no credentials or external -assembler): +For a single package, generate and recheck exact-set checksums with: ```sh -python -m unittest discover -s tools -p test_release.py -v -python -m unittest discover -s tools -p test_ci.py -v +python3 tools/release.py checksums --directory /tmp/whale-dist --version 0.1.0 \ + --source FULL_40_DIGIT_COMMIT --target x86_64-unknown-linux-gnu +python3 tools/release.py verify --directory /tmp/whale-dist --version 0.1.0 \ + --source FULL_40_DIGIT_COMMIT --target x86_64-unknown-linux-gnu ``` +Repeat `--target` for an explicit set; omission selects the six native package +hosts. Missing, extra or stale-version archives fail. The manual workflow requires +an exact commit, matching Cargo version and existing `vVERSION` tag. Draft +publication is separately requested, defaults off and refuses existing releases. +Implementing or testing these helpers does not publish a release. + The CI runner is non-interactive and retains process-tree ownership until output cleanup finishes. POSIX uses a private process group; Windows uses a gated launcher inside a kill-on-close Job before the requested command can spawn. diff --git a/tools/benchmark_cli.py b/tools/benchmark_cli.py new file mode 100755 index 0000000..3415dee --- /dev/null +++ b/tools/benchmark_cli.py @@ -0,0 +1,610 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Measure actual selected-ISA, IR and bytecode CLI processes on Linux.""" + +import argparse +import hashlib +import json +import math +import os +import platform +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +import benchmark +from benchmark import ( + compare_reports, + execute, + host_metadata, + sha256, + summarize, + text_command, +) + +ARCHITECTURES = { + "amd64": ( + 62, + "section .text\nglobal bench\nbench:\nmov eax,42\n", + "add eax,0\n", + "ret\n", + bytes.fromhex("b82a000000"), + bytes.fromhex("83c000"), + bytes.fromhex("c3"), + ), + "aarch64": ( + 183, + ".text\n.global bench\nbench:\nmov x0,#42\n", + "add x0,x0,#0\n", + "ret\n", + bytes.fromhex("400580d2"), + bytes.fromhex("00000091"), + bytes.fromhex("c0035fd6"), + ), + "riscv64": ( + 243, + ".text\n.global bench\nbench:\naddi a0,zero,42\n", + "addi a0,a0,0\n", + "ret\n", + bytes.fromhex("1305a002"), + bytes.fromhex("13050500"), + bytes.fromhex("67800000"), + ), + "loongarch64": ( + 258, + ".text\n.global bench\nbench:\naddi.d $a0,$zero,42\n", + "addi.d $a0,$a0,0\n", + "ret\n", + bytes.fromhex("04a8c002"), + bytes.fromhex("8400c002"), + bytes.fromhex("2000004c"), + ), +} +STRIDES = (40, 8, 88, 32, 136, 8, 8, 64, 32, 16, 1, 16, 56, 40, 8, 8) +FORMAT_VERSION = 1 +GENERATOR = "scalar-cli-pipelines-v1" + + +def digest(data): + return hashlib.sha256(data).hexdigest() + + +def ir_source(count): + lines = [ + "module {", + " format_version 8", + " semantics_version 1", + ' target "whale-bytecode-v1"', + " datalayout { ptr=64, endian=little }", + ' declare @f0 "bench": whale () -> i32, linkage internal', + ' fn @f0 "bench"() -> i32, entry %b0 {', + ' %b0 "entry":', + " %v0: i32 = const i32 42", + " %v1: i32 = const i32 0", + ] + for index in range(count): + previous = index + 1 if index else 0 + lines.append(f" %v{index + 2}: i32 = add i32 %v{previous}, %v1") + lines.extend([f" ret i32 %v{count + 1 if count else 0}", " }", "}"]) + return "\n".join(lines) + "\n" + + +def ast_source(count): + # Flat unused parameter references preserve O0 loads while fitting the + # existing AST node/depth budgets even at 32768 operations. + kind = {"Int": {"bits": 32, "signed": True}} + body = [{"ExprStmt": {"Var": "x"}} for _ in range(count)] + body.append({"Return": {"Var": "x"}}) + program = { + "declarations": [], + "globals": [], + "functions": [ + { + "name": "bench", + "parameters": [{"name": "x", "ty": kind}], + "return_type": kind, + "body": body, + "convention": "Whale", + "linkage": "Internal", + "link_name": None, + } + ], + } + return ( + json.dumps( + {"format_version": 5, "semantics_version": 1, "features": [], "program": program}, + separators=(",", ":"), + ) + + "\n" + ) + + +def elf_text(data, machine): + if len(data) < 64 or data[:7] != b"\x7fELF\x02\x01\x01": + raise ValueError("expected little-endian ELF64") + word16 = lambda at: struct.unpack_from(" len(data): + raise ValueError("invalid ELF section table") + header = offset + names * stride + first, size = word64(header + 24), word64(header + 32) + if first + size > len(data): + raise ValueError("invalid ELF section names") + strings = data[first : first + size] + code = [] + for index in range(1, count): + header = offset + index * stride + name = word32(header) + if name >= len(strings) or b"\0" not in strings[name:]: + raise ValueError("invalid ELF section name") + if strings[name:].split(b"\0", 1)[0] == b".text": + first, size = word64(header + 24), word64(header + 32) + if word64(header + 8) != 6 or first + size > len(data): + raise ValueError("invalid ELF code section") + code.append(data[first : first + size]) + if len(code) != 1: + raise ValueError("expected exactly one ELF code section") + return code[0] + + +def check_assembly(data, architecture, count): + machine, _, _, _, head, body, tail = ARCHITECTURES[architecture] + if elf_text(data, machine) != head + body * count + tail: + raise ValueError("ELF text differs from independent ISA encoding") + + +def check_folded(data, count): + text = data.decode() + constants = re.findall(r"^\s*%v(\d+): i32 = const i32 (-?\d+)\s*$", text, re.MULTILINE) + expected = [(str(index), "0" if index == 1 else "42") for index in range(count + 2)] + if constants != expected or "= add " in text: + raise ValueError("folded values/IDs differ from independent expected constants") + if f"ret i32 %v{count + 1 if count else 0}\n" not in text: + raise ValueError("folded return identity changed") + + +def check_lowered(data, count): + text = data.decode() + loads = re.findall(r"^\s*%v(\d+): i32 = load i32,", text, re.MULTILINE) + if loads != [str(index) for index in range(2, count + 3)]: + raise ValueError("lowering lost unused O0 loads or their source order") + if f"ret i32 %v{count + 2}\n" not in text: + raise ValueError("lowered return identity changed") + + +def check_bytecode(data, count): + if len(data) < 576 or struct.unpack_from("<8s7Q", data) != ( + b"WHALEBC\0", + 1, + 1, + 1, + len(data), + 16, + 0, + 576, + ): + raise ValueError("wrong canonical bytecode header") + tables = [] + end = 576 + for table, stride in enumerate(STRIDES, 1): + kind, offset, amount, width = struct.unpack_from("<4Q", data, 64 + (table - 1) * 32) + if (kind, offset, width) != (table, end, stride) or amount > (len(data) - end) // stride: + raise ValueError("invalid canonical bytecode directory") + tables.append(data[offset : offset + amount * stride]) + end += amount * stride + if end != len(data) or len(tables[4]) != (count + 3) * 136: + raise ValueError("wrong bytecode instruction count") + instructions = list(struct.iter_unpack("<17Q", tables[4])) + if [row[0] for row in instructions] != [4, 4] + [7] * count + [34]: + raise ValueError("bytecode lost O0 instructions") + if [(row[11], row[12], row[13]) for row in instructions[:2]] != [(42, 0, 1), (0, 0, 1)]: + raise ValueError("bytecode literal bits changed") + for index, row in enumerate(instructions[2:-1]): + if (row[1], row[4], row[5], row[6]) != (0, index + 2, index + 1 if index else 0, 1): + raise ValueError("bytecode arithmetic or SSA identity changed") + if list(struct.iter_unpack("= args.warmups: + samples.append( + {"phase_seconds": wall, "process_wall_seconds": wall, "peak_rss_bytes": peak} + ) + return { + "name": name, + "command": list(map(str, command)), + "fingerprint": expected, + "output_sha256": digest(payload), + "output_bytes": len(payload), + "samples": samples, + "median": summarize(samples), + } + + +def prepare(directory, count, architectures): + directory.mkdir(parents=True, exist_ok=True) + sources = {"input.wir": ir_source(count), "input.json": ast_source(count)} + for architecture in architectures: + _, head, body, tail, *_ = ARCHITECTURES[architecture] + sources[architecture + ".s"] = head + body * count + tail + for name, text in sources.items(): + (directory / name).write_text(text) + return {name: sha256(directory / name) for name in sources} + + +def benchmark_size(cli, directory, count, architectures, args, timer): + inputs = prepare(directory, count, architectures) + source, json_source = directory / "input.wir", directory / "input.json" + image = directory / "input.wbc" + invoke(cli, ["ir", "emit", source, "-o", image], args.timeout) + check_bytecode(image.read_bytes(), count) + expected_run = b"i32 42\n" + + def require_run(arguments): + if invoke(cli, arguments, args.timeout) != expected_run: + raise ValueError("generated program did not return independent expected i32 42") + + require_run(["bytecode", "run", image, "--function", "@f0"]) + measurements = [] + for architecture in architectures: + measurements.append( + run_phase( + f"asm/{architecture}", + count, + [ + cli, + "asm", + "--arch", + architecture, + directory / (architecture + ".s"), + "-o", + directory / (architecture + ".o"), + ], + directory / (architecture + ".s"), + directory / (architecture + ".o"), + lambda data, isa=architecture: check_assembly(data, isa, count), + args, + timer, + ) + ) + + def verify_stdout(data, kind, path): + if data != f"Verified {kind} {path}\n".encode(): + raise ValueError("verifier did not confirm input") + # Verifier stdout contains a filesystem path. Retain its actual hash in + # the report but compare the verified content across output locations. + return path.read_bytes() + + def lower(data): + check_lowered(data, count) + require_run(["ir", "run", directory / "lowered.wir", "--function", "@f0", "--arg", "42"]) + + def folded(data): + check_folded(data, count) + require_run(["ir", "run", directory / "folded.wir", "--function", "@f0"]) + repeated = directory / "folded-twice.wir" + invoke(cli, ["ir", "fold", directory / "folded.wir", "-o", repeated], args.timeout) + if repeated.read_bytes() != data: + raise ValueError("folding is not idempotent") + + def compiled(data): + check_bytecode(data, count) + if data != image.read_bytes(): + raise ValueError("bytecode compilation is not deterministic") + require_run(["bytecode", "run", directory / "actual.wbc", "--function", "@f0"]) + + def run(data): + if data != expected_run: + raise ValueError("bytecode returned wrong result") + + phases = [ + ( + "ir/verify", + ["ir", "verify", source], + source, + None, + lambda data: verify_stdout(data, "IR", source), + ), + ( + "ir/lower", + [ + "ir", + "lower", + json_source, + "--target", + "whale-bytecode-v1", + "-o", + directory / "lowered.wir", + ], + json_source, + directory / "lowered.wir", + lower, + ), + ( + "ir/fold", + ["ir", "fold", source, "-o", directory / "folded.wir"], + source, + directory / "folded.wir", + folded, + ), + ( + "bytecode/compile", + ["ir", "emit", source, "--target", "whale-bytecode-v1", "-o", directory / "actual.wbc"], + source, + directory / "actual.wbc", + compiled, + ), + ( + "bytecode/verify", + ["bytecode", "verify", image], + image, + None, + lambda data: verify_stdout(data, "bytecode", image), + ), + ("bytecode/run", ["bytecode", "run", image, "--function", "@f0"], image, None, run), + ] + for name, arguments, source, output, validator in phases: + measurements.append( + run_phase(name, count, [cli, *arguments], source, output, validator, args, timer) + ) + inputs["input.wbc"] = sha256(image) + return inputs, measurements + + +def build_environment(): + names = ( + "RUSTFLAGS", + "CARGO_ENCODED_RUSTFLAGS", + "RUSTUP_TOOLCHAIN", + "RUSTC", + "RUSTC_WRAPPER", + "RUSTC_WORKSPACE_WRAPPER", + ) + environment = {name: os.environ.get(name) for name in names} + environment.update( + {name: value for name, value in os.environ.items() if name.startswith("CARGO_PROFILE_")} + ) + environment.update(CARGO_INCREMENTAL="0", CARGO_BUILD_JOBS="2") + return environment + + +def native_modules(): + modules = {} + for name in ( + "WHALE_ASMOBJ_DIR", + "WHALE_WAVE_IR_DIR", + "WHALE_WAVE_ASSEMBLER_DIR", + *("WHALE_WAVE_" + isa.upper() + "_DIR" for isa in ARCHITECTURES), + ): + directory = os.environ.get(name) + if directory is None: + modules[name] = None + continue + path = Path(directory).resolve(strict=True) + artifacts = [ + file + for pattern in ("*.meta", "*.a", "*.lib", "provenance.json") + for file in sorted(path.glob(pattern)) + ] + modules[name] = { + "directory": str(path), + "sha256": {file.name: sha256(file) for file in artifacts}, + "metadata": { + file.name: dict( + line.split("=", 1) for line in file.read_text().splitlines() if "=" in line + ) + for file in artifacts + if file.suffix == ".meta" + }, + } + return modules + + +def benchmark_timer(): + timer = Path("/usr/bin/time") + if not sys.platform.startswith("linux") or not timer.is_file(): + raise ValueError("Linux with GNU /usr/bin/time is required") + return timer + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--target-dir", type=Path, default=Path("target/benchmark-cli")) + parser.add_argument("--profile", choices=("debug", "release"), default="release") + parser.add_argument("--cli", type=Path) + parser.add_argument("--compare", type=Path) + parser.add_argument("--skip-build", action="store_true") + parser.add_argument("--isa", action="append", choices=tuple(ARCHITECTURES)) + parser.add_argument("--small", type=int, default=64) + parser.add_argument("--large", type=int, default=32768) + parser.add_argument("--runs", type=int, default=5) + parser.add_argument("--warmups", type=int, default=1) + parser.add_argument("--timeout", type=float, default=60) + args = parser.parse_args(argv) + if not ( + 0 <= args.small < args.large <= 32768 + and 1 <= args.runs <= 100 + and 0 <= args.warmups <= 20 + and math.isfinite(args.timeout) + and args.timeout > 0 + ): + parser.error("require 0 <= small < large <= 32768, runs 1..100, warmups 0..20, timeout > 0") + architectures = list(dict.fromkeys(args.isa or ARCHITECTURES)) + try: + timer = benchmark_timer() + target = args.target_dir.resolve() + features = ",".join(["socket-cli", *("asm-" + isa for isa in architectures)]) + command = [ + "cargo", + "build", + "--locked", + "--offline", + "--jobs", + "2", + "--no-default-features", + "--features", + features, + "--bin", + "whale", + "--target-dir", + str(target), + ] + if args.profile == "release": + command.append("--release") + if not args.skip_build: + execute(command, 600, env=dict(os.environ, CARGO_INCREMENTAL="0")) + cli = (args.cli or target / args.profile / "whale").resolve(strict=True) + product = product_info(cli, architectures, args.timeout) + environment = build_environment() + environment["product_configuration"] = { + "reference_feature": product.get("reference_feature"), + "native_linker": product.get("native_linker"), + "wave_compilers": { + module: { + key: data.get(key) + for key in ( + "wave_revision", + "target", + "opt_level", + "compiler_sha256", + "std_sha256", + ) + } + for module, data in product["wave_modules"].items() + }, + } + report = { + "format_version": FORMAT_VERSION, + "generator": GENERATOR, + "revision": text_command(["git", "rev-parse", "HEAD"]), + "dirty": bool(text_command(["git", "status", "--porcelain"])), + "rustc": text_command(["rustc", "-vV"]), + "cargo": text_command(["cargo", "-V"]), + "python": platform.python_version(), + "host": host_metadata(), + "profile": args.profile, + "build_command": command, + "build_executed": not args.skip_build, + "binaries_built_by_command": not args.skip_build and args.cli is None, + "cli_sha256": sha256(cli), + "product_build_info": product, + "driver_sha256": sha256(Path(__file__)), + "shared_driver_sha256": sha256(Path(benchmark.__file__)), + "runs": args.runs, + "warmups": args.warmups, + "counts": [args.small, args.large], + "architectures": architectures, + "cli_measured": True, + "build_environment": environment, + "native_modules": native_modules(), + "rss_method": text_command([str(timer), "--version"]).splitlines()[0] + + "; %M KiB converted to bytes; whole child-process high-water RSS", + "workloads": [], + "measurements": [], + } + args.output.parent.mkdir(parents=True, exist_ok=True) + inputs = args.output.parent / (args.output.stem + "-inputs") + for size, count in (("small", args.small), ("large", args.large)): + hashes, measurements = benchmark_size( + cli, (inputs / size).resolve(), count, architectures, args, timer + ) + report["workloads"].append({"size": size, "count": count, "sha256": hashes}) + for measurement in measurements: + measurement["name"] = size + "/" + measurement["name"] + report["measurements"].extend(measurements) + if sha256(cli) != report["cli_sha256"]: + raise ValueError("CLI executable changed during measurements") + if args.compare: + report["comparison"] = compare_reports(json.loads(args.compare.read_text()), report) + with tempfile.NamedTemporaryFile( + mode="w", encoding="utf-8", dir=args.output.parent, delete=False + ) as stream: + temporary = Path(stream.name) + try: + json.dump(report, stream, indent=2) + stream.write("\n") + stream.flush() + os.fsync(stream.fileno()) + stream.close() + os.replace(temporary, args.output) + finally: + temporary.unlink(missing_ok=True) + for measurement in report["measurements"]: + sample = measurement["median"] + print( + f"{measurement['name']}: {sample['phase_seconds'] * 1000:.3f} ms; " + f"{sample['peak_rss_bytes'] / 1048576:.2f} MiB RSS" + ) + print(f"saved {args.output}") + return 0 + except ( + ValueError, + OSError, + KeyError, + TypeError, + struct.error, + subprocess.SubprocessError, + ) as error: + print(f"CLI benchmark failed: {error}", file=sys.stderr) + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/build_wave_assembler.py b/tools/build_wave_assembler.py index 11ad067..2a56cbc 100644 --- a/tools/build_wave_assembler.py +++ b/tools/build_wave_assembler.py @@ -36,6 +36,7 @@ 'assembler/src/tokens_wave.rs', 'assembler/src/fixed.rs', 'assembler/src/fixed_wave.rs', + 'assembler/src/lib.rs', ), 'name': 'assembler', }, @@ -72,6 +73,7 @@ 'assembler/amd64/src/encoding/modrm.rs', 'assembler/amd64/src/encoding/rex.rs', 'assembler/amd64/src/encoding/sib.rs', + 'assembler/amd64/src/lib.rs', ), 'name': 'amd64', }, diff --git a/tools/build_wave_ir.py b/tools/build_wave_ir.py index e2cf01c..dad85e1 100644 --- a/tools/build_wave_ir.py +++ b/tools/build_wave_ir.py @@ -100,6 +100,9 @@ 'ir/src/printer_wave.rs', 'ir/src/verifier/wave_cfg.rs', 'ir/src/verifier/wave_shape.rs', + 'ir/src/lib.rs', + 'ir/src/function.rs', + 'ir/src/global_storage.rs', ) TARGETS = ( 'x86_64-unknown-linux-gnu', diff --git a/tools/check_wave_bytecode.py b/tools/check_wave_bytecode.py index 0a9e810..97aa7bb 100644 --- a/tools/check_wave_bytecode.py +++ b/tools/check_wave_bytecode.py @@ -4,6 +4,10 @@ import argparse import ctypes as C import json +import os +import sys + +from fuzz_checkpoint import Checkpoint from pathlib import Path import random import struct @@ -38,7 +42,7 @@ def __init__(self, **changes): class Result(C.Structure): _fields_ = [(field, U) for field in - 'status code table index work decoded_bytes scratch_words'.split()] + [('counts', U * 16)] + 'status code table index work decoded_bytes scratch_words estimated_workspace_bytes'.split()] + [('counts', U * 16)] def words(*values): @@ -180,7 +184,9 @@ def fixtures(): class Native: - def __init__(self, path): + def __init__(self, path, checkpoint=None): + self.checkpoint = checkpoint + self.context = {} self.library = C.CDLL(str(path)) self.probe = self.library.whale_ir_bytecode_probe self.probe.argtypes = [C.c_void_p, U, C.POINTER(Limits), C.POINTER(Result)] @@ -196,12 +202,16 @@ def __init__(self, path): def admit(self, data, limits=None): limits = limits or Limits() + if self.checkpoint: + self.checkpoint.before(data, **self.context, + limits={key: getattr(limits, key) for key, _ in Limits._fields_}) raw, result = C.create_string_buffer(data), Result() status = self.probe(raw, len(data), C.byref(limits), C.byref(result)) assert status == result.status and result.work <= limits.max_work if status: assert status != 4, ('file caused transport error', status, result.code) return status, result, None + assert result.estimated_workspace_bytes == result.decoded_bytes + result.scratch_words * 8 program, buffers = Program(), [] for name, count, stride in zip(FIELDS, result.counts, NATIVE_STRIDES): buffer = (U * max(1, (count * stride + 7) // 8))() @@ -213,16 +223,44 @@ def admit(self, data, limits=None): C.byref(limits), C.byref(result)) assert status == result.status and result.work <= limits.max_work assert status != 4, ('file caused transport error', status, result.code, result.table, result.index) + if status == 0: + assert result.estimated_workspace_bytes == workspace_estimate(data, result) + assert result.estimated_workspace_bytes <= limits.max_workspace_bytes return status, result, (program, buffers, scratch) +def workspace_estimate(data, result): + tables = parse_directory(data) + rows = [list(struct.iter_unpack('<' + 'Q' * (stride // 8), table)) + if stride != 1 else table for table, stride in zip(tables, STRIDES)] + expanded = [] + for kind, child, first, count, _ in rows[0]: + if kind in (17, 19): + expanded.append(1 + expanded[child]) + elif kind in (18, 20, 21): + expanded.append(1 + sum(expanded[rows[1][first + i][0]] for i in range(count))) + else: + expanded.append(1) + owned = 512 * (sum(expanded) + sum(expanded[function[1]] for function in rows[2])) + owned += len(tables[10]) + sum(rows[9][file[1]][1] for file in rows[11]) + for table, allowance in [(8, 64), (9, 32), (11, 96), (12, 96), (13, 96), (15, 16)]: + owned += len(rows[table]) * allowance + return result.decoded_bytes + result.scratch_words * 8 + owned + + def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--library', type=Path) parser.add_argument('--cases', type=int, default=10000) parser.add_argument('--scale', type=int, default=0) + parser.add_argument('--seed', type=int, default=0x57424331) + parser.add_argument('--artifacts', type=Path, + default=None) + parser.add_argument('--replay', type=Path) parser.add_argument('--write-fixtures', type=Path) args = parser.parse_args() + if not 0 <= args.cases <= 100000 or not 0 <= args.scale <= 32768 or not 0 <= args.seed < 2**64: + parser.error('cases must be 0..100000, scale 0..32768 and seed an unsigned 64-bit integer') cases = fixtures() if args.write_fixtures: args.write_fixtures.mkdir(parents=True, exist_ok=True) @@ -231,17 +269,43 @@ def main(): if not args.library: assert args.write_fixtures, 'provide --library or --write-fixtures' return - native, checked = Native(args.library), 0 + if args.artifacts is None: + import hashlib + root = Path(os.environ.get('WHALE_FUZZ_ARTIFACT_DIR', '.ci-artifacts/bytecode')) + args.artifacts = root / hashlib.sha256(args.library.read_bytes()).hexdigest()[:16] + args.artifacts = args.artifacts.resolve() + checkpoint = Checkpoint(args.artifacts, 'admission', + [sys.executable, str(Path(__file__).resolve()), '--library', str(args.library.resolve())]) + native, checked = Native(args.library, checkpoint), 0 + if args.replay: + metadata_path = args.replay.with_suffix('.json') + record = json.loads(metadata_path.read_text()) if metadata_path.is_file() else {} + with args.replay.open('rb') as stream: + data = stream.read((64 << 20) + 1) + native.context = {key: record[key] for key in ('case', 'seed', 'expected') if key in record} + status, _, _ = native.admit(data, Limits(**record.get('limits', {}))) + if record.get('expected') is not None: + assert (status == 0) == record['expected'] + checkpoint.finish(replay=str(args.replay), status=status) + print(json.dumps(dict(replay=str(args.replay), status=status))) + return for name, (data, expected) in cases.items(): + native.context = dict(case=name, expected=expected) status, result, _ = native.admit(data) assert (status == 0) == expected, (name, status, result.code, result.table, result.index) if expected: parse_directory(data) checked += 1 + native.context = dict(case='resource-boundaries', expected=None) valid = cases['return42.wbc'][0] status, result, _ = native.admit(valid) assert status == 0 exact_work = result.work + exact_workspace = result.estimated_workspace_bytes + for maximum, expected in [(exact_workspace, 0), (exact_workspace - 1, 2)]: + status, _, _ = native.admit(valid, Limits(max_workspace_bytes=maximum)) + assert status == expected, ('full workspace estimate', maximum, status, expected) + checked += 1 for maximum, expected in [(exact_work, 0), (exact_work - 1, 3), (575, 3), (0, 3)]: status, _, _ = native.admit(valid, Limits(max_work=maximum)) assert status == expected, ('cumulative work', maximum, status, expected) @@ -250,6 +314,17 @@ def main(): status, result, _ = native.admit(image(scale_tables(args.scale))) assert status == 0, ('scale', args.scale, status, result.code, result.table, result.index) checked += 1 + tables = simple_tables() + tables[0] += words(7, 0, 0, 0, 0) * min(args.scale * 8, 262144) + status, result, _ = native.admit(image(tables), Limits(max_workspace_bytes=256 << 20)) + assert status == 0, ('flat type O0 stack bound', status, result.code) + checked += 1 + tables = simple_tables() + tables[9], tables[10] = words(0, 2 << 20), b'x' * (2 << 20) + tables[11] = words(1, 0) + status, result, _ = native.admit(image(tables), Limits(max_workspace_bytes=8 << 20)) + assert status == 0, ('large UTF8 O0 stack bound', status, result.code) + checked += 1 # Small shared type DAGs cannot trigger exponentially expanded host Types. tables = simple_tables() for node in range(4, 25): @@ -266,9 +341,10 @@ def main(): status, _, _ = native.admit(image(tables), Limits(max_workspace_bytes=256 << 10)) assert status == 2, ('repeated filename budget', status) checked += 1 - rng = random.Random(0x57424331) + rng = random.Random(args.seed) accepted = 0 - for _ in range(args.cases): + for case in range(args.cases): + native.context = dict(case=case, seed=args.seed, expected=None) data = bytearray(valid) for _ in range(rng.randrange(1, 5)): at = rng.randrange(len(data)) @@ -278,6 +354,7 @@ def main(): parse_directory(data) accepted += 1 checked += 1 + checkpoint.finish(checked=checked, mutations=args.cases, seed=args.seed) print(json.dumps(dict(status='passed', checked=checked, mutations=args.cases, accepted_mutations=accepted, exact_valid_work=exact_work))) diff --git a/tools/check_wave_bytecode_writer.py b/tools/check_wave_bytecode_writer.py index dfc22c9..abd366b 100755 --- a/tools/check_wave_bytecode_writer.py +++ b/tools/check_wave_bytecode_writer.py @@ -9,10 +9,14 @@ import argparse import ctypes as c import hashlib +import json import random import struct +import sys from pathlib import Path +from fuzz_checkpoint import Checkpoint + U64 = c.c_uint64 MISSING = (1 << 64) - 1 STRIDES = (40, 8, 88, 32, 136, 8, 8, 64, 32, 16, 1, 16, 56, 40, 8, 8) @@ -83,7 +87,16 @@ def __init__(self, **changes): class Result(c.Structure): _fields_ = [ (name, U64) - for name in ["status", "code", "table", "index", "work", "decoded_bytes", "scratch_words"] + for name in [ + "status", + "code", + "table", + "index", + "work", + "decoded_bytes", + "scratch_words", + "estimated_workspace_bytes", + ] ] + [("counts", U64 * 16)] @@ -184,20 +197,112 @@ def expected_image(tables): return header + b"".join(directory) + b"".join(bodies) +def snapshot(packet): + tables = [] + for name, width in zip(PROGRAM_FIELDS, NATIVE_WORDS): + count = getattr(packet, name + "_count") + address = getattr(packet, name) + if width == 0: + tables.append(list(c.string_at(address, count))) + else: + words = c.cast(address, c.POINTER(U64)) + tables.append( + [list(words[index * width : (index + 1) * width]) for index in range(count)] + ) + return tables + + +def replay(native, path): + with path.open("rb") as stream: + original = stream.read((64 << 20) + 1) + if len(original) > 64 << 20: + raise ValueError("writer replay exceeds 64 MiB") + record = json.loads(original) + if not isinstance(record, dict): + raise TypeError("writer replay must be an object") + if record.get("schema") != 1 or record.get("operation") not in ("verify", "write"): + raise ValueError("unsupported writer replay schema") + tables = record["tables"] + if not isinstance(tables, list) or len(tables) != 16: + raise ValueError("writer replay requires 16 raw semantic tables") + amount = 0 + for rows, width in zip(tables, NATIVE_WORDS): + if not isinstance(rows, list): + raise TypeError("invalid writer replay table") + amount += len(rows) * (width * 8 if width else 1) + if amount > 64 << 20: + raise ValueError("writer replay table allocation exceeds 64 MiB") + for row in rows: + values = [row] if width == 0 else row + if not isinstance(values, list) or len(values) != (width if width else 1): + raise ValueError("invalid writer replay row") + maximum = MISSING if width else 255 + if any(type(value) is not int or not 0 <= value <= maximum for value in values): + raise ValueError("invalid writer replay unsigned field") + tables[10] = bytes(tables[10]) + raw_limits = record["limits"] + if ( + not isinstance(raw_limits, dict) + or set(raw_limits) != {name for name, _ in Limits._fields_} + or any(type(value) is not int or not 0 <= value <= MISSING for value in raw_limits.values()) + ): + raise ValueError("invalid writer replay limits") + limits = Limits(**raw_limits) + capacity, words = record["capacity"], record["scratch_words"] + if any( + type(value) is not int or not 0 <= value <= maximum + for value, maximum in ((capacity, 64 << 20), (words, (128 << 20) // 8)) + ): + raise ValueError("invalid writer replay capacity") + expected = record["expected_status"] + if type(expected) is not int or not -1 <= expected <= 5: + raise ValueError("invalid writer replay expectation") + packet, keep = native.packet(tables) + scratch = (U64 * words)() + native.phase = "replay/" + record["operation"] + if record["operation"] == "verify": + result = Result() + status = native.verify(c.byref(packet), scratch, words, c.byref(limits), c.byref(result)) + assert status == result.status and result.work <= limits.max_work, vars_result(result) + else: + query = record["query"] + if type(query) is not bool or (query and capacity != 0): + raise ValueError("invalid writer replay query") + status, required, output, result = native.publish( + packet, scratch, limits, capacity, query=query, expected_status=expected + ) + if status == 0: + image = expected_image(tables) + assert required == len(image) + if not query: + assert output[:required] == image + assert output[required:] == bytes([0xA5]) * (capacity - required) + else: + assert output is None or output == bytes([0xA5]) * capacity + if expected == -1: + assert status != 0, vars_result(result) + else: + assert status == expected, vars_result(result) + assert keep + + class Native: - def __init__(self, library): + def __init__(self, library, checkpoint=None): + self.checkpoint = checkpoint + self.phase = "admission" + self.case = 0 self.library = c.CDLL(str(library.resolve())) - self.verify = self.library.whale_ir_bytecode_verify - self.verify.argtypes = [ + self._verify = self.library.whale_ir_bytecode_verify + self._verify.argtypes = [ c.POINTER(Program), c.POINTER(U64), U64, c.POINTER(Limits), c.POINTER(Result), ] - self.verify.restype = c.c_int32 - self.write = self.library.whale_ir_bytecode_write - self.write.argtypes = [ + self._verify.restype = c.c_int32 + self._write = self.library.whale_ir_bytecode_write + self._write.argtypes = [ c.POINTER(Program), c.POINTER(c.c_uint8), U64, @@ -207,7 +312,35 @@ def __init__(self, library): c.POINTER(Limits), c.POINTER(Result), ] - self.write.restype = c.c_int32 + self._write.restype = c.c_int32 + + def remember( + self, operation, packet, limits, capacity, scratch_words, expected_status, query=False + ): + if self.checkpoint is None: + return + tables = snapshot(packet) + record = { + "schema": 1, + "operation": operation, + "tables": tables, + "limits": {name: getattr(limits, name) for name, _ in Limits._fields_}, + "capacity": capacity, + "scratch_words": scratch_words, + "expected_status": expected_status, + "query": query, + } + original = (json.dumps(record, separators=(",", ":"), sort_keys=True) + "\n").encode() + self.checkpoint.before( + original, seed=0x363_2026, case=self.case, phase=self.phase, operation=operation + ) + self.case += 1 + + def verify(self, packet, scratch, capacity, limits, result): + program = c.cast(packet, c.POINTER(Program)).contents + settings = c.cast(limits, c.POINTER(Limits)).contents + self.remember("verify", program, settings, 0, capacity, 2 if capacity == 0 else 0) + return self._verify(packet, scratch, capacity, limits, result) def packet(self, tables): packet = Program() @@ -228,6 +361,8 @@ def admitted(self, packet, limits): result = Result() status = self.verify(c.byref(packet), None, 0, c.byref(limits), c.byref(result)) assert status == result.status == 2 and result.scratch_words > 0, vars_result(result) + assert result.decoded_bytes + result.scratch_words * 8 <= result.estimated_workspace_bytes + assert result.estimated_workspace_bytes <= limits.max_workspace_bytes scratch = (U64 * result.scratch_words)() status = self.verify( c.byref(packet), scratch, len(scratch), c.byref(limits), c.byref(result) @@ -235,11 +370,12 @@ def admitted(self, packet, limits): assert status == result.status == 0, vars_result(result) return scratch - def publish(self, packet, scratch, limits, capacity, *, query=False): + def publish(self, packet, scratch, limits, capacity, *, query=False, expected_status=0): output = None if query else (c.c_uint8 * capacity)(*([0xA5] * capacity)) required = U64(MISSING) result = Result() - status = self.write( + self.remember("write", packet, limits, capacity, len(scratch), expected_status, query) + status = self._write( c.byref(packet), output, capacity, @@ -276,6 +412,7 @@ def golden_cases(native, output_dir): ] hashes = {} for name, tables in cases: + native.phase = "golden/" + name packet, keep = native.packet(tables) limits = Limits() scratch = native.admitted(packet, limits) @@ -285,6 +422,9 @@ def golden_cases(native, output_dir): status, required, actual, result = native.publish(packet, scratch, limits, required) assert status == 0 and required == len(expected), (name, vars_result(result)) assert actual == expected, name + status, needed, padded, result = native.publish(packet, scratch, limits, required + 17) + assert status == 0 and needed == required, vars_result(result) + assert padded[:required] == expected and padded[required:] == bytes([0xA5]) * 17 assert keep # Keep all borrowed native arrays alive through both calls. hashes[name] = hashlib.sha256(expected).hexdigest() if output_dir: @@ -294,17 +434,23 @@ def golden_cases(native, output_dir): text_end = struct.unpack_from(" self.max_bytes: + raise ValueError('checkpoint input exceeds its byte ceiling') + if not self.started: + (self.directory / (self.name + '.completed.json')).unlink(missing_ok=True) + self.started = True + # The manifest is the commit point. Its original stays immutable until + # a new manifest is published, including interruption between the writes. + previous = self.input if self.input.is_file() else None + if previous is None and self.manifest.is_file(): + saved = Path(json.loads(self.manifest.read_text())['input']) + suffix = saved.name.removeprefix(self.name + '.current-') + if saved.parent == self.directory and len(suffix) == 64 and all(c in '0123456789abcdef' for c in suffix): + previous = saved + digest = hashlib.sha256(original).hexdigest() + candidate = self.directory / (self.name + '.current-' + digest) + atomic_write(candidate, original) + record = dict(metadata, state='active', input=str(candidate), + bytes=len(original), sha256=digest, + replay=[*self.replay_command, '--replay', str(candidate)]) + try: + atomic_write(self.manifest, (json.dumps(record, indent=2) + '\n').encode()) + except BaseException: + if candidate != previous: + candidate.unlink(missing_ok=True) + raise + self.input = candidate + self.digest = digest + if previous is not None and previous != candidate: + previous.unlink(missing_ok=True) + + def finish(self, **metadata): + atomic_write(self.directory / (self.name + '.completed.json'), + (json.dumps(dict(metadata, state='completed', input_sha256=self.digest), indent=2) + '\n').encode()) diff --git a/tools/fuzz_smoke.py b/tools/fuzz_smoke.py index bb3f871..519c83a 100644 --- a/tools/fuzz_smoke.py +++ b/tools/fuzz_smoke.py @@ -17,7 +17,7 @@ def main(): parser.add_argument("--cases", type=int, default=512) parser.add_argument("--seed", type=int, default=1464353100) parser.add_argument("--timeout", type=int, default=60) - parser.add_argument("--target", choices=["assembler", "object", "ir", "ast"], action="append") + parser.add_argument("--target", choices=["assembler", "object", "ir", "ast", "bytecode"], action="append") parser.add_argument("--memory-mib", type=int, default=512) args = parser.parse_args() if not 1 <= args.cases <= 100000 or not 1 <= args.timeout <= 300 or not 0 <= args.seed < 2**64 or not 64 <= args.memory_mib <= 4096: @@ -26,7 +26,7 @@ def main(): binary = args.binary.resolve() env = dict(os.environ) env.setdefault("WHALE_FUZZ_ARTIFACT_DIR", str(root / ".ci-artifacts/fuzz")) - for target in args.target or ["assembler", "object", "ir", "ast"]: + for target in args.target or ["assembler", "object", "ir", "ast", "bytecode"]: subprocess.run([sys.executable, str(root / "tools/fuzz_limits.py"), "--memory-mib", str(args.memory_mib), "--", str(binary), target, str(args.cases), str(args.seed)], cwd=root, env=env, check=True, timeout=args.timeout) diff --git a/tools/meson_cargo.py b/tools/meson_cargo.py index ec2a955..bb2722f 100644 --- a/tools/meson_cargo.py +++ b/tools/meson_cargo.py @@ -8,6 +8,7 @@ import argparse import json +import json import os from pathlib import Path import re @@ -21,7 +22,7 @@ class BuildError(ValueError): ASSEMBLERS = ("amd64", "aarch64", "riscv64", "loongarch64") -FEATURES = {"asm-" + arch for arch in ASSEMBLERS} | {"socket-cli", "native-linker"} +FEATURES = {"asm-" + arch for arch in ASSEMBLERS} | {"socket-cli", "native-linker", "rust-reference"} COMPONENTS = ("diagnostic", "assembler", "backend-api", "toolchain", "reverse", "target-spec", "object", "linker", "ir") TRIPLE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]+\Z") @@ -38,7 +39,8 @@ def validate_features(features): def cargo_environment(target_dir, asmobj_directory, profile, optimization, debug_info, wave_ir_directory=None, wave_assembler_directory=None, wave_amd64_directory=None, wave_aarch64_directory=None, - wave_riscv64_directory=None, wave_loongarch64_directory=None): + wave_riscv64_directory=None, wave_loongarch64_directory=None, + source_root=None): environment = os.environ.copy() environment.pop("WHALE_ASMOBJ_DIR", None) environment.pop("WHALE_WAVE_IR_DIR", None) @@ -54,6 +56,19 @@ def cargo_environment(target_dir, asmobj_directory, profile, optimization, debug prefix = "CARGO_PROFILE_" + profile.upper() + "_" environment[prefix + "OPT_LEVEL"] = optimization environment[prefix + "DEBUG"] = debug_info + if source_root: + # Cargo's encoded form preserves paths with spaces and existing flags. + encoded = environment.get("CARGO_ENCODED_RUSTFLAGS") + if encoded is not None: + flags = encoded.split("\x1f") if encoded else [] + else: + flags = environment.get("RUSTFLAGS", "").split() + cargo_home = Path(environment.get("CARGO_HOME", Path.home() / ".cargo")).resolve() + flags += [f"--remap-path-prefix={source_root}=/whale-src", + f"--remap-path-prefix={target_dir}=/whale-build", + f"--remap-path-prefix={cargo_home}=/cargo"] + environment["CARGO_ENCODED_RUSTFLAGS"] = "\x1f".join(flags) + environment.pop("RUSTFLAGS", None) if asmobj_directory: environment["WHALE_ASMOBJ_DIR"] = str(asmobj_directory) if wave_ir_directory: @@ -174,7 +189,8 @@ def source_dependencies(source, features): dependencies.add(path) dependencies.update(path.iterdir()) dependencies.add(source / "assembler/asmobj") - dependencies.update((source / "assembler/asmobj").glob("*.wave")) + dependencies.update((source / "assembler/asmobj").rglob("*.wave")) + dependencies.update(path for path in (source / "assembler/asmobj").rglob("*") if path.is_dir()) dependencies.update((source / "ir").glob("*.wave")) dependencies.update((source / "assembler").glob("*.wave")) if (source / "assembler/build_support.rs").is_file(): @@ -185,6 +201,28 @@ def source_dependencies(source, features): return dependencies +def revision_dependencies(source): + """Track provenance changes for normal and linked Git worktrees.""" + marker = source / ".git" + directory = marker + if marker.is_file(): + text = marker.read_text().strip() + if not text.startswith("gitdir: "): + return set() + directory = (source / text[8:]).resolve() + if not directory.is_dir(): + return set() + common = directory + if (directory / "commondir").is_file(): + common = (directory / (directory / "commondir").read_text().strip()).resolve() + dependencies = {directory / "HEAD", directory / "index", common / "packed-refs"} + if (directory / "HEAD").is_file(): + head = (directory / "HEAD").read_text().strip() + if head.startswith("ref: "): + dependencies.add(common / head[5:]) + return {path for path in dependencies if path.is_file()} + + def _temporary_copy(source, destination): with tempfile.NamedTemporaryFile(prefix=".whale-", dir=destination.parent, delete=False) as temporary: path = Path(temporary.name) @@ -241,7 +279,7 @@ def build(arguments): arguments.opt_level, arguments.debug_info, wave_ir_directory, wave_assembler_directory, wave_amd64_directory, wave_aarch64_directory, wave_riscv64_directory, - wave_loongarch64_directory) + wave_loongarch64_directory, source_root=source) target = arguments.host_target or native_target(arguments.cargo, source, environment) if not TRIPLE.fullmatch(target): raise BuildError("cargo host target must be a Rust target triple") @@ -254,11 +292,12 @@ def build(arguments): if not binary.is_file(): raise BuildError("Cargo did not produce the requested Whale host executable") dependencies = source_dependencies(source, features) + dependencies.update(revision_dependencies(source)) dependencies.update(Path(path) if Path(path).is_absolute() else source / path for path in cargo_dependencies(directory / "whale.d")) if asmobj_directory: archive = "whale_asmobj.lib" if "msvc" in target else "libwhale_asmobj.a" - dependencies.update(asmobj_directory / name for name in [archive, "asmobj.meta"]) + dependencies.update(asmobj_directory / name for name in [archive, "asmobj.meta", "provenance.json"]) if wave_ir_directory: archive = "whale_wave_ir.lib" if "msvc" in target else "libwhale_wave_ir.a" dependencies.update(wave_ir_directory / name for name in [archive, "wave-ir.meta", "provenance.json"]) @@ -332,6 +371,27 @@ def invoke(values): result = invoke(["ir", "run", ir, "--function", "@f0"]) if result.returncode or result.stdout != b"i32 42\n": raise BuildError("Whale IR smoke failed") + metadata = invoke(["build-info", "--json"]) + try: + info = json.loads(metadata.stdout) + except (ValueError, UnicodeError) as error: + raise BuildError("Whale build provenance is invalid") from error + selected = sorted(arch for arch in ASSEMBLERS if "asm-" + arch in features) + if (metadata.returncode or info.get("assemblers") != selected + or info.get("native_linker") != ("native-linker" in features)): + raise BuildError("Whale build provenance differs from selected components") + if "rust-reference" not in features and info.get("product_mode") != "wave": + raise BuildError("the default Meson product must execute Wave modules") + if info.get("implementations", {}).get("ir") == "wave": + ir.write_text(ir.read_text().replace('"x86_64-whale-linux"', '"whale-bytecode-v1"')) + image = directory / "answer.wbc" + emitted = invoke(["ir", "emit", ir, "-o", image]) + if emitted.returncode or not image.is_file() or image.read_bytes()[:8] != b"WHALEBC\0": + raise BuildError("Whale bytecode emission smoke failed") + verified = invoke(["bytecode", "verify", image]) + result = invoke(["bytecode", "run", image, "--function", "@f0"]) + if verified.returncode or result.returncode or result.stdout != b"i32 42\n": + raise BuildError("Whale bytecode execution smoke failed") def bootstrap(arguments): diff --git a/tools/release.py b/tools/release.py index 11ceec2..512b902 100644 --- a/tools/release.py +++ b/tools/release.py @@ -16,6 +16,7 @@ import zipfile from ci_smoke import text_section +from wave_bootstrap import WAVE_REVISION ROOT = Path(__file__).resolve().parents[1] TARGETS = { @@ -28,6 +29,62 @@ } MAX_BINARY = 256 * 1024 * 1024 MAX_ARCHIVE = 300 * 1024 * 1024 +ISAS = {"amd64", "aarch64", "riscv64", "loongarch64"} + + +def validate_product(info, version, target, source, socket, require_wave=False): + required = {"schema_version", "source_commit", "source_dirty", "host_target", "rustc", + "reference_feature", "wave_modules", "product_mode", "implementations", "version", + "ir_format_version", "semantics_version", "bytecode_format_version", "assemblers", + "native_linker", "socket_cli"} + if type(info) is not dict or set(info) != required: + raise ValueError("invalid product provenance fields") + if (type(info["schema_version"]) is not int or info["schema_version"] != 1 + or info["version"] != version or info["host_target"] != target + or info["source_commit"] != source or info["socket_cli"] is not socket + or any(type(info[key]) is not bool for key in + ("source_dirty", "reference_feature", "native_linker", "socket_cli")) + or type(info["rustc"]) is not str or not info["rustc"].startswith("rustc ") + or any(type(info[key]) is not int or info[key] != expected for key, expected in + (("ir_format_version", 8), ("semantics_version", 1), ("bytecode_format_version", 1)))): + raise ValueError("product provenance identity mismatch") + selected = info["assemblers"] + if (type(selected) is not list or any(type(arch) is not str or arch not in ISAS for arch in selected) + or selected != sorted(set(selected))): + raise ValueError("invalid product assembler selection") + implementations, modules = info["implementations"], info["wave_modules"] + expected = {"ir", "assembler", "asmobj", *selected} + if (type(implementations) is not dict or set(implementations) != expected + or any(value not in ("wave", "rust-reference", "unavailable") + for value in implementations.values()) or type(modules) is not dict + or set(modules) != {name for name, value in implementations.items() if value == "wave"}): + raise ValueError("product module identities and archives disagree") + provenance_fields = {"wave_revision", "target", "opt_level", "source_sha256", "abi_sha256", + "archive_sha256", "compiler_sha256", "std_sha256", "bootstrap_rust_version", + "required_llvm_major"} + for module in modules.values(): + if (type(module) is not dict or set(module) != provenance_fields + or module["wave_revision"] != WAVE_REVISION or module["target"] != target + or module["opt_level"] not in ("0", "2") + or module["bootstrap_rust_version"] != "1.89.0" + or type(module["required_llvm_major"]) is not int or module["required_llvm_major"] != 21 + or any(type(module[key]) is not str or not re.fullmatch("[0-9a-f]{64}", module[key]) + for key in ("source_sha256", "abi_sha256", "archive_sha256", "compiler_sha256", "std_sha256"))): + raise ValueError("invalid Wave compiler/source/archive provenance") + mode = ("wave" if all(value == "wave" for value in implementations.values()) else + "rust-reference" if implementations["ir"] == "rust-reference" else "mixed") + if info["product_mode"] != mode: + raise ValueError("product mode disagrees with linked module identities") + if require_wave and (mode != "wave" or info["source_dirty"] or target != "x86_64-unknown-linux-gnu"): + raise ValueError("a clean, fully Wave-backed Linux AMD64 product is required") + return info + + +def product_info(binary, directory, version, target, source, socket, require_wave=False): + result = invoke(binary, ["build-info", "--json"], directory) + if result.returncode or len(result.stdout) > 16384: + raise ValueError("binary did not provide bounded product provenance") + return validate_product(json.loads(result.stdout), version, target, source, socket, require_wave) def identity(version, target, source): @@ -94,7 +151,9 @@ def publish_bytes(path, data): def invoke(binary, args, cwd): - environment = dict(os.environ, PATH=str(cwd / "empty-path")) + environment = {key: value for key, value in os.environ.items() + if not key.startswith(("WHALE_", "LLVM_SYS_"))} + environment["PATH"] = str(cwd / "empty-path") return subprocess.run([str(binary), *map(str, args)], cwd=cwd, env=environment, capture_output=True, timeout=20, check=False) @@ -106,7 +165,7 @@ def check_socket(binary, directory, enabled): raise ValueError("manifest socket-cli availability disagrees with binary") -def package(binary, output, version, target, source, socket=False, root=ROOT): +def package(binary, output, version, target, source, socket=False, root=ROOT, require_wave=False): stem = identity(version, target, source) cargo_version = tomllib.loads((root / "Cargo.toml").read_text())["package"]["version"] if cargo_version != version: @@ -119,9 +178,10 @@ def package(binary, output, version, target, source, socket=False, root=ROOT): if result.returncode or result.stdout.strip() != f"whale {version}".encode(): raise ValueError("binary version does not match requested version") check_socket(binary, Path(directory), socket) - manifest = {"format_version": 1, "version": version, "target": target, + product = product_info(binary, Path(directory), version, target, source, socket, require_wave) + manifest = {"format_version": 2, "version": version, "target": target, "source_commit": source, "socket_cli": socket, - "binary": binary_name(target), "binary_sha256": digest(payload)} + "binary": binary_name(target), "binary_sha256": digest(payload), "product": product} entries = {manifest["binary"]: payload, "LICENSE": limited_read(root / "LICENSE", 1024 * 1024), "README.md": limited_read(root / "README.md", 1024 * 1024), @@ -223,8 +283,10 @@ def keep(name, size, mode, stream): raise ValueError("incomplete release archive") manifest = json.loads(entries[f"{stem}/manifest.json"][0]) required = {"format_version", "version", "target", "source_commit", "socket_cli", "binary", "binary_sha256"} + if type(manifest) is dict and manifest.get("format_version") == 2: + required.add("product") if (type(manifest) is not dict or set(manifest) != required - or type(manifest["format_version"]) is not int or manifest["format_version"] != 1 + or type(manifest["format_version"]) is not int or manifest["format_version"] not in (1, 2) or type(manifest["socket_cli"]) is not bool or any(type(manifest[key]) is not str for key in ("version", "target", "source_commit", "binary", "binary_sha256")) @@ -232,6 +294,8 @@ def keep(name, size, mode, stream): or manifest["target"] != target or manifest["source_commit"] != source or manifest["binary"] != binary_name(target)): raise ValueError("archive manifest identity mismatch") + if manifest["format_version"] == 2: + validate_product(manifest["product"], version, target, source, manifest["socket_cli"]) data, mode = entries[f"{stem}/{manifest['binary']}"] if digest(data) != manifest["binary_sha256"] or not mode & 0o111: raise ValueError("binary checksum or executable permission mismatch") @@ -245,10 +309,73 @@ def keep(name, size, mode, stream): return directory / stem / manifest["binary"], manifest -def validate(archive, version, target, source, execute=True): +def object_text(data, machine): + if len(data) < 64 or data[:7] != b"\x7fELF\x02\x01\x01" or struct.unpack_from(" len(data): + raise ValueError("invalid assembler object table") + headers = [struct.unpack_from(" len(data): + raise ValueError("invalid assembler section payload") + return data[start:start + size] + + names = payload(headers[names_index]) + for header in headers: + first = header[0] + end = names.find(b"\0", first) + if first >= len(names) or end < 0: + raise ValueError("invalid assembler section name") + if names[first:end] == b".text": + return payload(header) + raise ValueError("missing assembler text section") + + +def smoke_product(binary, outside, product): + fixtures = { + "amd64": (62, "mov eax, 42\nret\n", "b82a000000c3"), + "aarch64": (183, "mov x0, #42\nret\n", "400580d2c0035fd6"), + "riscv64": (243, "addi a0,zero,42\nret\n", "1305a00267800000"), + "loongarch64": (258, "addi.d $a0,$zero,42\njirl $zero,$ra,0\n", "04a8c0022000004c"), + } + for arch in product["assemblers"]: + machine, text, expected = fixtures[arch] + assembly, obj = outside / (arch + ".asm"), outside / (arch + ".o") + assembly.write_text(".text\n" + text if arch != "amd64" else "section .text\n" + text) + result = invoke(binary, ["asm", "--arch", arch, assembly, "-o", obj], outside) + if result.returncode or object_text(limited_read(obj, 65536), machine) != bytes.fromhex(expected): + raise ValueError(f"extracted {arch} assembly failed") + before = obj.read_bytes() + assembly.write_text("invalid_instruction\n") + result = invoke(binary, ["asm", "--arch", arch, assembly, "-o", obj], outside) + if not result.returncode or obj.read_bytes() != before: + raise ValueError("extracted malformed-input preservation failed") + if product["implementations"]["ir"] == "wave": + text, image = outside / "answer.wir", outside / "answer.wbc" + text.write_text('module { format_version 8 semantics_version 1 target "whale-bytecode-v1" ' + 'datalayout {ptr=64,endian=little} ' + 'declare @f0 "answer": whale () -> i32, linkage internal ' + 'fn @f0 "answer"() -> i32, entry %b0 { %b0 "entry": ' + '%v0: i32 = const i32 42 ret i32 %v0 } }') + emitted = invoke(binary, ["ir", "emit", text, "-o", image], outside) + verified = invoke(binary, ["bytecode", "verify", image], outside) + ran = invoke(binary, ["bytecode", "run", image, "--function", "@f0"], outside) + if emitted.returncode or verified.returncode or ran.returncode or ran.stdout != b"i32 42\n": + raise ValueError("extracted bytecode compile/verify/run failed") + + +def validate(archive, version, target, source, execute=True, require_wave=False): with tempfile.TemporaryDirectory(prefix="whale extracted ") as directory: root = Path(directory) binary, manifest = unpack(archive, root, version, target, source) + if require_wave: + if "product" not in manifest: + raise ValueError("Wave packages require embedded product provenance") + validate_product(manifest["product"], version, target, source, manifest["socket_cli"], True) if not execute: return manifest outside = root / "outside checkout" @@ -258,6 +385,13 @@ def validate(archive, version, target, source, execute=True): expected = b"whale asm" if flag == "--help" else f"whale {version}".encode() if result.returncode or expected not in result.stdout: raise ValueError("extracted CLI help/version failed") + if "product" in manifest: + actual = product_info(binary, outside, version, target, source, manifest["socket_cli"], require_wave) + if actual != manifest["product"]: + raise ValueError("extracted binary provenance differs from package manifest") + smoke_product(binary, outside, actual) + check_socket(binary, outside, manifest["socket_cli"]) + return manifest assembly, obj = outside / "input.asm", outside / "out.o" assembly.write_text("section .text\nmov eax, 42\nret\n", encoding="utf-8") result = invoke(binary, ["asm", "--amd64", assembly, "-o", obj], outside) @@ -301,6 +435,7 @@ def main(): parser.add_argument("--target", action="append", choices=TARGETS) parser.add_argument("--binary", type=Path) parser.add_argument("--socket-cli", action="store_true") + parser.add_argument("--require-wave", action="store_true", help="require a clean validated Wave product") parser.add_argument("--directory", type=Path, default=Path("dist")) args = parser.parse_args() targets = args.target or list(TARGETS) @@ -312,10 +447,11 @@ def main(): if args.operation == "package": if args.binary is None: parser.error("package requires --binary") - package(args.binary, args.directory, args.version, target, args.source, args.socket_cli) + package(args.binary, args.directory, args.version, target, args.source, args.socket_cli, + require_wave=args.require_wave) else: validate(args.directory / archive_name(args.version, target, args.source), - args.version, target, args.source) + args.version, target, args.source, require_wave=args.require_wave) else: checksums(args.directory, args.version, args.source, targets, args.operation == "verify") except (ValueError, OSError, subprocess.SubprocessError, tarfile.TarError, diff --git a/tools/test_benchmark_cli.py b/tools/test_benchmark_cli.py new file mode 100644 index 0000000..520499f --- /dev/null +++ b/tools/test_benchmark_cli.py @@ -0,0 +1,206 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Correctness and publication gates for actual CLI performance evidence.""" + +import contextlib +import io +import struct +import tempfile +import unittest +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import patch + +import benchmark_cli as bench + + +def elf_object(code, machine=62): + """A small independently constructed ELF64 object with just section headers.""" + strings = b"\0.shstrtab\0.text\0" + names = 64 + len(code) + table = (names + len(strings) + 7) & ~7 + data = bytearray(table + 3 * 64) + data[:7] = b"\x7fELF\x02\x01\x01" + struct.pack_into(" %v1, align 4\n" for index in range(2, 5)] + text = "".join(loads) + "ret i32 %v4\n" + bench.check_lowered(text.encode(), 2) + for wrong in ( + text.replace(loads[1], ""), + loads[1] + loads[0] + loads[2] + "ret i32 %v4\n", + text.replace("ret i32 %v4", "ret i32 %v3"), + ): + with self.subTest(wrong=wrong), self.assertRaises(ValueError): + bench.check_lowered(wrong.encode(), 2) + + def test_phase_deletes_outputs_checks_warmups_and_uses_measured_samples(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + source, output = root / "source", root / "output" + source.write_bytes(b"input") + output.write_bytes(b"stale") + times = iter([999, 1, 3, 2]) + + def execute(*_args): + self.assertFalse(output.exists()) + output.write_bytes(b"validated") + return b"status", next(times), 1024 + + args = SimpleNamespace(runs=3, warmups=1, timeout=1) + with patch("benchmark_cli.execute", side_effect=execute) as invoked: + result = bench.run_phase( + "phase", + 1, + ["cli"], + source, + output, + lambda data: self.assertEqual(data, b"validated"), + args, + "timer", + ) + self.assertEqual(invoked.call_count, 4) + self.assertEqual(len(result["samples"]), 3) + self.assertEqual(result["median"]["phase_seconds"], 2) + self.assertEqual(result["fingerprint"]["result_sha256"], bench.digest(b"validated")) + + def test_missing_output_cannot_reuse_an_earlier_success(self): + with tempfile.TemporaryDirectory() as directory: + source, output = Path(directory) / "source", Path(directory) / "output" + source.write_bytes(b"input") + output.write_bytes(b"old valid output") + with ( + patch("benchmark_cli.execute", return_value=(b"", 1, 1024)), + self.assertRaises(FileNotFoundError), + ): + bench.run_phase( + "phase", + 1, + ["cli"], + source, + output, + lambda _: None, + SimpleNamespace(runs=1, warmups=0, timeout=1), + "timer", + ) + + def test_changed_validated_output_and_input_are_rejected(self): + with tempfile.TemporaryDirectory() as directory: + source = Path(directory) / "source" + source.write_bytes(b"input") + args = SimpleNamespace(runs=1, warmups=1, timeout=1) + with ( + patch( + "benchmark_cli.execute", + side_effect=[(b"first", 1, 1024), (b"different", 1, 1024)], + ), + self.assertRaisesRegex(ValueError, "non-deterministic"), + ): + bench.run_phase("phase", 1, ["cli"], source, None, lambda _: None, args, "timer") + + def changed_input(*_args): + source.write_bytes(b"changed") + return b"output", 1, 1024 + + with ( + patch("benchmark_cli.execute", side_effect=changed_input), + self.assertRaisesRegex(ValueError, "changed input"), + ): + bench.run_phase("phase", 1, ["cli"], source, None, lambda _: None, args, "timer") + + def test_failed_command_preserves_an_existing_report(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + binary, report = root / "whale", root / "report.json" + binary.write_bytes(b"selected executable") + report.write_bytes(b"previous complete report") + with ( + patch("benchmark_cli.benchmark_timer", return_value=root / "timer"), + patch("benchmark_cli.text_command", return_value="test version"), + patch("benchmark_cli.native_modules", return_value={}), + patch("benchmark_cli.product_info", return_value={"wave_modules": {}}), + patch("benchmark_cli.benchmark_size", side_effect=ValueError("bad artifact")), + contextlib.redirect_stderr(io.StringIO()), + ): + status = bench.main( + [ + "--output", + str(report), + "--cli", + str(binary), + "--skip-build", + "--small", + "1", + "--large", + "2", + "--runs", + "1", + "--warmups", + "0", + ] + ) + self.assertEqual(status, 1) + self.assertEqual(report.read_bytes(), b"previous complete report") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_build_wave_assembler.py b/tools/test_build_wave_assembler.py index 183f23f..a57176e 100644 --- a/tools/test_build_wave_assembler.py +++ b/tools/test_build_wave_assembler.py @@ -103,7 +103,7 @@ def setUpClass(cls): def tearDownClass(cls): cls.temporary.cleanup() - def test_plain_cargo_is_available_and_all_stale_or_corrupt_inputs_are_rejected(self): + def test_reference_is_explicit_and_all_stale_or_corrupt_inputs_are_rejected(self): for module, config in helper.MODULES.items(): with self.subTest(module=module), tempfile.TemporaryDirectory() as tmp: root = Path(tmp).resolve() @@ -126,12 +126,19 @@ def test_plain_cargo_is_available_and_all_stale_or_corrupt_inputs_are_rejected(s helper.abi_bytes(root, module), archive.read_bytes(), provenance.read_bytes(), NATIVE, "2") metadata.write_text(original) env = os.environ.copy() - for variable in ("WHALE_WAVE_ASSEMBLER_DIR", "WHALE_WAVE_AMD64_DIR"): + for variable in (f"WHALE_WAVE_{config['name'].upper()}_DIR" + for config in helper.MODULES.values()): env.pop(variable, None) env.update(CARGO_MANIFEST_DIR=str(source), TARGET=NATIVE) + env.pop("CARGO_FEATURE_RUST_REFERENCE", None) plain = subprocess.run([str(self.guards[module])], env=env, capture_output=True) - self.assertEqual(plain.returncode, 0, plain.stderr) - self.assertNotIn(b"rustc-link-lib", plain.stdout) + self.assertNotEqual(plain.returncode, 0, plain.stderr) + self.assertIn(b"requires its Wave module", plain.stderr) + env["CARGO_FEATURE_RUST_REFERENCE"] = "1" + reference = subprocess.run([str(self.guards[module])], env=env, capture_output=True) + self.assertEqual(reference.returncode, 0, reference.stderr) + self.assertNotIn(b"rustc-link-lib", reference.stdout) + env.pop("CARGO_FEATURE_RUST_REFERENCE") env["WHALE_WAVE_ASSEMBLER_DIR"] = str(output) env[f"WHALE_WAVE_{name.upper()}_DIR"] = str(output) diff --git a/tools/test_build_wave_ir.py b/tools/test_build_wave_ir.py index be4c81e..bc1ea95 100644 --- a/tools/test_build_wave_ir.py +++ b/tools/test_build_wave_ir.py @@ -132,7 +132,7 @@ def setUpClass(cls): def tearDownClass(cls): cls.temporary.cleanup() - def test_plain_build_and_corrupt_artifact_rejection(self): + def test_explicit_reference_and_corrupt_artifact_rejection(self): with tempfile.TemporaryDirectory() as temporary: root = Path(temporary).resolve() source = root / "ir" @@ -175,8 +175,14 @@ def check(changes, expected): for key, data in originals.items(): paths[key].write_bytes(data) + environment.pop("CARGO_FEATURE_RUST_REFERENCE", None) plain = subprocess.run([str(self.guard)], env=environment, capture_output=True) - self.assertEqual(plain.returncode, 0) + self.assertNotEqual(plain.returncode, 0) + self.assertIn(b"requires its Wave module", plain.stderr) + reference = subprocess.run([str(self.guard)], env={**environment, + "CARGO_FEATURE_RUST_REFERENCE": "1"}, capture_output=True) + self.assertEqual(reference.returncode, 0, reference.stderr) + self.assertNotIn(b"cargo:rustc-link-lib", reference.stdout) check({}, None) check({"source": b"changed"}, "stale Wave IR archive") for name in abi_paths: diff --git a/tools/test_bytecode_writer_replay.py b/tools/test_bytecode_writer_replay.py new file mode 100644 index 0000000..6ad8ea7 --- /dev/null +++ b/tools/test_bytecode_writer_replay.py @@ -0,0 +1,75 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Raw writer cases survive failure without dropping malformed native fields.""" + +import hashlib +import json +import tempfile +import unittest +from pathlib import Path +from unittest.mock import Mock + +import check_wave_bytecode_writer as writer +from fuzz_checkpoint import Checkpoint + + +class WriterReplayChecks(unittest.TestCase): + def test_original_preserves_derived_fields_before_a_failed_native_call(self): + with tempfile.TemporaryDirectory(prefix="writer replay ") as directory: + checkpoint = Checkpoint( + directory, "writer", ["python", "writer.py", "--library", "ir.so"] + ) + native = writer.Native.__new__(writer.Native) + native.checkpoint, native.phase, native.case = checkpoint, "mutation/7", 7 + tables = writer.fixture() + fields = list(tables[4][0]) + fields[9] = 0xDEADBEEF + fields[19] = writer.MISSING + tables[4][0] = tuple(fields) + packet, keep = native.packet(tables) + with self.assertRaisesRegex(RuntimeError, "native failure"): + native.remember("write", packet, writer.Limits(), 1024, 4096, -1) + raise RuntimeError("native failure") + original = checkpoint.input.read_bytes() + saved = json.loads(original) + self.assertEqual(saved["tables"][4][0][9], 0xDEADBEEF) + self.assertEqual(saved["tables"][4][0][19], writer.MISSING) + self.assertEqual(saved["tables"][10], list(tables[10])) + manifest = json.loads(checkpoint.manifest.read_bytes()) + self.assertEqual(manifest["sha256"], hashlib.sha256(original).hexdigest()) + self.assertEqual(manifest["phase"], "mutation/7") + self.assertEqual(manifest["replay"][-2:], ["--replay", str(checkpoint.input)]) + self.assertTrue(keep) + + def test_invalid_replay_capacities_and_unsigned_fields_fail_before_allocation(self): + native = writer.Native.__new__(writer.Native) + packet, keep = native.packet(writer.fixture()) + original = { + "schema": 1, + "operation": "write", + "tables": writer.snapshot(packet), + "limits": {name: getattr(writer.Limits(), name) for name, _ in writer.Limits._fields_}, + "capacity": 1024, + "scratch_words": 4096, + "expected_status": 0, + "query": False, + } + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "original.json" + for change in ("capacity", "scratch", "unsigned"): + record = json.loads(json.dumps(original)) + if change == "capacity": + record["capacity"] = 1 << 64 + elif change == "scratch": + record["scratch_words"] = 1 << 64 + else: + record["tables"][4][0][13] = -1 + path.write_text(json.dumps(record)) + never_entered = Mock() + with self.subTest(change=change), self.assertRaises(ValueError): + writer.replay(never_entered, path) + never_entered.packet.assert_not_called() + self.assertTrue(keep) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_fuzz_checkpoint.py b/tools/test_fuzz_checkpoint.py new file mode 100644 index 0000000..4892dcf --- /dev/null +++ b/tools/test_fuzz_checkpoint.py @@ -0,0 +1,71 @@ +import json +from pathlib import Path +import tempfile +import unittest +from unittest.mock import patch + +from fuzz_checkpoint import Checkpoint + + +class CheckpointTests(unittest.TestCase): + def test_original_and_literal_replay_are_ready_before_native_call(self): + with tempfile.TemporaryDirectory() as directory: + checkpoint = Checkpoint(directory, 'case', ['python', 'a file.py', '--library', '$x.so']) + checkpoint.before(b'\x00\xff', seed=7, case=3) + record = json.loads(checkpoint.manifest.read_text()) + self.assertEqual(checkpoint.input.read_bytes(), b'\x00\xff') + self.assertEqual(record['replay'][:4], ['python', 'a file.py', '--library', '$x.so']) + self.assertEqual(record['case'], 3) + checkpoint.finish(cases=4) + self.assertTrue((Path(directory) / 'case.completed.json').is_file()) + + def test_rejected_checkpoint_preserves_previous_original(self): + with tempfile.TemporaryDirectory() as directory: + checkpoint = Checkpoint(directory, 'case', [], max_bytes=2) + checkpoint.before(b'ok') + with self.assertRaises(ValueError): + checkpoint.before(b'too long') + self.assertEqual(checkpoint.input.read_bytes(), b'ok') + + def test_atomic_publish_failure_preserves_original(self): + with tempfile.TemporaryDirectory() as directory: + checkpoint = Checkpoint(directory, 'case', []) + checkpoint.before(b'old') + with patch('fuzz_checkpoint.os.replace', side_effect=OSError('failure')): + with self.assertRaises(OSError): + checkpoint.before(b'new') + self.assertEqual(checkpoint.input.read_bytes(), b'old') + self.assertEqual(set(Path(directory).iterdir()), {checkpoint.input, checkpoint.manifest}) + + def test_manifest_failure_keeps_previous_pair_consistent(self): + import os + with tempfile.TemporaryDirectory() as directory: + checkpoint = Checkpoint(directory, 'case', []) + checkpoint.before(b'old') + previous = checkpoint.input + replace = os.replace + def publish(source, destination): + if Path(destination) == checkpoint.manifest: + raise OSError('manifest failure') + replace(source, destination) + with patch('fuzz_checkpoint.os.replace', side_effect=publish): + with self.assertRaises(OSError): + checkpoint.before(b'new') + record = json.loads(checkpoint.manifest.read_text()) + self.assertEqual(Path(record['input']), previous) + self.assertEqual(previous.read_bytes(), b'old') + self.assertEqual(len(list(Path(directory).iterdir())), 2) + + def test_new_campaign_removes_old_completion(self): + with tempfile.TemporaryDirectory() as directory: + first = Checkpoint(directory, 'case', []) + first.before(b'old') + first.finish(cases=1) + second = Checkpoint(directory, 'case', []) + second.before(b'new') + self.assertFalse((Path(directory) / 'case.completed.json').exists()) + self.assertEqual(len(list(Path(directory).iterdir())), 2) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/test_meson_build.py b/tools/test_meson_build.py index 35d3ad2..1521393 100644 --- a/tools/test_meson_build.py +++ b/tools/test_meson_build.py @@ -2,6 +2,7 @@ """Meson/Cargo bridge checks independent of installed Rust/Wave compilers.""" import argparse +import json import os from pathlib import Path import subprocess @@ -11,7 +12,8 @@ from meson_cargo import (BuildError, build, cargo_command, cargo_dependencies, cargo_environment, make_escape, native_target, - smoke, source_dependencies, validate_features, validate_host) + smoke, source_dependencies, revision_dependencies, + validate_features, validate_host) class CommandTests(unittest.TestCase): @@ -64,6 +66,17 @@ def test_wave_is_explicit_and_unknown_features_fail(self): with self.subTest(features=features), self.assertRaises(BuildError): validate_features(features) + def test_reproducible_paths_preserve_encoded_arguments(self): + with patch.dict(os.environ, {"CARGO_ENCODED_RUSTFLAGS": "-C\x1flink-arg=literal path", + "RUSTFLAGS": "ignored", "CARGO_HOME": "/cache/cargo"}): + environment = cargo_environment("/build with space", None, "release", "3", "0", + source_root="/source with space") + flags = environment["CARGO_ENCODED_RUSTFLAGS"].split("\x1f") + self.assertEqual(flags[:2], ["-C", "link-arg=literal path"]) + self.assertIn("--remap-path-prefix=/source with space=/whale-src", flags) + self.assertIn("--remap-path-prefix=/build with space=/whale-build", flags) + self.assertNotIn("RUSTFLAGS", environment) + def test_native_host_is_observed_only_when_requested_at_build(self): result = subprocess.CompletedProcess([], 0, stdout="cargo 1.96\nhost: x86_64-unknown-linux-gnu\n") with patch("meson_cargo.subprocess.run", return_value=result) as execute: @@ -94,14 +107,36 @@ def answer(command, **kwargs): return subprocess.CompletedProcess(command, 0, b"whale 0.1.0\n", b"") if "asm" in command: return subprocess.CompletedProcess(command, 1, b"", b"Error: unregistered assembler; available: \n") + if "build-info" in command: + payload = {"assemblers": [], "native_linker": False, "product_mode": "wave", + "implementations": {"ir": "wave"}} + return subprocess.CompletedProcess(command, 0, json.dumps(payload).encode(), b"") + if "emit" in command: + Path(command[-1]).write_bytes(b"WHALEBC\0fixture") return subprocess.CompletedProcess(command, 0, b"i32 42\n", b"") with patch("meson_cargo.subprocess.run", side_effect=answer) as execute: smoke(arguments) - self.assertEqual(execute.call_count, 3) + self.assertEqual(execute.call_count, 7) class DependencyTests(unittest.TestCase): + def test_linked_worktree_revision_is_a_build_dependency(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary).resolve() + source, common = root / "source", root / "common" + worktree = common / "worktrees/task" + source.mkdir() + worktree.mkdir(parents=True) + (source / ".git").write_text("gitdir: ../common/worktrees/task\n") + (worktree / "commondir").write_text("../..\n") + (worktree / "HEAD").write_text("ref: refs/heads/task\n") + (worktree / "index").write_bytes(b"index") + (common / "refs/heads").mkdir(parents=True) + revision = common / "refs/heads/task" + revision.write_text("a" * 40) + self.assertEqual(revision_dependencies(source), {worktree / "HEAD", worktree / "index", revision}) + def test_depfile_roundtrip_handles_spaces_unicode_and_make_metacharacters(self): dependencies = ["/source with space/α.rs", "/source/hash#dollar$.rs", r"C:\source folder\a.rs"] with tempfile.TemporaryDirectory() as temporary: diff --git a/tools/test_release.py b/tools/test_release.py index 1a13bce..c6f63ed 100644 --- a/tools/test_release.py +++ b/tools/test_release.py @@ -19,6 +19,22 @@ SOURCE = "a" * 40 +def product(target, socket=False, reference=False): + implementations = {name: "wave" for name in ("ir", "assembler", "asmobj", "amd64")} + if reference: + implementations.update(ir="rust-reference", assembler="rust-reference", amd64="rust-reference") + provenance = {"wave_revision": release.WAVE_REVISION, "target": target, "opt_level": "2", + "source_sha256": "1" * 64, "abi_sha256": "2" * 64, + "archive_sha256": "3" * 64, "compiler_sha256": "4" * 64, "std_sha256": "5" * 64, + "bootstrap_rust_version": "1.89.0", "required_llvm_major": 21} + return {"schema_version": 1, "version": VERSION, "source_commit": SOURCE, "source_dirty": False, + "host_target": target, "rustc": "rustc 1.86.0", "reference_feature": reference, + "wave_modules": {name: provenance.copy() for name, value in implementations.items() if value == "wave"}, + "product_mode": "rust-reference" if reference else "wave", "implementations": implementations, + "ir_format_version": 8, "semantics_version": 1, "bytecode_format_version": 1, + "assemblers": ["amd64"], "native_linker": True, "socket_cli": socket} + + def executable(target): kind, machine = release.TARGETS[target] data = bytearray(128) @@ -47,10 +63,15 @@ def setUp(self): invoke = self.version.start() self.addCleanup(self.version.stop) self.actual_socket = False + self.actual_target = "x86_64-unknown-linux-gnu" + self.product_override = None def probe(binary, args, cwd): if args == ["--version"]: return subprocess.CompletedProcess([], 0, b"whale 0.1.0\n", b"") + if args == ["build-info", "--json"]: + info = self.product_override or product(self.actual_target, self.actual_socket) + return subprocess.CompletedProcess([], 0, json.dumps(info).encode(), b"") return subprocess.CompletedProcess([], 1 if self.actual_socket else 2, b"", b"missing input" if self.actual_socket else b"requires feature 'socket-cli'") @@ -59,6 +80,7 @@ def probe(binary, args, cwd): def package(self, target, directory, **kwargs): self.binary.write_bytes(executable(target)) self.actual_socket = kwargs.get("socket", False) + self.actual_target = target return release.package(self.binary, self.root / directory, VERSION, target, SOURCE, **kwargs) def test_every_native_target_is_reproducible_and_readable(self): @@ -71,6 +93,40 @@ def test_every_native_target_is_reproducible_and_readable(self): self.assertTrue(manifest["socket_cli"]) self.assertEqual(manifest["source_commit"], SOURCE) self.assertEqual(manifest["target"], target) + self.assertEqual(manifest["product"]["implementations"]["ir"], "wave") + + def test_wave_requirement_and_provenance_fail_before_publication(self): + target = "x86_64-unknown-linux-gnu" + good = self.package(target, "good", require_wave=True) + previous = good.read_bytes() + for defect in ("reference", "dirty", "commit", "selection", "pin", "hash", "unknown"): + info = product(target, reference=defect == "reference") + if defect == "dirty": + info["source_dirty"] = True + if defect == "commit": + info["source_commit"] = "b" * 40 + if defect == "selection": + info["assemblers"].append("aarch64") + if defect == "pin": + info["wave_modules"]["ir"]["wave_revision"] = "b" * 40 + if defect == "hash": + info["wave_modules"]["ir"]["archive_sha256"] = "invalid" + if defect == "unknown": + info["private_build_path"] = "/private/source" + self.product_override = info + with self.subTest(defect=defect), self.assertRaises(ValueError): + self.package(target, "bad-" + defect, require_wave=True) + self.assertFalse((self.root / ("bad-" + defect)).exists()) + self.assertEqual(good.read_bytes(), previous) + + def test_reference_packages_are_explicit_and_retain_their_mode(self): + target = "aarch64-apple-darwin" + self.product_override = product(target, reference=True) + archive = self.package(target, "reference") + manifest = release.validate(archive, VERSION, target, SOURCE, execute=False) + self.assertEqual(manifest["product"]["product_mode"], "rust-reference") + with self.assertRaisesRegex(ValueError, "fully Wave-backed"): + release.validate(archive, VERSION, target, SOURCE, execute=False, require_wave=True) def test_identity_mismatch_and_duplicate_publication_fail(self): target = next(iter(release.TARGETS)) @@ -185,7 +241,7 @@ def test_archive_rejects_tampering_links_paths_duplicates_and_missing_files(self def test_manifest_requires_an_object_and_exact_field_types(self): target = "x86_64-pc-windows-msvc" original = self.package(target, "manifest-control") - self.assertEqual(release.validate(original, VERSION, target, SOURCE, execute=False)["format_version"], 1) + self.assertEqual(release.validate(original, VERSION, target, SOURCE, execute=False)["format_version"], 2) with zipfile.ZipFile(original) as reader: entries = [(info, reader.read(info)) for info in reader.infolist()] for mutation in (None, True, {"format_version": True}, {"format_version": 1.0}):