translate.rs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  1. //! The offline batch: every shader found goes through the translator, and
  2. //! what it cannot handle yet is tallied (decision 0003).
  3. use std::collections::{BTreeMap, HashSet};
  4. use std::path::{Path, PathBuf};
  5. use std::sync::Mutex;
  6. use std::sync::atomic::{AtomicUsize, Ordering};
  7. use anyhow::Result;
  8. use victory_shader::emit::host::{self, Host};
  9. use victory_shader::emit::{self, validator::Validator};
  10. use victory_shader::structure::{self, Atom, LaneExit};
  11. use victory_shader::{
  12. Container, FourCC, HwStage, NativeProgram, RootType, ShaderError, ir, native_programs,
  13. };
  14. use victory_shader::{io, resource};
  15. use crate::shader::{MAX_FILE, Source, sources};
  16. #[derive(Default)]
  17. struct Tally {
  18. containers: usize,
  19. duplicates: usize,
  20. programs: usize,
  21. translated: usize,
  22. instructions: usize,
  23. structured: usize,
  24. vector: usize,
  25. guarded: usize,
  26. /// Guards that read a mask the pass cannot see into.
  27. opaque: usize,
  28. lane_branches: usize,
  29. uniform_branches: usize,
  30. tracked: usize,
  31. loaded: usize,
  32. built: usize,
  33. constant: usize,
  34. /// Descriptors and scalar accesses with a computed address term.
  35. dynamic: usize,
  36. scalar: usize,
  37. used: usize,
  38. /// Used-resource entries whose root parameter no descriptor traces
  39. /// to, by resource and root type.
  40. untraced_used: BTreeMap<String, usize>,
  41. /// Root parameters descriptors trace to that no used entry names.
  42. unlisted: usize,
  43. /// Vertex and pixel programs, and those whose I/O was raised.
  44. io_programs: usize,
  45. io_raised: usize,
  46. interpolated: usize,
  47. vertex_values: usize,
  48. /// Exports by target kind.
  49. exports: BTreeMap<&'static str, usize>,
  50. /// Exports still packed as f16 pairs after the export patch.
  51. compressed: usize,
  52. /// Vertex and pixel programs every earlier stage handled, and how far
  53. /// emission got with them.
  54. emit_programs: usize,
  55. emitted: usize,
  56. validated: usize,
  57. pipelines: usize,
  58. /// The same for compute programs.
  59. cs_programs: usize,
  60. cs_emitted: usize,
  61. cs_validated: usize,
  62. cs_pipelines: usize,
  63. /// The same for mesh programs.
  64. ms_programs: usize,
  65. ms_emitted: usize,
  66. ms_validated: usize,
  67. ms_pipelines: usize,
  68. /// Reason → programs stopped by it, and the first one.
  69. failed: BTreeMap<String, (usize, String)>,
  70. /// With `--list`: one line per program and outcome.
  71. list: bool,
  72. lines: Vec<String>,
  73. }
  74. impl Tally {
  75. fn fail(&mut self, reason: String, example: impl FnOnce() -> String) {
  76. if self.list {
  77. let e = example();
  78. self.lines.push(format!("{e} {reason}"));
  79. self.failed.entry(reason).or_insert((0, e)).0 += 1;
  80. return;
  81. }
  82. self.failed
  83. .entry(reason)
  84. .or_insert_with(|| (0, example()))
  85. .0 += 1;
  86. }
  87. fn merge(&mut self, other: Tally) {
  88. self.containers += other.containers;
  89. self.duplicates += other.duplicates;
  90. self.programs += other.programs;
  91. self.translated += other.translated;
  92. self.instructions += other.instructions;
  93. self.structured += other.structured;
  94. self.vector += other.vector;
  95. self.guarded += other.guarded;
  96. self.opaque += other.opaque;
  97. self.lane_branches += other.lane_branches;
  98. self.uniform_branches += other.uniform_branches;
  99. self.tracked += other.tracked;
  100. self.loaded += other.loaded;
  101. self.built += other.built;
  102. self.constant += other.constant;
  103. self.dynamic += other.dynamic;
  104. self.scalar += other.scalar;
  105. self.used += other.used;
  106. for (k, n) in other.untraced_used {
  107. *self.untraced_used.entry(k).or_default() += n;
  108. }
  109. self.unlisted += other.unlisted;
  110. self.io_programs += other.io_programs;
  111. self.io_raised += other.io_raised;
  112. self.interpolated += other.interpolated;
  113. self.vertex_values += other.vertex_values;
  114. self.compressed += other.compressed;
  115. self.emit_programs += other.emit_programs;
  116. self.emitted += other.emitted;
  117. self.validated += other.validated;
  118. self.pipelines += other.pipelines;
  119. self.cs_programs += other.cs_programs;
  120. self.cs_emitted += other.cs_emitted;
  121. self.cs_validated += other.cs_validated;
  122. self.cs_pipelines += other.cs_pipelines;
  123. self.ms_programs += other.ms_programs;
  124. self.ms_emitted += other.ms_emitted;
  125. self.ms_validated += other.ms_validated;
  126. self.ms_pipelines += other.ms_pipelines;
  127. for (k, n) in other.exports {
  128. *self.exports.entry(k).or_default() += n;
  129. }
  130. self.lines.extend(other.lines);
  131. for (reason, (n, example)) in other.failed {
  132. self.failed.entry(reason).or_insert((0, example)).0 += n;
  133. }
  134. }
  135. }
  136. /// Emitted shaders by label, shared between threads.
  137. type Kept = std::sync::Arc<Mutex<Vec<(String, emit::HostShader)>>>;
  138. /// The optional checks after emission, one set per thread.
  139. struct Checks {
  140. /// Shaders named in `VICTORY_PAIRS` (`vs+ps,...`, label substrings),
  141. /// kept to build those pipelines after the walk.
  142. keep: Option<Kept>,
  143. validator: Option<Validator>,
  144. host: Option<(Host, emit::HostShader)>,
  145. }
  146. /// `translate --warm <file>`: the containers whose hash the file names are
  147. /// translated into the run's shader cache, on `jobs` threads; nothing is
  148. /// made on the GPU. A run of the title then finds them there instead of
  149. /// translating each at its first use.
  150. pub fn warm(paths: Vec<PathBuf>, file: &Path, jobs: Option<usize>) -> Result<()> {
  151. // `--warm all`: every container found, whatever its hash.
  152. let all = file.as_os_str() == "all";
  153. let mut wanted: HashSet<String> = HashSet::new();
  154. if !all {
  155. let text = std::fs::read_to_string(file)?;
  156. for line in text.lines() {
  157. for word in line.split(|c: char| !c.is_ascii_hexdigit()) {
  158. if word.len() == 16 {
  159. wanted.insert(word.to_ascii_lowercase());
  160. }
  161. }
  162. }
  163. anyhow::ensure!(!wanted.is_empty(), "no 16-digit shader hash in {}", file.display());
  164. }
  165. // `VICTORY_WARM_SECONDS=<n>`: stop taking new shaders after n seconds
  166. // (what is done stays in the cache; the next warm-up goes on from there).
  167. let limit = std::env::var("VICTORY_WARM_SECONDS").ok().and_then(|v| v.trim().parse::<u64>().ok());
  168. let cfg = victory_core::Config::load()?;
  169. victory_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?);
  170. let paths = crate::default_paths(paths)?;
  171. let threads = jobs.unwrap_or(4).max(1);
  172. let began = std::time::Instant::now();
  173. let done = Mutex::new(HashSet::new());
  174. let counts = [const { AtomicUsize::new(0) }; 5];
  175. for root in &paths {
  176. for entry in walkdir::WalkDir::new(root).into_iter().filter_map(Result::ok) {
  177. if !entry.file_type().is_file() || entry.metadata().map_or(0, |m| m.len()) > MAX_FILE {
  178. continue;
  179. }
  180. let Ok(data) = std::fs::read(entry.path()) else {
  181. continue;
  182. };
  183. let jobs = sources(&data);
  184. let next = AtomicUsize::new(0);
  185. std::thread::scope(|s| {
  186. for _ in 0..threads.min(jobs.len()) {
  187. s.spawn(|| {
  188. while let Some(job) = jobs.get(next.fetch_add(1, Ordering::Relaxed)) {
  189. let Some(bytes) = job.bytes() else {
  190. continue;
  191. };
  192. let hash = blake3::hash(&bytes).to_hex()[..16].to_owned();
  193. if limit.is_some_and(|n| began.elapsed().as_secs() >= n) {
  194. counts[3].fetch_add(1, Ordering::Relaxed);
  195. break;
  196. }
  197. if (!all && !wanted.contains(&hash)) || !lock(&done).insert(hash) {
  198. continue;
  199. }
  200. let n = counts[4].fetch_add(1, Ordering::Relaxed) + 1;
  201. if n.is_multiple_of(1000) {
  202. println!("warm-up {n} shaders so far, {:.0} s", began.elapsed().as_secs_f64());
  203. }
  204. let which = match victory_hle::modules::d3d12x::warm_shader(&bytes) {
  205. Ok(true) => 0,
  206. Ok(false) => 1,
  207. Err(_) => 2,
  208. };
  209. counts[which].fetch_add(1, Ordering::Relaxed);
  210. }
  211. });
  212. }
  213. });
  214. }
  215. }
  216. let [translated, there, failed] = [0, 1, 2].map(|i| counts[i].load(Ordering::Relaxed));
  217. let asked = if all { "all".to_owned() } else { wanted.len().to_string() };
  218. let stopped = if counts[3].load(Ordering::Relaxed) > 0 { " (stopped at the time limit)" } else { "" };
  219. println!(
  220. "warm-up {asked} hashes asked, {} found: {translated} translated now, {there} in the cache already, {failed} do not translate; {:.1} s on {threads} threads{stopped}",
  221. translated + there + failed,
  222. began.elapsed().as_secs_f64()
  223. );
  224. Ok(())
  225. }
  226. pub fn run(
  227. paths: Vec<PathBuf>,
  228. validate: bool,
  229. pipelines: bool,
  230. list: bool,
  231. jobs: Option<usize>,
  232. ) -> Result<()> {
  233. // Dumped shaders and validator reports are game-derived (rule #1).
  234. if let Some(dir) = std::env::var_os("VICTORY_EMIT_DUMP") {
  235. victory_core::ensure_outside_repo(Path::new(&dir))?;
  236. }
  237. let paths = crate::default_paths(paths)?;
  238. // `VICTORY_HOST_MAX_WAVE=32`: translate as for a host whose waves have
  239. // at most 32 lanes (as the runtime does on such a card).
  240. if let Some(n) = std::env::var("VICTORY_HOST_MAX_WAVE").ok().and_then(|v| v.parse().ok()) {
  241. victory_shader::emit::set_host_max_wave(n);
  242. }
  243. let dll = validate.then(Validator::default_path).flatten();
  244. if validate {
  245. Validator::load(dll.as_deref()).map_err(anyhow::Error::msg)?;
  246. println!(
  247. "validator {}",
  248. dll.as_ref()
  249. .map_or("dxil.dll".into(), |p| p.display().to_string())
  250. );
  251. }
  252. if pipelines {
  253. Host::new(false).map_err(anyhow::Error::msg)?;
  254. }
  255. let pairs: Vec<(String, String)> = std::env::var("VICTORY_PAIRS")
  256. .unwrap_or_default()
  257. .split(',')
  258. .filter_map(|p| p.split_once('+'))
  259. .map(|(v, p)| (v.trim().to_owned(), p.trim().to_owned()))
  260. .collect();
  261. let kept = std::sync::Arc::new(Mutex::new(Vec::new()));
  262. let threads =
  263. jobs.unwrap_or_else(|| std::thread::available_parallelism().map_or(4, |n| n.get()));
  264. let seen = Mutex::new(HashSet::new());
  265. let total = Mutex::new(Tally::default());
  266. for root in &paths {
  267. for entry in walkdir::WalkDir::new(root)
  268. .into_iter()
  269. .filter_map(Result::ok)
  270. {
  271. if !entry.file_type().is_file() || entry.metadata().map_or(0, |m| m.len()) > MAX_FILE {
  272. continue;
  273. }
  274. let Ok(data) = std::fs::read(entry.path()) else {
  275. continue;
  276. };
  277. let jobs = sources(&data);
  278. let next = AtomicUsize::new(0);
  279. std::thread::scope(|s| {
  280. for _ in 0..threads.min(jobs.len()) {
  281. s.spawn(|| {
  282. let mut t = Tally {
  283. list,
  284. ..Tally::default()
  285. };
  286. let mut checks = Checks {
  287. keep: (!pairs.is_empty()).then(|| kept.clone()),
  288. validator: validate
  289. .then(|| Validator::load(dll.as_deref()).ok())
  290. .flatten(),
  291. host: pipelines
  292. .then(|| Host::new(false).ok().map(|h| (h, host::stub_ps())))
  293. .flatten(),
  294. };
  295. while let Some(job) = jobs.get(next.fetch_add(1, Ordering::Relaxed)) {
  296. translate(job, entry.path(), &seen, &mut t, &mut checks);
  297. }
  298. lock(&total).merge(t);
  299. });
  300. }
  301. });
  302. }
  303. }
  304. let t = total.into_inner().unwrap_or_else(|e| e.into_inner());
  305. println!(
  306. "containers {} ({} duplicates skipped)",
  307. t.containers, t.duplicates
  308. );
  309. println!(
  310. "programs {} translated of {} ({} IR instructions)",
  311. t.translated, t.programs, t.instructions
  312. );
  313. println!(
  314. "structured {} of {} ({} vector instructions, {} guarded, {} on opaque masks; \
  315. branches {} per lane, {} uniform)",
  316. t.structured,
  317. t.translated,
  318. t.vector,
  319. t.guarded,
  320. t.opaque,
  321. t.lane_branches,
  322. t.uniform_branches
  323. );
  324. println!(
  325. "resources {} of {} tracked (descriptors {} loaded, {} built, {} constant; \
  326. {} scalar accesses; {} with a computed term)",
  327. t.tracked, t.translated, t.loaded, t.built, t.constant, t.scalar, t.dynamic
  328. );
  329. println!(
  330. " used-resource entries {}: {} not traced {:?}; {} traced parameters not listed",
  331. t.used,
  332. t.untraced_used.values().sum::<usize>(),
  333. t.untraced_used,
  334. t.unlisted
  335. );
  336. println!(
  337. "I/O {} of {} vertex and pixel programs raised ({} interpolations, \
  338. {} vertex values; exports {:?}, {} still f16 pairs)",
  339. t.io_raised, t.io_programs, t.interpolated, t.vertex_values, t.exports, t.compressed
  340. );
  341. println!(
  342. "DXIL {} emitted of {} vertex and pixel programs; {} validated, {} pipelines",
  343. t.emitted, t.emit_programs, t.validated, t.pipelines
  344. );
  345. println!(
  346. " {} emitted of {} compute programs; {} validated, {} pipelines",
  347. t.cs_emitted, t.cs_programs, t.cs_validated, t.cs_pipelines
  348. );
  349. println!(
  350. " {} emitted of {} mesh programs; {} validated, {} pipelines",
  351. t.ms_emitted, t.ms_programs, t.ms_validated, t.ms_pipelines
  352. );
  353. if !pairs.is_empty() {
  354. let host = Host::new(false).map_err(anyhow::Error::msg)?;
  355. let kept = lock(&kept);
  356. let find = |name: &str| kept.iter().find(|(l, _)| l.contains(name));
  357. for (v, p) in &pairs {
  358. let made = match (find(v), find(p)) {
  359. (Some((_, vs)), Some((_, ps))) => if vs.stage == HwStage::Ms {
  360. host.mesh_pipeline(vs, ps)
  361. } else {
  362. host.pipeline(vs, ps)
  363. }
  364. .map(|_| "pipeline created".to_owned())
  365. .unwrap_or_else(|e| e),
  366. _ => "not emitted".to_owned(),
  367. };
  368. println!("pair {v} + {p}: {made}");
  369. }
  370. }
  371. let mut lines = t.lines;
  372. lines.sort();
  373. for l in lines {
  374. println!("{l}");
  375. }
  376. let mut failed: Vec<_> = t.failed.into_iter().collect();
  377. failed.sort_by_key(|(_, (n, _))| std::cmp::Reverse(*n));
  378. for (reason, (n, example)) in failed {
  379. println!(" {n:>7} {reason} (e.g. {example})");
  380. }
  381. Ok(())
  382. }
  383. /// Every shader found into the cache runs translate from.
  384. pub fn precompile(paths: Vec<PathBuf>, jobs: Option<usize>) -> Result<()> {
  385. let cfg = victory_core::Config::load()?;
  386. victory_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?);
  387. let paths = crate::default_paths(paths)?;
  388. let threads =
  389. jobs.unwrap_or_else(|| std::thread::available_parallelism().map_or(4, |n| n.get()));
  390. let started = std::time::Instant::now();
  391. let seen = Mutex::new(HashSet::new());
  392. let done = AtomicUsize::new(0);
  393. let failed = Mutex::new(BTreeMap::<String, (usize, String)>::new());
  394. for root in &paths {
  395. for entry in walkdir::WalkDir::new(root).into_iter().filter_map(Result::ok) {
  396. if !entry.file_type().is_file() || entry.metadata().map_or(0, |m| m.len()) > MAX_FILE {
  397. continue;
  398. }
  399. let Ok(data) = std::fs::read(entry.path()) else {
  400. continue;
  401. };
  402. let jobs = sources(&data);
  403. let next = AtomicUsize::new(0);
  404. std::thread::scope(|s| {
  405. for _ in 0..threads.min(jobs.len()) {
  406. s.spawn(|| {
  407. while let Some(job) = jobs.get(next.fetch_add(1, Ordering::Relaxed)) {
  408. let Some(bytes) = job.bytes() else { continue };
  409. let hash = blake3::hash(&bytes);
  410. if !lock(&seen).insert(hash) {
  411. continue;
  412. }
  413. match victory_hle::modules::d3d12x::precompile(&bytes) {
  414. Ok(_) => {
  415. let n = done.fetch_add(1, Ordering::Relaxed) + 1;
  416. if n.is_multiple_of(1000) {
  417. println!("{n} shaders in the cache, {:.0} s", started.elapsed().as_secs_f64());
  418. }
  419. }
  420. Err(why) => {
  421. let mut failed = lock(&failed);
  422. failed.entry(why).or_insert_with(|| (0, hash.to_hex()[..16].to_owned())).0 += 1;
  423. }
  424. }
  425. }
  426. });
  427. }
  428. });
  429. }
  430. }
  431. let failed = failed.into_inner().unwrap_or_else(|e| e.into_inner());
  432. println!(
  433. "{} shaders in the cache, {} do not translate, {:.0} s",
  434. done.load(Ordering::Relaxed),
  435. failed.values().map(|f| f.0).sum::<usize>(),
  436. started.elapsed().as_secs_f64()
  437. );
  438. for (why, (n, hash)) in failed {
  439. println!(" {n:>5} {why} (e.g. {hash})");
  440. }
  441. Ok(())
  442. }
  443. fn translate(
  444. source: &Source,
  445. path: &Path,
  446. seen: &Mutex<HashSet<blake3::Hash>>,
  447. t: &mut Tally,
  448. checks: &mut Checks,
  449. ) {
  450. let example = || format!("{}{}", path.display(), source.label());
  451. let Some(bytes) = source.bytes() else {
  452. return t.fail("corrupt record".into(), example);
  453. };
  454. // The hash a run's log names the shader by (`hash=` in "first bind",
  455. // "shader does not translate", "host pipeline refused").
  456. let hash = blake3::hash(&bytes).to_hex()[..16].to_owned();
  457. // Diagnostics: `VICTORY_TRANSLATE_ONLY=<hash prefix>,...` translates
  458. // those containers alone.
  459. static ONLY: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();
  460. let only = ONLY.get_or_init(|| {
  461. std::env::var("VICTORY_TRANSLATE_ONLY")
  462. .unwrap_or_default()
  463. .split(',')
  464. .map(|h| h.trim().to_lowercase())
  465. .filter(|h| !h.is_empty())
  466. .collect()
  467. });
  468. if !only.is_empty() && !only.iter().any(|o| hash.starts_with(o.as_str())) {
  469. return;
  470. }
  471. let example = || format!("{}{} #{hash}", path.display(), source.label());
  472. t.containers += 1;
  473. let Ok(container) = Container::parse(&bytes) else {
  474. return t.fail("no DXIL part (SM5 or older)".into(), example);
  475. };
  476. let Some(dxil) = container.part(FourCC::DXIL).or(container.part(FourCC::ACCC)).map(|p| p.data) else {
  477. return t.fail("no DXIL part (SM5 or older)".into(), example);
  478. };
  479. // `~`: the hash of the code alone; containers that differ only around
  480. // it are translated once, the others listed as duplicates of it.
  481. let code = blake3::hash(dxil);
  482. let code8 = code.to_hex()[..8].to_owned();
  483. let example = || format!("{} ~{code8}", example());
  484. // `VICTORY_DUMP_MATCH=<dir>;<text>|<text>...`: the containers whose
  485. // line holds one of the texts (a name, `#hash`), as the title has them.
  486. if let Ok(spec) = std::env::var("VICTORY_DUMP_MATCH")
  487. && let Some((dir, texts)) = spec.split_once(';')
  488. {
  489. let line = example();
  490. if texts.split('|').any(|text| !text.is_empty() && line.contains(text)) {
  491. let name: String = source
  492. .label()
  493. .chars()
  494. .skip_while(|c| *c != ' ')
  495. .filter(|c| c.is_ascii_alphanumeric() || *c == '_')
  496. .take(70)
  497. .collect();
  498. let _ = std::fs::create_dir_all(dir);
  499. let _ = std::fs::write(std::path::Path::new(dir).join(format!("{name}.{hash}.cdxil")), &bytes[..]);
  500. }
  501. }
  502. if !lock(seen).insert(code) {
  503. t.duplicates += 1;
  504. if t.list {
  505. t.lines.push(format!("{} duplicate", example()));
  506. }
  507. return;
  508. }
  509. let programs = match native_programs(dxil) {
  510. Ok(p) => p,
  511. Err(e) => return t.fail(e.to_string(), example),
  512. };
  513. // `VICTORY_FAIL_DUMP=<dir>`: the first 3 containers of each failure reason, as the title
  514. // has them (`.cdxil`), to work on a translator gap offline
  515. let dump = std::env::var_os("VICTORY_FAIL_DUMP");
  516. let before: Option<BTreeMap<String, usize>> = dump.as_ref().map(|_| t.failed.iter().map(|(k, v)| (k.clone(), v.0)).collect());
  517. translate_programs(&container, programs, &example, t, checks);
  518. if let (Some(dir), Some(before)) = (dump, before) {
  519. for (reason, (n, _)) in &t.failed {
  520. let was = before.get(reason).copied().unwrap_or(0);
  521. if *n > was && was < 3 {
  522. let stem: String = reason.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).take(60).collect();
  523. let _ = std::fs::create_dir_all(&dir);
  524. let _ = std::fs::write(std::path::Path::new(&dir).join(format!("{stem}_{was}.cdxil")), &bytes[..]);
  525. }
  526. }
  527. }
  528. }
  529. fn translate_programs(container: &Container, programs: Vec<NativeProgram>, example: &dyn Fn() -> String, t: &mut Tally, checks: &mut Checks) {
  530. for p in programs {
  531. t.programs += 1;
  532. match victory_shader::spill::build(&p) {
  533. Ok(program) => {
  534. t.translated += 1;
  535. t.instructions += program.blocks.iter().map(|b| b.insts.len()).sum::<usize>();
  536. // Per-lane descriptors are traced on the per-lane form; its
  537. // failure is listed after the resources' and I/O's.
  538. let structured = structure::structure(&program);
  539. let lanes = structured.as_ref().ok();
  540. let res = match resource::track(&program, &p.layout, p.stage, lanes) {
  541. Ok(r) => {
  542. tally_resources(&p, &r, t);
  543. Some(r)
  544. }
  545. Err(ShaderError::Unsupported { offset, what }) => {
  546. t.fail(format!("resources: {what}"), || {
  547. format!("{} {:?} at {offset:#x}", example(), p.stage)
  548. });
  549. None
  550. }
  551. Err(e) => {
  552. t.fail(e.to_string(), || format!("{} {:?}", example(), p.stage));
  553. None
  554. }
  555. };
  556. let graphics = matches!(p.stage, HwStage::Vs | HwStage::Ps);
  557. let compute = p.stage == HwStage::Cs;
  558. let mut raised = None;
  559. if graphics || compute || p.stage == HwStage::Ms {
  560. t.io_programs += usize::from(graphics);
  561. match io::raise(&program, &p) {
  562. Ok(r) => {
  563. if graphics {
  564. tally_io(&r, t);
  565. }
  566. raised = Some(r);
  567. }
  568. Err(ShaderError::Unsupported { offset, what }) => t
  569. .fail(format!("I/O: {what}"), || {
  570. format!("{} {:?} at {offset:#x}", example(), p.stage)
  571. }),
  572. Err(e) => t.fail(e.to_string(), || format!("{} {:?}", example(), p.stage)),
  573. }
  574. }
  575. let structured = match structured {
  576. Ok(s) => {
  577. tally_structured(&program, &s, t);
  578. Some(s)
  579. }
  580. Err(e) => {
  581. let reason = match e {
  582. ShaderError::Unsupported { what, .. } => format!("structure: {what}"),
  583. ShaderError::Isa { reason, .. } => format!("structure: {reason}"),
  584. e => e.to_string(),
  585. };
  586. t.fail(reason, || format!("{} {:?}", example(), p.stage));
  587. None
  588. }
  589. };
  590. if let (Some(r), Some(i), Some(s)) = (res, raised, structured) {
  591. let label = || format!("{} {:?}", example(), p.stage);
  592. *counter(t, p.stage, 0) += 1;
  593. match emit::emit(container, &p, &program, &s, &i, &r) {
  594. Ok(shader) => {
  595. census_line(&label(), &p, &program, &shader);
  596. *counter(t, p.stage, 1) += 1;
  597. check(shader, t, checks, label);
  598. }
  599. Err(ShaderError::Unsupported { offset, what }) => t
  600. .fail(format!("emit: {what}"), || {
  601. format!("{} at {offset:#x}", label())
  602. }),
  603. Err(e) => t.fail(format!("emit: {e}"), label),
  604. }
  605. }
  606. }
  607. Err(e) => {
  608. let reason = match e {
  609. ShaderError::Unsupported { what, .. } => format!("unsupported: {what}"),
  610. e => e.to_string(),
  611. };
  612. t.fail(reason, || format!("{} {:?}", example(), p.stage));
  613. }
  614. }
  615. }
  616. }
  617. /// `VICTORY_SHADER_CENSUS=<file>`: one line per emitted program, appended:
  618. /// its label, the console program's instructions by encoding class (a
  619. /// static count of the whole program, not of one thread's path), and the
  620. /// host module's instructions by kind (`emit::census::KINDS`).
  621. fn census_line(label: &str, native: &NativeProgram, p: &ir::Program, shader: &emit::HostShader) {
  622. use std::io::Write;
  623. use victory_shader::gfx10::Fields;
  624. static OUT: std::sync::OnceLock<Option<Mutex<std::fs::File>>> = std::sync::OnceLock::new();
  625. let Some(out) = OUT.get_or_init(|| {
  626. let path = std::env::var_os("VICTORY_SHADER_CENSUS")?;
  627. let file = std::fs::OpenOptions::new().create(true).append(true).open(path).ok()?;
  628. Some(Mutex::new(file))
  629. }) else {
  630. return;
  631. };
  632. let Some(census) = emit::census::take(&shader.dxil) else {
  633. return;
  634. };
  635. // total, vector, scalar, descriptor loads, buffer and memory, image, LDS, control, other
  636. let mut console = [0u32; 9];
  637. for inst in p.blocks.iter().flat_map(|b| &b.insts) {
  638. console[0] += 1;
  639. let k = match &inst.fields {
  640. Fields::Valu(_) => 1,
  641. Fields::Sop { .. } => 2,
  642. Fields::Smem { .. } => 3,
  643. Fields::Buffer { .. } | Fields::Flat { .. } => 4,
  644. Fields::Image { .. } => 5,
  645. Fields::Ds { .. } => 6,
  646. Fields::Sopp { .. } => 7,
  647. _ => 8,
  648. };
  649. console[k] += 1;
  650. }
  651. let mut line = format!("{label}\twave64={}", u8::from(native.wave64));
  652. for (name, n) in ["c_total", "c_valu", "c_sop", "c_smem", "c_buffer", "c_image", "c_ds", "c_sopp", "c_other"].iter().zip(console) {
  653. line.push_str(&format!("\t{name}={n}"));
  654. }
  655. for (name, n) in emit::census::KINDS.iter().zip(census.counts) {
  656. line.push_str(&format!("\t{name}={n}"));
  657. }
  658. line.push('\n');
  659. let _ = lock(out).write_all(line.as_bytes());
  660. }
  661. /// Validates an emitted shader if asked to.
  662. fn check(
  663. mut shader: emit::HostShader,
  664. t: &mut Tally,
  665. checks: &mut Checks,
  666. label: impl Fn() -> String,
  667. ) {
  668. if let Some(keep) = &checks.keep {
  669. lock(keep).push((label(), shader.clone()));
  670. }
  671. // With `--list`: a hash of the module and of what the host binds for it,
  672. // to show which shaders a change to the translator touches.
  673. if t.list {
  674. let hash = blake3::hash(format!("{shader:?}").as_bytes()).to_hex();
  675. t.lines.push(format!("{} emitted {}", label(), &hash[..16]));
  676. }
  677. // `VICTORY_EMIT_DUMP` with `--list`: every emitted shader as a file.
  678. if t.list
  679. && let Ok(dir) = std::env::var("VICTORY_EMIT_DUMP")
  680. {
  681. let name: String = label()
  682. .chars()
  683. .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
  684. .collect();
  685. let _ = std::fs::write(
  686. format!("{dir}/{}.dxil", &name[name.len().saturating_sub(100)..]),
  687. &shader.dxil,
  688. );
  689. }
  690. if let Some((h, stub_ps)) = &checks.host {
  691. let made = match shader.stage {
  692. HwStage::Vs => h.pipeline(&shader, stub_ps).map(drop),
  693. HwStage::Cs => h.compute_pipeline(&shader).map(drop),
  694. HwStage::Ms => h.mesh_pipeline(&shader, stub_ps).map(drop),
  695. _ => host::stub_vs(&shader).and_then(|vs| h.pipeline(&vs, &shader).map(drop)),
  696. };
  697. match made {
  698. Ok(()) => {
  699. *counter(t, shader.stage, 3) += 1;
  700. if t.list {
  701. t.lines.push(format!("{} pipeline created", label()));
  702. }
  703. }
  704. Err(e) => t.fail(format!("pipeline: {e}"), &label),
  705. }
  706. }
  707. let Some(v) = checks.validator.as_mut() else {
  708. if t.list && checks.host.is_none() {
  709. t.lines.push(format!("{} emitted", label()));
  710. }
  711. return;
  712. };
  713. match v.validate(&mut shader.dxil) {
  714. Ok(()) => {
  715. *counter(t, shader.stage, 2) += 1;
  716. if t.list {
  717. t.lines.push(format!("{} validated", label()));
  718. }
  719. }
  720. Err(text) => {
  721. let first = text
  722. .lines()
  723. .find(|l| l.contains("error"))
  724. .unwrap_or(text.lines().next().unwrap_or(""))
  725. .to_owned();
  726. if let Ok(dir) = std::env::var("VICTORY_EMIT_DUMP") {
  727. let n = t
  728. .failed
  729. .get(&format!("validator: {first}"))
  730. .map_or(0, |f| f.0);
  731. if n < 3 {
  732. let name = format!(
  733. "{dir}/{}_{n}",
  734. first
  735. .chars()
  736. .filter(char::is_ascii_alphanumeric)
  737. .take(40)
  738. .collect::<String>()
  739. );
  740. let _ = std::fs::write(format!("{name}.dxil"), &shader.dxil);
  741. let _ = std::fs::write(format!("{name}.txt"), format!("{}\n{text}", label()));
  742. }
  743. }
  744. t.fail(format!("validator: {first}"), label);
  745. }
  746. }
  747. }
  748. /// Emission counts of `stage`'s kind: 0 programs, 1 emitted, 2 validated,
  749. /// 3 pipelines.
  750. fn counter(t: &mut Tally, stage: HwStage, k: usize) -> &mut usize {
  751. let [a, b, c, d] = match stage {
  752. HwStage::Cs => [
  753. &mut t.cs_programs,
  754. &mut t.cs_emitted,
  755. &mut t.cs_validated,
  756. &mut t.cs_pipelines,
  757. ],
  758. HwStage::Ms => [
  759. &mut t.ms_programs,
  760. &mut t.ms_emitted,
  761. &mut t.ms_validated,
  762. &mut t.ms_pipelines,
  763. ],
  764. _ => [
  765. &mut t.emit_programs,
  766. &mut t.emitted,
  767. &mut t.validated,
  768. &mut t.pipelines,
  769. ],
  770. };
  771. [a, b, c, d].into_iter().nth(k).expect("0 to 3")
  772. }
  773. fn tally_io(r: &io::Io, t: &mut Tally) {
  774. t.io_raised += 1;
  775. for (_, i) in &r.interps {
  776. match i {
  777. io::Interp::Interpolated { .. } => t.interpolated += 1,
  778. io::Interp::Vertex { .. } => t.vertex_values += 1,
  779. io::Interp::Weighted { .. } => t.interpolated += 1,
  780. }
  781. }
  782. for e in &r.exports {
  783. let kind = match e.target {
  784. io::Target::Color(_) => "color",
  785. io::Target::Depth => "depth",
  786. io::Target::Null => "null",
  787. io::Target::Position(_) => "position",
  788. io::Target::Param { .. } => "param",
  789. io::Target::Unread => "unread param",
  790. io::Target::Primitive => "primitive",
  791. io::Target::PrimitiveParam { .. } => "primitive param",
  792. };
  793. *t.exports.entry(kind).or_default() += 1;
  794. t.compressed += usize::from(e.compressed);
  795. }
  796. }
  797. fn tally_resources(p: &NativeProgram, r: &resource::Resources, t: &mut Tally) {
  798. t.tracked += 1;
  799. t.scalar += r.scalar.len();
  800. t.dynamic += r.scalar.iter().filter(|s| s.1.dynamic.is_some()).count();
  801. let address = |load| r.scalar.iter().find(|s| s.0 == load).map(|s| s.1);
  802. let mut traced = HashSet::new();
  803. for leaf in r.descriptors.iter().flat_map(|d| d.source.leaves()) {
  804. let a = match *leaf {
  805. resource::Source::Loaded { load, .. } | resource::Source::Fetched { load, .. } => {
  806. t.loaded += 1;
  807. address(load)
  808. }
  809. resource::Source::Built { address, .. } => {
  810. t.built += 1;
  811. t.dynamic += usize::from(address.dynamic.is_some());
  812. Some(address)
  813. }
  814. resource::Source::Constant(_) => {
  815. t.constant += 1;
  816. None
  817. }
  818. resource::Source::Phi { .. }
  819. | resource::Source::Select { .. }
  820. | resource::Source::Lanes { .. }
  821. | resource::Source::LanePhi { .. } => {
  822. unreachable!("leaves are no phis, selects or per-lane choices")
  823. }
  824. };
  825. // Heaps hold dynamic resources, which no used entry lists; code
  826. // tables are no root parameter.
  827. if let Some(a) = a
  828. && a.param != resource::CODE
  829. && !matches!(
  830. p.layout[a.param].root,
  831. RootType::ResourceHeap | RootType::SamplerHeap
  832. )
  833. {
  834. traced.insert(p.layout[a.param].user_data);
  835. }
  836. }
  837. // Root constants are listed as a CBV, read straight from the SGPRs.
  838. traced.extend(
  839. r.params
  840. .iter()
  841. .map(|&(_, param, _)| &p.layout[param])
  842. .filter(|l| l.root == RootType::Constants)
  843. .map(|l| l.user_data),
  844. );
  845. let listed: HashSet<u8> = p.used.iter().map(|u| u.user_data).collect();
  846. t.used += p.used.len();
  847. // Immediate samplers are literals in the code: the distinct sampler
  848. // values (decoded) are matched against the listed entries, which do not
  849. // say which value is whose.
  850. let mut values: Vec<emit::StaticSampler> = Vec::new();
  851. for d in r
  852. .descriptors
  853. .iter()
  854. .filter(|d| d.role == resource::Role::Sampler)
  855. {
  856. for leaf in d.source.leaves() {
  857. if let resource::Source::Constant(words) = leaf
  858. && let Ok(w) = <[u32; 4]>::try_from(&words[..words.len().min(4)])
  859. {
  860. let s = emit::StaticSampler::from_words(w);
  861. if !values.contains(&s) {
  862. values.push(s);
  863. }
  864. }
  865. }
  866. }
  867. // Engines often declare equal samplers at several registers, so equal
  868. // values may stand for several entries, but never more values than
  869. // entries.
  870. let immediate = p
  871. .used
  872. .iter()
  873. .filter(|u| u.root == RootType::ImmediateSampler)
  874. .count();
  875. let samplers_match = !values.is_empty() && values.len() <= immediate;
  876. let matched = |u: &&victory_shader::UsedResource| {
  877. if u.root == RootType::ImmediateSampler {
  878. samplers_match
  879. } else {
  880. traced.contains(&u.user_data)
  881. }
  882. };
  883. for u in p.used.iter().filter(|u| !matched(u)) {
  884. *t.untraced_used
  885. .entry(format!("{:?} via {:?}", u.kind, u.root))
  886. .or_default() += 1;
  887. }
  888. t.unlisted += traced.difference(&listed).count();
  889. }
  890. fn tally_structured(program: &ir::Program, s: &structure::Structured, t: &mut Tally) {
  891. t.structured += 1;
  892. for (block, guards) in program.blocks.iter().zip(&s.guards) {
  893. t.vector += block
  894. .insts
  895. .iter()
  896. .filter(|i| i.read(ir::Reg::S(ir::EXEC)).is_some())
  897. .count();
  898. for &g in guards.iter().flatten() {
  899. t.guarded += 1;
  900. let support = s.bools.support(g);
  901. t.opaque += usize::from(support.iter().any(|a| matches!(a, Atom::Opaque(_))));
  902. }
  903. }
  904. for exit in &s.exits {
  905. if let LaneExit::Branch { when, .. } = *exit {
  906. if s.bools
  907. .support(when)
  908. .iter()
  909. .all(|a| matches!(a, Atom::Uniform(_)))
  910. {
  911. t.uniform_branches += 1;
  912. } else {
  913. t.lane_branches += 1;
  914. }
  915. }
  916. }
  917. }
  918. fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
  919. m.lock().unwrap_or_else(|e| e.into_inner())
  920. }
  921. #[cfg(test)]
  922. mod tests {
  923. /// Shader dumps are game-derived, so a dump directory in the repo is refused.
  924. #[test]
  925. fn emit_dump_inside_repo_is_refused() {
  926. // SAFETY: no other test in this binary touches the environment.
  927. unsafe { std::env::set_var("VICTORY_EMIT_DUMP", env!("CARGO_MANIFEST_DIR")) };
  928. let missing = std::env::temp_dir().join("victory-translate-no-such-dir");
  929. let err = super::run(vec![missing], false, false, false, Some(1)).unwrap_err();
  930. // SAFETY: as above; unset so a later test's `run` is not refused.
  931. unsafe { std::env::remove_var("VICTORY_EMIT_DUMP") };
  932. assert!(
  933. matches!(
  934. err.downcast_ref(),
  935. Some(victory_core::PolicyError::InsideRepo { .. })
  936. ),
  937. "{err}"
  938. );
  939. }
  940. }