Shader tests: LLVM's verifier over every module the tests emit #68

Closed
lcg007xd-c wants to merge 0 commits from upstream-pr/68 into main
lcg007xd-c commented 2026-11-25 21:34:22 +00:00 (Migrated from github.com)

Imported from uiliannn/VItoriaBr. Originally posted by lcg007xd-c on 2026-11-25T21:34:22Z.


What

The DXIL we emit is LLVM bitcode, so LLVM's own verifier can check it on any platform. Today a broken module is caught only by dxil.dll, and only on Windows. That covers the class of bug the README mentions: a phi or value that does not dominate its uses.

This adds a test-only hook where Shader::finish writes the bitcode, right next to the census hook. When VICTORY_LLVM_OPT names an opt binary, every module any test emits goes through opt -passes=verify. A rejected module fails the test that made it, with LLVM's message, and the module is saved to the temp directory for llvm-dis. When the variable is unset, nothing happens. The Windows job is unchanged.

Details:

  • Data layout override. The module's own data layout predates current LLVM's rule that i8 is 8-bit aligned. Plain opt/llvm-dis refuse it ("i8 must be 8-bit aligned"), so the check passes DXIL's layout as -data-layout.
  • Only real verifier failures fail a test. That means LLVM's "input module is broken". An opt that can't read the module at all (too old, or something else named opt) is reported once and then not asked again.
  • CI. The portable job sets VICTORY_LLVM_OPT to the newest opt on the runner image, if there is one, and prints its version.

Tests

  • the_verifier_rejects_a_use_its_definition_does_not_dominate builds a two-armed diamond with the bitcode writer. It checks that the phi version verifies and that the version reading the arm's value directly is rejected ("Instruction does not dominate all uses!"). So the hook is shown to really run, not just to be silent.
  • Locally (LLVM 23.1 opt), VICTORY_LLVM_OPT=opt cargo test on the portable crates passes. opt ran on 99 modules from the victory-shader tests and added about 2 s.
  • Without the variable, the suites run as before. The portable clippy and Windows-target clippy (--target x86_64-pc-windows-msvc) are clean.

Not tested: which LLVM the ubuntu-latest image has, and whether that version reads DXIL. I only had LLVM 23 here. This PR's CI log will show it on the "VICTORY_LLVM_OPT=" line. If it can't read the modules, the tests still pass, and the step only says so once.

Note: the Windows check job fails on current main for an unrelated reason (5668b8b, missing Layout::bytes_from), which #64 fixes.

🤖 Generated with Claude Code

<!-- greyfinch-sync:uiliannn/VItoriaBr:issue:5499552241 --> Imported from [uiliannn/VItoriaBr](https://github.com/uiliannn/VitoriaBr2.0/pull/68). Originally posted by [lcg007xd-c](https://github.com/lcg007xd-c) on 2026-11-25T21:34:22Z. --- ## What The DXIL we emit is LLVM bitcode, so LLVM's own verifier can check it on any platform. Today a broken module is caught only by `dxil.dll`, and only on Windows. That covers the class of bug the README mentions: a phi or value that does not dominate its uses. This adds a test-only hook where `Shader::finish` writes the bitcode, right next to the `census` hook. When `VICTORY_LLVM_OPT` names an `opt` binary, every module any test emits goes through `opt -passes=verify`. A rejected module fails the test that made it, with LLVM's message, and the module is saved to the temp directory for `llvm-dis`. When the variable is unset, nothing happens. The Windows job is unchanged. Details: - **Data layout override.** The module's own data layout predates current LLVM's rule that `i8` is 8-bit aligned. Plain `opt`/`llvm-dis` refuse it ("i8 must be 8-bit aligned"), so the check passes DXIL's layout as `-data-layout`. - **Only real verifier failures fail a test.** That means LLVM's "input module is broken". An `opt` that can't read the module at all (too old, or something else named `opt`) is reported once and then not asked again. - **CI.** The `portable` job sets `VICTORY_LLVM_OPT` to the newest `opt` on the runner image, if there is one, and prints its version. ## Tests - `the_verifier_rejects_a_use_its_definition_does_not_dominate` builds a two-armed diamond with the bitcode writer. It checks that the phi version verifies and that the version reading the arm's value directly is rejected ("Instruction does not dominate all uses!"). So the hook is shown to really run, not just to be silent. - Locally (LLVM 23.1 `opt`), `VICTORY_LLVM_OPT=opt cargo test` on the portable crates passes. `opt` ran on 99 modules from the `victory-shader` tests and added about 2 s. - Without the variable, the suites run as before. The portable clippy and Windows-target clippy (`--target x86_64-pc-windows-msvc`) are clean. Not tested: which LLVM the `ubuntu-latest` image has, and whether that version reads DXIL. I only had LLVM 23 here. This PR's CI log will show it on the "VICTORY_LLVM_OPT=" line. If it can't read the modules, the tests still pass, and the step only says so once. Note: the Windows `check` job fails on current main for an unrelated reason (5668b8b, missing `Layout::bytes_from`), which #64 fixes. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
lmouz823-lang commented 2026-11-28 08:26:27 +00:00 (Migrated from github.com)

Imported from uiliannn/VItoriaBr. Originally posted by lmouz823-lang on 2026-11-28T08:26:27Z.


I can take native Windows validation of the verifier hook at exact head a062b942493def27c41eea0ce84f0f0bdfc90bd9. I will inspect the external-tool and compatibility paths, run actual LLVM verification with valid and invalid controls where the required tool is available, and report missing/incompatible-tool coverage explicitly. Any justified small regression or fix will include a normal-entry reproduction, a negative control, restored-source verification and precise LLVM/module counts. AI-assisted with Codex.

<!-- greyfinch-sync:uiliannn/VItoriaBr:comment:7236584306 --> Imported from [uiliannn/VItoriaBr](https://github.com/uiliannn/VItoriaBr/pull/68#issuecomment-7236584306). Originally posted by [lmouz823-lang](https://github.com/lmouz823-lang) on 2026-11-28T08:26:27Z. --- I can take native Windows validation of the verifier hook at exact head `a062b942493def27c41eea0ce84f0f0bdfc90bd9`. I will inspect the external-tool and compatibility paths, run actual LLVM verification with valid and invalid controls where the required tool is available, and report missing/incompatible-tool coverage explicitly. Any justified small regression or fix will include a normal-entry reproduction, a negative control, restored-source verification and precise LLVM/module counts. AI-assisted with Codex.
lmouz823-lang commented 2026-11-28 08:54:26 +00:00 (Migrated from github.com)

Imported from uiliannn/VItoriaBr. Originally posted by lmouz823-lang on 2026-11-28T08:54:26Z.


Windows CPU verification for head a062b942493def27c41eea0ce84f0f0bdfc90bd9 is complete. I found a diagnostic-file overwrite issue and included a small follow-up patch below.

Actual LLVM verification

I used Rust 1.98.1 on x86_64-pc-windows-msvc and the official LLVM 23.1.6 Windows portable archive. Its SHA256 matched the digest in the official release asset metadata, 16af05919cf36958dfb4ddaa4fc4d9d4ff577f5daeb76bc112ea49cd8ced82b2. VICTORY_LLVM_OPT pointed directly to its opt.exe. The commands ran with VICTORY_STRICT_TESTS=1 and without VICTORY_BLESS or VICTORY_WARP. LLVM release

After removing all temporary diagnostic instrumentation and cleaning the victory-shader package in an isolated target directory, the final source rebuilt and produced these results. Independent review also corrected the parameterized fixture operand name from two to rhs. The final reviewed source was package-cleaned, freshly compiled in 19.68 seconds, and exercised again through all selections and tool-availability cases below.

Selection Result
Original dominance verifier test, exact 1 passed, 0 ignored
Added hook and diagnostic-retention test, exact 1 passed, 0 ignored
emit::llvm_verify::tests:: 2 passed, 0 ignored
emit::lower::tests:: 16 passed, 1 ignored

The original test accepted the valid diamond and rejected the non-dominating definition using real LLVM. The new test also checks a valid module through check, then catches the expected rejection panics for two different broken modules. It reads both retained files after both failures and compares each file with its own input bytes.

A separate, temporary diagnostic run of the lowering group recorded 23 Shader::finish hook invocations and 23 successful real opt calls. These are call counts. Distinct bitcode modules were not counted. The temporary markers were removed and shader.rs was restored byte-for-byte before the final rebuild and runs above.

Diagnostic preservation fix and regression controls

The current victory-broken-{pid}.bc filename is reused within one test process. With the new regression applied to the original implementation, both rejections reported the same path and the test failed. Inspecting the retained file showed the second module's add i32 1, 3, confirming that it had overwritten the first diagnostic. This control ran in a fresh child process with its own temporary directory.

The patch adds an atomic per-process sequence and opens each diagnostic with create_new. Existing paths are skipped. A write failure closes the newly created file before attempting to remove it. check retains its existing panic and unusable-tool behavior.

As a second negative control, temporarily returning immediately from check left the original direct-verify test passing, while the new regression failed with the hook accepted a broken module. The bypass was removed before the final rebuild. The upstream test changes no process-global environment variables and removes only the two distinct files created by these calls.

Tool-unavailable behavior and skipped coverage

These cases were exercised in separate processes with strict tests enabled.

Configuration Observed behavior
VICTORY_LLVM_OPT unset Existing diagnostic says the verifier is not run, libtest reports a pass
Configured executable missing Spawn panic, exact test fails with Cargo exit 101
Deliberately incompatible command Existing cannot-read diagnostic disables verification, libtest reports a pass

The unset and incompatible cases provide no LLVM verification coverage. The incompatible command is fault injection. The final real-LLVM runs had none of these omission diagnostics.

The lowering group's existing ignored case is a_missing_value_stays_missing_through_two_live_joins. Its declared reason is ours marks joins read through joins only with VICTORY_STRICT_JOINS (40 programs stop otherwise). It remained ignored. An initial local group wrapper expected zero ignored tests and rejected the upstream 16-pass/1-ignored result. Its expectation was corrected to that declared ignored case before acceptance. This validation covers the selected CPU tests. GPU execution, dxil.dll validation, game performance, other platforms, and the full workspace test suite were not exercised.

Quality checks

cargo clippy --locked -p victory-shader --all-targets -- -D warnings, standalone Rustfmt checks for both the original and final llvm_verify.rs, git diff --check, and cargo run --locked -p xtask -- policy passed. The asset policy checked 197 files.

An additional cargo fmt --all -- --check returned exit 1 for formatting differences in 75 existing files. Each reported file's Git blob was checked against this PR's head and was identical. The changed llvm_verify.rs was absent from that output and passed its own format check.

The final patch changes one file, with 77 insertions and 10 deletions. It can be exercised through the normal test entry points with a compatible real opt configured.

cargo test --locked -p victory-shader --lib emit::llvm_verify::tests:: -- --nocapture --test-threads=1
cargo test --locked -p victory-shader --lib emit::lower::tests:: -- --nocapture --test-threads=1

AI assistance from Codex covered the audit, patch, execution and this report.

Complete diagnostic-retention patch against this head
diff --git a/crates/victory-shader/src/emit/llvm_verify.rs b/crates/victory-shader/src/emit/llvm_verify.rs
index dd5d31f..78239fc 100644
--- a/crates/victory-shader/src/emit/llvm_verify.rs
+++ b/crates/victory-shader/src/emit/llvm_verify.rs
@@ -15,7 +15,7 @@
 
 use std::io::Write;
 use std::process::{Command, Stdio};
-use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
 
 /// DXIL's data layout (`dxil.dll`'s), with `i8` aligned to 8 bits.
 const DATA_LAYOUT: &str =
@@ -30,14 +30,38 @@ pub(super) fn check(bitcode: &[u8]) {
     let Err(err) = verify(bitcode) else {
         return;
     };
-    let path = std::env::temp_dir().join(format!("victory-broken-{}.bc", std::process::id()));
-    let kept = std::fs::write(&path, bitcode).map_or_else(
+    let kept = keep_module(bitcode).map_or_else(
         |e| format!("(not kept: {e})"),
-        |()| format!("kept at {}", path.display()),
+        |path| format!("kept at {}", path.display()),
     );
     panic!("LLVM's verifier rejects an emitted module, {kept}:\n{err}");
 }
 
+fn keep_module(bitcode: &[u8]) -> std::io::Result<std::path::PathBuf> {
+    static NEXT_DUMP: AtomicUsize = AtomicUsize::new(0);
+    loop {
+        let serial = NEXT_DUMP.fetch_add(1, Ordering::Relaxed);
+        let path =
+            std::env::temp_dir().join(format!("victory-broken-{}-{serial}.bc", std::process::id()));
+        let mut file = match std::fs::OpenOptions::new()
+            .write(true)
+            .create_new(true)
+            .open(&path)
+        {
+            Ok(file) => file,
+            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
+            Err(error) => return Err(error),
+        };
+        let written = file.write_all(bitcode);
+        drop(file);
+        if let Err(error) = written {
+            let _ = std::fs::remove_file(&path);
+            return Err(error);
+        }
+        return Ok(path);
+    }
+}
+
 /// LLVM's complaint if it reads `bitcode` and finds it broken. `Ok` if
 /// it is valid, or if no usable `opt` is configured.
 fn verify(bitcode: &[u8]) -> Result<(), String> {
@@ -85,7 +109,7 @@ mod tests {
 
     /// A diamond whose join adds 1 to `x`, made in one arm: through a phi
     /// (valid), or directly (`x` does not dominate the join).
-    fn diamond(broken: bool) -> Vec<u8> {
+    fn diamond(broken: bool, right: u32) -> Vec<u8> {
         let mut m = Module::default();
         let i32t = m.int(32);
         let void = m.void();
@@ -93,10 +117,10 @@ mod tests {
         m.function("main", main_ty, None, true);
         let (entry, then, other, join) =
             (m.new_block(), m.new_block(), m.new_block(), m.new_block());
-        let (one, two) = (m.i32(1), m.i32(2));
-        let c = m.cmp(entry, pred::EQ, one, two);
+        let (one, rhs) = (m.i32(1), m.i32(right));
+        let c = m.cmp(entry, pred::EQ, one, rhs);
         m.terminate(entry, Term::CondBr(c, then, other));
-        let x = m.bin(then, Bin::Add, one, two);
+        let x = m.bin(then, Bin::Add, one, rhs);
         m.terminate(then, Term::Br(join));
         m.terminate(other, Term::Br(join));
         let v = if broken {
@@ -117,12 +141,55 @@ mod tests {
             eprintln!("VICTORY_LLVM_OPT is not set; the verifier is not run");
             return;
         }
-        assert_eq!(super::verify(&diamond(false)), Ok(()));
+        assert_eq!(super::verify(&diamond(false, 2)), Ok(()));
         if super::UNUSABLE.load(std::sync::atomic::Ordering::Relaxed) {
             eprintln!("VICTORY_LLVM_OPT cannot read DXIL; the verifier is not run");
             return;
         }
-        let why = super::verify(&diamond(true)).expect_err("a broken module passes");
+        let why = super::verify(&diamond(true, 2)).expect_err("a broken module passes");
         assert!(why.contains("does not dominate all uses"), "{why}");
     }
+
+    #[test]
+    fn rejected_modules_keep_distinct_diagnostics() {
+        if std::env::var_os("VICTORY_LLVM_OPT").is_none_or(|v| v.is_empty()) {
+            eprintln!("VICTORY_LLVM_OPT is not set; the verifier is not run");
+            return;
+        }
+        let valid = diamond(false, 2);
+        assert_eq!(super::verify(&valid), Ok(()));
+        if super::UNUSABLE.load(std::sync::atomic::Ordering::Relaxed) {
+            eprintln!("VICTORY_LLVM_OPT cannot read DXIL; the verifier is not run");
+            return;
+        }
+        super::check(&valid);
+        let rejected = |bitcode: &[u8]| {
+            let failure = std::panic::catch_unwind(|| super::check(bitcode))
+                .expect_err("the hook accepted a broken module");
+            let message = failure
+                .downcast_ref::<String>()
+                .expect("formatted hook panic");
+            let path = message
+                .lines()
+                .next()
+                .unwrap()
+                .strip_prefix("LLVM's verifier rejects an emitted module, kept at ")
+                .and_then(|line| line.strip_suffix(':'))
+                .expect("kept diagnostic path");
+            std::path::PathBuf::from(path)
+        };
+        let first_bad = diamond(true, 2);
+        let second_bad = diamond(true, 3);
+        let first = rejected(&first_bad);
+        let second = rejected(&second_bad);
+        let first_bytes = std::fs::read(&first).expect("first diagnostic");
+        let second_bytes = std::fs::read(&second).expect("second diagnostic");
+        if first != second {
+            std::fs::remove_file(&first).expect("remove first owned diagnostic");
+            std::fs::remove_file(&second).expect("remove second owned diagnostic");
+        }
+        assert_ne!(first, second, "rejected modules overwrite one diagnostic");
+        assert_eq!(first_bytes, first_bad);
+        assert_eq!(second_bytes, second_bad);
+    }
 }
<!-- greyfinch-sync:uiliannn/VItoriaBr:comment:7236888199 --> Imported from [uiliannn/VItoriaBr](https://github.com/uiliannn/VItoriaBr/pull/68#issuecomment-7236888199). Originally posted by [lmouz823-lang](https://github.com/lmouz823-lang) on 2026-11-28T08:54:26Z. --- Windows CPU verification for head `a062b942493def27c41eea0ce84f0f0bdfc90bd9` is complete. I found a diagnostic-file overwrite issue and included a small follow-up patch below. ## Actual LLVM verification I used Rust 1.98.1 on `x86_64-pc-windows-msvc` and the official LLVM 23.1.6 Windows portable archive. Its SHA256 matched the digest in the official release asset metadata, `16af05919cf36958dfb4ddaa4fc4d9d4ff577f5daeb76bc112ea49cd8ced82b2`. `VICTORY_LLVM_OPT` pointed directly to its `opt.exe`. The commands ran with `VICTORY_STRICT_TESTS=1` and without `VICTORY_BLESS` or `VICTORY_WARP`. [LLVM release](https://github.com/llvm/llvm-project/releases/tag/llvmorg-23.1.6) After removing all temporary diagnostic instrumentation and cleaning the `victory-shader` package in an isolated target directory, the final source rebuilt and produced these results. Independent review also corrected the parameterized fixture operand name from `two` to `rhs`. The final reviewed source was package-cleaned, freshly compiled in 19.68 seconds, and exercised again through all selections and tool-availability cases below. | Selection | Result | | --- | --- | | Original dominance verifier test, exact | 1 passed, 0 ignored | | Added hook and diagnostic-retention test, exact | 1 passed, 0 ignored | | `emit::llvm_verify::tests::` | 2 passed, 0 ignored | | `emit::lower::tests::` | 16 passed, 1 ignored | The original test accepted the valid diamond and rejected the non-dominating definition using real LLVM. The new test also checks a valid module through `check`, then catches the expected rejection panics for two different broken modules. It reads both retained files after both failures and compares each file with its own input bytes. A separate, temporary diagnostic run of the lowering group recorded 23 `Shader::finish` hook invocations and 23 successful real `opt` calls. These are call counts. Distinct bitcode modules were not counted. The temporary markers were removed and `shader.rs` was restored byte-for-byte before the final rebuild and runs above. ## Diagnostic preservation fix and regression controls The current `victory-broken-{pid}.bc` filename is reused within one test process. With the new regression applied to the original implementation, both rejections reported the same path and the test failed. Inspecting the retained file showed the second module's `add i32 1, 3`, confirming that it had overwritten the first diagnostic. This control ran in a fresh child process with its own temporary directory. The patch adds an atomic per-process sequence and opens each diagnostic with `create_new`. Existing paths are skipped. A write failure closes the newly created file before attempting to remove it. `check` retains its existing panic and unusable-tool behavior. As a second negative control, temporarily returning immediately from `check` left the original direct-`verify` test passing, while the new regression failed with `the hook accepted a broken module`. The bypass was removed before the final rebuild. The upstream test changes no process-global environment variables and removes only the two distinct files created by these calls. ## Tool-unavailable behavior and skipped coverage These cases were exercised in separate processes with strict tests enabled. | Configuration | Observed behavior | | --- | --- | | `VICTORY_LLVM_OPT` unset | Existing diagnostic says the verifier is not run, libtest reports a pass | | Configured executable missing | Spawn panic, exact test fails with Cargo exit 101 | | Deliberately incompatible command | Existing cannot-read diagnostic disables verification, libtest reports a pass | The unset and incompatible cases provide no LLVM verification coverage. The incompatible command is fault injection. The final real-LLVM runs had none of these omission diagnostics. The lowering group's existing ignored case is `a_missing_value_stays_missing_through_two_live_joins`. Its declared reason is `ours marks joins read through joins only with VICTORY_STRICT_JOINS (40 programs stop otherwise)`. It remained ignored. An initial local group wrapper expected zero ignored tests and rejected the upstream 16-pass/1-ignored result. Its expectation was corrected to that declared ignored case before acceptance. This validation covers the selected CPU tests. GPU execution, `dxil.dll` validation, game performance, other platforms, and the full workspace test suite were not exercised. ## Quality checks `cargo clippy --locked -p victory-shader --all-targets -- -D warnings`, standalone Rustfmt checks for both the original and final `llvm_verify.rs`, `git diff --check`, and `cargo run --locked -p xtask -- policy` passed. The asset policy checked 197 files. An additional `cargo fmt --all -- --check` returned exit 1 for formatting differences in 75 existing files. Each reported file's Git blob was checked against this PR's head and was identical. The changed `llvm_verify.rs` was absent from that output and passed its own format check. The final patch changes one file, with 77 insertions and 10 deletions. It can be exercised through the normal test entry points with a compatible real `opt` configured. ```text cargo test --locked -p victory-shader --lib emit::llvm_verify::tests:: -- --nocapture --test-threads=1 cargo test --locked -p victory-shader --lib emit::lower::tests:: -- --nocapture --test-threads=1 ``` AI assistance from Codex covered the audit, patch, execution and this report. <details> <summary>Complete diagnostic-retention patch against this head</summary> ```diff diff --git a/crates/victory-shader/src/emit/llvm_verify.rs b/crates/victory-shader/src/emit/llvm_verify.rs index dd5d31f..78239fc 100644 --- a/crates/victory-shader/src/emit/llvm_verify.rs +++ b/crates/victory-shader/src/emit/llvm_verify.rs @@ -15,7 +15,7 @@ use std::io::Write; use std::process::{Command, Stdio}; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; /// DXIL's data layout (`dxil.dll`'s), with `i8` aligned to 8 bits. const DATA_LAYOUT: &str = @@ -30,14 +30,38 @@ pub(super) fn check(bitcode: &[u8]) { let Err(err) = verify(bitcode) else { return; }; - let path = std::env::temp_dir().join(format!("victory-broken-{}.bc", std::process::id())); - let kept = std::fs::write(&path, bitcode).map_or_else( + let kept = keep_module(bitcode).map_or_else( |e| format!("(not kept: {e})"), - |()| format!("kept at {}", path.display()), + |path| format!("kept at {}", path.display()), ); panic!("LLVM's verifier rejects an emitted module, {kept}:\n{err}"); } +fn keep_module(bitcode: &[u8]) -> std::io::Result<std::path::PathBuf> { + static NEXT_DUMP: AtomicUsize = AtomicUsize::new(0); + loop { + let serial = NEXT_DUMP.fetch_add(1, Ordering::Relaxed); + let path = + std::env::temp_dir().join(format!("victory-broken-{}-{serial}.bc", std::process::id())); + let mut file = match std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&path) + { + Ok(file) => file, + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => return Err(error), + }; + let written = file.write_all(bitcode); + drop(file); + if let Err(error) = written { + let _ = std::fs::remove_file(&path); + return Err(error); + } + return Ok(path); + } +} + /// LLVM's complaint if it reads `bitcode` and finds it broken. `Ok` if /// it is valid, or if no usable `opt` is configured. fn verify(bitcode: &[u8]) -> Result<(), String> { @@ -85,7 +109,7 @@ mod tests { /// A diamond whose join adds 1 to `x`, made in one arm: through a phi /// (valid), or directly (`x` does not dominate the join). - fn diamond(broken: bool) -> Vec<u8> { + fn diamond(broken: bool, right: u32) -> Vec<u8> { let mut m = Module::default(); let i32t = m.int(32); let void = m.void(); @@ -93,10 +117,10 @@ mod tests { m.function("main", main_ty, None, true); let (entry, then, other, join) = (m.new_block(), m.new_block(), m.new_block(), m.new_block()); - let (one, two) = (m.i32(1), m.i32(2)); - let c = m.cmp(entry, pred::EQ, one, two); + let (one, rhs) = (m.i32(1), m.i32(right)); + let c = m.cmp(entry, pred::EQ, one, rhs); m.terminate(entry, Term::CondBr(c, then, other)); - let x = m.bin(then, Bin::Add, one, two); + let x = m.bin(then, Bin::Add, one, rhs); m.terminate(then, Term::Br(join)); m.terminate(other, Term::Br(join)); let v = if broken { @@ -117,12 +141,55 @@ mod tests { eprintln!("VICTORY_LLVM_OPT is not set; the verifier is not run"); return; } - assert_eq!(super::verify(&diamond(false)), Ok(())); + assert_eq!(super::verify(&diamond(false, 2)), Ok(())); if super::UNUSABLE.load(std::sync::atomic::Ordering::Relaxed) { eprintln!("VICTORY_LLVM_OPT cannot read DXIL; the verifier is not run"); return; } - let why = super::verify(&diamond(true)).expect_err("a broken module passes"); + let why = super::verify(&diamond(true, 2)).expect_err("a broken module passes"); assert!(why.contains("does not dominate all uses"), "{why}"); } + + #[test] + fn rejected_modules_keep_distinct_diagnostics() { + if std::env::var_os("VICTORY_LLVM_OPT").is_none_or(|v| v.is_empty()) { + eprintln!("VICTORY_LLVM_OPT is not set; the verifier is not run"); + return; + } + let valid = diamond(false, 2); + assert_eq!(super::verify(&valid), Ok(())); + if super::UNUSABLE.load(std::sync::atomic::Ordering::Relaxed) { + eprintln!("VICTORY_LLVM_OPT cannot read DXIL; the verifier is not run"); + return; + } + super::check(&valid); + let rejected = |bitcode: &[u8]| { + let failure = std::panic::catch_unwind(|| super::check(bitcode)) + .expect_err("the hook accepted a broken module"); + let message = failure + .downcast_ref::<String>() + .expect("formatted hook panic"); + let path = message + .lines() + .next() + .unwrap() + .strip_prefix("LLVM's verifier rejects an emitted module, kept at ") + .and_then(|line| line.strip_suffix(':')) + .expect("kept diagnostic path"); + std::path::PathBuf::from(path) + }; + let first_bad = diamond(true, 2); + let second_bad = diamond(true, 3); + let first = rejected(&first_bad); + let second = rejected(&second_bad); + let first_bytes = std::fs::read(&first).expect("first diagnostic"); + let second_bytes = std::fs::read(&second).expect("second diagnostic"); + if first != second { + std::fs::remove_file(&first).expect("remove first owned diagnostic"); + std::fs::remove_file(&second).expect("remove second owned diagnostic"); + } + assert_ne!(first, second, "rejected modules overwrite one diagnostic"); + assert_eq!(first_bytes, first_bad); + assert_eq!(second_bytes, second_bad); + } } ``` </details>

Pull request closed

Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
uiliannn/VItoriaBr!68
No description provided.