translate.rs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852
  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. pub fn run(
  147. paths: Vec<PathBuf>,
  148. validate: bool,
  149. pipelines: bool,
  150. list: bool,
  151. jobs: Option<usize>,
  152. ) -> Result<()> {
  153. let paths = crate::default_paths(paths)?;
  154. // `VICTORY_HOST_MAX_WAVE=32`: translate as for a host whose waves have
  155. // at most 32 lanes (as the runtime does on such a card).
  156. if let Some(n) = std::env::var("VICTORY_HOST_MAX_WAVE").ok().and_then(|v| v.parse().ok()) {
  157. victory_shader::emit::set_host_max_wave(n);
  158. }
  159. let dll = validate.then(Validator::default_path).flatten();
  160. if validate {
  161. Validator::load(dll.as_deref()).map_err(anyhow::Error::msg)?;
  162. println!(
  163. "validator {}",
  164. dll.as_ref()
  165. .map_or("dxil.dll".into(), |p| p.display().to_string())
  166. );
  167. }
  168. if pipelines {
  169. Host::new(false).map_err(anyhow::Error::msg)?;
  170. }
  171. let pairs: Vec<(String, String)> = std::env::var("VICTORY_PAIRS")
  172. .unwrap_or_default()
  173. .split(',')
  174. .filter_map(|p| p.split_once('+'))
  175. .map(|(v, p)| (v.trim().to_owned(), p.trim().to_owned()))
  176. .collect();
  177. let kept = std::sync::Arc::new(Mutex::new(Vec::new()));
  178. let threads =
  179. jobs.unwrap_or_else(|| std::thread::available_parallelism().map_or(4, |n| n.get()));
  180. let seen = Mutex::new(HashSet::new());
  181. let total = Mutex::new(Tally::default());
  182. for root in &paths {
  183. for entry in walkdir::WalkDir::new(root)
  184. .into_iter()
  185. .filter_map(Result::ok)
  186. {
  187. if !entry.file_type().is_file() || entry.metadata().map_or(0, |m| m.len()) > MAX_FILE {
  188. continue;
  189. }
  190. let Ok(data) = std::fs::read(entry.path()) else {
  191. continue;
  192. };
  193. let jobs = sources(&data);
  194. let next = AtomicUsize::new(0);
  195. std::thread::scope(|s| {
  196. for _ in 0..threads.min(jobs.len()) {
  197. s.spawn(|| {
  198. let mut t = Tally {
  199. list,
  200. ..Tally::default()
  201. };
  202. let mut checks = Checks {
  203. keep: (!pairs.is_empty()).then(|| kept.clone()),
  204. validator: validate
  205. .then(|| Validator::load(dll.as_deref()).ok())
  206. .flatten(),
  207. host: pipelines
  208. .then(|| Host::new(false).ok().map(|h| (h, host::stub_ps())))
  209. .flatten(),
  210. };
  211. while let Some(job) = jobs.get(next.fetch_add(1, Ordering::Relaxed)) {
  212. translate(job, entry.path(), &seen, &mut t, &mut checks);
  213. }
  214. lock(&total).merge(t);
  215. });
  216. }
  217. });
  218. }
  219. }
  220. let t = total.into_inner().unwrap_or_else(|e| e.into_inner());
  221. println!(
  222. "containers {} ({} duplicates skipped)",
  223. t.containers, t.duplicates
  224. );
  225. println!(
  226. "programs {} translated of {} ({} IR instructions)",
  227. t.translated, t.programs, t.instructions
  228. );
  229. println!(
  230. "structured {} of {} ({} vector instructions, {} guarded, {} on opaque masks; \
  231. branches {} per lane, {} uniform)",
  232. t.structured,
  233. t.translated,
  234. t.vector,
  235. t.guarded,
  236. t.opaque,
  237. t.lane_branches,
  238. t.uniform_branches
  239. );
  240. println!(
  241. "resources {} of {} tracked (descriptors {} loaded, {} built, {} constant; \
  242. {} scalar accesses; {} with a computed term)",
  243. t.tracked, t.translated, t.loaded, t.built, t.constant, t.scalar, t.dynamic
  244. );
  245. println!(
  246. " used-resource entries {}: {} not traced {:?}; {} traced parameters not listed",
  247. t.used,
  248. t.untraced_used.values().sum::<usize>(),
  249. t.untraced_used,
  250. t.unlisted
  251. );
  252. println!(
  253. "I/O {} of {} vertex and pixel programs raised ({} interpolations, \
  254. {} vertex values; exports {:?}, {} still f16 pairs)",
  255. t.io_raised, t.io_programs, t.interpolated, t.vertex_values, t.exports, t.compressed
  256. );
  257. println!(
  258. "DXIL {} emitted of {} vertex and pixel programs; {} validated, {} pipelines",
  259. t.emitted, t.emit_programs, t.validated, t.pipelines
  260. );
  261. println!(
  262. " {} emitted of {} compute programs; {} validated, {} pipelines",
  263. t.cs_emitted, t.cs_programs, t.cs_validated, t.cs_pipelines
  264. );
  265. println!(
  266. " {} emitted of {} mesh programs; {} validated, {} pipelines",
  267. t.ms_emitted, t.ms_programs, t.ms_validated, t.ms_pipelines
  268. );
  269. if !pairs.is_empty() {
  270. let host = Host::new(false).map_err(anyhow::Error::msg)?;
  271. let kept = lock(&kept);
  272. let find = |name: &str| kept.iter().find(|(l, _)| l.contains(name));
  273. for (v, p) in &pairs {
  274. let made = match (find(v), find(p)) {
  275. (Some((_, vs)), Some((_, ps))) => if vs.stage == HwStage::Ms {
  276. host.mesh_pipeline(vs, ps)
  277. } else {
  278. host.pipeline(vs, ps)
  279. }
  280. .map(|_| "pipeline created".to_owned())
  281. .unwrap_or_else(|e| e),
  282. _ => "not emitted".to_owned(),
  283. };
  284. println!("pair {v} + {p}: {made}");
  285. }
  286. }
  287. let mut lines = t.lines;
  288. lines.sort();
  289. for l in lines {
  290. println!("{l}");
  291. }
  292. let mut failed: Vec<_> = t.failed.into_iter().collect();
  293. failed.sort_by_key(|(_, (n, _))| std::cmp::Reverse(*n));
  294. for (reason, (n, example)) in failed {
  295. println!(" {n:>7} {reason} (e.g. {example})");
  296. }
  297. Ok(())
  298. }
  299. /// Every shader found into the cache runs translate from.
  300. pub fn precompile(paths: Vec<PathBuf>, jobs: Option<usize>) -> Result<()> {
  301. let cfg = victory_core::Config::load()?;
  302. victory_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?);
  303. let paths = crate::default_paths(paths)?;
  304. let threads =
  305. jobs.unwrap_or_else(|| std::thread::available_parallelism().map_or(4, |n| n.get()));
  306. let started = std::time::Instant::now();
  307. let seen = Mutex::new(HashSet::new());
  308. let done = AtomicUsize::new(0);
  309. let failed = Mutex::new(BTreeMap::<String, (usize, String)>::new());
  310. for root in &paths {
  311. for entry in walkdir::WalkDir::new(root).into_iter().filter_map(Result::ok) {
  312. if !entry.file_type().is_file() || entry.metadata().map_or(0, |m| m.len()) > MAX_FILE {
  313. continue;
  314. }
  315. let Ok(data) = std::fs::read(entry.path()) else {
  316. continue;
  317. };
  318. let jobs = sources(&data);
  319. let next = AtomicUsize::new(0);
  320. std::thread::scope(|s| {
  321. for _ in 0..threads.min(jobs.len()) {
  322. s.spawn(|| {
  323. while let Some(job) = jobs.get(next.fetch_add(1, Ordering::Relaxed)) {
  324. let Some(bytes) = job.bytes() else { continue };
  325. let hash = blake3::hash(&bytes);
  326. if !lock(&seen).insert(hash) {
  327. continue;
  328. }
  329. match victory_hle::modules::d3d12x::precompile(&bytes) {
  330. Ok(_) => {
  331. let n = done.fetch_add(1, Ordering::Relaxed) + 1;
  332. if n.is_multiple_of(1000) {
  333. println!("{n} shaders in the cache, {:.0} s", started.elapsed().as_secs_f64());
  334. }
  335. }
  336. Err(why) => {
  337. let mut failed = lock(&failed);
  338. failed.entry(why).or_insert_with(|| (0, hash.to_hex()[..16].to_owned())).0 += 1;
  339. }
  340. }
  341. }
  342. });
  343. }
  344. });
  345. }
  346. }
  347. let failed = failed.into_inner().unwrap_or_else(|e| e.into_inner());
  348. println!(
  349. "{} shaders in the cache, {} do not translate, {:.0} s",
  350. done.load(Ordering::Relaxed),
  351. failed.values().map(|f| f.0).sum::<usize>(),
  352. started.elapsed().as_secs_f64()
  353. );
  354. for (why, (n, hash)) in failed {
  355. println!(" {n:>5} {why} (e.g. {hash})");
  356. }
  357. Ok(())
  358. }
  359. fn translate(
  360. source: &Source,
  361. path: &Path,
  362. seen: &Mutex<HashSet<blake3::Hash>>,
  363. t: &mut Tally,
  364. checks: &mut Checks,
  365. ) {
  366. let example = || format!("{}{}", path.display(), source.label());
  367. let Some(bytes) = source.bytes() else {
  368. return t.fail("corrupt record".into(), example);
  369. };
  370. // The hash a run's log names the shader by (`hash=` in "first bind",
  371. // "shader does not translate", "host pipeline refused").
  372. let hash = blake3::hash(&bytes).to_hex()[..16].to_owned();
  373. // Diagnostics: `VICTORY_TRANSLATE_ONLY=<hash prefix>,...` translates
  374. // those containers alone.
  375. static ONLY: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();
  376. let only = ONLY.get_or_init(|| {
  377. std::env::var("VICTORY_TRANSLATE_ONLY")
  378. .unwrap_or_default()
  379. .split(',')
  380. .map(|h| h.trim().to_lowercase())
  381. .filter(|h| !h.is_empty())
  382. .collect()
  383. });
  384. if !only.is_empty() && !only.iter().any(|o| hash.starts_with(o.as_str())) {
  385. return;
  386. }
  387. let example = || format!("{}{} #{hash}", path.display(), source.label());
  388. t.containers += 1;
  389. let Ok(container) = Container::parse(&bytes) else {
  390. return t.fail("no DXIL part (SM5 or older)".into(), example);
  391. };
  392. let Some(dxil) = container.part(FourCC::DXIL).or(container.part(FourCC::ACCC)).map(|p| p.data) else {
  393. return t.fail("no DXIL part (SM5 or older)".into(), example);
  394. };
  395. // `~`: the hash of the code alone; containers that differ only around
  396. // it are translated once, the others listed as duplicates of it.
  397. let code = blake3::hash(dxil);
  398. let code8 = code.to_hex()[..8].to_owned();
  399. let example = || format!("{} ~{code8}", example());
  400. // `VICTORY_DUMP_MATCH=<dir>;<text>|<text>...`: the containers whose
  401. // line holds one of the texts (a name, `#hash`), as the title has them.
  402. if let Ok(spec) = std::env::var("VICTORY_DUMP_MATCH")
  403. && let Some((dir, texts)) = spec.split_once(';')
  404. {
  405. let line = example();
  406. if texts.split('|').any(|text| !text.is_empty() && line.contains(text)) {
  407. let name: String = source
  408. .label()
  409. .chars()
  410. .skip_while(|c| *c != ' ')
  411. .filter(|c| c.is_ascii_alphanumeric() || *c == '_')
  412. .take(70)
  413. .collect();
  414. let _ = std::fs::create_dir_all(dir);
  415. let _ = std::fs::write(std::path::Path::new(dir).join(format!("{name}.{hash}.cdxil")), &bytes[..]);
  416. }
  417. }
  418. if !lock(seen).insert(code) {
  419. t.duplicates += 1;
  420. if t.list {
  421. t.lines.push(format!("{} duplicate", example()));
  422. }
  423. return;
  424. }
  425. let programs = match native_programs(dxil) {
  426. Ok(p) => p,
  427. Err(e) => return t.fail(e.to_string(), example),
  428. };
  429. // `VICTORY_FAIL_DUMP=<dir>`: the first 3 containers of each failure reason, as the title
  430. // has them (`.cdxil`), to work on a translator gap offline
  431. let dump = std::env::var_os("VICTORY_FAIL_DUMP");
  432. let before: Option<BTreeMap<String, usize>> = dump.as_ref().map(|_| t.failed.iter().map(|(k, v)| (k.clone(), v.0)).collect());
  433. translate_programs(&container, programs, &example, t, checks);
  434. if let (Some(dir), Some(before)) = (dump, before) {
  435. for (reason, (n, _)) in &t.failed {
  436. let was = before.get(reason).copied().unwrap_or(0);
  437. if *n > was && was < 3 {
  438. let stem: String = reason.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).take(60).collect();
  439. let _ = std::fs::create_dir_all(&dir);
  440. let _ = std::fs::write(std::path::Path::new(&dir).join(format!("{stem}_{was}.cdxil")), &bytes[..]);
  441. }
  442. }
  443. }
  444. }
  445. fn translate_programs(container: &Container, programs: Vec<NativeProgram>, example: &dyn Fn() -> String, t: &mut Tally, checks: &mut Checks) {
  446. for p in programs {
  447. t.programs += 1;
  448. match victory_shader::spill::build(&p) {
  449. Ok(program) => {
  450. t.translated += 1;
  451. t.instructions += program.blocks.iter().map(|b| b.insts.len()).sum::<usize>();
  452. // Per-lane descriptors are traced on the per-lane form; its
  453. // failure is listed after the resources' and I/O's.
  454. let structured = structure::structure(&program);
  455. let lanes = structured.as_ref().ok();
  456. let res = match resource::track(&program, &p.layout, p.stage, lanes) {
  457. Ok(r) => {
  458. tally_resources(&p, &r, t);
  459. Some(r)
  460. }
  461. Err(ShaderError::Unsupported { offset, what }) => {
  462. t.fail(format!("resources: {what}"), || {
  463. format!("{} {:?} at {offset:#x}", example(), p.stage)
  464. });
  465. None
  466. }
  467. Err(e) => {
  468. t.fail(e.to_string(), || format!("{} {:?}", example(), p.stage));
  469. None
  470. }
  471. };
  472. let graphics = matches!(p.stage, HwStage::Vs | HwStage::Ps);
  473. let compute = p.stage == HwStage::Cs;
  474. let mut raised = None;
  475. if graphics || compute || p.stage == HwStage::Ms {
  476. t.io_programs += usize::from(graphics);
  477. match io::raise(&program, &p) {
  478. Ok(r) => {
  479. if graphics {
  480. tally_io(&r, t);
  481. }
  482. raised = Some(r);
  483. }
  484. Err(ShaderError::Unsupported { offset, what }) => t
  485. .fail(format!("I/O: {what}"), || {
  486. format!("{} {:?} at {offset:#x}", example(), p.stage)
  487. }),
  488. Err(e) => t.fail(e.to_string(), || format!("{} {:?}", example(), p.stage)),
  489. }
  490. }
  491. let structured = match structured {
  492. Ok(s) => {
  493. tally_structured(&program, &s, t);
  494. Some(s)
  495. }
  496. Err(e) => {
  497. let reason = match e {
  498. ShaderError::Unsupported { what, .. } => format!("structure: {what}"),
  499. ShaderError::Isa { reason, .. } => format!("structure: {reason}"),
  500. e => e.to_string(),
  501. };
  502. t.fail(reason, || format!("{} {:?}", example(), p.stage));
  503. None
  504. }
  505. };
  506. if let (Some(r), Some(i), Some(s)) = (res, raised, structured) {
  507. let label = || format!("{} {:?}", example(), p.stage);
  508. *counter(t, p.stage, 0) += 1;
  509. match emit::emit(container, &p, &program, &s, &i, &r) {
  510. Ok(shader) => {
  511. census_line(&label(), &p, &program, &shader);
  512. *counter(t, p.stage, 1) += 1;
  513. check(shader, t, checks, label);
  514. }
  515. Err(ShaderError::Unsupported { offset, what }) => t
  516. .fail(format!("emit: {what}"), || {
  517. format!("{} at {offset:#x}", label())
  518. }),
  519. Err(e) => t.fail(format!("emit: {e}"), label),
  520. }
  521. }
  522. }
  523. Err(e) => {
  524. let reason = match e {
  525. ShaderError::Unsupported { what, .. } => format!("unsupported: {what}"),
  526. e => e.to_string(),
  527. };
  528. t.fail(reason, || format!("{} {:?}", example(), p.stage));
  529. }
  530. }
  531. }
  532. }
  533. /// `VICTORY_SHADER_CENSUS=<file>`: one line per emitted program, appended:
  534. /// its label, the console program's instructions by encoding class (a
  535. /// static count of the whole program, not of one thread's path), and the
  536. /// host module's instructions by kind (`emit::census::KINDS`).
  537. fn census_line(label: &str, native: &NativeProgram, p: &ir::Program, shader: &emit::HostShader) {
  538. use std::io::Write;
  539. use victory_shader::gfx10::Fields;
  540. static OUT: std::sync::OnceLock<Option<Mutex<std::fs::File>>> = std::sync::OnceLock::new();
  541. let Some(out) = OUT.get_or_init(|| {
  542. let path = std::env::var_os("VICTORY_SHADER_CENSUS")?;
  543. let file = std::fs::OpenOptions::new().create(true).append(true).open(path).ok()?;
  544. Some(Mutex::new(file))
  545. }) else {
  546. return;
  547. };
  548. let Some(census) = emit::census::take(&shader.dxil) else {
  549. return;
  550. };
  551. // total, vector, scalar, descriptor loads, buffer and memory, image, LDS, control, other
  552. let mut console = [0u32; 9];
  553. for inst in p.blocks.iter().flat_map(|b| &b.insts) {
  554. console[0] += 1;
  555. let k = match &inst.fields {
  556. Fields::Valu(_) => 1,
  557. Fields::Sop { .. } => 2,
  558. Fields::Smem { .. } => 3,
  559. Fields::Buffer { .. } | Fields::Flat { .. } => 4,
  560. Fields::Image { .. } => 5,
  561. Fields::Ds { .. } => 6,
  562. Fields::Sopp { .. } => 7,
  563. _ => 8,
  564. };
  565. console[k] += 1;
  566. }
  567. let mut line = format!("{label}\twave64={}", u8::from(native.wave64));
  568. 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) {
  569. line.push_str(&format!("\t{name}={n}"));
  570. }
  571. for (name, n) in emit::census::KINDS.iter().zip(census.counts) {
  572. line.push_str(&format!("\t{name}={n}"));
  573. }
  574. line.push('\n');
  575. let _ = lock(out).write_all(line.as_bytes());
  576. }
  577. /// Validates an emitted shader if asked to.
  578. fn check(
  579. mut shader: emit::HostShader,
  580. t: &mut Tally,
  581. checks: &mut Checks,
  582. label: impl Fn() -> String,
  583. ) {
  584. if let Some(keep) = &checks.keep {
  585. lock(keep).push((label(), shader.clone()));
  586. }
  587. // With `--list`: a hash of the module and of what the host binds for it,
  588. // to show which shaders a change to the translator touches.
  589. if t.list {
  590. let hash = blake3::hash(format!("{shader:?}").as_bytes()).to_hex();
  591. t.lines.push(format!("{} emitted {}", label(), &hash[..16]));
  592. }
  593. // `VICTORY_EMIT_DUMP` with `--list`: every emitted shader as a file.
  594. if t.list
  595. && let Ok(dir) = std::env::var("VICTORY_EMIT_DUMP")
  596. {
  597. let name: String = label()
  598. .chars()
  599. .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
  600. .collect();
  601. let _ = std::fs::write(
  602. format!("{dir}/{}.dxil", &name[name.len().saturating_sub(100)..]),
  603. &shader.dxil,
  604. );
  605. }
  606. if let Some((h, stub_ps)) = &checks.host {
  607. let made = match shader.stage {
  608. HwStage::Vs => h.pipeline(&shader, stub_ps).map(drop),
  609. HwStage::Cs => h.compute_pipeline(&shader).map(drop),
  610. HwStage::Ms => h.mesh_pipeline(&shader, stub_ps).map(drop),
  611. _ => host::stub_vs(&shader).and_then(|vs| h.pipeline(&vs, &shader).map(drop)),
  612. };
  613. match made {
  614. Ok(()) => {
  615. *counter(t, shader.stage, 3) += 1;
  616. if t.list {
  617. t.lines.push(format!("{} pipeline created", label()));
  618. }
  619. }
  620. Err(e) => t.fail(format!("pipeline: {e}"), &label),
  621. }
  622. }
  623. let Some(v) = checks.validator.as_mut() else {
  624. return;
  625. };
  626. match v.validate(&mut shader.dxil) {
  627. Ok(()) => {
  628. *counter(t, shader.stage, 2) += 1;
  629. if t.list {
  630. t.lines.push(format!("{} validated", label()));
  631. }
  632. }
  633. Err(text) => {
  634. let first = text
  635. .lines()
  636. .find(|l| l.contains("error"))
  637. .unwrap_or(text.lines().next().unwrap_or(""))
  638. .to_owned();
  639. if let Ok(dir) = std::env::var("VICTORY_EMIT_DUMP") {
  640. let n = t
  641. .failed
  642. .get(&format!("validator: {first}"))
  643. .map_or(0, |f| f.0);
  644. if n < 3 {
  645. let name = format!(
  646. "{dir}/{}_{n}",
  647. first
  648. .chars()
  649. .filter(char::is_ascii_alphanumeric)
  650. .take(40)
  651. .collect::<String>()
  652. );
  653. let _ = std::fs::write(format!("{name}.dxil"), &shader.dxil);
  654. let _ = std::fs::write(format!("{name}.txt"), format!("{}\n{text}", label()));
  655. }
  656. }
  657. t.fail(format!("validator: {first}"), label);
  658. }
  659. }
  660. }
  661. /// Emission counts of `stage`'s kind: 0 programs, 1 emitted, 2 validated,
  662. /// 3 pipelines.
  663. fn counter(t: &mut Tally, stage: HwStage, k: usize) -> &mut usize {
  664. let [a, b, c, d] = match stage {
  665. HwStage::Cs => [
  666. &mut t.cs_programs,
  667. &mut t.cs_emitted,
  668. &mut t.cs_validated,
  669. &mut t.cs_pipelines,
  670. ],
  671. HwStage::Ms => [
  672. &mut t.ms_programs,
  673. &mut t.ms_emitted,
  674. &mut t.ms_validated,
  675. &mut t.ms_pipelines,
  676. ],
  677. _ => [
  678. &mut t.emit_programs,
  679. &mut t.emitted,
  680. &mut t.validated,
  681. &mut t.pipelines,
  682. ],
  683. };
  684. [a, b, c, d].into_iter().nth(k).expect("0 to 3")
  685. }
  686. fn tally_io(r: &io::Io, t: &mut Tally) {
  687. t.io_raised += 1;
  688. for (_, i) in &r.interps {
  689. match i {
  690. io::Interp::Interpolated { .. } => t.interpolated += 1,
  691. io::Interp::Vertex { .. } => t.vertex_values += 1,
  692. io::Interp::Weighted { .. } => t.interpolated += 1,
  693. }
  694. }
  695. for e in &r.exports {
  696. let kind = match e.target {
  697. io::Target::Color(_) => "color",
  698. io::Target::Depth => "depth",
  699. io::Target::Null => "null",
  700. io::Target::Position(_) => "position",
  701. io::Target::Param { .. } => "param",
  702. io::Target::Unread => "unread param",
  703. io::Target::Primitive => "primitive",
  704. io::Target::PrimitiveParam { .. } => "primitive param",
  705. };
  706. *t.exports.entry(kind).or_default() += 1;
  707. t.compressed += usize::from(e.compressed);
  708. }
  709. }
  710. fn tally_resources(p: &NativeProgram, r: &resource::Resources, t: &mut Tally) {
  711. t.tracked += 1;
  712. t.scalar += r.scalar.len();
  713. t.dynamic += r.scalar.iter().filter(|s| s.1.dynamic.is_some()).count();
  714. let address = |load| r.scalar.iter().find(|s| s.0 == load).map(|s| s.1);
  715. let mut traced = HashSet::new();
  716. for leaf in r.descriptors.iter().flat_map(|d| d.source.leaves()) {
  717. let a = match *leaf {
  718. resource::Source::Loaded { load, .. } | resource::Source::Fetched { load, .. } => {
  719. t.loaded += 1;
  720. address(load)
  721. }
  722. resource::Source::Built { address, .. } => {
  723. t.built += 1;
  724. t.dynamic += usize::from(address.dynamic.is_some());
  725. Some(address)
  726. }
  727. resource::Source::Constant(_) => {
  728. t.constant += 1;
  729. None
  730. }
  731. resource::Source::Phi { .. }
  732. | resource::Source::Select { .. }
  733. | resource::Source::Lanes { .. }
  734. | resource::Source::LanePhi { .. } => {
  735. unreachable!("leaves are no phis, selects or per-lane choices")
  736. }
  737. };
  738. // Heaps hold dynamic resources, which no used entry lists; code
  739. // tables are no root parameter.
  740. if let Some(a) = a
  741. && a.param != resource::CODE
  742. && !matches!(
  743. p.layout[a.param].root,
  744. RootType::ResourceHeap | RootType::SamplerHeap
  745. )
  746. {
  747. traced.insert(p.layout[a.param].user_data);
  748. }
  749. }
  750. // Root constants are listed as a CBV, read straight from the SGPRs.
  751. traced.extend(
  752. r.params
  753. .iter()
  754. .map(|&(_, param, _)| &p.layout[param])
  755. .filter(|l| l.root == RootType::Constants)
  756. .map(|l| l.user_data),
  757. );
  758. let listed: HashSet<u8> = p.used.iter().map(|u| u.user_data).collect();
  759. t.used += p.used.len();
  760. // Immediate samplers are literals in the code: the distinct sampler
  761. // values (decoded) are matched against the listed entries, which do not
  762. // say which value is whose.
  763. let mut values: Vec<emit::StaticSampler> = Vec::new();
  764. for d in r
  765. .descriptors
  766. .iter()
  767. .filter(|d| d.role == resource::Role::Sampler)
  768. {
  769. for leaf in d.source.leaves() {
  770. if let resource::Source::Constant(words) = leaf
  771. && let Ok(w) = <[u32; 4]>::try_from(&words[..words.len().min(4)])
  772. {
  773. let s = emit::StaticSampler::from_words(w);
  774. if !values.contains(&s) {
  775. values.push(s);
  776. }
  777. }
  778. }
  779. }
  780. // Engines often declare equal samplers at several registers, so equal
  781. // values may stand for several entries, but never more values than
  782. // entries.
  783. let immediate = p
  784. .used
  785. .iter()
  786. .filter(|u| u.root == RootType::ImmediateSampler)
  787. .count();
  788. let samplers_match = !values.is_empty() && values.len() <= immediate;
  789. let matched = |u: &&victory_shader::UsedResource| {
  790. if u.root == RootType::ImmediateSampler {
  791. samplers_match
  792. } else {
  793. traced.contains(&u.user_data)
  794. }
  795. };
  796. for u in p.used.iter().filter(|u| !matched(u)) {
  797. *t.untraced_used
  798. .entry(format!("{:?} via {:?}", u.kind, u.root))
  799. .or_default() += 1;
  800. }
  801. t.unlisted += traced.difference(&listed).count();
  802. }
  803. fn tally_structured(program: &ir::Program, s: &structure::Structured, t: &mut Tally) {
  804. t.structured += 1;
  805. for (block, guards) in program.blocks.iter().zip(&s.guards) {
  806. t.vector += block
  807. .insts
  808. .iter()
  809. .filter(|i| i.read(ir::Reg::S(ir::EXEC)).is_some())
  810. .count();
  811. for &g in guards.iter().flatten() {
  812. t.guarded += 1;
  813. let support = s.bools.support(g);
  814. t.opaque += usize::from(support.iter().any(|a| matches!(a, Atom::Opaque(_))));
  815. }
  816. }
  817. for exit in &s.exits {
  818. if let LaneExit::Branch { when, .. } = *exit {
  819. if s.bools
  820. .support(when)
  821. .iter()
  822. .all(|a| matches!(a, Atom::Uniform(_)))
  823. {
  824. t.uniform_branches += 1;
  825. } else {
  826. t.lane_branches += 1;
  827. }
  828. }
  829. }
  830. }
  831. fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
  832. m.lock().unwrap_or_else(|e| e.into_inner())
  833. }