mod.rs 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743
  1. //! DXIL emission (decision 0003, step 3): a console vertex, pixel, compute
  2. //! or mesh shader as a PC DXIL container (SM 6.6) that host D3D12 accepts.
  3. //! Compute shaders keep the console's thread-group size; one that depends
  4. //! on the lane layout (cross-lane operations) declares the console's wave
  5. //! size (`WaveSize`), so the host device must support it.
  6. //!
  7. //! What the host binds for a translated shader ([`HostShader`]):
  8. //!
  9. //! * **User data** at `b0, space 0` (32-bit root constants or a constant
  10. //! buffer, per stage): dword `index` holds a root parameter's value, as
  11. //! [`UserData`] lists. A root-constant dword is the constant. A
  12. //! descriptor table is the byte offset of its first descriptor in its
  13. //! heap: the descriptor index times 32 for CBV/SRV/UAV tables, times 16
  14. //! for sampler tables (the console's descriptor sizes; the code adds
  15. //! offsets in those units). The heap bases of dynamic resources are 0
  16. //! and not listed.
  17. //! * **Descriptors** through SM 6.6 `ResourceDescriptorHeap[]` and
  18. //! `SamplerDescriptorHeap[]`, at the index the console address gives, so
  19. //! the host heaps keep the title's descriptor order. The root signature
  20. //! needs `CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` and
  21. //! `SAMPLER_HEAP_DIRECTLY_INDEXED`.
  22. //! * **Immediate samplers** as static samplers `s<n>, space 0`, `n` the
  23. //! position in [`HostShader::samplers`] (the console sampler words) and
  24. //! [`HostShader::static_samplers`] (the same decoded into a D3D12 static
  25. //! sampler description). Comparison sampling (added 2026-11-23): an
  26. //! immediate sampler it uses has a comparison filter there (bit 0x80);
  27. //! a heap sampler it uses must be a comparison sampler on the host.
  28. //! * **Root CBVs and root SRVs** (raw buffers) as root descriptors
  29. //! `b<i>` / `t<i>` in [`ROOT_CBV_SPACE`], `i` the title's root parameter
  30. //! index ([`HostShader::root_cbvs`], [`HostShader::root_srvs`]); the
  31. //! address the title sets is the buffer's.
  32. //! * **Vertex fetch** (added 2026-11-23). The title's mesh and
  33. //! vertex programs fetch vertices themselves with typed-format loads
  34. //! (`tbuffer_load_format_*`): the format (8_8_8_8 unorm, 16_16 snorm,
  35. //! 2_10_10_10 unorm, 8_8_8_8 and 16_16_16_16 uint...) is in the
  36. //! instruction, so the translation reads raw bytes and converts them
  37. //! itself. Their descriptors are built around a root SRV (stride 1, no
  38. //! record limit): the host binds the root SRV `t<slot>` above with the
  39. //! address the title sets, nothing more. The vertex index, the stride
  40. //! and the attribute offset are the shader's own arithmetic on data in
  41. //! that buffer (per-stream headers), not descriptor fields.
  42. //! * **Buffer views in the heap** are declared by how the shader reads
  43. //! them: raw (ByteAddressBuffer) for dword loads and stores, atomics and
  44. //! typed-format loads without an index; structured with the used-resource
  45. //! entry's stride when indexed; typed with four 32-bit float channels for
  46. //! `buffer_load_format_*` and `buffer_store_format_*`. The host's view at
  47. //! that index must be of that kind and start at the console descriptor's
  48. //! base address (raw: `R32_TYPELESS` with the raw flag), whatever kind the
  49. //! title's view description says. Typed-format loads from heap
  50. //! descriptors (1,024 world compute programs, ray-tracing material
  51. //! resolves) read raw views this way.
  52. //!
  53. //! * **Texture atomics** use a scalar integer UAV. The host binds R32_UINT
  54. //! for 32-bit operations and R32G32_UINT for 64-bit operations. The latter
  55. //! require SM 6.6 atomic support on typed and descriptor-heap resources.
  56. //!
  57. //! Entry points: [`translate`] (container bytes as the title passes them
  58. //! at pipeline creation → [`HostShader`]), [`emit`] (the same with the
  59. //! earlier stages already run). The root constants of each stage must
  60. //! cover [`HostShader::user_data_dwords`]. Stability: these types and the
  61. //! binding scheme are what pipeline creation builds on; changes are
  62. //! announced.
  63. //! * **Signatures** as the console container has them (same semantics,
  64. //! registers and masks), so the input layout and stage linking are the
  65. //! title's; pixel outputs are plain 32-bit values.
  66. //! * **Mesh shaders** ([`HwStage::Ms`], `ms_6_6`): user data and
  67. //! descriptors as above (the root constants visible to the mesh stage);
  68. //! the pipeline is a mesh pipeline (pipeline-state stream, no input
  69. //! layout) with the title's pixel shader. The thread group is the
  70. //! console's in lanes (`[numthreads]` in the DXIL), the vertex and
  71. //! primitive maxima its own, triangles only, no wave size required. The
  72. //! console numbers groups in x only: the draw path passes the title's
  73. //! count as `DispatchMesh(x, 1, 1)`. Per-primitive outputs (`PSG1`) are
  74. //! the console's, without `SV_PrimitiveID` and `SV_CullPrimitive` (the
  75. //! console never exports them).
  76. //! * **Rectangle lists** ([`rect_list_gs`], `gs_6_6`): the console draws a
  77. //! rectangle from three vertices; the host has no such topology. A
  78. //! pipeline the title makes for rectangles (topology type 19) gets a
  79. //! geometry shader of ours between the translated vertex and pixel
  80. //! shaders and draws triangle lists with the title's own vertex counts.
  81. //! It binds nothing.
  82. mod bitcode;
  83. mod container;
  84. #[cfg(all(test, windows))]
  85. mod diff_tests;
  86. #[cfg(all(test, windows))]
  87. mod intersect_tests;
  88. #[cfg(all(windows, any(test, feature = "host")))]
  89. pub mod host;
  90. mod lower;
  91. mod own_bits;
  92. mod rect;
  93. mod sampler;
  94. mod shader;
  95. mod threading;
  96. #[cfg(windows)]
  97. pub mod validator;
  98. #[cfg(all(test, windows))]
  99. mod valu_tests;
  100. #[cfg(all(test, windows))]
  101. mod waterfall_tests;
  102. #[cfg(all(test, windows))]
  103. mod wave64_tests;
  104. mod wave;
  105. use crate::dxbc::{Container, FourCC};
  106. use crate::native::{HwStage, NativeProgram, RootType};
  107. use crate::{ShaderError, io, ir, resource, structure};
  108. pub use bitcode::census;
  109. pub use sampler::StaticSampler;
  110. pub use lower::set_host_max_wave;
  111. pub use rect::rect_list_gs;
  112. pub use shader::{
  113. MEMORY_FAULTS, MEMORY_PAGES, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES,
  114. SLOT_STRIDES_COUNT, USER_DATA_SPACE, USER_MEMORY_BASE, USER_VIEW_ADDRESS, USER_VIEW_BIAS,
  115. set_view_heap_limit, view_heap_limit,
  116. };
  117. /// The loop limit without an override: 2^20.
  118. pub const DEFAULT_LOOP_LIMIT: u32 = lower::LOOP_LIMIT;
  119. /// The iteration count after which a translated loop is left, per lane and
  120. /// per entry into the loop: [`DEFAULT_LOOP_LIMIT`].
  121. ///
  122. /// With the `diagnostics` feature, `VICTORY_SHADER_LOOP_LIMIT` (decimal or
  123. /// `0x` hex, at least 1) sets it instead. A loop that hits the limit in
  124. /// every lane of a full-screen pass still runs for seconds (2^20 times a
  125. /// 4K screen is about 10^13 iterations); a much lower limit shows whether
  126. /// such loops are what makes a frame slow. The value is part of the
  127. /// translation, so the shader cache must key on it (`victory-gpu`'s does).
  128. pub fn loop_limit() -> u32 {
  129. static LIMIT: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
  130. *LIMIT.get_or_init(|| {
  131. if cfg!(feature = "diagnostics") {
  132. parse_loop_limit(std::env::var("VICTORY_SHADER_LOOP_LIMIT").ok().as_deref())
  133. } else {
  134. lower::LOOP_LIMIT
  135. }
  136. })
  137. }
  138. /// Which of a translated program's group barriers wait for the whole
  139. /// group (`GroupMemoryBarrierWithGroupSync`); the others keep their memory
  140. /// fence and lose the wait. A wait that some thread of the group never
  141. /// reaches is undefined on the host, and NVIDIA's wait is for every
  142. /// thread: the group stands until Windows resets the card. (The console's
  143. /// barrier is the wave's, whatever lanes are live, and a wave that ended
  144. /// is not waited for.) `VICTORY_GROUP_SYNC`:
  145. /// - unset or `2`: every barrier waits, as before.
  146. /// - `1`: the title's `s_barrier` waits only in a block every lane runs,
  147. /// in a program no lane can be cut out of at the iteration limit.
  148. /// - `0`: no barrier waits, neither the title's nor the ones the
  149. /// translation adds (wave64 programs in two host waves exchange through
  150. /// them, so such programs compute wrong values). For one run that tells
  151. /// whether a barrier is what stops the card: with it no run can stand in
  152. /// a barrier.
  153. ///
  154. /// Part of the translation: the shader cache keys on it (`victory-gpu`'s
  155. /// does).
  156. pub fn group_sync() -> u8 {
  157. static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
  158. *MODE.get_or_init(|| match std::env::var("VICTORY_GROUP_SYNC").ok().as_deref().map(str::trim) {
  159. Some("0") => 0,
  160. Some("1") => 1,
  161. _ => 2,
  162. })
  163. }
  164. /// The clean-up passes that run over a translated program before it is
  165. /// written (`bitcode::opt`): a set of that module's pass bits. Every pass
  166. /// is exact, so the switch is for telling a translator fault from a
  167. /// clean-up fault, and for measuring what the clean-up is worth.
  168. /// `VICTORY_SHADER_OPT`:
  169. /// - unset: every pass.
  170. /// - `0`: none (the module as the lowering made it).
  171. /// - a number (decimal or `0x` hex): those passes; 1 dead code, 2 constants
  172. /// and identities, 4 one instruction for one value, 8 what a branch taken
  173. /// says about its condition, 16 one read for one place within a block,
  174. /// 32 a first-lane read of two host waves without the round that asks
  175. /// which half has a lane (where every lane has one).
  176. ///
  177. /// Part of the translation: the shader cache keys on it (`victory-gpu`'s
  178. /// does).
  179. pub fn shader_opt() -> u32 {
  180. static PASSES: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
  181. *PASSES.get_or_init(|| parse_shader_opt(std::env::var("VICTORY_SHADER_OPT").ok().as_deref()))
  182. }
  183. /// `VICTORY_SHADER_OPT`'s value; every pass when it is unset or
  184. /// unreadable. Pure, for testing.
  185. fn parse_shader_opt(value: Option<&str>) -> u32 {
  186. let parsed = value
  187. .map(str::trim)
  188. .and_then(|v| match v.strip_prefix("0x") {
  189. Some(hex) => u32::from_str_radix(hex, 16).ok(),
  190. None => v.parse().ok(),
  191. });
  192. parsed.map_or(bitcode::opt::ALL, |n| n & bitcode::opt::ALL)
  193. }
  194. /// `VICTORY_SHADER_LOOP_LIMIT`'s value; the default when it is unset,
  195. /// unreadable or 0. Pure, for testing.
  196. fn parse_loop_limit(value: Option<&str>) -> u32 {
  197. let parsed = value
  198. .map(str::trim)
  199. .and_then(|v| match v.strip_prefix("0x") {
  200. Some(hex) => u32::from_str_radix(hex, 16).ok(),
  201. None => v.parse().ok(),
  202. });
  203. match parsed {
  204. Some(n) if n > 0 => n,
  205. _ => lower::LOOP_LIMIT,
  206. }
  207. }
  208. /// A translated shader and what the host binds for it.
  209. #[derive(Debug, Clone, PartialEq, Eq)]
  210. pub struct HostShader {
  211. pub stage: HwStage,
  212. /// The DXIL container, hashed as D3D12 expects.
  213. pub dxil: Vec<u8>,
  214. /// The user-data dwords the shader reads.
  215. pub user_data: Vec<UserData>,
  216. /// Immediate samplers: the four sampler words of `s<n>`.
  217. pub samplers: Vec<[u32; 4]>,
  218. /// The same samplers decoded, `s<n>` at position n: the static sampler
  219. /// descriptions the host's root signature declares.
  220. pub static_samplers: Vec<StaticSampler>,
  221. /// Root CBVs the shader reads: root parameter indices, each bound as
  222. /// `b<index>` in [`ROOT_CBV_SPACE`].
  223. pub root_cbvs: Vec<u8>,
  224. /// Root SRVs (raw buffers) the shader reads: `t<index>` in
  225. /// [`ROOT_CBV_SPACE`].
  226. pub root_srvs: Vec<u8>,
  227. /// Root UAVs (raw buffers) the shader reads or writes: `u<index>` in
  228. /// [`ROOT_CBV_SPACE`].
  229. pub root_uavs: Vec<u8>,
  230. /// Heap descriptors that can be selected from root state at bind time.
  231. pub root_indexed_views: Vec<crate::resource::RootIndexedView>,
  232. }
  233. impl HostShader {
  234. /// Size of the user-data buffer the shader declares, in dwords (a
  235. /// multiple of 4; 0 when it reads none). Root constants must cover it.
  236. pub fn user_data_dwords(&self) -> u32 {
  237. let n = self
  238. .user_data
  239. .iter()
  240. .map(|u| u.index + 1)
  241. .max()
  242. .unwrap_or(0);
  243. n.next_multiple_of(4)
  244. }
  245. }
  246. /// One dword of user data and the root parameter that fills it.
  247. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  248. pub struct UserData {
  249. /// Dword in the user-data buffer (the console's user-data index).
  250. pub index: u32,
  251. /// Root parameter index in the title's root signature.
  252. pub slot: u8,
  253. /// `Constants` or `Table` (see the module notes for the value).
  254. pub root: RootType,
  255. /// Dword within the parameter.
  256. pub dword: u32,
  257. }
  258. /// Translates the vertex, pixel, compute or mesh program of a console
  259. /// shader container.
  260. pub fn translate(container: &[u8]) -> Result<HostShader, ShaderError> {
  261. let c = Container::parse(container)?;
  262. let dxil = c
  263. .part(FourCC::DXIL)
  264. .ok_or(ShaderError::Malformed("no DXIL part"))?;
  265. let native = crate::native_programs(dxil.data)?
  266. .into_iter()
  267. .find(|p| {
  268. matches!(
  269. p.stage,
  270. HwStage::Vs | HwStage::Ps | HwStage::Cs | HwStage::Ms
  271. )
  272. })
  273. .ok_or(ShaderError::Unsupported {
  274. offset: 0,
  275. what: "a container without a vertex, pixel, compute or mesh program",
  276. })?;
  277. let p = crate::spill::build(&native)?;
  278. // Structurisation first: tracing per-lane descriptors needs it (its
  279. // failure is reported after the earlier stages').
  280. let st = structure::structure(&p);
  281. let res = resource::track(&p, &native.layout, native.stage, st.as_ref().ok())?;
  282. let io = io::raise(&p, &native)?;
  283. let st = st?;
  284. emit(&c, &native, &p, &st, &io, &res)
  285. }
  286. /// Emits a program whose earlier stages already ran.
  287. pub fn emit(
  288. c: &Container,
  289. native: &NativeProgram,
  290. p: &ir::Program,
  291. st: &structure::Structured,
  292. io: &io::Io,
  293. res: &resource::Resources,
  294. ) -> Result<HostShader, ShaderError> {
  295. // (what an earlier program's lowering on this thread left behind)
  296. lower::take_needs();
  297. let original = emit_program(c, native, p, st, io, res);
  298. // A console wave64 compute program on a host of 32-lane waves that
  299. // still needs 64 lanes, or whose cross-lane code sits where not every
  300. // lane runs: once more with its early-outs left out
  301. // ([`ir::without_early_outs`]), which is what usually keeps the whole
  302. // body from being a block every lane runs.
  303. let stuck = match &original {
  304. Ok((_, wave)) => *wave == Some(64),
  305. Err(ShaderError::Unsupported { what, .. }) => lower::needs_every_lane(what),
  306. Err(_) => false,
  307. };
  308. // (a mask with lanes elsewhere is only helped by the exact forms: not by each half-wave
  309. // on its own)
  310. let exact_only = matches!(&original, Err(ShaderError::Unsupported { what, .. }) if *what == lower::MASK_ELSEWHERE);
  311. if stuck && native.stage == HwStage::Cs && native.wave64 && lower::host_max_wave() == 32 {
  312. let why = std::env::var_os("VICTORY_WAVE_WHY").is_some();
  313. let report = |what: &str, r: &Result<(HostShader, Option<u32>), ShaderError>| {
  314. if why {
  315. match r {
  316. Ok((_, wave)) => eprintln!("WAVE64-RETRY {what}: wave {wave:?}"),
  317. Err(e) => eprintln!("WAVE64-RETRY {what}: {e}"),
  318. }
  319. }
  320. };
  321. let done = |r: &Result<(HostShader, Option<u32>), ShaderError>| matches!(r, Ok((_, wave)) if *wave != Some(64));
  322. // Each host wave as a wave of its own (`lower::with_local_waves`),
  323. // for programs still stopped where not every lane runs.
  324. let local_on = std::env::var_os("VICTORY_WAVE_LOCAL").is_none_or(|v| v != "0");
  325. // Where the wave operations are the allocation idiom
  326. // ([`lower::wave_local`]) that is exact. Other programs are taken
  327. // the same way last of all, each half-wave giving its own results
  328. // (approximate: a tile-wide result becomes two half-tile ones);
  329. // `VICTORY_WAVE_LOCAL=idiom` refuses those instead.
  330. let strict = std::env::var_os("VICTORY_WAVE_LOCAL").is_some_and(|v| v == "idiom");
  331. let idiom = |p: &ir::Program, st: &structure::Structured| match lower::wave_local(p, st) {
  332. Ok(()) => true,
  333. Err((offset, what)) => {
  334. if why {
  335. eprintln!("WAVE64-RETRY local waves: not the allocation idiom at {offset:#x}: {what}");
  336. }
  337. false
  338. }
  339. };
  340. // The program in two other forms: without its early-outs, and
  341. // without any branch that only skips code no lane is left for.
  342. let form = |p: Option<ir::Program>| {
  343. p.and_then(|p| {
  344. let st = structure::structure(&p).ok()?;
  345. let io = io::raise(&p, native).ok()?;
  346. let res = resource::track(&p, &native.layout, native.stage, Some(&st)).ok()?;
  347. Some((p, st, io, res))
  348. })
  349. };
  350. let forms = [
  351. ("without early-outs", form(ir::without_early_outs(p))),
  352. ("without skips", form(ir::without_skips(p, false))),
  353. ];
  354. for (name, f) in &forms {
  355. if let Some((p, st, io, res)) = f {
  356. let again = emit_program(c, native, p, st, io, res);
  357. report(name, &again);
  358. if done(&again) {
  359. return again.map(|(shader, _)| shader);
  360. }
  361. }
  362. }
  363. // Off unless asked for (`VICTORY_WAVE_WIDE=1`), for a console wave run as two host
  364. // waves: this form puts group barriers inside branches and loops, and runs 121-124
  365. // lost the card in a submission of two programs that had just moved to it
  366. // (`ptfx_CS_lightAtlas_Sprite` and `_Trail`). The 32-lane programs' form below, which
  367. // has no barrier, stays on.
  368. let wide_on = std::env::var_os("VICTORY_WAVE_WIDE").is_some_and(|v| v == "1");
  369. // exact first: each host wave on its own where that is exact (the idiom, every
  370. // form; no barriers), then the other exact forms; then approximate
  371. for exact in [true, false] {
  372. if !exact {
  373. // Before anything approximate, the exact forms that cost group barriers.
  374. // Every skip left out that the code after it cannot see
  375. // ([`ir::without_skips`], `deep`): most of the body is then code every
  376. // lane runs, where the two host waves can exchange.
  377. // (`VICTORY_WAVE_DEEP_SKIPS=0` and `VICTORY_WAVE_WIDE=0` turn the two off.)
  378. let deep_on = std::env::var_os("VICTORY_WAVE_DEEP_SKIPS").is_none_or(|v| v != "0");
  379. let deep = if deep_on { form(ir::without_skips(p, true)) } else { None };
  380. if let Some((p, st, io, res)) = &deep {
  381. let again = emit_program(c, native, p, st, io, res);
  382. report("without skips, scalars followed", &again);
  383. if done(&again) {
  384. return again.map(|(shader, _)| shader);
  385. }
  386. }
  387. // Still stopped where not every lane runs: the per-lane branches around
  388. // those places taken as the console takes them, by the whole wave at once
  389. // ([`widen`]), at two group barriers per such branch.
  390. if wide_on {
  391. let bases = [
  392. deep.as_ref().map(|f| &f.0),
  393. forms[1].1.as_ref().map(|f| &f.0),
  394. forms[0].1.as_ref().map(|f| &f.0),
  395. Some(p),
  396. ];
  397. if let Some(base) = bases.into_iter().flatten().next() {
  398. let again = widen(c, native, base, why);
  399. report("wave-wide branches", &again);
  400. if done(&again) {
  401. return again.map(|(shader, _)| shader);
  402. }
  403. }
  404. }
  405. if strict {
  406. break;
  407. }
  408. }
  409. if !local_on || exact_only {
  410. continue;
  411. }
  412. for (name, f) in &forms {
  413. if let Some((p, st, io, res)) = f
  414. && idiom(p, st) == exact
  415. {
  416. let local = lower::with_local_waves(|| emit_program(c, native, p, st, io, res));
  417. report(&format!("local waves ({}), {name}", if exact { "idiom" } else { "APPROXIMATE" }), &local);
  418. if done(&local) {
  419. return local.map(|(shader, _)| shader);
  420. }
  421. }
  422. }
  423. if idiom(p, st) == exact {
  424. let local = lower::with_local_waves(|| emit_program(c, native, p, st, io, res));
  425. report(if exact { "local waves (idiom)" } else { "local waves (APPROXIMATE)" }, &local);
  426. if done(&local) {
  427. return local.map(|(shader, _)| shader);
  428. }
  429. }
  430. }
  431. if local_on && !exact_only {
  432. // Last: every mask and lane read per host wave.
  433. if !strict {
  434. for (name, f) in &forms {
  435. if let Some((p, st, io, res)) = f {
  436. let local = lower::with_local_waves_any(|| emit_program(c, native, p, st, io, res));
  437. report(&format!("local waves (APPROXIMATE, any mask), {name}"), &local);
  438. if done(&local) {
  439. return local.map(|(shader, _)| shader);
  440. }
  441. }
  442. }
  443. let local = lower::with_local_waves_any(|| emit_program(c, native, p, st, io, res));
  444. report("local waves (APPROXIMATE, any mask)", &local);
  445. if done(&local) {
  446. return local.map(|(shader, _)| shader);
  447. }
  448. }
  449. }
  450. }
  451. // SCC of a mask operation joined with a scalar test behind a per-lane skip (the 32-lane
  452. // trace programs): right once the wave takes that skip together ([`widen`]; the
  453. // lowering has named the skipped blocks).
  454. let original = match original {
  455. Err(ShaderError::Unsupported { what, .. })
  456. if native.stage == HwStage::Cs
  457. && what == lower::LANE_MASK
  458. && std::env::var_os("VICTORY_WAVE_WIDE").is_none_or(|v| v != "0") =>
  459. {
  460. let again = widen(c, native, p, std::env::var_os("VICTORY_WAVE_WHY").is_some());
  461. match again {
  462. Ok(_) => again,
  463. Err(_) => emit_program(c, native, p, st, io, res),
  464. }
  465. }
  466. other => other,
  467. };
  468. let original = original.map(|(shader, _)| shader);
  469. // Retry unsupported programs only. Threading can separate an unknown
  470. // register value from its apparent use on a mutually exclusive path.
  471. if !matches!(original, Err(ShaderError::Unsupported { .. })) {
  472. return original;
  473. }
  474. let edges = threading::constant_edges(p, st);
  475. if edges.is_empty() {
  476. return original;
  477. }
  478. let p = ir::thread_edges(p, &edges)?;
  479. let st = structure::structure(&p)?;
  480. let io = io::raise(&p, native)?;
  481. let res = resource::track(&p, &native.layout, native.stage, Some(&st))?;
  482. emit_program(c, native, &p, &st, &io, &res).map(|(shader, _)| shader)
  483. }
  484. /// `p` (a console wave64 compute program on a host of 32-lane waves) with the per-lane
  485. /// branches around its cross-lane code taken wave-wide ([`structure::structure_wide`]): the
  486. /// lowering names the blocks where the two host waves must meet and could not
  487. /// (`lower::take_needs`), the branches whose regions hold them are widened, and so on until
  488. /// it translates or a branch cannot be widened. Only where a thread group is one console
  489. /// wave: with several, the waves of a group would decide differently and a barrier inside
  490. /// such a branch would wait for threads that never come.
  491. fn widen(
  492. c: &Container,
  493. native: &NativeProgram,
  494. p: &ir::Program,
  495. why: bool,
  496. ) -> Result<(HostShader, Option<u32>), ShaderError> {
  497. const NOT: ShaderError = ShaderError::Unsupported {
  498. offset: 0,
  499. what: "wave-wide branches in a thread group of several console waves",
  500. };
  501. match native.io {
  502. // (a program whose waves are the host's meets no one: no barrier, any group)
  503. crate::native::StageIo::Cs(_) if !(native.wave64 && lower::host_max_wave() == 32) => {}
  504. crate::native::StageIo::Cs(cs) if cs.threads.iter().product::<u32>() == 64 => {}
  505. crate::native::StageIo::Cs(cs) => {
  506. if why {
  507. eprintln!("WAVE64-WIDE not tried: thread groups of {:?}", cs.threads);
  508. }
  509. return Err(NOT);
  510. }
  511. _ => return Err(NOT),
  512. }
  513. let mut wide = std::collections::HashSet::new();
  514. loop {
  515. let st = structure::structure_wide(p, &wide)?;
  516. let io = io::raise(p, native)?;
  517. let res = resource::track(p, &native.layout, native.stage, Some(&st))?;
  518. lower::take_needs();
  519. let r = emit_program(c, native, p, &st, &io, &res);
  520. let needs = lower::take_needs();
  521. // (or translated for 64-lane waves still: shared memory read and written where not
  522. // every lane runs, whose blocks the lowering names too)
  523. let stuck = matches!(&r, Err(ShaderError::Unsupported { what, .. })
  524. if lower::needs_every_lane(what) || *what == lower::LANE_MASK && !needs.is_empty())
  525. || matches!(&r, Ok((_, Some(64)))) && !needs.is_empty();
  526. if !stuck {
  527. if why {
  528. eprintln!("WAVE64-WIDE {} branches taken wave-wide", wide.len());
  529. }
  530. return r;
  531. }
  532. let more: Vec<usize> = lower::branches_around(&st, &needs)
  533. .unwrap_or_default()
  534. .into_iter()
  535. .filter(|b| !wide.contains(b))
  536. .collect();
  537. if more.is_empty() {
  538. if why {
  539. eprintln!("WAVE64-WIDE stopped with {} branches wave-wide: a branch around it cannot be", wide.len());
  540. }
  541. return r;
  542. }
  543. wide.extend(more);
  544. }
  545. }
  546. /// The translated program, and the wave size it requires of the host.
  547. fn emit_program(
  548. c: &Container,
  549. native: &NativeProgram,
  550. p: &ir::Program,
  551. st: &structure::Structured,
  552. io: &io::Io,
  553. res: &resource::Resources,
  554. ) -> Result<(HostShader, Option<u32>), ShaderError> {
  555. let sig = |fourcc| -> Result<Vec<container::SigElement>, ShaderError> {
  556. match c.part(fourcc) {
  557. Some(part) => signature(part.data),
  558. None => Ok(Vec::new()),
  559. }
  560. };
  561. let pixel = native.stage == HwStage::Ps;
  562. let mut inputs = sig(FourCC::ISG1)?;
  563. let mut outputs = sig(FourCC::OSG1)?;
  564. // Interpolation as DXC declares it by default; pixel inputs that are
  565. // read get the mode their barycentrics say.
  566. let interpolated = if pixel { &mut inputs } else { &mut outputs };
  567. for e in interpolated {
  568. e.interp = match (e.kind, e.comp) {
  569. (3, _) => 4,
  570. // Constant, as DXC declares it (the AMD compiler crashed on a
  571. // front face without a mode).
  572. (13, _) => 1,
  573. // Until a read says which mode (`lower`).
  574. (28, _) => 2,
  575. (0 | 6 | 7, 9) => 2,
  576. (0, _) => 1,
  577. _ => 0,
  578. };
  579. }
  580. // With a conservative depth output (SV_DepthLessEqual, GreaterEqual) DXIL
  581. // wants the position centroid (or per sample), as DXC declares it then.
  582. if pixel && outputs.iter().any(|e| matches!(e.kind, 18 | 19)) {
  583. for e in inputs.iter_mut().filter(|e| e.kind == 3) {
  584. e.interp = 5;
  585. }
  586. }
  587. // Per-primitive outputs are constant. The console never exports a
  588. // primitive id or cull flag a mesh shader writes (it culls with the
  589. // primitive export), so those rows are left out.
  590. let mut prims = sig(FourCC::PSG1)?;
  591. prims.retain(|e| !matches!(e.kind, 10 | 30));
  592. for e in &mut prims {
  593. e.interp = 1;
  594. }
  595. // A mesh group's id arrives multiplied by max(threads, vertices,
  596. // primitives) (the code divides by that); the thread count is in PSV0
  597. // from runtime info version 2 on.
  598. // shortcut: older containers fall back to the group's lane count, right
  599. // when the HLSL group fills its waves (the title's do).
  600. let mesh_stride = match &native.io {
  601. crate::native::StageIo::Ms(ms) => {
  602. let psv = c.part(FourCC::PSV0).map(|p| p.data);
  603. let threads = psv
  604. .filter(|d| crate::dxbc::u32_at(d, 0).is_ok_and(|n| n >= 48))
  605. .and_then(|d| crate::dxbc::u32_at(d, 4 + 36).ok());
  606. threads.map_or(ms.threads, |t| {
  607. t.max(ms.max_vertices).max(ms.max_primitives)
  608. })
  609. }
  610. _ => 0,
  611. };
  612. let l = lower::lower(&lower::Parts {
  613. native,
  614. p,
  615. st,
  616. io,
  617. res,
  618. inputs,
  619. outputs,
  620. prims,
  621. mesh_stride,
  622. })?;
  623. let wave_size = l.wave_size;
  624. let shader = HostShader {
  625. stage: native.stage,
  626. dxil: l.dxil,
  627. user_data: l.user_data,
  628. static_samplers: l
  629. .samplers
  630. .iter()
  631. .enumerate()
  632. .map(|(n, &w)| {
  633. let mut s = StaticSampler::from_words(w);
  634. if l.cmp_samplers >> n & 1 != 0 {
  635. s.filter |= 0x80;
  636. }
  637. s
  638. })
  639. .collect(),
  640. samplers: l.samplers,
  641. root_cbvs: l.root_cbvs,
  642. root_srvs: l.root_srvs,
  643. root_uavs: l.root_uavs,
  644. root_indexed_views: res.root_indexed_views.clone(),
  645. };
  646. Ok((shader, wave_size))
  647. }
  648. /// The rows of an `ISG1`/`OSG1` part.
  649. fn signature(part: &[u8]) -> Result<Vec<container::SigElement>, ShaderError> {
  650. use crate::dxbc::u32_at;
  651. let count = u32_at(part, 0)? as usize;
  652. let base = u32_at(part, 4)? as usize;
  653. let mut out = Vec::with_capacity(count);
  654. for i in 0..count {
  655. let at = base + 32 * i;
  656. let name_at = u32_at(part, at + 4)? as usize;
  657. let name = part
  658. .get(name_at..)
  659. .and_then(|s| s.split(|&b| b == 0).next())
  660. .ok_or(ShaderError::Malformed("signature name out of bounds"))?;
  661. let mask = *part
  662. .get(at + 24)
  663. .ok_or(ShaderError::Malformed("truncated"))?;
  664. if u32_at(part, at + 28)? != 0 {
  665. return Err(ShaderError::Unsupported {
  666. offset: 0,
  667. what: "a minimum-precision signature element",
  668. });
  669. }
  670. if u32_at(part, at)? != 0 {
  671. return Err(ShaderError::Unsupported {
  672. offset: 0,
  673. what: "a signature element of another stream",
  674. });
  675. }
  676. let kind = match u32_at(part, at + 12)? {
  677. 0 => 0,
  678. 1 => 3,
  679. 2 => 6,
  680. 3 => 7,
  681. 4 => 4,
  682. 5 => 5,
  683. 6 => 1,
  684. 7 => 10,
  685. 8 => 2,
  686. 9 => 13,
  687. 10 => 12,
  688. 64 => 16,
  689. 65 => 17,
  690. 66 => 14,
  691. 67 => 19,
  692. 68 => 18,
  693. 69 => 20,
  694. 70 => 15,
  695. 23 => 28, // barycentrics
  696. 25 => 30, // cull primitive
  697. _ => {
  698. return Err(ShaderError::Unsupported {
  699. offset: 0,
  700. what: "a system value in the signature",
  701. });
  702. }
  703. };
  704. // 16-bit elements are declared 32-bit; reading or writing one
  705. // converts (16-bit values travel packed on the console).
  706. let raw = u32_at(part, at + 16)?;
  707. let comp = match (kind, raw) {
  708. // DXIL declares the front face a uint (the validator insists).
  709. (13, _) => 5,
  710. (_, 1 | 4) => 5,
  711. (_, 2 | 5) => 4,
  712. (_, 3 | 6) => 9,
  713. (_, c) => {
  714. return Err(ShaderError::Unsupported {
  715. offset: 0,
  716. what: match c {
  717. 0 => "a signature element of unknown type",
  718. _ => "a 64-bit signature element",
  719. },
  720. });
  721. }
  722. };
  723. let register = u32_at(part, at + 20)?;
  724. out.push(container::SigElement {
  725. name: String::from_utf8_lossy(name).into_owned(),
  726. index: u32_at(part, at + 8)?,
  727. kind,
  728. comp,
  729. interp: 0,
  730. row: (register != u32::MAX).then_some(register),
  731. col: mask.trailing_zeros().min(3) as u8,
  732. cols: mask.count_ones().max(1) as u8,
  733. usage: 0,
  734. half: (4..=6).contains(&raw),
  735. });
  736. }
  737. Ok(out)
  738. }
  739. #[cfg(test)]
  740. mod tests {
  741. use super::bitcode::Attr;
  742. use super::lower::LOOP_LIMIT;
  743. use super::parse_loop_limit;
  744. #[test]
  745. fn the_clean_up_switch_parses_or_runs_every_pass() {
  746. let all = super::bitcode::opt::ALL;
  747. assert_eq!(parse_shader_opt(None), all);
  748. assert_eq!(parse_shader_opt(Some("0")), 0);
  749. assert_eq!(parse_shader_opt(Some(" 1 ")), 1);
  750. assert_eq!(parse_shader_opt(Some("0x1")), 1);
  751. assert_eq!(parse_shader_opt(Some("0xffffffff")), all);
  752. assert_eq!(parse_shader_opt(Some("on")), all);
  753. }
  754. #[test]
  755. fn the_loop_limit_switch_parses_or_falls_back() {
  756. assert_eq!(parse_loop_limit(None), LOOP_LIMIT);
  757. assert_eq!(parse_loop_limit(Some("4096")), 4096);
  758. assert_eq!(parse_loop_limit(Some(" 0x1000 ")), 4096);
  759. assert_eq!(parse_loop_limit(Some("1")), 1);
  760. for bad in ["", "0", "-5", "lots", "0x", "4294967296"] {
  761. assert_eq!(parse_loop_limit(Some(bad)), LOOP_LIMIT, "{bad:?}");
  762. }
  763. }
  764. use super::container::SigElement;
  765. use super::shader::Shader;
  766. use super::*;
  767. use crate::native::{ComputeIo, StageIo};
  768. /// A pixel shader writing SV_StencilRef (channel y of `exp mrtz`).
  769. /// DXC sets ShaderFlags.StencilRef (bit 11) for a pixel shader whose
  770. /// output signature has SV_StencilRef, and the feature bit
  771. /// D3D_SHADER_FEATURE_STENCIL_REF (0x200) in SFI0; the validator checks
  772. /// both against the module.
  773. #[test]
  774. fn a_stencil_export_declares_the_stencil_ref_feature() {
  775. let words = [
  776. 0x7E00_02F2u32, // v_mov_b32 v0, 1.0
  777. 0x7E02_0285, // v_mov_b32 v1, 5
  778. 0xF800_1883,
  779. 0x0000_0100, // exp mrtz v0, v1, off, off done vm
  780. 0xBF81_0000,
  781. ];
  782. let native = NativeProgram {
  783. stage: HwStage::Ps,
  784. wave64: false,
  785. vgprs: 2,
  786. layout: vec![],
  787. used: vec![],
  788. io: StageIo::Ps {
  789. inputs: vec![],
  790. input_addr: 0,
  791. db_shader_control: 0,
  792. patches: vec![],
  793. },
  794. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  795. };
  796. let el = |name: &str, kind, comp| SigElement {
  797. name: name.into(),
  798. index: 0,
  799. kind,
  800. comp,
  801. interp: 0,
  802. row: None,
  803. col: 0,
  804. cols: 1,
  805. usage: 1,
  806. half: false,
  807. };
  808. let osg1 =
  809. container::signature(&[el("SV_Depth", 17, 9), el("SV_StencilRef", 20, 5)], false);
  810. let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]);
  811. let c = Container::parse(&bytes).unwrap();
  812. let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap();
  813. let st = structure::structure(&p).unwrap();
  814. let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
  815. let io = io::raise(&p, &native).unwrap();
  816. let out = emit(&c, &native, &p, &st, &io, &res).unwrap();
  817. // dxil.dll, where there is one, checks the flags against the module.
  818. #[cfg(windows)]
  819. if let Ok(mut v) = super::validator::Validator::load(
  820. super::validator::Validator::default_path().as_deref(),
  821. ) {
  822. v.validate(&mut out.dxil.clone()).unwrap();
  823. }
  824. let host = Container::parse(&out.dxil).unwrap();
  825. let sfi0 = host.part(FourCC::SFI0).unwrap().data;
  826. let features = u64::from_le_bytes(sfi0.try_into().unwrap());
  827. assert_ne!(features & 0x200, 0, "SFI0 {features:#x}: no StencilRef");
  828. }
  829. /// A wave64 compute program that writes only EXEC's high dword
  830. /// (`s_mov_b32 exec_hi, 0`) before a vector instruction. The new mask was
  831. /// opaque and keyed by the unchanged low dword, so building its lane bit
  832. /// needed the mask's own value: lowering recursed until the stack
  833. /// overflowed, which takes the whole process down (found by
  834. /// random-input testing). Now that low dword, seen with two high
  835. /// dwords, has no mask, and the instruction fails like any other that
  836. /// cannot be expressed: its result is missing, and only a side effect
  837. /// that uses it would stop the translation.
  838. #[test]
  839. fn an_exec_high_write_does_not_overflow_the_stack() {
  840. // s_mov_b32 exec_hi, 0; v_mov_b32 v1, v0; s_endpgm
  841. let words = [0xBEFF_0380u32, 0x7E02_0300, 0xBF81_0000];
  842. let native = NativeProgram {
  843. stage: HwStage::Cs,
  844. wave64: true,
  845. vgprs: 2,
  846. layout: vec![],
  847. used: vec![],
  848. io: StageIo::Cs(ComputeIo {
  849. rsrc2: 0,
  850. threads: [64, 1, 1],
  851. }),
  852. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  853. };
  854. let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap();
  855. let st = structure::structure(&p).unwrap();
  856. let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
  857. let io = io::raise(&p, &native).unwrap();
  858. let container = crate::dxbc::build(&[]);
  859. let c = Container::parse(&container).unwrap();
  860. if let Err(e) = emit(&c, &native, &p, &st, &io, &res) {
  861. assert!(e.to_string().contains("its own value"), "{e}");
  862. }
  863. }
  864. /// A wave64 compute program: `body`, then a store of v1 to a UAV.
  865. fn stores_v1(body: &[u32]) -> Result<(), ShaderError> {
  866. use crate::native::RootParam;
  867. use crate::{ResourceType, RootType, UsedResource};
  868. // s_mov_b32 s1, 0; s_load_dwordx4 s[8:11], s[0:1], 0
  869. let mut words = vec![0xBE81_0380, 0xF408_0200, 0xFA00_0000];
  870. words.extend_from_slice(body);
  871. // v_lshlrev_b32 v3, 2, v0; buffer_store_dword v1, v3, s[8:11], 0 offen;
  872. // s_endpgm
  873. words.extend_from_slice(&[0x3406_0082, 0xE070_1000, 0x8002_0103, 0xBF81_0000]);
  874. let native = NativeProgram {
  875. stage: HwStage::Cs,
  876. wave64: true,
  877. vgprs: 4,
  878. layout: vec![RootParam {
  879. root: RootType::Table,
  880. table_offset_dwords: 0,
  881. sgprs: 1,
  882. base_register: 0,
  883. user_data: 0,
  884. slot: 0,
  885. }],
  886. used: vec![UsedResource {
  887. kind: ResourceType::Uav,
  888. root: RootType::Table,
  889. table_offset_dwords: 0,
  890. lower_bound: 0,
  891. stride: 0,
  892. dwords: 4,
  893. user_data: 0,
  894. slot: 0,
  895. }],
  896. io: StageIo::Cs(ComputeIo {
  897. rsrc2: 2,
  898. threads: [64, 1, 1],
  899. }),
  900. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  901. };
  902. let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap();
  903. let res = resource::track(&p, &native.layout, native.stage, None).unwrap();
  904. let io = io::raise(&p, &native).unwrap();
  905. let st = structure::structure(&p).unwrap();
  906. let container = crate::dxbc::build(&[]);
  907. let c = Container::parse(&container).unwrap();
  908. emit(&c, &native, &p, &st, &io, &res).map(|_| ())
  909. }
  910. /// The high dword of a wave64 mask rewritten alone (`s_mov_b32 vcc_hi`
  911. /// or `exec_hi`): lanes 32-63 took the mask the low dword was first
  912. /// written with (the compare's, EXEC's on entry). Now the store refuses;
  913. /// without the write it translates.
  914. #[test]
  915. fn a_mask_whose_high_dword_is_rewritten_is_refused() {
  916. // v_cmp_eq_u32 vcc, 0, v0; v_mov_b32 v2, 11; v_cndmask_b32 v1, 0, v2, vcc
  917. let select = [0x7D84_0080, 0x7E04_028B, 0x0202_0480];
  918. // The same with v_add_co_ci_u32 v1, vcc, 0, v2, vcc.
  919. let carry = [0x7D84_0080, 0x7E04_028B, 0x5002_0480];
  920. // v_mov_b32 v1, 7
  921. let mov = [0x7E02_0287];
  922. for body in [&select[..], &carry, &mov] {
  923. stores_v1(body).unwrap();
  924. }
  925. // s_mov_b32 vcc_hi, 0 after the compare.
  926. let select_hi = [0x7D84_0080, 0xBEEB_0380, 0x7E04_028B, 0x0202_0480];
  927. let carry_hi = [0x7D84_0080, 0xBEEB_0380, 0x7E04_028B, 0x5002_0480];
  928. // s_mov_b32 exec_hi, 0; v_mov_b32 v1, 7, then the same after
  929. // s_mov_b64 s[2:3], exec.
  930. let exec_hi = [0xBEFF_0380, 0x7E02_0287];
  931. let exec_hi_saved = [0xBE82_047E, 0xBEFF_0380, 0x7E02_0287];
  932. for body in [&select_hi[..], &carry_hi, &exec_hi, &exec_hi_saved] {
  933. assert!(stores_v1(body).is_err(), "{body:x?}");
  934. }
  935. }
  936. /// `ds_bpermute_b32` stores nothing: each lane reads the lane its address
  937. /// names. It stopped as "LDS the program does not allocate" (sticky lips)
  938. /// or "an LDS operation" (the checkerboard shadow masks).
  939. #[test]
  940. fn a_backward_permute_reads_the_lane_its_address_names() {
  941. // v_mov_b32 v2, 11; ds_bpermute_b32 v1, v0, v2
  942. stores_v1(&[0x7E04_028B, 0xDACC_0000, 0x0100_0200]).unwrap();
  943. }
  944. /// A carry-in reading a join of compares after a divergent branch. A
  945. /// lane that skipped the inner compare has VCC clear there (VOPC clears
  946. /// inactive lanes), not the first compare's bit, so the join is no
  947. /// per-lane phi: lowering refuses it.
  948. #[test]
  949. fn a_carry_in_from_a_divergent_join_is_refused() {
  950. let body = [
  951. 0x7E04_028B, // v_mov_b32 v2, 11
  952. 0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0
  953. 0xBE82_376A, // s_andn1_saveexec_b64 s[2:3], vcc
  954. 0xBF88_0001, // s_cbranch_execz 1
  955. 0x7D84_0081, // v_cmp_eq_u32 vcc, 1, v0
  956. 0x88FE_027E, // s_or_b64 exec, exec, s[2:3]
  957. 0x5002_0480, // v_add_co_ci_u32 v1, vcc, 0, v2, vcc
  958. ];
  959. let e = stores_v1(&body).unwrap_err().to_string();
  960. assert!(e.contains("a carry-in from an untracked mask"), "{e}");
  961. }
  962. /// A pixel shader writing a constant colour.
  963. #[cfg(windows)]
  964. fn constant_color() -> Vec<u8> {
  965. let mut s = Shader::new(true);
  966. s.outputs.push(SigElement {
  967. name: "SV_Target".into(),
  968. index: 0,
  969. kind: 16,
  970. comp: 9,
  971. interp: 0,
  972. row: Some(0),
  973. col: 0,
  974. cols: 4,
  975. usage: 15,
  976. half: false,
  977. });
  978. let b = s.entry;
  979. for (c, v) in [1.0f32, 0.5, 0.25, 1.0].into_iter().enumerate() {
  980. let args = [
  981. s.m.i32(0),
  982. s.m.i32(0),
  983. s.m.i8(c as u8),
  984. s.m.f32(v.to_bits()),
  985. ];
  986. s.op(b, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args);
  987. }
  988. s.m.terminate(b, super::bitcode::Term::Ret);
  989. s.finish()
  990. }
  991. #[test]
  992. #[cfg(windows)]
  993. fn stub_pipeline_is_created() {
  994. let Ok(host) = super::host::Host::new(false) else {
  995. eprintln!("no SM 6.6 device; skipped");
  996. return;
  997. };
  998. let ps = super::HostShader {
  999. stage: crate::HwStage::Ps,
  1000. dxil: constant_color(),
  1001. user_data: Vec::new(),
  1002. samplers: Vec::new(),
  1003. static_samplers: Vec::new(),
  1004. root_cbvs: Vec::new(),
  1005. root_srvs: Vec::new(),
  1006. root_uavs: Vec::new(),
  1007. root_indexed_views: Vec::new(),
  1008. };
  1009. let file = |var: &str, stage| {
  1010. std::env::var(var).ok().map(|p| super::HostShader {
  1011. stage,
  1012. dxil: std::fs::read(p).unwrap(),
  1013. user_data: Vec::new(),
  1014. samplers: Vec::new(),
  1015. static_samplers: Vec::new(),
  1016. root_cbvs: Vec::new(),
  1017. root_srvs: Vec::new(),
  1018. root_uavs: Vec::new(),
  1019. root_indexed_views: Vec::new(),
  1020. })
  1021. };
  1022. let ps = file("VICTORY_REF_PS", crate::HwStage::Ps).unwrap_or(ps);
  1023. let vs = file("VICTORY_REF_VS", crate::HwStage::Vs)
  1024. .unwrap_or_else(|| super::host::stub_vs(&ps).unwrap());
  1025. if let Ok(mut v) = super::validator::Validator::load(
  1026. super::validator::Validator::default_path().as_deref(),
  1027. ) {
  1028. v.validate(&mut vs.dxil.clone()).unwrap();
  1029. }
  1030. host.pipeline(&vs, &ps).unwrap();
  1031. // The runtime checks the container hash: no hash or a wrong one is
  1032. // refused. (Recent runtimes also take sixteen 0x01 bytes, a bypass
  1033. // value; ours works with older ones too.)
  1034. let mut wrong = ps.dxil[4..20].to_vec();
  1035. wrong[0] ^= 1;
  1036. for digest in [&[0u8; 16][..], &wrong] {
  1037. let mut other = ps.clone();
  1038. other.dxil[4..20].copy_from_slice(digest);
  1039. assert!(
  1040. host.pipeline(&vs, &other).is_err(),
  1041. "digest {digest:02x?} accepted"
  1042. );
  1043. }
  1044. }
  1045. #[test]
  1046. #[cfg(windows)]
  1047. fn constant_color_validates() {
  1048. let mut c = constant_color();
  1049. let path = super::validator::Validator::default_path();
  1050. let Ok(mut v) = super::validator::Validator::load(path.as_deref()) else {
  1051. eprintln!("no dxil.dll; skipped");
  1052. return;
  1053. };
  1054. let ours = c[4..20].to_vec();
  1055. v.validate(&mut c).unwrap();
  1056. assert_eq!(c[4..20], ours[..], "our hash differs from the validator's");
  1057. }
  1058. /// A pixel shader interpolating at sample positions (PERSP_SAMPLE
  1059. /// barycentrics, `SPI_PS_INPUT_ADDR` bit 0) runs at sample frequency:
  1060. /// DXC's PSV0 says so in PSInfo.SampleFrequency (runtime info byte 1)
  1061. /// whenever an input is interpolated per sample.
  1062. #[test]
  1063. fn sample_interpolated_inputs_set_psv_sample_frequency() {
  1064. let words = [
  1065. 0xC808_0000u32, // v_interp_p1_f32 v2, v0, attr0.x
  1066. 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
  1067. 0xF800_180F,
  1068. 0x0202_0202, // exp mrt0, v2, v2, v2, v2 done vm
  1069. 0xBF81_0000,
  1070. ];
  1071. let psv_of = |input_addr: u32| {
  1072. let native = super::NativeProgram {
  1073. stage: super::HwStage::Ps,
  1074. wave64: false,
  1075. vgprs: 4,
  1076. layout: vec![],
  1077. used: vec![],
  1078. io: crate::native::StageIo::Ps {
  1079. inputs: vec![crate::native::PsInput {
  1080. usage: crate::native::Usage::Generic,
  1081. row: 0,
  1082. mask: 0b1111,
  1083. attr: 0,
  1084. flat: false,
  1085. fp16: false,
  1086. pack2: false,
  1087. row2: 0,
  1088. }],
  1089. input_addr,
  1090. db_shader_control: 0,
  1091. patches: vec![],
  1092. },
  1093. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  1094. };
  1095. let el = |name: &str, kind, usage| SigElement {
  1096. name: name.into(),
  1097. index: 0,
  1098. kind,
  1099. comp: 9,
  1100. interp: 0,
  1101. row: Some(0),
  1102. col: 0,
  1103. cols: 4,
  1104. usage,
  1105. half: false,
  1106. };
  1107. let isg1 = super::container::signature(&[el("TEXCOORD", 0, 0)], true);
  1108. let osg1 = super::container::signature(&[el("SV_Target", 16, 15)], false);
  1109. let bytes =
  1110. crate::dxbc::build(&[(super::FourCC::ISG1, &isg1), (super::FourCC::OSG1, &osg1)]);
  1111. let c = super::Container::parse(&bytes).unwrap();
  1112. let p = crate::ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap();
  1113. let st = crate::structure::structure(&p).unwrap();
  1114. let res =
  1115. crate::resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
  1116. let io = crate::io::raise(&p, &native).unwrap();
  1117. let out = super::emit(&c, &native, &p, &st, &io, &res).unwrap();
  1118. // dxil.dll, where there is one, checks PSV0 against the module.
  1119. #[cfg(windows)]
  1120. if let Ok(mut v) = super::validator::Validator::load(
  1121. super::validator::Validator::default_path().as_deref(),
  1122. ) {
  1123. v.validate(&mut out.dxil.clone()).unwrap();
  1124. }
  1125. let host = super::Container::parse(&out.dxil).unwrap();
  1126. host.part(super::FourCC::PSV0).unwrap().data.to_vec()
  1127. };
  1128. // Runtime info starts after its size; PSInfo is {DepthOutput, SampleFrequency}.
  1129. let center = psv_of(1 << 1);
  1130. assert_eq!(center[4 + 1], 0, "center interpolation is per pixel");
  1131. let sample = psv_of(1 << 0);
  1132. assert_eq!(sample[4 + 1], 1, "PSInfo.SampleFrequency");
  1133. }
  1134. /// A pixel shader reading channel z of an input whose element starts at
  1135. /// w. Looking the channel up subtracted the element's first channel
  1136. /// before checking the channel lies in it, so in a build with overflow
  1137. /// checks (tests, debug) any read below an element that starts at z or
  1138. /// w panicked, whichever row it was in (found by random-input testing).
  1139. #[test]
  1140. fn reading_a_channel_below_an_input_element_does_not_underflow() {
  1141. // v_interp_mov_f32 v3, p0, attr0.z; s_endpgm
  1142. let words = [0xC80E_0202u32, 0xBF81_0000];
  1143. let native = super::NativeProgram {
  1144. stage: super::HwStage::Ps,
  1145. wave64: false,
  1146. vgprs: 4,
  1147. layout: vec![],
  1148. used: vec![],
  1149. io: crate::native::StageIo::Ps {
  1150. inputs: vec![crate::native::PsInput {
  1151. usage: crate::native::Usage::Generic,
  1152. row: 0,
  1153. mask: 0b1000,
  1154. attr: 0,
  1155. flat: false,
  1156. fp16: false,
  1157. pack2: false,
  1158. row2: 0,
  1159. }],
  1160. input_addr: 0,
  1161. db_shader_control: 0,
  1162. patches: vec![],
  1163. },
  1164. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  1165. };
  1166. let w_only = SigElement {
  1167. name: "TEXCOORD".into(),
  1168. index: 0,
  1169. kind: 0,
  1170. comp: 9,
  1171. interp: 0,
  1172. row: Some(0),
  1173. col: 3,
  1174. cols: 1,
  1175. usage: 0,
  1176. half: false,
  1177. };
  1178. let isg1 = super::container::signature(&[w_only], true);
  1179. let bytes = crate::dxbc::build(&[(super::FourCC::ISG1, &isg1)]);
  1180. let c = super::Container::parse(&bytes).unwrap();
  1181. let p = crate::ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap();
  1182. let st = crate::structure::structure(&p).unwrap();
  1183. let res = crate::resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
  1184. let io = crate::io::raise(&p, &native).unwrap();
  1185. // Translated or refused with a reason; it must not panic.
  1186. let _ = super::emit(&c, &native, &p, &st, &io, &res);
  1187. }
  1188. #[test]
  1189. fn valu_div_f32_sequence_executes_on_gpu() {
  1190. let words: &[u32] = &[
  1191. 0xBE85_0380, // s_mov_b32 s5, 0
  1192. 0xF408_0202,
  1193. 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0x0
  1194. 0xF408_0302,
  1195. 0xFA00_0020, // s_load_dwordx4 s[12:15], s[4:5], 0x20
  1196. 0x340E_0083, // v_lshlrev_b32 v7, 3, v0
  1197. 0xE034_1000,
  1198. 0x8002_0107, // buffer_load_dwordx2 v[1:2], v7, s[8:11], 0 offen
  1199. 0xD56D_6A03,
  1200. 0x0406_0502, // v_div_scale_f32 v3, vcc_lo, v2, v2, v1
  1201. 0xD56D_1008,
  1202. 0x0406_0501, // v_div_scale_f32 v8, s16, v1, v2, v1
  1203. 0x7E08_5503, // v_rcp_f32 v4, v3
  1204. 0xD54B_0005,
  1205. 0x23CA_0903, // v_fma_f32 v5, -v3, v4, 1.0
  1206. 0xD54B_0004,
  1207. 0x0412_0905, // v_fma_f32 v4, v5, v4, v4
  1208. 0x100A_0908, // v_mul_f32 v5, v8, v4
  1209. 0xD54B_0006,
  1210. 0x2422_0B03, // v_fma_f32 v6, -v3, v5, v8
  1211. 0xD56F_0004,
  1212. 0x0416_0906, // v_div_fmas_f32 v4, v6, v4, v5
  1213. 0xD55F_0001,
  1214. 0x0406_0504, // v_div_fixup_f32 v1, v4, v2, v1
  1215. 0x340E_0082, // v_lshlrev_b32 v7, 2, v0
  1216. 0xE070_1000,
  1217. 0x8003_0107, // buffer_store_dword v1, v7, s[12:15], 0 offen
  1218. 0xBF81_0000, // s_endpgm
  1219. ];
  1220. let native = super::NativeProgram {
  1221. stage: super::HwStage::Cs,
  1222. wave64: false,
  1223. vgprs: 9,
  1224. layout: vec![
  1225. crate::RootParam {
  1226. root: crate::RootType::Constants,
  1227. table_offset_dwords: 0,
  1228. sgprs: 4,
  1229. base_register: 0,
  1230. user_data: 0,
  1231. slot: 0,
  1232. },
  1233. crate::RootParam {
  1234. root: crate::RootType::Table,
  1235. table_offset_dwords: 0,
  1236. sgprs: 1,
  1237. base_register: 0,
  1238. user_data: 4,
  1239. slot: 1,
  1240. },
  1241. ],
  1242. used: vec![
  1243. crate::UsedResource {
  1244. kind: crate::ResourceType::Srv,
  1245. root: crate::RootType::Table,
  1246. table_offset_dwords: 0,
  1247. lower_bound: 0,
  1248. stride: 4,
  1249. dwords: 4,
  1250. user_data: 4,
  1251. slot: 1,
  1252. },
  1253. crate::UsedResource {
  1254. kind: crate::ResourceType::Uav,
  1255. root: crate::RootType::Table,
  1256. table_offset_dwords: 8,
  1257. lower_bound: 0,
  1258. stride: 4,
  1259. dwords: 4,
  1260. user_data: 4,
  1261. slot: 1,
  1262. },
  1263. ],
  1264. io: crate::native::StageIo::Cs(crate::native::ComputeIo {
  1265. rsrc2: 5 << 1,
  1266. threads: [7, 1, 1],
  1267. }),
  1268. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  1269. };
  1270. let p = crate::ir::build(&native.code, native.wave64, native.vgprs).unwrap();
  1271. let res = crate::resource::track(&p, &native.layout, native.stage, None).unwrap();
  1272. let io = crate::io::raise(&p, &native).unwrap();
  1273. let st = crate::structure::structure(&p).unwrap();
  1274. let l = super::lower::lower(&super::lower::Parts {
  1275. native: &native,
  1276. p: &p,
  1277. st: &st,
  1278. io: &io,
  1279. res: &res,
  1280. inputs: Vec::new(),
  1281. outputs: Vec::new(),
  1282. prims: Vec::new(),
  1283. mesh_stride: 0,
  1284. })
  1285. .unwrap();
  1286. let mut dxil = l.dxil;
  1287. #[cfg(windows)]
  1288. if let Ok(mut v) = super::validator::Validator::load(
  1289. super::validator::Validator::default_path().as_deref(),
  1290. ) {
  1291. v.validate(&mut dxil).unwrap();
  1292. }
  1293. #[cfg(windows)]
  1294. if let Ok(host) = super::host::Host::new(false) {
  1295. let cs = super::HostShader {
  1296. stage: super::HwStage::Cs,
  1297. dxil,
  1298. user_data: l.user_data,
  1299. samplers: Vec::new(),
  1300. static_samplers: Vec::new(),
  1301. root_cbvs: l.root_cbvs,
  1302. root_srvs: l.root_srvs,
  1303. root_uavs: l.root_uavs,
  1304. root_indexed_views: Vec::new(),
  1305. };
  1306. let (root, pso) = host.compute_pipeline(&cs).unwrap();
  1307. let inputs: Vec<u32> = [
  1308. 7.0f32, 3.0, -1.0, 1e-40, 1.0, 1e35, 1e-35, 1e-36, 0.0, 0.0, -1.0, 0.0, -1e35, 1e35,
  1309. ]
  1310. .into_iter()
  1311. .map(f32::to_bits)
  1312. .collect();
  1313. let out = host
  1314. .dispatch(
  1315. &root,
  1316. &pso,
  1317. &super::host::Dispatch {
  1318. roots: vec![(0, super::host::Root::Constants(vec![0, 0, 0, 0, 0]))],
  1319. views: &[
  1320. super::host::View::Buffer {
  1321. data: &inputs,
  1322. stride: super::host::Stride::Raw,
  1323. },
  1324. super::host::View::RawUav(64),
  1325. ],
  1326. samplers: &[],
  1327. groups: [1, 1, 1],
  1328. },
  1329. )
  1330. .unwrap();
  1331. let got: Vec<f32> = out[0][..7].iter().copied().map(f32::from_bits).collect();
  1332. assert!((got[0] - (7.0f32 / 3.0)).abs() < 1e-6, "got {:?}", got);
  1333. assert_eq!(out[0][1], (-1.0f32 / 1e-40).to_bits());
  1334. assert!(
  1335. (got[2] - 1e-35).abs() <= 1e-40,
  1336. "lane 2 got {:?} ({:#x})",
  1337. got[2],
  1338. out[0][2]
  1339. );
  1340. assert!(
  1341. (got[3] - 10.0).abs() < 1e-5,
  1342. "lane 3 got {:?} ({:#x})",
  1343. got[3],
  1344. out[0][3]
  1345. );
  1346. assert_eq!(out[0][4], 0xFFC0_0000);
  1347. assert_eq!(out[0][5], (-1.0f32 / 0.0).to_bits());
  1348. assert!(
  1349. (got[6] - (-1.0)).abs() < 1e-6,
  1350. "lane 6 got {:?} ({:#x})",
  1351. got[6],
  1352. out[0][6]
  1353. );
  1354. }
  1355. }
  1356. }
  1357. #[cfg(test)]
  1358. mod atomic_tests {
  1359. use super::*;
  1360. use crate::native::{ComputeIo, RootParam, StageIo};
  1361. #[test]
  1362. fn heap_texture_atomic_widths() {
  1363. // A synthetic compute shader loads a 2D UAV from a root table,
  1364. // compares or adds at (0, 0), then uses the returned register(s).
  1365. for (opcode, mask, wide) in [
  1366. (16u32, 3, false),
  1367. (16, 15, true),
  1368. (17, 1, false),
  1369. (17, 3, true),
  1370. ] {
  1371. let words = [
  1372. 0xBE81_0380, // s_mov_b32 s1, 0 (table address high)
  1373. 0xF40C_0200,
  1374. 0xFA00_0000, // s_load_dwordx8 s[8:15], s[0:1], 0
  1375. 0x7E00_0280,
  1376. 0x7E02_0280, // v0, v1 = coordinates
  1377. 0x7E04_0281,
  1378. 0x7E06_0282,
  1379. 0x7E08_0283,
  1380. 0x7E0A_0284, // v2..v5 = 1..4
  1381. 0xF000_2008 | opcode << 18 | mask << 8,
  1382. 0x0002_0200,
  1383. // Use the old value in a second atomic at the same location.
  1384. 0xF044_0008 | (if wide { 3 } else { 1 }) << 8,
  1385. 0x0002_0200,
  1386. 0xBF81_0000,
  1387. ];
  1388. let native = NativeProgram {
  1389. stage: HwStage::Cs,
  1390. wave64: false,
  1391. vgprs: 6,
  1392. layout: vec![RootParam {
  1393. root: RootType::Table,
  1394. table_offset_dwords: 0,
  1395. sgprs: 1,
  1396. base_register: 0,
  1397. user_data: 0,
  1398. slot: 0,
  1399. }],
  1400. used: vec![],
  1401. io: StageIo::Cs(ComputeIo {
  1402. rsrc2: 2,
  1403. threads: [32, 1, 1],
  1404. }),
  1405. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  1406. };
  1407. let p = ir::build(&native.code, false, native.vgprs).unwrap();
  1408. let bytes = crate::dxbc::build(&[]);
  1409. let shader = emit(
  1410. &Container::parse(&bytes).unwrap(),
  1411. &native,
  1412. &p,
  1413. &structure::structure(&p).unwrap(),
  1414. &io::raise(&p, &native).unwrap(),
  1415. &resource::track(&p, &native.layout, native.stage, None).unwrap(),
  1416. )
  1417. .unwrap();
  1418. let container = Container::parse(&shader.dxil).unwrap();
  1419. let features = u64::from_le_bytes(
  1420. container
  1421. .part(FourCC::SFI0)
  1422. .unwrap()
  1423. .data
  1424. .try_into()
  1425. .unwrap(),
  1426. );
  1427. let required = 0x1040_8000; // heap atomics, typed atomics, Int64Ops
  1428. assert_eq!(features & required, if wide { required } else { 0 });
  1429. #[cfg(windows)]
  1430. if let Ok(mut v) =
  1431. validator::Validator::load(validator::Validator::default_path().as_deref())
  1432. {
  1433. v.validate(&mut shader.dxil.clone()).unwrap();
  1434. }
  1435. }
  1436. }
  1437. }
  1438. #[cfg(test)]
  1439. mod barycentric_tests {
  1440. use super::container::SigElement;
  1441. use super::*;
  1442. use crate::native::{PsInput, StageIo, Usage};
  1443. /// `SPI_PS_INPUT_ADDR` bits: PERSP_CENTER, LINEAR_CENTER.
  1444. const PERSP_CENTER: u32 = 1 << 1;
  1445. const LINEAR_CENTER: u32 = 1 << 5;
  1446. /// `exp mrt0, v<r>, v<r>, v<r>, v<r> done vm`.
  1447. fn exp_mrt0(r: u32) -> [u32; 2] {
  1448. [0xF800_180F, r * 0x0101_0101]
  1449. }
  1450. /// VOP2 `v_add_f32 v<dst>, v<a>, v<b>`.
  1451. fn v_add_f32(dst: u32, a: u32, b: u32) -> u32 {
  1452. 3 << 25 | dst << 17 | b << 9 | (256 + a)
  1453. }
  1454. fn element(name: &str, kind: u8, row: u32) -> SigElement {
  1455. SigElement {
  1456. name: name.into(),
  1457. index: 0,
  1458. kind,
  1459. comp: 9,
  1460. interp: 0,
  1461. row: Some(row),
  1462. col: 0,
  1463. cols: 4,
  1464. usage: 0,
  1465. half: false,
  1466. }
  1467. }
  1468. /// Translates a pixel program with the input VGPRs `input_addr`
  1469. /// enables and one float4 TEXCOORD0 attribute (attr 0, row 0).
  1470. fn pixel(words: &[u32], input_addr: u32) -> Result<HostShader, ShaderError> {
  1471. let native = NativeProgram {
  1472. stage: HwStage::Ps,
  1473. wave64: false,
  1474. vgprs: 8,
  1475. layout: vec![],
  1476. used: vec![],
  1477. io: StageIo::Ps {
  1478. inputs: vec![PsInput {
  1479. usage: Usage::Generic,
  1480. row: 0,
  1481. mask: 0b1111,
  1482. attr: 0,
  1483. flat: false,
  1484. fp16: false,
  1485. pack2: false,
  1486. row2: 0,
  1487. }],
  1488. input_addr,
  1489. db_shader_control: 0,
  1490. patches: vec![],
  1491. },
  1492. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  1493. };
  1494. let mut target = element("SV_Target", 16, 0);
  1495. target.usage = 15;
  1496. let isg1 = container::signature(&[element("TEXCOORD", 0, 0)], true);
  1497. let osg1 = container::signature(&[target], false);
  1498. let bytes = crate::dxbc::build(&[(FourCC::ISG1, &isg1), (FourCC::OSG1, &osg1)]);
  1499. let c = Container::parse(&bytes).unwrap();
  1500. let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?;
  1501. let res = resource::track(&p, &native.layout, native.stage, None)?;
  1502. let io = io::raise(&p, &native)?;
  1503. let st = structure::structure(&p)?;
  1504. emit(&c, &native, &p, &st, &io, &res)
  1505. }
  1506. /// The translation's `SFI0` features and `ISG1` rows.
  1507. fn parts(shader: &HostShader) -> (u64, Vec<SigElement>) {
  1508. let c = Container::parse(&shader.dxil).unwrap();
  1509. let sfi0 = c.part(FourCC::SFI0).unwrap().data.try_into().unwrap();
  1510. (
  1511. u64::from_le_bytes(sfi0),
  1512. signature(c.part(FourCC::ISG1).unwrap().data).unwrap(),
  1513. )
  1514. }
  1515. fn validate(shader: &HostShader) {
  1516. #[cfg(windows)]
  1517. if let Ok(mut v) =
  1518. validator::Validator::load(validator::Validator::default_path().as_deref())
  1519. {
  1520. v.validate(&mut shader.dxil.clone()).unwrap();
  1521. }
  1522. let _ = shader;
  1523. }
  1524. /// Custom interpolation reads I and J (v0, v1 with PERSP_CENTER) as
  1525. /// plain floats: they are channels y and z of `SV_Barycentrics`, the
  1526. /// weights of vertices 1 and 2.
  1527. #[test]
  1528. fn barycentrics_read_as_values_are_sv_barycentrics() {
  1529. let [e0, e1] = exp_mrt0(2);
  1530. let words = [v_add_f32(2, 0, 1), e0, e1, 0xBF81_0000];
  1531. let shader = pixel(&words, PERSP_CENTER).unwrap();
  1532. let (features, inputs) = parts(&shader);
  1533. assert_ne!(features & 0x2_0000, 0, "no Barycentrics feature");
  1534. let bary: Vec<_> = inputs.iter().filter(|e| e.kind == 28).collect();
  1535. assert_eq!(bary.len(), 1, "{inputs:?}");
  1536. assert_eq!((bary[0].index, bary[0].col, bary[0].cols), (0, 0, 3));
  1537. // Not packed: the validator wants packing location -1.
  1538. assert_eq!(bary[0].row, None);
  1539. // Only y and z (I and J) are read.
  1540. let isg1 = Container::parse(&shader.dxil).unwrap();
  1541. let isg1 = isg1.part(FourCC::ISG1).unwrap().data;
  1542. let rw: Vec<u8> = (0..2).map(|k| isg1[8 + 32 * k + 25]).collect();
  1543. assert!(rw.contains(&0b110), "{rw:?}");
  1544. validate(&shader);
  1545. }
  1546. /// Two kinds of barycentrics read directly: one element per mode.
  1547. #[test]
  1548. fn two_barycentric_modes_get_two_elements() {
  1549. // v0-v1 perspective i, j; v2-v3 linear i, j.
  1550. let [e0, e1] = exp_mrt0(4);
  1551. let words = [v_add_f32(4, 0, 3), e0, e1, 0xBF81_0000];
  1552. let shader = pixel(&words, PERSP_CENTER | LINEAR_CENTER).unwrap();
  1553. let (_, inputs) = parts(&shader);
  1554. let mut indices: Vec<u32> = inputs
  1555. .iter()
  1556. .filter(|e| e.kind == 28)
  1557. .map(|e| e.index)
  1558. .collect();
  1559. indices.sort();
  1560. assert_eq!(indices, [0, 1], "{inputs:?}");
  1561. validate(&shader);
  1562. }
  1563. /// I and J only fed to `v_interp_*` stay host interpolation: no
  1564. /// barycentrics are declared.
  1565. #[test]
  1566. fn interpolation_alone_declares_no_barycentrics() {
  1567. let [e0, e1] = exp_mrt0(2);
  1568. let words = [
  1569. 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x
  1570. 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
  1571. e0,
  1572. e1,
  1573. 0xBF81_0000,
  1574. ];
  1575. let shader = pixel(&words, PERSP_CENTER).unwrap();
  1576. let (features, inputs) = parts(&shader);
  1577. assert_eq!(features & 0x2_0000, 0);
  1578. assert!(inputs.iter().all(|e| e.kind != 28), "{inputs:?}");
  1579. validate(&shader);
  1580. }
  1581. /// Both: the attribute is interpolated and J is used as a value.
  1582. #[test]
  1583. fn interpolation_and_a_barycentric_value_together() {
  1584. let [e0, e1] = exp_mrt0(3);
  1585. let words = [
  1586. 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x
  1587. 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
  1588. v_add_f32(3, 2, 1), // v3 = attribute + j
  1589. e0,
  1590. e1,
  1591. 0xBF81_0000,
  1592. ];
  1593. let shader = pixel(&words, PERSP_CENTER).unwrap();
  1594. let (features, inputs) = parts(&shader);
  1595. assert_ne!(features & 0x2_0000, 0);
  1596. assert_eq!(inputs.iter().filter(|e| e.kind == 28).count(), 1);
  1597. validate(&shader);
  1598. }
  1599. /// The `PSV0` interpolation mode of TEXCOORD0 (row 0, x-w, float).
  1600. fn texcoord_mode(shader: &HostShader) -> u8 {
  1601. let c = Container::parse(&shader.dxil).unwrap();
  1602. let psv = c.part(FourCC::PSV0).unwrap().data;
  1603. let row = [1, 0, 0x44, 0, 3];
  1604. let at = psv.windows(5).position(|w| w == row).unwrap();
  1605. psv[at + 5]
  1606. }
  1607. const S_ENDPGM: u32 = 0xBF81_0000;
  1608. /// An interpolation whose i is computed (`v_mul_f32 v3, 0.5, v0`) reads
  1609. /// the attribute's vertices: TEXCOORD0 becomes constant, read with
  1610. /// `attributeAtVertex`; i and j are `SV_Barycentrics` values.
  1611. #[test]
  1612. fn computed_barycentrics_read_the_vertices() {
  1613. let [e0, e1] = exp_mrt0(2);
  1614. let words = [
  1615. 0x1006_00F0, // v_mul_f32 v3, 0.5, v0
  1616. 0xC808_0003, // v_interp_p1_f32 v2, v3, attr0.x
  1617. 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
  1618. e0,
  1619. e1,
  1620. S_ENDPGM,
  1621. ];
  1622. let shader = pixel(&words, PERSP_CENTER).unwrap();
  1623. let (features, inputs) = parts(&shader);
  1624. assert_ne!(features & 0x2_0000, 0, "no Barycentrics feature");
  1625. assert_eq!(inputs.iter().filter(|e| e.kind == 28).count(), 1);
  1626. assert_eq!(texcoord_mode(&shader), 1);
  1627. validate(&shader);
  1628. }
  1629. /// Weights from constants alone: the vertices, no `SV_Barycentrics`.
  1630. #[test]
  1631. fn constant_weights_need_no_barycentrics() {
  1632. let [e0, e1] = exp_mrt0(2);
  1633. let words = [
  1634. 0x7E06_02F0, // v_mov_b32 v3, 0.5
  1635. 0xC808_0003, // v_interp_p1_f32 v2, v3, attr0.x
  1636. 0xC809_0003, // v_interp_p2_f32 v2, v3, attr0.x
  1637. e0,
  1638. e1,
  1639. S_ENDPGM,
  1640. ];
  1641. let shader = pixel(&words, PERSP_CENTER).unwrap();
  1642. let (features, inputs) = parts(&shader);
  1643. assert_ne!(features & 0x2_0000, 0, "no Barycentrics feature");
  1644. assert!(inputs.iter().all(|e| e.kind != 28), "{inputs:?}");
  1645. assert_eq!(texcoord_mode(&shader), 1);
  1646. validate(&shader);
  1647. }
  1648. /// The same attribute interpolated with the loaded i and j and with a
  1649. /// computed j: both from its vertices, the first weighed with
  1650. /// `SV_Barycentrics`.
  1651. #[test]
  1652. fn computed_and_loaded_barycentrics_on_one_attribute() {
  1653. let [e0, e1] = exp_mrt0(2);
  1654. let words = [
  1655. 0xC810_0100, // v_interp_p1_f32 v4, v0, attr0.y
  1656. 0xC811_0101, // v_interp_p2_f32 v4, v1, attr0.y
  1657. 0x1006_02F0, // v_mul_f32 v3, 0.5, v1
  1658. 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x
  1659. 0xC809_0003, // v_interp_p2_f32 v2, v3, attr0.x
  1660. v_add_f32(2, 2, 4),
  1661. e0,
  1662. e1,
  1663. S_ENDPGM,
  1664. ];
  1665. let shader = pixel(&words, PERSP_CENTER).unwrap();
  1666. let (_, inputs) = parts(&shader);
  1667. assert_eq!(inputs.iter().filter(|e| e.kind == 28).count(), 1);
  1668. assert_eq!(texcoord_mode(&shader), 1);
  1669. validate(&shader);
  1670. }
  1671. /// P10 of an attribute the program interpolates is P1 - P0.
  1672. #[test]
  1673. fn p10_of_an_interpolated_attribute() {
  1674. let [e0, e1] = exp_mrt0(2);
  1675. let words = [
  1676. 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x
  1677. 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
  1678. 0xC812_0000, // v_interp_mov_f32 v4, p10, attr0.x
  1679. v_add_f32(2, 2, 4),
  1680. e0,
  1681. e1,
  1682. S_ENDPGM,
  1683. ];
  1684. let shader = pixel(&words, PERSP_CENTER).unwrap();
  1685. assert_eq!(texcoord_mode(&shader), 1);
  1686. validate(&shader);
  1687. // Alone, what the hardware holds is not known.
  1688. let [e0, e1] = exp_mrt0(4);
  1689. let words = [0xC812_0000, e0, e1, S_ENDPGM];
  1690. assert!(pixel(&words, PERSP_CENTER).is_err());
  1691. }
  1692. }