mod.rs 110 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738
  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. #[cfg(all(test, windows))]
  93. mod permlane_tests;
  94. mod rect;
  95. mod sampler;
  96. mod shader;
  97. mod threading;
  98. #[cfg(windows)]
  99. pub mod validator;
  100. #[cfg(all(test, windows))]
  101. mod size_tests;
  102. #[cfg(all(test, windows))]
  103. mod valu_tests;
  104. #[cfg(all(test, windows))]
  105. mod waterfall_tests;
  106. #[cfg(all(test, windows))]
  107. mod wave64_tests;
  108. mod wave;
  109. use crate::dxbc::{Container, FourCC};
  110. use crate::native::{HwStage, NativeProgram, RootType};
  111. use crate::{ShaderError, io, ir, resource, structure};
  112. pub use bitcode::census;
  113. pub use sampler::StaticSampler;
  114. pub use lower::{host_settings, set_host_max_wave};
  115. pub use rect::rect_list_gs;
  116. pub use shader::{
  117. MEMORY_FAULTS, MEMORY_PAGES, MEMORY_READ_ONLY, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES,
  118. SLOT_STRIDES_COUNT, USER_DATA_SPACE, USER_DISPATCH_THREADS_X, USER_MEMORY_BASE, USER_ROOT_ADDRESS, USER_VIEW_ADDRESS, USER_VIEW_BIAS,
  119. raw_views, set_raw_views, set_view_heap_limit, view_heap_limit,
  120. };
  121. /// The loop limit without an override: 2^20.
  122. pub const DEFAULT_LOOP_LIMIT: u32 = lower::LOOP_LIMIT;
  123. /// The iteration count after which a translated loop is left, per lane and
  124. /// per entry into the loop: [`DEFAULT_LOOP_LIMIT`].
  125. ///
  126. /// With the `diagnostics` feature, `VICTORY_SHADER_LOOP_LIMIT` (decimal or
  127. /// `0x` hex, at least 1) sets it instead. A loop that hits the limit in
  128. /// every lane of a full-screen pass still runs for seconds (2^20 times a
  129. /// 4K screen is about 10^13 iterations); a much lower limit shows whether
  130. /// such loops are what makes a frame slow. The value is part of the
  131. /// translation, so the shader cache must key on it (`victory-gpu`'s does).
  132. pub fn loop_limit() -> u32 {
  133. static LIMIT: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
  134. *LIMIT.get_or_init(|| {
  135. if cfg!(feature = "diagnostics") {
  136. parse_loop_limit(std::env::var("VICTORY_SHADER_LOOP_LIMIT").ok().as_deref())
  137. } else {
  138. lower::LOOP_LIMIT
  139. }
  140. })
  141. }
  142. /// Whether a pixel shader's helper lane reads its own value where the console reads the first
  143. /// lane's (`lower.rs` `first_lane`); on unless `VICTORY_HELPER_OWN=0`. Part of the translation:
  144. /// the shader cache keys on it.
  145. pub fn helper_own() -> bool {
  146. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  147. *ON.get_or_init(|| std::env::var_os("VICTORY_HELPER_OWN").is_none_or(|v| v != "0"))
  148. }
  149. /// Which of a translated program's group barriers wait for the whole
  150. /// group (`GroupMemoryBarrierWithGroupSync`); the others keep their memory
  151. /// fence and lose the wait. A wait that some thread of the group never
  152. /// reaches is undefined on the host, and NVIDIA's wait is for every
  153. /// thread: the group stands until Windows resets the card. (The console's
  154. /// barrier is the wave's, whatever lanes are live, and a wave that ended
  155. /// is not waited for.) `VICTORY_GROUP_SYNC`:
  156. /// - unset or `2`: every barrier waits, as before.
  157. /// - `1`: the title's `s_barrier` waits only in a block every lane runs,
  158. /// in a program no lane can be cut out of at the iteration limit.
  159. /// - `0`: no barrier waits, neither the title's nor the ones the
  160. /// translation adds (wave64 programs in two host waves exchange through
  161. /// them, so such programs compute wrong values). For one run that tells
  162. /// whether a barrier is what stops the card: with it no run can stand in
  163. /// a barrier.
  164. ///
  165. /// Part of the translation: the shader cache keys on it (`victory-gpu`'s
  166. /// does).
  167. pub fn group_sync() -> u8 {
  168. static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
  169. *MODE.get_or_init(|| match std::env::var("VICTORY_GROUP_SYNC").ok().as_deref().map(str::trim) {
  170. Some("0") => 0,
  171. Some("1") => 1,
  172. _ => 2,
  173. })
  174. }
  175. /// Whether buffer atomics of the ray-tracing structure builder stand between
  176. /// two fences (`VICTORY_BVH_FENCES=0`: they do not). Part of the
  177. /// translation: the shader cache keys on it.
  178. pub fn builder_fences() -> bool {
  179. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  180. *ON.get_or_init(|| std::env::var_os("VICTORY_BVH_FENCES").is_none_or(|v| v != "0"))
  181. }
  182. /// The clean-up passes that run over a translated program before it is
  183. /// written (`bitcode::opt`): a set of that module's pass bits. Every pass
  184. /// is exact, so the switch is for telling a translator fault from a
  185. /// clean-up fault, and for measuring what the clean-up is worth.
  186. /// `VICTORY_SHADER_OPT`:
  187. /// - unset: every pass.
  188. /// - `0`: none (the module as the lowering made it).
  189. /// - a number (decimal or `0x` hex): those passes; 1 dead code, 2 constants
  190. /// and identities, 4 one instruction for one value, 8 what a branch taken
  191. /// says about its condition, 16 one read for one place within a block,
  192. /// 32 a first-lane read of two host waves without the round that asks
  193. /// which half has a lane (where every lane has one).
  194. ///
  195. /// Part of the translation: the shader cache keys on it (`victory-gpu`'s
  196. /// does).
  197. pub fn shader_opt() -> u32 {
  198. static PASSES: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
  199. *PASSES.get_or_init(|| parse_shader_opt(std::env::var("VICTORY_SHADER_OPT").ok().as_deref()))
  200. }
  201. /// Everything a translation depends on besides the container: the
  202. /// translator's own source (hashed at build time), the value of every
  203. /// `VICTORY_*` switch it reads, the host facts the device hands it (widest
  204. /// wave, view heap limit) and the settings above. The shader cache keys on
  205. /// this instead of on the whole executable, so a rebuild that leaves the
  206. /// translator alone keeps its translations. Call it after the device is made.
  207. pub fn translation_fingerprint() -> Vec<u8> {
  208. let mut out = Vec::new();
  209. out.extend_from_slice(env!("VICTORY_SHADER_SOURCE_HASH").as_bytes());
  210. out.push(u8::from(cfg!(feature = "diagnostics")));
  211. out.push(u8::from(cfg!(debug_assertions)));
  212. for name in env!("VICTORY_SHADER_SWITCHES").split(',').filter(|n| !n.is_empty()) {
  213. out.extend_from_slice(name.as_bytes());
  214. out.push(b'=');
  215. if let Some(value) = std::env::var_os(name) {
  216. out.extend_from_slice(value.as_encoded_bytes());
  217. }
  218. out.push(0);
  219. }
  220. out.extend_from_slice(&lower::host_max_wave().to_le_bytes());
  221. out.extend_from_slice(&shader::view_heap_limit().to_le_bytes());
  222. out.extend_from_slice(&shader::raw_views().to_le_bytes());
  223. out.extend_from_slice(&loop_limit().to_le_bytes());
  224. out.push(group_sync());
  225. out.extend_from_slice(&shader_opt().to_le_bytes());
  226. out
  227. }
  228. /// `VICTORY_SHADER_OPT`'s value; every pass when it is unset or
  229. /// unreadable. Pure, for testing.
  230. fn parse_shader_opt(value: Option<&str>) -> u32 {
  231. let parsed = value
  232. .map(str::trim)
  233. .and_then(|v| match v.strip_prefix("0x") {
  234. Some(hex) => u32::from_str_radix(hex, 16).ok(),
  235. None => v.parse().ok(),
  236. });
  237. parsed.map_or(bitcode::opt::ALL, |n| n & bitcode::opt::ALL)
  238. }
  239. /// `VICTORY_SHADER_LOOP_LIMIT`'s value; the default when it is unset,
  240. /// unreadable or 0. Pure, for testing.
  241. fn parse_loop_limit(value: Option<&str>) -> u32 {
  242. let parsed = value
  243. .map(str::trim)
  244. .and_then(|v| match v.strip_prefix("0x") {
  245. Some(hex) => u32::from_str_radix(hex, 16).ok(),
  246. None => v.parse().ok(),
  247. });
  248. match parsed {
  249. Some(n) if n > 0 => n,
  250. _ => lower::LOOP_LIMIT,
  251. }
  252. }
  253. /// A translated shader and what the host binds for it.
  254. #[derive(Debug, Clone, PartialEq, Eq)]
  255. pub struct HostShader {
  256. pub stage: HwStage,
  257. /// The DXIL container, hashed as D3D12 expects.
  258. pub dxil: Vec<u8>,
  259. /// The user-data dwords the shader reads.
  260. pub user_data: Vec<UserData>,
  261. /// Immediate samplers: the four sampler words of `s<n>`.
  262. pub samplers: Vec<[u32; 4]>,
  263. /// The same samplers decoded, `s<n>` at position n: the static sampler
  264. /// descriptions the host's root signature declares.
  265. pub static_samplers: Vec<StaticSampler>,
  266. /// Root CBVs the shader reads: root parameter indices, each bound as
  267. /// `b<index>` in [`ROOT_CBV_SPACE`].
  268. pub root_cbvs: Vec<u8>,
  269. /// Root SRVs (raw buffers) the shader reads: `t<index>` in
  270. /// [`ROOT_CBV_SPACE`].
  271. pub root_srvs: Vec<u8>,
  272. /// Root UAVs (raw buffers) the shader reads or writes: `u<index>` in
  273. /// [`ROOT_CBV_SPACE`].
  274. pub root_uavs: Vec<u8>,
  275. /// Heap descriptors that can be selected from root state at bind time.
  276. pub root_indexed_views: Vec<crate::resource::RootIndexedView>,
  277. }
  278. impl HostShader {
  279. /// Size of the user-data buffer the shader declares, in dwords (a
  280. /// multiple of 4; 0 when it reads none). Root constants must cover it.
  281. pub fn user_data_dwords(&self) -> u32 {
  282. let n = self
  283. .user_data
  284. .iter()
  285. .map(|u| u.index + 1)
  286. .max()
  287. .unwrap_or(0);
  288. n.next_multiple_of(4)
  289. }
  290. }
  291. /// One dword of user data and the root parameter that fills it.
  292. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  293. pub struct UserData {
  294. /// Dword in the user-data buffer (the console's user-data index).
  295. pub index: u32,
  296. /// Root parameter index in the title's root signature.
  297. pub slot: u8,
  298. /// `Constants` or `Table` (see the module notes for the value).
  299. pub root: RootType,
  300. /// Dword within the parameter.
  301. pub dword: u32,
  302. }
  303. /// Translates the vertex, pixel, compute or mesh program of a console
  304. /// shader container.
  305. ///
  306. /// A program refused because the first half of an interpolation is read as
  307. /// data is translated once more with first halves evaluated as the pair
  308. /// they start (`lower::with_first_half_pairs`), and only such a program:
  309. /// with that on for every program, 8,551 pixel programs of the title that
  310. /// already translated came out changed (an extra evaluation in each), for
  311. /// the sake of 9 that did not translate.
  312. pub fn translate(container: &[u8]) -> Result<HostShader, ShaderError> {
  313. match translate_plain(container) {
  314. Err(ShaderError::Unsupported { what, .. }) if what == lower::FIRST_HALF => {
  315. lower::with_first_half_pairs(|| translate_plain(container))
  316. }
  317. other => other,
  318. }
  319. }
  320. fn translate_plain(container: &[u8]) -> Result<HostShader, ShaderError> {
  321. let c = Container::parse(container)?;
  322. let dxil = c
  323. .part(FourCC::DXIL)
  324. .or(c.part(FourCC::ACCC))
  325. .ok_or(ShaderError::Malformed("no DXIL part"))?;
  326. let native = crate::native_programs(dxil.data)?
  327. .into_iter()
  328. .find(|p| {
  329. matches!(
  330. p.stage,
  331. HwStage::Vs | HwStage::Ps | HwStage::Cs | HwStage::Ms
  332. )
  333. })
  334. .ok_or(ShaderError::Unsupported {
  335. offset: 0,
  336. what: "a container without a vertex, pixel, compute or mesh program",
  337. })?;
  338. let p = crate::spill::build(&native)?;
  339. // Structurisation first: tracing per-lane descriptors needs it (its
  340. // failure is reported after the earlier stages').
  341. let st = structure::structure(&p);
  342. let res = resource::track(&p, &native.layout, native.stage, st.as_ref().ok())?;
  343. let io = io::raise(&p, &native)?;
  344. let st = st?;
  345. emit(&c, &native, &p, &st, &io, &res)
  346. }
  347. /// Emits a program whose earlier stages already ran.
  348. pub fn emit(
  349. c: &Container,
  350. native: &NativeProgram,
  351. p: &ir::Program,
  352. st: &structure::Structured,
  353. io: &io::Io,
  354. res: &resource::Resources,
  355. ) -> Result<HostShader, ShaderError> {
  356. // (what an earlier program's lowering on this thread left behind)
  357. lower::take_needs();
  358. let original = emit_program(c, native, p, st, io, res);
  359. // A console wave64 compute program on a host of 32-lane waves that
  360. // still needs 64 lanes, or whose cross-lane code sits where not every
  361. // lane runs: once more with its early-outs left out
  362. // ([`ir::without_early_outs`]), which is what usually keeps the whole
  363. // body from being a block every lane runs.
  364. let stuck = match &original {
  365. Ok((_, wave)) => *wave == Some(64),
  366. Err(ShaderError::Unsupported { what, .. }) => lower::needs_every_lane(what),
  367. Err(_) => false,
  368. };
  369. // (a mask with lanes elsewhere is only helped by the exact forms: not by each half-wave
  370. // on its own)
  371. let exact_only = matches!(&original, Err(ShaderError::Unsupported { what, .. }) if *what == lower::MASK_ELSEWHERE);
  372. if stuck && native.stage == HwStage::Cs && native.wave64 && lower::host_max_wave() == 32 {
  373. let why = std::env::var_os("VICTORY_WAVE_WHY").is_some();
  374. let report = |what: &str, r: &Result<(HostShader, Option<u32>), ShaderError>| {
  375. if why {
  376. match r {
  377. Ok((_, wave)) => eprintln!("WAVE64-RETRY {what}: wave {wave:?}"),
  378. Err(e) => eprintln!("WAVE64-RETRY {what}: {e}"),
  379. }
  380. }
  381. };
  382. let done = |r: &Result<(HostShader, Option<u32>), ShaderError>| matches!(r, Ok((_, wave)) if *wave != Some(64));
  383. // Each host wave as a wave of its own (`lower::with_local_waves`),
  384. // for programs still stopped where not every lane runs.
  385. let local_on = std::env::var_os("VICTORY_WAVE_LOCAL").is_none_or(|v| v != "0");
  386. // Where the wave operations are the allocation idiom
  387. // ([`lower::wave_local`]) that is exact. Other programs are taken
  388. // the same way last of all, each half-wave giving its own results
  389. // (approximate: a tile-wide result becomes two half-tile ones);
  390. // `VICTORY_WAVE_LOCAL=idiom` refuses those instead.
  391. let strict = std::env::var_os("VICTORY_WAVE_LOCAL").is_some_and(|v| v == "idiom");
  392. let idiom = |p: &ir::Program, st: &structure::Structured| match lower::wave_local(p, st) {
  393. Ok(()) => true,
  394. Err((offset, what)) => {
  395. if why {
  396. eprintln!("WAVE64-RETRY local waves: not the allocation idiom at {offset:#x}: {what}");
  397. }
  398. false
  399. }
  400. };
  401. // The program in two other forms: without its early-outs, and
  402. // without any branch that only skips code no lane is left for.
  403. let form = |p: Option<ir::Program>| {
  404. p.and_then(|p| {
  405. let st = structure::structure(&p).ok()?;
  406. let io = io::raise(&p, native).ok()?;
  407. let res = resource::track(&p, &native.layout, native.stage, Some(&st)).ok()?;
  408. Some((p, st, io, res))
  409. })
  410. };
  411. let forms = [
  412. ("without early-outs", form(ir::without_early_outs(p))),
  413. ("without skips", form(ir::without_skips(p, false))),
  414. ];
  415. for (name, f) in &forms {
  416. if let Some((p, st, io, res)) = f {
  417. let again = emit_program(c, native, p, st, io, res);
  418. report(name, &again);
  419. if done(&again) {
  420. return again.map(|(shader, _)| shader);
  421. }
  422. }
  423. }
  424. // Off unless asked for (`VICTORY_WAVE_WIDE=1`), for a console wave run as two host
  425. // waves: this form puts group barriers inside branches and loops, and runs 121-124
  426. // lost the card in a submission of two programs that had just moved to it
  427. // (`ptfx_CS_lightAtlas_Sprite` and `_Trail`). The 32-lane programs' form below, which
  428. // has no barrier, stays on.
  429. let wide_on = std::env::var_os("VICTORY_WAVE_WIDE").is_some_and(|v| v == "1");
  430. // exact first: each host wave on its own where that is exact (the idiom, every
  431. // form; no barriers), then the other exact forms; then approximate
  432. for exact in [true, false] {
  433. if !exact {
  434. // Before anything approximate, the exact forms that cost group barriers.
  435. // Every skip left out that the code after it cannot see
  436. // ([`ir::without_skips`], `deep`): most of the body is then code every
  437. // lane runs, where the two host waves can exchange.
  438. // (`VICTORY_WAVE_DEEP_SKIPS=0` and `VICTORY_WAVE_WIDE=0` turn the two off.)
  439. let deep_on = std::env::var_os("VICTORY_WAVE_DEEP_SKIPS").is_none_or(|v| v != "0");
  440. let deep = if deep_on { form(ir::without_skips(p, true)) } else { None };
  441. if let Some((p, st, io, res)) = &deep {
  442. let again = emit_program(c, native, p, st, io, res);
  443. report("without skips, scalars followed", &again);
  444. if done(&again) {
  445. return again.map(|(shader, _)| shader);
  446. }
  447. }
  448. // Still stopped where not every lane runs: the per-lane branches around
  449. // those places taken as the console takes them, by the whole wave at once
  450. // ([`widen`]), at two group barriers per such branch.
  451. if wide_on {
  452. let bases = [
  453. deep.as_ref().map(|f| &f.0),
  454. forms[1].1.as_ref().map(|f| &f.0),
  455. forms[0].1.as_ref().map(|f| &f.0),
  456. Some(p),
  457. ];
  458. if let Some(base) = bases.into_iter().flatten().next() {
  459. let again = widen(c, native, base, why);
  460. report("wave-wide branches", &again);
  461. if done(&again) {
  462. return again.map(|(shader, _)| shader);
  463. }
  464. }
  465. }
  466. if strict {
  467. break;
  468. }
  469. }
  470. if !local_on || exact_only {
  471. continue;
  472. }
  473. for (name, f) in &forms {
  474. if let Some((p, st, io, res)) = f
  475. && idiom(p, st) == exact
  476. {
  477. let local = lower::with_local_waves(|| emit_program(c, native, p, st, io, res));
  478. report(&format!("local waves ({}), {name}", if exact { "idiom" } else { "APPROXIMATE" }), &local);
  479. if done(&local) {
  480. return local.map(|(shader, _)| shader);
  481. }
  482. }
  483. }
  484. if idiom(p, st) == exact {
  485. let local = lower::with_local_waves(|| emit_program(c, native, p, st, io, res));
  486. report(if exact { "local waves (idiom)" } else { "local waves (APPROXIMATE)" }, &local);
  487. if done(&local) {
  488. return local.map(|(shader, _)| shader);
  489. }
  490. }
  491. }
  492. if local_on && !exact_only {
  493. // Last: every mask and lane read per host wave.
  494. if !strict {
  495. for (name, f) in &forms {
  496. if let Some((p, st, io, res)) = f {
  497. let local = lower::with_local_waves_any(|| emit_program(c, native, p, st, io, res));
  498. report(&format!("local waves (APPROXIMATE, any mask), {name}"), &local);
  499. if done(&local) {
  500. return local.map(|(shader, _)| shader);
  501. }
  502. }
  503. }
  504. let local = lower::with_local_waves_any(|| emit_program(c, native, p, st, io, res));
  505. report("local waves (APPROXIMATE, any mask)", &local);
  506. if done(&local) {
  507. return local.map(|(shader, _)| shader);
  508. }
  509. }
  510. }
  511. }
  512. // SCC of a mask operation joined with a scalar test behind a per-lane skip (the 32-lane
  513. // trace programs): right once the wave takes that skip together ([`widen`]; the
  514. // lowering has named the skipped blocks).
  515. let original = match original {
  516. Err(ShaderError::Unsupported { what, .. })
  517. if native.stage == HwStage::Cs
  518. && what == lower::LANE_MASK
  519. && std::env::var_os("VICTORY_WAVE_WIDE").is_none_or(|v| v != "0") =>
  520. {
  521. let again = widen(c, native, p, std::env::var_os("VICTORY_WAVE_WHY").is_some());
  522. match again {
  523. Ok(_) => again,
  524. Err(_) => emit_program(c, native, p, st, io, res),
  525. }
  526. }
  527. other => other,
  528. };
  529. let original = original.map(|(shader, _)| shader);
  530. // Retry unsupported programs only. Threading can separate an unknown
  531. // register value from its apparent use on a mutually exclusive path.
  532. if !matches!(original, Err(ShaderError::Unsupported { .. })) {
  533. return original;
  534. }
  535. let edges = threading::constant_edges(p, st);
  536. if edges.is_empty() {
  537. return original;
  538. }
  539. let p = ir::thread_edges(p, &edges)?;
  540. let st = structure::structure(&p)?;
  541. let io = io::raise(&p, native)?;
  542. let res = resource::track(&p, &native.layout, native.stage, Some(&st))?;
  543. emit_program(c, native, &p, &st, &io, &res).map(|(shader, _)| shader)
  544. }
  545. /// `p` (a console wave64 compute program on a host of 32-lane waves) with the per-lane
  546. /// branches around its cross-lane code taken wave-wide ([`structure::structure_wide`]): the
  547. /// lowering names the blocks where the two host waves must meet and could not
  548. /// (`lower::take_needs`), the branches whose regions hold them are widened, and so on until
  549. /// it translates or a branch cannot be widened. Only where a thread group is one console
  550. /// wave: with several, the waves of a group would decide differently and a barrier inside
  551. /// such a branch would wait for threads that never come.
  552. fn widen(
  553. c: &Container,
  554. native: &NativeProgram,
  555. p: &ir::Program,
  556. why: bool,
  557. ) -> Result<(HostShader, Option<u32>), ShaderError> {
  558. const NOT: ShaderError = ShaderError::Unsupported {
  559. offset: 0,
  560. what: "wave-wide branches in a thread group of several console waves",
  561. };
  562. match native.io {
  563. // (a program whose waves are the host's meets no one: no barrier, any group)
  564. crate::native::StageIo::Cs(_) if !(native.wave64 && lower::host_max_wave() == 32) => {}
  565. crate::native::StageIo::Cs(cs) if cs.threads.iter().product::<u32>() == 64 => {}
  566. crate::native::StageIo::Cs(cs) => {
  567. if why {
  568. eprintln!("WAVE64-WIDE not tried: thread groups of {:?}", cs.threads);
  569. }
  570. return Err(NOT);
  571. }
  572. _ => return Err(NOT),
  573. }
  574. let mut wide = std::collections::HashSet::new();
  575. loop {
  576. let st = structure::structure_wide(p, &wide)?;
  577. let io = io::raise(p, native)?;
  578. let res = resource::track(p, &native.layout, native.stage, Some(&st))?;
  579. lower::take_needs();
  580. let r = emit_program(c, native, p, &st, &io, &res);
  581. let needs = lower::take_needs();
  582. // (or translated for 64-lane waves still: shared memory read and written where not
  583. // every lane runs, whose blocks the lowering names too)
  584. let stuck = matches!(&r, Err(ShaderError::Unsupported { what, .. })
  585. if lower::needs_every_lane(what) || *what == lower::LANE_MASK && !needs.is_empty())
  586. || matches!(&r, Ok((_, Some(64)))) && !needs.is_empty();
  587. if !stuck {
  588. if why {
  589. eprintln!("WAVE64-WIDE {} branches taken wave-wide", wide.len());
  590. }
  591. return r;
  592. }
  593. let more: Vec<usize> = lower::branches_around(&st, &needs)
  594. .unwrap_or_default()
  595. .into_iter()
  596. .filter(|b| !wide.contains(b))
  597. .collect();
  598. if more.is_empty() {
  599. if why {
  600. eprintln!("WAVE64-WIDE stopped with {} branches wave-wide: a branch around it cannot be", wide.len());
  601. }
  602. return r;
  603. }
  604. wide.extend(more);
  605. }
  606. }
  607. /// The translated program, and the wave size it requires of the host.
  608. fn emit_program(
  609. c: &Container,
  610. native: &NativeProgram,
  611. p: &ir::Program,
  612. st: &structure::Structured,
  613. io: &io::Io,
  614. res: &resource::Resources,
  615. ) -> Result<(HostShader, Option<u32>), ShaderError> {
  616. let sig = |fourcc| -> Result<Vec<container::SigElement>, ShaderError> {
  617. match c.part(fourcc) {
  618. Some(part) => signature(part.data),
  619. None => Ok(Vec::new()),
  620. }
  621. };
  622. let pixel = native.stage == HwStage::Ps;
  623. let mut inputs = sig(FourCC::ISG1)?;
  624. let mut outputs = sig(FourCC::OSG1)?;
  625. // Interpolation as DXC declares it by default; pixel inputs that are
  626. // read get the mode their barycentrics say.
  627. let interpolated = if pixel { &mut inputs } else { &mut outputs };
  628. for e in interpolated {
  629. e.interp = match (e.kind, e.comp) {
  630. (3, _) => 4,
  631. // Constant, as DXC declares it (the AMD compiler crashed on a
  632. // front face without a mode).
  633. (13, _) => 1,
  634. // Until a read says which mode (`lower`).
  635. (28, _) => 2,
  636. (0 | 6 | 7, 9) => 2,
  637. (0, _) => 1,
  638. _ => 0,
  639. };
  640. }
  641. // (DexNom/VIctory 5f4c3df4.)
  642. if native.stage == HwStage::Vs
  643. && let Some(psv) = c.part(FourCC::PSV0)
  644. {
  645. vertex_output_interpolation(psv.data, &mut outputs)?;
  646. }
  647. // With a conservative depth output (SV_DepthLessEqual, GreaterEqual) DXIL
  648. // wants the position centroid (or per sample), as DXC declares it then.
  649. if pixel && outputs.iter().any(|e| matches!(e.kind, 18 | 19)) {
  650. for e in inputs.iter_mut().filter(|e| e.kind == 3) {
  651. e.interp = 5;
  652. }
  653. }
  654. // Per-primitive outputs are constant. The console never exports a
  655. // primitive id or cull flag a mesh shader writes (it culls with the
  656. // primitive export), so those rows are left out.
  657. let mut prims = sig(FourCC::PSG1)?;
  658. prims.retain(|e| !matches!(e.kind, 10 | 30));
  659. for e in &mut prims {
  660. e.interp = 1;
  661. }
  662. // A mesh group's id arrives multiplied by max(threads, vertices,
  663. // primitives) (the code divides by that); the thread count is in PSV0
  664. // from runtime info version 2 on.
  665. // shortcut: older containers fall back to the group's lane count, right
  666. // when the HLSL group fills its waves (the title's do).
  667. let mesh_stride = match &native.io {
  668. crate::native::StageIo::Ms(ms) => {
  669. let psv = c.part(FourCC::PSV0).map(|p| p.data);
  670. let threads = psv
  671. .filter(|d| crate::dxbc::u32_at(d, 0).is_ok_and(|n| n >= 48))
  672. .and_then(|d| crate::dxbc::u32_at(d, 4 + 36).ok());
  673. threads.map_or(ms.threads, |t| {
  674. t.max(ms.max_vertices).max(ms.max_primitives)
  675. })
  676. }
  677. _ => 0,
  678. };
  679. let l = lower::lower(&lower::Parts {
  680. native,
  681. p,
  682. st,
  683. io,
  684. res,
  685. inputs,
  686. outputs,
  687. prims,
  688. mesh_stride,
  689. })?;
  690. let wave_size = l.wave_size;
  691. let shader = HostShader {
  692. stage: native.stage,
  693. dxil: l.dxil,
  694. user_data: l.user_data,
  695. static_samplers: l
  696. .samplers
  697. .iter()
  698. .enumerate()
  699. .map(|(n, &w)| {
  700. let mut s = StaticSampler::from_words(w);
  701. if l.cmp_samplers >> n & 1 != 0 {
  702. s.filter |= 0x80;
  703. }
  704. s
  705. })
  706. .collect(),
  707. samplers: l.samplers,
  708. root_cbvs: l.root_cbvs,
  709. root_srvs: l.root_srvs,
  710. root_uavs: l.root_uavs,
  711. root_indexed_views: res.root_indexed_views.clone(),
  712. };
  713. Ok((shader, wave_size))
  714. }
  715. /// The title's vertex output interpolation lives in PSV0. A float packed
  716. /// beside an integer can be explicitly constant, as can a float on its own.
  717. /// OSG1 supplies the physical rows and columns used to match both tables.
  718. fn vertex_output_interpolation(
  719. mut data: &[u8],
  720. outputs: &mut [container::SigElement],
  721. ) -> Result<(), ShaderError> {
  722. const TRUNCATED: ShaderError =
  723. ShaderError::Malformed("truncated vertex pipeline validation data");
  724. fn take<'a>(data: &mut &'a [u8], len: usize) -> Result<&'a [u8], ShaderError> {
  725. let (head, tail) = data.split_at_checked(len).ok_or(TRUNCATED)?;
  726. *data = tail;
  727. Ok(head)
  728. }
  729. fn size(data: &mut &[u8]) -> Result<usize, ShaderError> {
  730. Ok(u32::from_le_bytes(take(data, 4)?.try_into().unwrap()) as usize)
  731. }
  732. let info_size = size(&mut data)?;
  733. let info = take(&mut data, info_size)?;
  734. // PSVRuntimeInfo0 has no signature. PSVRuntimeInfo1 and later share
  735. // these stage and signature count fields.
  736. if info.len() < 36 || info[24] != 1 || info[29] == 0 {
  737. return Ok(());
  738. }
  739. let resources = size(&mut data)?;
  740. if resources != 0 {
  741. let stride = size(&mut data)?;
  742. take(&mut data, resources.checked_mul(stride).ok_or(TRUNCATED)?)?;
  743. }
  744. let strings = size(&mut data)?;
  745. take(&mut data, strings)?;
  746. let indices = size(&mut data)?;
  747. take(&mut data, indices.checked_mul(4).ok_or(TRUNCATED)?)?;
  748. let stride = size(&mut data)?;
  749. if stride < 16 {
  750. return Err(TRUNCATED);
  751. }
  752. let count = usize::from(info[28]) + usize::from(info[29]);
  753. let elements = take(&mut data, count.checked_mul(stride).ok_or(TRUNCATED)?)?;
  754. for record in elements.chunks_exact(stride).skip(usize::from(info[28])) {
  755. let packed = record[10];
  756. if packed & 0x40 == 0 {
  757. continue;
  758. }
  759. if record[13] > 7 {
  760. return Err(ShaderError::Malformed("invalid vertex output interpolation"));
  761. }
  762. let first = u32::from(record[9]);
  763. let rows = first..first + u32::from(record[8]);
  764. for output in outputs.iter_mut().filter(|e| {
  765. e.row.is_some_and(|r| rows.contains(&r))
  766. && e.col == ((packed >> 4) & 3)
  767. && e.cols == (packed & 15)
  768. && e.kind == record[11]
  769. }) {
  770. output.interp = record[13];
  771. }
  772. }
  773. Ok(())
  774. }
  775. /// The rows of an `ISG1`/`OSG1` part.
  776. fn signature(part: &[u8]) -> Result<Vec<container::SigElement>, ShaderError> {
  777. use crate::dxbc::u32_at;
  778. let count = u32_at(part, 0)? as usize;
  779. let base = u32_at(part, 4)? as usize;
  780. let mut out = Vec::with_capacity(count);
  781. for i in 0..count {
  782. let at = base + 32 * i;
  783. let name_at = u32_at(part, at + 4)? as usize;
  784. let name = part
  785. .get(name_at..)
  786. .and_then(|s| s.split(|&b| b == 0).next())
  787. .ok_or(ShaderError::Malformed("signature name out of bounds"))?;
  788. let mask = *part
  789. .get(at + 24)
  790. .ok_or(ShaderError::Malformed("truncated"))?;
  791. if u32_at(part, at + 28)? != 0 {
  792. return Err(ShaderError::Unsupported {
  793. offset: 0,
  794. what: "a minimum-precision signature element",
  795. });
  796. }
  797. if u32_at(part, at)? != 0 {
  798. return Err(ShaderError::Unsupported {
  799. offset: 0,
  800. what: "a signature element of another stream",
  801. });
  802. }
  803. let kind = match u32_at(part, at + 12)? {
  804. 0 => 0,
  805. 1 => 3,
  806. 2 => 6,
  807. 3 => 7,
  808. 4 => 4,
  809. 5 => 5,
  810. 6 => 1,
  811. 7 => 10,
  812. 8 => 2,
  813. 9 => 13,
  814. 10 => 12,
  815. 64 => 16,
  816. 65 => 17,
  817. 66 => 14,
  818. 67 => 19,
  819. 68 => 18,
  820. 69 => 20,
  821. 70 => 15,
  822. 23 => 28, // barycentrics
  823. 25 => 30, // cull primitive
  824. _ => {
  825. return Err(ShaderError::Unsupported {
  826. offset: 0,
  827. what: "a system value in the signature",
  828. });
  829. }
  830. };
  831. // 16-bit elements are declared 32-bit; reading or writing one
  832. // converts (16-bit values travel packed on the console).
  833. let raw = u32_at(part, at + 16)?;
  834. let comp = match (kind, raw) {
  835. // DXIL declares the front face a uint (the validator insists).
  836. (13, _) => 5,
  837. (_, 1 | 4) => 5,
  838. (_, 2 | 5) => 4,
  839. (_, 3 | 6) => 9,
  840. (_, c) => {
  841. return Err(ShaderError::Unsupported {
  842. offset: 0,
  843. what: match c {
  844. 0 => "a signature element of unknown type",
  845. _ => "a 64-bit signature element",
  846. },
  847. });
  848. }
  849. };
  850. let register = u32_at(part, at + 20)?;
  851. out.push(container::SigElement {
  852. name: String::from_utf8_lossy(name).into_owned(),
  853. index: u32_at(part, at + 8)?,
  854. kind,
  855. comp,
  856. interp: 0,
  857. row: (register != u32::MAX).then_some(register),
  858. col: mask.trailing_zeros().min(3) as u8,
  859. cols: mask.count_ones().max(1) as u8,
  860. usage: 0,
  861. half: (4..=6).contains(&raw),
  862. });
  863. }
  864. Ok(out)
  865. }
  866. #[cfg(test)]
  867. mod tests {
  868. use super::bitcode::Attr;
  869. use super::lower::LOOP_LIMIT;
  870. use super::parse_loop_limit;
  871. /// The LLVM text `dxc -dumpbin` prints for a DXIL container, when dxc
  872. /// is installed.
  873. #[cfg(windows)]
  874. fn dump_dxil(container: &[u8]) -> Option<String> {
  875. let dxc = match std::env::var_os("VICTORY_PC_DXC") {
  876. Some(p) => std::path::PathBuf::from(p),
  877. None => super::validator::Validator::default_path()?.with_file_name("dxc.exe"),
  878. };
  879. if !dxc.exists() {
  880. return None;
  881. }
  882. let file = std::env::temp_dir().join(format!("victory-interp-{}.dxil", std::process::id()));
  883. std::fs::write(&file, container).ok()?;
  884. let out = std::process::Command::new(dxc)
  885. .arg("-dumpbin")
  886. .arg(&file)
  887. .output()
  888. .ok()?;
  889. let _ = std::fs::remove_file(&file);
  890. assert!(
  891. out.status.success(),
  892. "dxc -dumpbin failed: {}",
  893. String::from_utf8_lossy(&out.stderr)
  894. );
  895. Some(String::from_utf8_lossy(&out.stdout).into_owned())
  896. }
  897. #[cfg(windows)]
  898. #[test]
  899. fn interpolated_f16_writes_the_op_sel_half_with_modifiers() {
  900. // p1_f32 v2, v0, attr0.x; then a p2_f16 completing it into v3, which holds a value
  901. // (v2's own is no number here: a first half is evaluated with its second).
  902. let p2 = |dst_high: bool, omod: u32, clamp: bool| {
  903. let vgpr = |n: u32| 256 + n;
  904. let mut w0 = 0x35u32 << 26 | 0x35au32 << 16 | 3;
  905. if dst_high {
  906. w0 |= 1 << 14; // op_sel[3]: the high destination half.
  907. }
  908. if clamp {
  909. w0 |= 1 << 15;
  910. }
  911. let w1 = vgpr(1) << 9 | vgpr(2) << 18;
  912. [w0, w1 | omod << 27]
  913. };
  914. let dump = |dst_high: bool, omod: u32, clamp: bool| {
  915. let [w0, w1] = p2(dst_high, omod, clamp);
  916. let words = [
  917. 0x7E06_0301u32, // v_mov_b32 v3, v1
  918. 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x
  919. w0,
  920. w1, // v_interp_p2_f16 v3, attr0, v1, v2
  921. 0xF800_180F,
  922. 0x0303_0303, // exp mrt0, v3, v3, v3, v3 done vm
  923. 0xBF81_0000,
  924. ];
  925. let native = super::NativeProgram {
  926. stage: super::HwStage::Ps,
  927. wave64: false,
  928. vgprs: 4,
  929. layout: vec![],
  930. used: vec![],
  931. io: crate::native::StageIo::Ps {
  932. inputs: vec![crate::native::PsInput {
  933. usage: crate::native::Usage::Generic,
  934. row: 0,
  935. mask: 0b1111,
  936. attr: 0,
  937. flat: false,
  938. fp16: true,
  939. pack2: false,
  940. row2: 0,
  941. }],
  942. input_addr: 2,
  943. db_shader_control: 0,
  944. patches: vec![],
  945. },
  946. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  947. };
  948. let el = |name: &str, kind, usage, half| SigElement {
  949. name: name.into(),
  950. index: 0,
  951. kind,
  952. comp: 9,
  953. interp: 0,
  954. row: Some(0),
  955. col: 0,
  956. cols: 4,
  957. usage,
  958. half,
  959. };
  960. let isg1 = super::container::signature(&[el("TEXCOORD", 0, 0, true)], true);
  961. let osg1 = super::container::signature(&[el("SV_Target", 16, 15, false)], false);
  962. let bytes =
  963. crate::dxbc::build(&[(super::FourCC::ISG1, &isg1), (super::FourCC::OSG1, &osg1)]);
  964. let c = super::Container::parse(&bytes).unwrap();
  965. let p = crate::ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap();
  966. let st = crate::structure::structure(&p).unwrap();
  967. let res = crate::resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
  968. let io = crate::io::raise(&p, &native).unwrap();
  969. super::emit(&c, &native, &p, &st, &io, &res).unwrap().dxil
  970. };
  971. let (Some(low), Some(high)) = (
  972. dump_dxil(&dump(false, 0, false)),
  973. dump_dxil(&dump(true, 1, true)),
  974. ) else {
  975. eprintln!("no dxc.exe; DXIL check skipped");
  976. return;
  977. };
  978. // The low-half write keeps the destination's high half.
  979. assert!(low.contains("-65536"), "low write keeps the high half");
  980. // The high-half write shifts the result up by 16.
  981. assert!(high.contains("shl i32"), "op_sel[3] writes the high half");
  982. // omod mul:2 and clamp (dx.op.unary.f32, opcode 7) are applied.
  983. assert!(high.contains("2.000000e+00"), "omod multiplies by two");
  984. assert!(
  985. high.contains("dx.op.unary.f32(i32 7"),
  986. "clamp saturates the result"
  987. );
  988. assert!(!low.contains("dx.op.unary.f32(i32 7"));
  989. }
  990. #[test]
  991. fn the_clean_up_switch_parses_or_runs_every_pass() {
  992. let all = super::bitcode::opt::ALL;
  993. assert_eq!(parse_shader_opt(None), all);
  994. assert_eq!(parse_shader_opt(Some("0")), 0);
  995. assert_eq!(parse_shader_opt(Some(" 1 ")), 1);
  996. assert_eq!(parse_shader_opt(Some("0x1")), 1);
  997. assert_eq!(parse_shader_opt(Some("0xffffffff")), all);
  998. assert_eq!(parse_shader_opt(Some("on")), all);
  999. }
  1000. #[test]
  1001. fn the_loop_limit_switch_parses_or_falls_back() {
  1002. assert_eq!(parse_loop_limit(None), LOOP_LIMIT);
  1003. assert_eq!(parse_loop_limit(Some("4096")), 4096);
  1004. assert_eq!(parse_loop_limit(Some(" 0x1000 ")), 4096);
  1005. assert_eq!(parse_loop_limit(Some("1")), 1);
  1006. for bad in ["", "0", "-5", "lots", "0x", "4294967296"] {
  1007. assert_eq!(parse_loop_limit(Some(bad)), LOOP_LIMIT, "{bad:?}");
  1008. }
  1009. }
  1010. use super::container::SigElement;
  1011. use super::shader::Shader;
  1012. use super::*;
  1013. use crate::native::{ComputeIo, StageIo};
  1014. /// A pixel shader writing SV_StencilRef (channel y of `exp mrtz`).
  1015. /// DXC sets ShaderFlags.StencilRef (bit 11) for a pixel shader whose
  1016. /// output signature has SV_StencilRef, and the feature bit
  1017. /// D3D_SHADER_FEATURE_STENCIL_REF (0x200) in SFI0; the validator checks
  1018. /// both against the module.
  1019. #[test]
  1020. fn a_stencil_export_declares_the_stencil_ref_feature() {
  1021. let words = [
  1022. 0x7E00_02F2u32, // v_mov_b32 v0, 1.0
  1023. 0x7E02_0285, // v_mov_b32 v1, 5
  1024. 0xF800_1883,
  1025. 0x0000_0100, // exp mrtz v0, v1, off, off done vm
  1026. 0xBF81_0000,
  1027. ];
  1028. let native = NativeProgram {
  1029. stage: HwStage::Ps,
  1030. wave64: false,
  1031. vgprs: 2,
  1032. layout: vec![],
  1033. used: vec![],
  1034. io: StageIo::Ps {
  1035. inputs: vec![],
  1036. input_addr: 0,
  1037. db_shader_control: 0,
  1038. patches: vec![],
  1039. },
  1040. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  1041. };
  1042. let el = |name: &str, kind, comp| SigElement {
  1043. name: name.into(),
  1044. index: 0,
  1045. kind,
  1046. comp,
  1047. interp: 0,
  1048. row: None,
  1049. col: 0,
  1050. cols: 1,
  1051. usage: 1,
  1052. half: false,
  1053. };
  1054. let osg1 =
  1055. container::signature(&[el("SV_Depth", 17, 9), el("SV_StencilRef", 20, 5)], false);
  1056. let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]);
  1057. let c = Container::parse(&bytes).unwrap();
  1058. let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap();
  1059. let st = structure::structure(&p).unwrap();
  1060. let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
  1061. let io = io::raise(&p, &native).unwrap();
  1062. let out = emit(&c, &native, &p, &st, &io, &res).unwrap();
  1063. // dxil.dll, where there is one, checks the flags against the module.
  1064. #[cfg(windows)]
  1065. if let Ok(mut v) = super::validator::Validator::load(
  1066. super::validator::Validator::default_path().as_deref(),
  1067. ) {
  1068. v.validate(&mut out.dxil.clone()).unwrap();
  1069. }
  1070. let host = Container::parse(&out.dxil).unwrap();
  1071. let sfi0 = host.part(FourCC::SFI0).unwrap().data;
  1072. let features = u64::from_le_bytes(sfi0.try_into().unwrap());
  1073. assert_ne!(features & 0x200, 0, "SFI0 {features:#x}: no StencilRef");
  1074. }
  1075. /// A pixel program with an ordered section, as the console compiler
  1076. /// makes one of rasterizer ordered views (the title's hair cards keep
  1077. /// their nearest layers that way): the wait for overlapped waves is
  1078. /// skipped, the views inside the section are the host's ordered ones,
  1079. /// the one after it is not.
  1080. #[test]
  1081. fn an_ordered_section_uses_rasterizer_ordered_views() {
  1082. let section = [
  1083. 0xBE82_0300u32, // s_mov_b32 s2, s0
  1084. 0xBE83_0380, // s_mov_b32 s3, 0
  1085. 0xF40C_0201, // s_load_dwordx8 s[8:15], s[2:3], 0
  1086. 0xFA00_0000,
  1087. 0x9390_FF01, // s_bfe_u32 s16, s1, 0x2001c
  1088. 0x0002_001C,
  1089. 0x9391_FF01, // s_bfe_u32 s17, s1, 0xa0000
  1090. 0x000A_0000,
  1091. 0x8F10_8110, // s_lshl_b32 s16, s16, 1
  1092. 0x9392_FF01, // s_bfe_u32 s18, s1, 0xa0010
  1093. 0x000A_0010,
  1094. 0xBE91_0711, // s_not_b32 s17, s17
  1095. 0x9013_9F01, // s_lshr_b32 s19, s1, 31
  1096. 0x8810_8110, // s_or_b32 s16, s16, 1
  1097. 0x8112_1112, // s_add_i32 s18, s18, s17
  1098. 0xBF06_8013, // s_cmp_eq_u32 s19, 0
  1099. 0xB990_1019, // s_setreg_b32 hwreg(HW_REG_POPS_PACKER, 0, 3), s16
  1100. 0x8514_807E, // s_cselect_b32 s20, exec_lo, 0
  1101. 0x8115_11EF, // s_add_i32 s21, src_pops_exiting_wave_id, s17
  1102. 0xBF08_1215, // s_cmp_gt_u32 s21, s18
  1103. 0x8516_807E, // s_cselect_b32 s22, exec_lo, 0
  1104. 0x8814_1614, // s_or_b32 s20, s20, s22
  1105. 0x876A_147E, // s_and_b32 vcc_lo, exec_lo, s20
  1106. 0xBF87_0004, // s_cbranch_vccnz past the wait
  1107. 0xBF8E_FFFF, // s_sleep 0xffff
  1108. 0x8115_11EF, // s_add_i32 s21, src_pops_exiting_wave_id, s17
  1109. 0xBF0A_1512, // s_cmp_lt_u32 s18, s21
  1110. 0xBF84_FFFC, // s_cbranch_scc0 back to the sleep
  1111. 0x7E00_0280, // v_mov_b32 v0, 0
  1112. 0x7E02_0280, // v_mov_b32 v1, 0
  1113. 0xF000_3F88, // image_load v[2:5], v[0:1], s[8:15] dmask:0xf 2D glc dlc
  1114. 0x0002_0200,
  1115. 0x0604_04F2, // v_add_f32 v2, 1.0, v2
  1116. 0xF020_3F08, // image_store v[2:5], v[0:1], s[8:15] dmask:0xf 2D glc
  1117. 0x0002_0200,
  1118. 0xBEFC_0380, // s_mov_b32 m0, 0
  1119. 0xBF90_0007, // s_sendmsg sendmsg(MSG_ORDERED_PS_DONE)
  1120. ];
  1121. let end = [
  1122. 0xF800_180Fu32, // exp mrt0 v2, v2, v2, v2 done vm
  1123. 0x0202_0202,
  1124. 0xBF81_0000, // s_endpgm
  1125. ];
  1126. // A store after the section, through an ordinary view.
  1127. let after = [0xF020_3F08u32, 0x0002_0200];
  1128. let lower = |words: Vec<u32>| {
  1129. let native = NativeProgram {
  1130. stage: HwStage::Ps,
  1131. wave64: false,
  1132. vgprs: 8,
  1133. layout: vec![crate::native::RootParam {
  1134. root: RootType::Table,
  1135. table_offset_dwords: 0,
  1136. sgprs: 1,
  1137. base_register: 0,
  1138. user_data: 0,
  1139. slot: 0,
  1140. }],
  1141. used: vec![crate::native::UsedResource {
  1142. kind: crate::native::ResourceType::Uav,
  1143. root: RootType::Table,
  1144. table_offset_dwords: 0,
  1145. lower_bound: 0,
  1146. stride: 4,
  1147. dwords: 8,
  1148. user_data: 0,
  1149. slot: 0,
  1150. }],
  1151. io: StageIo::Ps {
  1152. inputs: vec![],
  1153. input_addr: 0,
  1154. db_shader_control: 0,
  1155. patches: vec![],
  1156. },
  1157. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  1158. };
  1159. let target = SigElement {
  1160. name: "SV_Target".into(),
  1161. index: 0,
  1162. kind: 16,
  1163. comp: 9,
  1164. interp: 0,
  1165. row: Some(0),
  1166. col: 0,
  1167. cols: 4,
  1168. usage: 15,
  1169. half: false,
  1170. };
  1171. let osg1 = container::signature(&[target], false);
  1172. let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]);
  1173. let c = Container::parse(&bytes).unwrap();
  1174. let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?;
  1175. let st = structure::structure(&p)?;
  1176. let res = resource::track(&p, &native.layout, native.stage, Some(&st))?;
  1177. let io = io::raise(&p, &native)?;
  1178. let out = emit(&c, &native, &p, &st, &io, &res)?;
  1179. #[cfg(windows)]
  1180. if let Ok(mut v) = super::validator::Validator::load(
  1181. super::validator::Validator::default_path().as_deref(),
  1182. ) {
  1183. v.validate(&mut out.dxil.clone()).unwrap();
  1184. }
  1185. let host = Container::parse(&out.dxil).unwrap();
  1186. let sfi0 = host.part(FourCC::SFI0).unwrap().data;
  1187. Ok::<u64, ShaderError>(u64::from_le_bytes(sfi0.try_into().unwrap()))
  1188. };
  1189. // D3D_SHADER_REQUIRES_ROVS
  1190. let features = lower([&section[..], &end].concat()).unwrap();
  1191. assert_ne!(features & 0x1000, 0, "SFI0 {features:#x}: no ROVs");
  1192. lower([&section[..], &after, &end].concat()).unwrap();
  1193. // The same accesses outside a section: ordinary views, no feature.
  1194. let plain = [&section[..4], &section[28..35], &end].concat();
  1195. let features = lower(plain).unwrap();
  1196. assert_eq!(features & 0x1000, 0, "SFI0 {features:#x}: ROVs");
  1197. // Without the section's start the wait stays unknown.
  1198. let mut unmarked = [&section[..], &end].concat();
  1199. unmarked.remove(16);
  1200. assert!(lower(unmarked).is_err());
  1201. }
  1202. #[test]
  1203. fn immediate_sampler_slots_distinguish_comparison_uses() {
  1204. let words = [
  1205. 0xBE81_0380u32, // s_mov_b32 s1, 0
  1206. 0xF40C_0000,
  1207. 0xFA00_0000, // s_load_dwordx8 s[0:7], s[0:1], null
  1208. 0xBE88_0380, // s_mov_b32 s8, 0
  1209. 0xBE89_0380, // s_mov_b32 s9, 0
  1210. 0xBE8A_0380, // s_mov_b32 s10, 0
  1211. 0xBE8B_0380, // s_mov_b32 s11, 0
  1212. 0x7E00_02F0, // v_mov_b32 v0, 0.5 (comparison reference)
  1213. 0x7E02_02F0, // v_mov_b32 v1, 0.5 (u)
  1214. 0x7E04_02F0, // v_mov_b32 v2, 0.5 (v)
  1215. 0xBF8C_0070, // s_waitcnt vmcnt(0) lgkmcnt(0)
  1216. 0xF080_0108,
  1217. 0x0040_0301, // image_sample v3, v[1:2], s[0:7], s[8:11]
  1218. 0xF0A0_0108,
  1219. 0x0040_0400, // image_sample_c v4, v[0:2], s[0:7], s[8:11]
  1220. 0xF0BC_0108,
  1221. 0x0040_0500, // image_sample_c_lz v5, v[0:2], s[0:7], s[8:11]
  1222. 0xF080_0108,
  1223. 0x0040_0601, // image_sample v6, v[1:2], s[0:7], s[8:11]
  1224. 0xBF8C_3F70, // s_waitcnt vmcnt(0)
  1225. 0xF800_180F,
  1226. 0x0605_0403, // exp mrt0, v3, v4, v5, v6 done vm
  1227. 0xBF81_0000,
  1228. ];
  1229. let native = NativeProgram {
  1230. stage: HwStage::Ps,
  1231. wave64: false,
  1232. vgprs: 7,
  1233. layout: vec![crate::native::RootParam {
  1234. root: RootType::Table,
  1235. table_offset_dwords: 0,
  1236. sgprs: 1,
  1237. base_register: 0,
  1238. user_data: 0,
  1239. slot: 0,
  1240. }],
  1241. used: vec![crate::native::UsedResource {
  1242. kind: crate::native::ResourceType::Srv,
  1243. root: RootType::Table,
  1244. table_offset_dwords: 0,
  1245. lower_bound: 0,
  1246. stride: 0,
  1247. dwords: 8,
  1248. user_data: 0,
  1249. slot: 0,
  1250. }],
  1251. io: StageIo::Ps {
  1252. inputs: vec![],
  1253. input_addr: 0,
  1254. db_shader_control: 0,
  1255. patches: vec![],
  1256. },
  1257. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  1258. };
  1259. let output = SigElement {
  1260. name: "SV_Target".into(),
  1261. index: 0,
  1262. kind: 16,
  1263. comp: 9,
  1264. interp: 0,
  1265. row: Some(0),
  1266. col: 0,
  1267. cols: 4,
  1268. usage: 15,
  1269. half: false,
  1270. };
  1271. let osg1 = container::signature(&[output], false);
  1272. let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]);
  1273. let c = Container::parse(&bytes).unwrap();
  1274. let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap();
  1275. let st = structure::structure(&p).unwrap();
  1276. let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
  1277. let io = io::raise(&p, &native).unwrap();
  1278. let out = emit(&c, &native, &p, &st, &io, &res).unwrap();
  1279. let sampler = StaticSampler::from_words([0; 4]);
  1280. let comparison = StaticSampler {
  1281. filter: sampler.filter | 0x80,
  1282. ..sampler
  1283. };
  1284. assert_eq!(out.samplers, [[0; 4]; 2]);
  1285. assert_eq!(out.static_samplers, [sampler, comparison]);
  1286. #[cfg(windows)]
  1287. if let Some(path) = super::validator::Validator::default_path() {
  1288. let mut v = super::validator::Validator::load(Some(&path)).unwrap();
  1289. v.validate(&mut out.dxil.clone()).unwrap();
  1290. }
  1291. }
  1292. /// A wave64 compute program that writes only EXEC's high dword
  1293. /// (`s_mov_b32 exec_hi, 0`) before a vector instruction. The new mask was
  1294. /// opaque and keyed by the unchanged low dword, so building its lane bit
  1295. /// needed the mask's own value: lowering recursed until the stack
  1296. /// overflowed, which takes the whole process down (found by
  1297. /// random-input testing). Now that low dword, seen with two high
  1298. /// dwords, has no mask, and the instruction fails like any other that
  1299. /// cannot be expressed: its result is missing, and only a side effect
  1300. /// that uses it would stop the translation.
  1301. #[test]
  1302. fn an_exec_high_write_does_not_overflow_the_stack() {
  1303. // s_mov_b32 exec_hi, 0; v_mov_b32 v1, v0; s_endpgm
  1304. let words = [0xBEFF_0380u32, 0x7E02_0300, 0xBF81_0000];
  1305. let native = NativeProgram {
  1306. stage: HwStage::Cs,
  1307. wave64: true,
  1308. vgprs: 2,
  1309. layout: vec![],
  1310. used: vec![],
  1311. io: StageIo::Cs(ComputeIo {
  1312. rsrc2: 0,
  1313. threads: [64, 1, 1],
  1314. }),
  1315. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  1316. };
  1317. let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap();
  1318. let st = structure::structure(&p).unwrap();
  1319. let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
  1320. let io = io::raise(&p, &native).unwrap();
  1321. let container = crate::dxbc::build(&[]);
  1322. let c = Container::parse(&container).unwrap();
  1323. if let Err(e) = emit(&c, &native, &p, &st, &io, &res) {
  1324. assert!(e.to_string().contains("its own value"), "{e}");
  1325. }
  1326. }
  1327. /// A wave64 compute program: `body`, then a store of v1 to a UAV.
  1328. fn stores_v1(body: &[u32]) -> Result<(), ShaderError> {
  1329. use crate::native::RootParam;
  1330. use crate::{ResourceType, RootType, UsedResource};
  1331. // s_mov_b32 s1, 0; s_load_dwordx4 s[8:11], s[0:1], 0
  1332. let mut words = vec![0xBE81_0380, 0xF408_0200, 0xFA00_0000];
  1333. words.extend_from_slice(body);
  1334. // v_lshlrev_b32 v3, 2, v0; buffer_store_dword v1, v3, s[8:11], 0 offen;
  1335. // s_endpgm
  1336. words.extend_from_slice(&[0x3406_0082, 0xE070_1000, 0x8002_0103, 0xBF81_0000]);
  1337. let native = NativeProgram {
  1338. stage: HwStage::Cs,
  1339. wave64: true,
  1340. vgprs: 4,
  1341. layout: vec![RootParam {
  1342. root: RootType::Table,
  1343. table_offset_dwords: 0,
  1344. sgprs: 1,
  1345. base_register: 0,
  1346. user_data: 0,
  1347. slot: 0,
  1348. }],
  1349. used: vec![UsedResource {
  1350. kind: ResourceType::Uav,
  1351. root: RootType::Table,
  1352. table_offset_dwords: 0,
  1353. lower_bound: 0,
  1354. stride: 0,
  1355. dwords: 4,
  1356. user_data: 0,
  1357. slot: 0,
  1358. }],
  1359. io: StageIo::Cs(ComputeIo {
  1360. rsrc2: 2,
  1361. threads: [64, 1, 1],
  1362. }),
  1363. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  1364. };
  1365. let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap();
  1366. let res = resource::track(&p, &native.layout, native.stage, None).unwrap();
  1367. let io = io::raise(&p, &native).unwrap();
  1368. let st = structure::structure(&p).unwrap();
  1369. let container = crate::dxbc::build(&[]);
  1370. let c = Container::parse(&container).unwrap();
  1371. emit(&c, &native, &p, &st, &io, &res).map(|_| ())
  1372. }
  1373. /// The high dword of a wave64 mask rewritten alone (`s_mov_b32 vcc_hi`
  1374. /// or `exec_hi`): lanes 32-63 took the mask the low dword was first
  1375. /// written with (the compare's, EXEC's on entry). Now the store refuses;
  1376. /// without the write it translates.
  1377. #[test]
  1378. fn a_mask_whose_high_dword_is_rewritten_is_refused() {
  1379. // v_cmp_eq_u32 vcc, 0, v0; v_mov_b32 v2, 11; v_cndmask_b32 v1, 0, v2, vcc
  1380. let select = [0x7D84_0080, 0x7E04_028B, 0x0202_0480];
  1381. // The same with v_add_co_ci_u32 v1, vcc, 0, v2, vcc.
  1382. let carry = [0x7D84_0080, 0x7E04_028B, 0x5002_0480];
  1383. // v_mov_b32 v1, 7
  1384. let mov = [0x7E02_0287];
  1385. for body in [&select[..], &carry, &mov] {
  1386. stores_v1(body).unwrap();
  1387. }
  1388. // s_mov_b32 vcc_hi, 0 after the compare.
  1389. let select_hi = [0x7D84_0080, 0xBEEB_0380, 0x7E04_028B, 0x0202_0480];
  1390. let carry_hi = [0x7D84_0080, 0xBEEB_0380, 0x7E04_028B, 0x5002_0480];
  1391. // s_mov_b32 exec_hi, 0; v_mov_b32 v1, 7, then the same after
  1392. // s_mov_b64 s[2:3], exec.
  1393. let exec_hi = [0xBEFF_0380, 0x7E02_0287];
  1394. let exec_hi_saved = [0xBE82_047E, 0xBEFF_0380, 0x7E02_0287];
  1395. for body in [&select_hi[..], &carry_hi, &exec_hi, &exec_hi_saved] {
  1396. assert!(stores_v1(body).is_err(), "{body:x?}");
  1397. }
  1398. }
  1399. /// `ds_bpermute_b32` stores nothing: each lane reads the lane its address
  1400. /// names. It stopped as "LDS the program does not allocate" (sticky lips)
  1401. /// or "an LDS operation" (the checkerboard shadow masks).
  1402. #[test]
  1403. fn a_backward_permute_reads_the_lane_its_address_names() {
  1404. // v_mov_b32 v2, 11; ds_bpermute_b32 v1, v0, v2
  1405. stores_v1(&[0x7E04_028B, 0xDACC_0000, 0x0100_0200]).unwrap();
  1406. }
  1407. /// A carry-in reading a join of compares after a divergent branch. A
  1408. /// lane that skipped the inner compare has VCC clear there (VOPC clears
  1409. /// inactive lanes), not the first compare's bit, so the join is no
  1410. /// per-lane phi: lowering refuses it.
  1411. #[test]
  1412. fn a_carry_in_from_a_divergent_join_is_refused() {
  1413. let body = [
  1414. 0x7E04_028B, // v_mov_b32 v2, 11
  1415. 0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0
  1416. 0xBE82_376A, // s_andn1_saveexec_b64 s[2:3], vcc
  1417. 0xBF88_0001, // s_cbranch_execz 1
  1418. 0x7D84_0081, // v_cmp_eq_u32 vcc, 1, v0
  1419. 0x88FE_027E, // s_or_b64 exec, exec, s[2:3]
  1420. 0x5002_0480, // v_add_co_ci_u32 v1, vcc, 0, v2, vcc
  1421. ];
  1422. let e = stores_v1(&body).unwrap_err().to_string();
  1423. assert!(e.contains("a carry-in from an untracked mask"), "{e}");
  1424. }
  1425. /// A pixel shader writing a constant colour.
  1426. #[cfg(windows)]
  1427. fn constant_color() -> Vec<u8> {
  1428. let mut s = Shader::new(true);
  1429. s.outputs.push(SigElement {
  1430. name: "SV_Target".into(),
  1431. index: 0,
  1432. kind: 16,
  1433. comp: 9,
  1434. interp: 0,
  1435. row: Some(0),
  1436. col: 0,
  1437. cols: 4,
  1438. usage: 15,
  1439. half: false,
  1440. });
  1441. let b = s.entry;
  1442. for (c, v) in [1.0f32, 0.5, 0.25, 1.0].into_iter().enumerate() {
  1443. let args = [
  1444. s.m.i32(0),
  1445. s.m.i32(0),
  1446. s.m.i8(c as u8),
  1447. s.m.f32(v.to_bits()),
  1448. ];
  1449. s.op(b, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args);
  1450. }
  1451. s.m.terminate(b, super::bitcode::Term::Ret);
  1452. s.finish()
  1453. }
  1454. #[test]
  1455. #[cfg(windows)]
  1456. fn stub_pipeline_is_created() {
  1457. let host = match super::host::Host::new(false) {
  1458. Ok(host) => host,
  1459. Err(e) => {
  1460. eprintln!("no SM 6.6 device ({e}); skipped");
  1461. return;
  1462. }
  1463. };
  1464. let ps = super::HostShader {
  1465. stage: crate::HwStage::Ps,
  1466. dxil: constant_color(),
  1467. user_data: Vec::new(),
  1468. samplers: Vec::new(),
  1469. static_samplers: Vec::new(),
  1470. root_cbvs: Vec::new(),
  1471. root_srvs: Vec::new(),
  1472. root_uavs: Vec::new(),
  1473. root_indexed_views: Vec::new(),
  1474. };
  1475. let file = |var: &str, stage| {
  1476. std::env::var(var).ok().map(|p| super::HostShader {
  1477. stage,
  1478. dxil: std::fs::read(p).unwrap(),
  1479. user_data: Vec::new(),
  1480. samplers: Vec::new(),
  1481. static_samplers: Vec::new(),
  1482. root_cbvs: Vec::new(),
  1483. root_srvs: Vec::new(),
  1484. root_uavs: Vec::new(),
  1485. root_indexed_views: Vec::new(),
  1486. })
  1487. };
  1488. let ps = file("VICTORY_REF_PS", crate::HwStage::Ps).unwrap_or(ps);
  1489. let vs = file("VICTORY_REF_VS", crate::HwStage::Vs)
  1490. .unwrap_or_else(|| super::host::stub_vs(&ps).unwrap());
  1491. if let Ok(mut v) = super::validator::Validator::load(
  1492. super::validator::Validator::default_path().as_deref(),
  1493. ) {
  1494. v.validate(&mut vs.dxil.clone()).unwrap();
  1495. }
  1496. host.pipeline(&vs, &ps).unwrap();
  1497. // The runtime checks the container hash: no hash or a wrong one is
  1498. // refused. (Recent runtimes also take sixteen 0x01 bytes, a bypass
  1499. // value; ours works with older ones too.)
  1500. let mut wrong = ps.dxil[4..20].to_vec();
  1501. wrong[0] ^= 1;
  1502. for digest in [&[0u8; 16][..], &wrong] {
  1503. let mut other = ps.clone();
  1504. other.dxil[4..20].copy_from_slice(digest);
  1505. assert!(
  1506. host.pipeline(&vs, &other).is_err(),
  1507. "digest {digest:02x?} accepted"
  1508. );
  1509. }
  1510. }
  1511. #[test]
  1512. #[cfg(windows)]
  1513. fn constant_color_validates() {
  1514. let mut c = constant_color();
  1515. let path = super::validator::Validator::default_path();
  1516. let Ok(mut v) = super::validator::Validator::load(path.as_deref()) else {
  1517. eprintln!("no dxil.dll; skipped");
  1518. return;
  1519. };
  1520. let ours = c[4..20].to_vec();
  1521. v.validate(&mut c).unwrap();
  1522. assert_eq!(c[4..20], ours[..], "our hash differs from the validator's");
  1523. }
  1524. /// A pixel program of `words` with no user data.
  1525. fn emit_native(words: &[u32], input_addr: u32) -> NativeProgram {
  1526. NativeProgram {
  1527. stage: HwStage::Ps,
  1528. wave64: false,
  1529. vgprs: 4,
  1530. layout: vec![],
  1531. used: vec![],
  1532. io: StageIo::Ps {
  1533. inputs: vec![],
  1534. input_addr,
  1535. db_shader_control: 0,
  1536. patches: vec![],
  1537. },
  1538. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  1539. }
  1540. }
  1541. /// A pixel program that takes its neighbour's position across its quad
  1542. /// (`ds_swizzle_b32`, as the console's compiler makes derivatives) and
  1543. /// exports the differences in x and y: 1 and -1 in every pixel of a
  1544. /// triangle, those at its edges too, whose neighbours are helpers.
  1545. #[test]
  1546. #[cfg(windows)]
  1547. fn quad_neighbours_at_a_triangles_edge_are_read() {
  1548. use super::host::{Draw, Host, Root};
  1549. use windows::Win32::Graphics::Direct3D12::{
  1550. D3D12_SHADER_VISIBILITY_MESH, D3D12_SHADER_VISIBILITY_PIXEL,
  1551. };
  1552. let _one = super::valu_tests::ONE_AT_A_TIME
  1553. .lock()
  1554. .unwrap_or_else(|e| e.into_inner());
  1555. // v2, v3: position x, y (input address: POS_X and POS_Y after the
  1556. // two perspective barycentrics).
  1557. let swizzle = |dst: u32, src: u32, pattern: u32| {
  1558. [
  1559. 0xD800_0000 | 0x35 << 18 | 0x8000 | pattern,
  1560. dst << 24 | src,
  1561. ]
  1562. };
  1563. let mut words = vec![0xBEFC_0380u32]; // s_mov_b32 m0, 0
  1564. words.extend(swizzle(4, 2, 0xB1)); // lanes 1 0 3 2
  1565. words.extend(swizzle(5, 3, 0x4E)); // lanes 2 3 0 1
  1566. words.extend(swizzle(6, 2, 0xA0)); // lanes 0 0 2 2
  1567. words.extend([
  1568. 0x0808_0504, // v_sub_f32 v4, v4, v2
  1569. 0x080A_0705, // v_sub_f32 v5, v5, v3
  1570. 0x080C_0506, // v_sub_f32 v6, v6, v2
  1571. 0xF800_180F,
  1572. 0x0302_0504, // exp mrt0 v4, v5, v2, v3 done vm
  1573. 0xBF81_0000,
  1574. ]);
  1575. let _ = 6;
  1576. let mut native = emit_native(&words, 1 << 1 | 1 << 8 | 1 << 9);
  1577. native.vgprs = 8;
  1578. let out = SigElement {
  1579. name: "SV_Target".into(),
  1580. index: 0,
  1581. kind: 16,
  1582. comp: 9,
  1583. interp: 0,
  1584. row: Some(0),
  1585. col: 0,
  1586. cols: 4,
  1587. usage: 15,
  1588. half: false,
  1589. };
  1590. let position = SigElement {
  1591. name: "SV_Position".into(),
  1592. index: 0,
  1593. kind: 3,
  1594. comp: 9,
  1595. interp: 4,
  1596. row: Some(0),
  1597. col: 0,
  1598. cols: 4,
  1599. usage: 3,
  1600. half: false,
  1601. };
  1602. let isg1 = container::signature(&[position], true);
  1603. let osg1 = container::signature(&[out], false);
  1604. let bytes = crate::dxbc::build(&[(FourCC::ISG1, &isg1), (FourCC::OSG1, &osg1)]);
  1605. let c = Container::parse(&bytes).unwrap();
  1606. let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap();
  1607. let st = structure::structure(&p).unwrap();
  1608. let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
  1609. let io = io::raise(&p, &native).unwrap();
  1610. let ps = emit(&c, &native, &p, &st, &io, &res).unwrap();
  1611. if let Some(path) = super::validator::Validator::default_path() {
  1612. let mut v = super::validator::Validator::load(Some(&path)).unwrap();
  1613. v.validate(&mut ps.dxil.clone()).unwrap();
  1614. }
  1615. let ms = triangle_mesh_to(TRIANGLE, 1.3).unwrap();
  1616. for (label, warp) in [("hardware", false), ("warp", true)] {
  1617. let Ok(host) = Host::new(warp) else {
  1618. continue;
  1619. };
  1620. let Ok(root) = host.root_signature_for(&[
  1621. (&ms, D3D12_SHADER_VISIBILITY_MESH),
  1622. (&ps, D3D12_SHADER_VISIBILITY_PIXEL),
  1623. ]) else {
  1624. continue;
  1625. };
  1626. let Ok(pso) = host.mesh_pipeline_with(&root, &ms.dxil, &ps.dxil) else {
  1627. eprintln!("no mesh pipeline on {label}; skipped");
  1628. continue;
  1629. };
  1630. let texels = host
  1631. .draw(
  1632. &root,
  1633. &pso,
  1634. &Draw {
  1635. roots: vec![(0, Root::Constants(vec![0])), (1, Root::Constants(vec![0]))],
  1636. textures: &[],
  1637. samplers: &[],
  1638. vertices: &[],
  1639. stride: 0,
  1640. size: (16, 16),
  1641. mesh_groups: 1,
  1642. },
  1643. )
  1644. .unwrap_or_else(|e| panic!("{label}: draw: {e}"));
  1645. let lit: Vec<(usize, &[f32; 4])> = texels.iter().enumerate().filter(|t| t.1[2] != 0.0).collect();
  1646. assert!((20..240).contains(&lit.len()), "{label}: {} texels lit", lit.len());
  1647. let bad: Vec<_> = lit
  1648. .iter()
  1649. .filter(|(n, t)| {
  1650. let x = if n % 2 == 0 { 1.0 } else { -1.0 };
  1651. let y = if n / 16 % 2 == 0 { 1.0 } else { -1.0 };
  1652. (t[0], t[1]) != (x, y)
  1653. })
  1654. .collect();
  1655. assert!(bad.is_empty(), "{label}: {} of {} texels: {:?}", bad.len(), lit.len(), bad[0]);
  1656. }
  1657. }
  1658. /// Triangle (0, 1, 2), each corner's 9-bit index in its 10-bit field.
  1659. const TRIANGLE: u32 = 1 << 10 | 2 << 20;
  1660. /// The edge flags of the three corners (bits 9, 19 and 29).
  1661. const EDGE_FLAGS: u32 = 1 << 9 | 1 << 19 | 1 << 29;
  1662. /// The culling bit.
  1663. const CULL: u32 = 1 << 31;
  1664. /// A one-wave (32-lane) triangle mesh program whose lanes all export
  1665. /// primitive `prim` and, as vertex `lane`, the position
  1666. /// (lane & 1 ? 3 : -1, lane & 2 ? 3 : -1, 0.5, 1): triangle (0, 1, 2)
  1667. /// covers the whole target.
  1668. fn triangle_mesh(prim: u32) -> Result<HostShader, ShaderError> {
  1669. triangle_mesh_to(prim, 4.0)
  1670. }
  1671. /// The triangle with its far corners at `reach` - 1.
  1672. fn triangle_mesh_to(prim: u32, reach: f32) -> Result<HostShader, ShaderError> {
  1673. // (the second corner's y comes out as 2 x its lane bit: half of it)
  1674. let [x, y] = [reach.to_bits(), (reach / 2.0).to_bits()];
  1675. let words = [
  1676. 0xD765_0001u32, // v_mbcnt_lo_u32_b32 v1, -1, 0
  1677. 0x0001_00C1,
  1678. 0x3604_0281, // v_and_b32 v2, 1, v1
  1679. 0x3606_0282, // v_and_b32 v3, 2, v1
  1680. 0x7E04_0D02, // v_cvt_f32_u32 v2, v2
  1681. 0x7E06_0D03, // v_cvt_f32_u32 v3, v3
  1682. 0x1008_04FF, // v_mul_f32 v4, reach, v2
  1683. x,
  1684. 0x0608_08F3, // v_add_f32 v4, -1.0, v4
  1685. 0x100A_06FF, // v_mul_f32 v5, reach / 2, v3
  1686. y,
  1687. 0x060A_0AF3, // v_add_f32 v5, -1.0, v5
  1688. 0x7E0C_02F0, // v_mov_b32 v6, 0.5
  1689. 0x7E0E_02F2, // v_mov_b32 v7, 1.0
  1690. 0x7E12_02FF, // v_mov_b32 v9, prim
  1691. prim,
  1692. 0xF800_0941, // exp prim v9, off, off, off done
  1693. 0x0000_0009,
  1694. 0xF800_08CF, // exp pos0 v4, v5, v6, v7 done
  1695. 0x0706_0504,
  1696. 0xBF81_0000, // s_endpgm
  1697. ];
  1698. let native = NativeProgram {
  1699. stage: HwStage::Ms,
  1700. wave64: false,
  1701. vgprs: 10,
  1702. layout: vec![],
  1703. used: vec![],
  1704. io: StageIo::Ms(crate::native::MeshIo {
  1705. outputs: vec![],
  1706. clip_cntl: 0,
  1707. threads: 32,
  1708. max_vertices: 32,
  1709. max_primitives: 32,
  1710. topology: 2,
  1711. lds_bytes: 0,
  1712. }),
  1713. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  1714. };
  1715. let position = SigElement {
  1716. name: "SV_Position".into(),
  1717. index: 0,
  1718. kind: 3,
  1719. comp: 9,
  1720. interp: 0,
  1721. row: Some(0),
  1722. col: 0,
  1723. cols: 4,
  1724. usage: 0xF,
  1725. half: false,
  1726. };
  1727. let osg1 = container::signature(&[position], false);
  1728. let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]);
  1729. let c = Container::parse(&bytes)?;
  1730. let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?;
  1731. let st = structure::structure(&p)?;
  1732. let res = resource::track(&p, &native.layout, native.stage, Some(&st))?;
  1733. let io = io::raise(&p, &native)?;
  1734. emit(&c, &native, &p, &st, &io, &res)
  1735. }
  1736. /// A primitive export's corners are 9-bit indices: the edge flag above
  1737. /// each (bits 9, 19, 29) is no part of it. Masking ten bits made a
  1738. /// flagged corner index 512 or more, past any mesh program's vertices
  1739. /// (the draw test below shows the triangle). Flagged, unflagged and
  1740. /// culled exports translate, and dxil.dll, where there is one, takes
  1741. /// each module.
  1742. #[test]
  1743. fn primitive_export_indices_drop_the_edge_flags() {
  1744. #[cfg(windows)]
  1745. let mut validator = super::validator::Validator::load(
  1746. super::validator::Validator::default_path().as_deref(),
  1747. )
  1748. .ok();
  1749. for prim in [
  1750. TRIANGLE,
  1751. TRIANGLE | EDGE_FLAGS,
  1752. TRIANGLE | EDGE_FLAGS | CULL,
  1753. ] {
  1754. let ms = triangle_mesh(prim).unwrap_or_else(|e| panic!("{prim:#x}: {e}"));
  1755. #[cfg(windows)]
  1756. if let Some(v) = validator.as_mut() {
  1757. v.validate(&mut ms.dxil.clone())
  1758. .unwrap_or_else(|e| panic!("{prim:#x}: {e}"));
  1759. }
  1760. }
  1761. }
  1762. /// A triangle mesh program on the host GPU and on WARP (where they have
  1763. /// mesh shaders): triangle (0, 1, 2) covers the target with its corners'
  1764. /// edge flags set as without them; with the culling bit, nothing is lit.
  1765. #[test]
  1766. #[cfg(windows)]
  1767. fn edge_flagged_triangles_draw_as_unflagged_ones() {
  1768. use super::host::{Draw, Host, Root};
  1769. use windows::Win32::Graphics::Direct3D12::{
  1770. D3D12_FEATURE_D3D12_OPTIONS7, D3D12_FEATURE_DATA_D3D12_OPTIONS7,
  1771. D3D12_MESH_SHADER_TIER_NOT_SUPPORTED, D3D12_SHADER_VISIBILITY_MESH,
  1772. };
  1773. let _one = super::valu_tests::ONE_AT_A_TIME
  1774. .lock()
  1775. .unwrap_or_else(|e| e.into_inner());
  1776. let ps = constant_color();
  1777. let mut ran = 0;
  1778. for (label, warp) in [("hardware", false), ("warp", true)] {
  1779. let Ok(host) = Host::new(warp) else {
  1780. eprintln!("no SM 6.6 {label} device; skipped");
  1781. continue;
  1782. };
  1783. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default();
  1784. // SAFETY: the query writes the structure of the given size.
  1785. let queried = unsafe {
  1786. host.device.CheckFeatureSupport(
  1787. D3D12_FEATURE_D3D12_OPTIONS7,
  1788. (&raw mut options).cast(),
  1789. size_of_val(&options) as u32,
  1790. )
  1791. };
  1792. if queried.is_err() || options.MeshShaderTier == D3D12_MESH_SHADER_TIER_NOT_SUPPORTED {
  1793. eprintln!("no mesh shaders on the {label} device; skipped");
  1794. continue;
  1795. }
  1796. for (prim, culled) in [
  1797. (TRIANGLE, false),
  1798. (TRIANGLE | EDGE_FLAGS, false),
  1799. (TRIANGLE | EDGE_FLAGS | CULL, true),
  1800. ] {
  1801. let ms = triangle_mesh(prim).unwrap();
  1802. let root = host
  1803. .root_signature_for(&[(&ms, D3D12_SHADER_VISIBILITY_MESH)])
  1804. .unwrap();
  1805. let pso = host
  1806. .mesh_pipeline_with(&root, &ms.dxil, &ps)
  1807. .unwrap_or_else(|e| panic!("{label}: mesh pipeline: {e}"));
  1808. let texels = host
  1809. .draw(
  1810. &root,
  1811. &pso,
  1812. &Draw {
  1813. roots: vec![(0, Root::Constants(vec![0]))],
  1814. textures: &[],
  1815. samplers: &[],
  1816. vertices: &[],
  1817. stride: 0,
  1818. size: (16, 16),
  1819. mesh_groups: 1,
  1820. },
  1821. )
  1822. .unwrap_or_else(|e| panic!("{label}: draw: {e}"));
  1823. let lit = texels.iter().filter(|t| t[3] != 0.0).count();
  1824. if culled {
  1825. assert_eq!(lit, 0, "{label}, {prim:#x}: a culled triangle lit texels");
  1826. continue;
  1827. }
  1828. assert!(
  1829. texels.iter().all(|t| *t == [1.0, 0.5, 0.25, 1.0]),
  1830. "{label}, {prim:#x}: {lit} of 256 texels lit"
  1831. );
  1832. }
  1833. eprintln!("{label}: edge-flagged triangles drew");
  1834. ran += 1;
  1835. }
  1836. if ran == 0 {
  1837. eprintln!("no device with mesh shaders; skipped");
  1838. }
  1839. }
  1840. /// A pixel shader interpolating at sample positions (PERSP_SAMPLE
  1841. /// barycentrics, `SPI_PS_INPUT_ADDR` bit 0) runs at sample frequency:
  1842. /// DXC's PSV0 says so in PSInfo.SampleFrequency (runtime info byte 1)
  1843. /// whenever an input is interpolated per sample.
  1844. #[test]
  1845. fn sample_interpolated_inputs_set_psv_sample_frequency() {
  1846. let words = [
  1847. 0xC808_0000u32, // v_interp_p1_f32 v2, v0, attr0.x
  1848. 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
  1849. 0xF800_180F,
  1850. 0x0202_0202, // exp mrt0, v2, v2, v2, v2 done vm
  1851. 0xBF81_0000,
  1852. ];
  1853. let psv_of = |input_addr: u32| {
  1854. let native = super::NativeProgram {
  1855. stage: super::HwStage::Ps,
  1856. wave64: false,
  1857. vgprs: 4,
  1858. layout: vec![],
  1859. used: vec![],
  1860. io: crate::native::StageIo::Ps {
  1861. inputs: vec![crate::native::PsInput {
  1862. usage: crate::native::Usage::Generic,
  1863. row: 0,
  1864. mask: 0b1111,
  1865. attr: 0,
  1866. flat: false,
  1867. fp16: false,
  1868. pack2: false,
  1869. row2: 0,
  1870. }],
  1871. input_addr,
  1872. db_shader_control: 0,
  1873. patches: vec![],
  1874. },
  1875. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  1876. };
  1877. let el = |name: &str, kind, usage| SigElement {
  1878. name: name.into(),
  1879. index: 0,
  1880. kind,
  1881. comp: 9,
  1882. interp: 0,
  1883. row: Some(0),
  1884. col: 0,
  1885. cols: 4,
  1886. usage,
  1887. half: false,
  1888. };
  1889. let isg1 = super::container::signature(&[el("TEXCOORD", 0, 0)], true);
  1890. let osg1 = super::container::signature(&[el("SV_Target", 16, 15)], false);
  1891. let bytes =
  1892. crate::dxbc::build(&[(super::FourCC::ISG1, &isg1), (super::FourCC::OSG1, &osg1)]);
  1893. let c = super::Container::parse(&bytes).unwrap();
  1894. let p = crate::ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap();
  1895. let st = crate::structure::structure(&p).unwrap();
  1896. let res =
  1897. crate::resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
  1898. let io = crate::io::raise(&p, &native).unwrap();
  1899. let out = super::emit(&c, &native, &p, &st, &io, &res).unwrap();
  1900. // dxil.dll, where there is one, checks PSV0 against the module.
  1901. #[cfg(windows)]
  1902. if let Ok(mut v) = super::validator::Validator::load(
  1903. super::validator::Validator::default_path().as_deref(),
  1904. ) {
  1905. v.validate(&mut out.dxil.clone()).unwrap();
  1906. }
  1907. let host = super::Container::parse(&out.dxil).unwrap();
  1908. host.part(super::FourCC::PSV0).unwrap().data.to_vec()
  1909. };
  1910. // Runtime info starts after its size; PSInfo is {DepthOutput, SampleFrequency}.
  1911. let center = psv_of(1 << 1);
  1912. assert_eq!(center[4 + 1], 0, "center interpolation is per pixel");
  1913. let sample = psv_of(1 << 0);
  1914. assert_eq!(sample[4 + 1], 1, "PSInfo.SampleFrequency");
  1915. }
  1916. /// A pixel shader reading channel z of an input whose element starts at
  1917. /// w. Looking the channel up subtracted the element's first channel
  1918. /// before checking the channel lies in it, so in a build with overflow
  1919. /// checks (tests, debug) any read below an element that starts at z or
  1920. /// w panicked, whichever row it was in (found by random-input testing).
  1921. #[test]
  1922. fn reading_a_channel_below_an_input_element_does_not_underflow() {
  1923. // v_interp_mov_f32 v3, p0, attr0.z; s_endpgm
  1924. let words = [0xC80E_0202u32, 0xBF81_0000];
  1925. let native = super::NativeProgram {
  1926. stage: super::HwStage::Ps,
  1927. wave64: false,
  1928. vgprs: 4,
  1929. layout: vec![],
  1930. used: vec![],
  1931. io: crate::native::StageIo::Ps {
  1932. inputs: vec![crate::native::PsInput {
  1933. usage: crate::native::Usage::Generic,
  1934. row: 0,
  1935. mask: 0b1000,
  1936. attr: 0,
  1937. flat: false,
  1938. fp16: false,
  1939. pack2: false,
  1940. row2: 0,
  1941. }],
  1942. input_addr: 0,
  1943. db_shader_control: 0,
  1944. patches: vec![],
  1945. },
  1946. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  1947. };
  1948. let w_only = SigElement {
  1949. name: "TEXCOORD".into(),
  1950. index: 0,
  1951. kind: 0,
  1952. comp: 9,
  1953. interp: 0,
  1954. row: Some(0),
  1955. col: 3,
  1956. cols: 1,
  1957. usage: 0,
  1958. half: false,
  1959. };
  1960. let isg1 = super::container::signature(&[w_only], true);
  1961. let bytes = crate::dxbc::build(&[(super::FourCC::ISG1, &isg1)]);
  1962. let c = super::Container::parse(&bytes).unwrap();
  1963. let p = crate::ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap();
  1964. let st = crate::structure::structure(&p).unwrap();
  1965. let res = crate::resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
  1966. let io = crate::io::raise(&p, &native).unwrap();
  1967. // Translated or refused with a reason; it must not panic.
  1968. let _ = super::emit(&c, &native, &p, &st, &io, &res);
  1969. }
  1970. #[test]
  1971. fn valu_div_f32_sequence_executes_on_gpu() {
  1972. let words: &[u32] = &[
  1973. 0xBE85_0380, // s_mov_b32 s5, 0
  1974. 0xF408_0202,
  1975. 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0x0
  1976. 0xF408_0302,
  1977. 0xFA00_0020, // s_load_dwordx4 s[12:15], s[4:5], 0x20
  1978. 0x340E_0083, // v_lshlrev_b32 v7, 3, v0
  1979. 0xE034_1000,
  1980. 0x8002_0107, // buffer_load_dwordx2 v[1:2], v7, s[8:11], 0 offen
  1981. 0xD56D_6A03,
  1982. 0x0406_0502, // v_div_scale_f32 v3, vcc_lo, v2, v2, v1
  1983. 0xD56D_1008,
  1984. 0x0406_0501, // v_div_scale_f32 v8, s16, v1, v2, v1
  1985. 0x7E08_5503, // v_rcp_f32 v4, v3
  1986. 0xD54B_0005,
  1987. 0x23CA_0903, // v_fma_f32 v5, -v3, v4, 1.0
  1988. 0xD54B_0004,
  1989. 0x0412_0905, // v_fma_f32 v4, v5, v4, v4
  1990. 0x100A_0908, // v_mul_f32 v5, v8, v4
  1991. 0xD54B_0006,
  1992. 0x2422_0B03, // v_fma_f32 v6, -v3, v5, v8
  1993. 0xD56F_0004,
  1994. 0x0416_0906, // v_div_fmas_f32 v4, v6, v4, v5
  1995. 0xD55F_0001,
  1996. 0x0406_0504, // v_div_fixup_f32 v1, v4, v2, v1
  1997. 0x340E_0082, // v_lshlrev_b32 v7, 2, v0
  1998. 0xE070_1000,
  1999. 0x8003_0107, // buffer_store_dword v1, v7, s[12:15], 0 offen
  2000. 0xBF81_0000, // s_endpgm
  2001. ];
  2002. let native = super::NativeProgram {
  2003. stage: super::HwStage::Cs,
  2004. wave64: false,
  2005. vgprs: 9,
  2006. layout: vec![
  2007. crate::RootParam {
  2008. root: crate::RootType::Constants,
  2009. table_offset_dwords: 0,
  2010. sgprs: 4,
  2011. base_register: 0,
  2012. user_data: 0,
  2013. slot: 0,
  2014. },
  2015. crate::RootParam {
  2016. root: crate::RootType::Table,
  2017. table_offset_dwords: 0,
  2018. sgprs: 1,
  2019. base_register: 0,
  2020. user_data: 4,
  2021. slot: 1,
  2022. },
  2023. ],
  2024. used: vec![
  2025. crate::UsedResource {
  2026. kind: crate::ResourceType::Srv,
  2027. root: crate::RootType::Table,
  2028. table_offset_dwords: 0,
  2029. lower_bound: 0,
  2030. stride: 4,
  2031. dwords: 4,
  2032. user_data: 4,
  2033. slot: 1,
  2034. },
  2035. crate::UsedResource {
  2036. kind: crate::ResourceType::Uav,
  2037. root: crate::RootType::Table,
  2038. table_offset_dwords: 8,
  2039. lower_bound: 0,
  2040. stride: 4,
  2041. dwords: 4,
  2042. user_data: 4,
  2043. slot: 1,
  2044. },
  2045. ],
  2046. io: crate::native::StageIo::Cs(crate::native::ComputeIo {
  2047. rsrc2: 5 << 1,
  2048. threads: [7, 1, 1],
  2049. }),
  2050. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  2051. };
  2052. let p = crate::ir::build(&native.code, native.wave64, native.vgprs).unwrap();
  2053. let res = crate::resource::track(&p, &native.layout, native.stage, None).unwrap();
  2054. let io = crate::io::raise(&p, &native).unwrap();
  2055. let st = crate::structure::structure(&p).unwrap();
  2056. let l = super::lower::lower(&super::lower::Parts {
  2057. native: &native,
  2058. p: &p,
  2059. st: &st,
  2060. io: &io,
  2061. res: &res,
  2062. inputs: Vec::new(),
  2063. outputs: Vec::new(),
  2064. prims: Vec::new(),
  2065. mesh_stride: 0,
  2066. })
  2067. .unwrap();
  2068. let mut dxil = l.dxil;
  2069. #[cfg(windows)]
  2070. if let Ok(mut v) = super::validator::Validator::load(
  2071. super::validator::Validator::default_path().as_deref(),
  2072. ) {
  2073. v.validate(&mut dxil).unwrap();
  2074. }
  2075. #[cfg(windows)]
  2076. if let Ok(host) = super::host::Host::new(false) {
  2077. let cs = super::HostShader {
  2078. stage: super::HwStage::Cs,
  2079. dxil,
  2080. user_data: l.user_data,
  2081. samplers: Vec::new(),
  2082. static_samplers: Vec::new(),
  2083. root_cbvs: l.root_cbvs,
  2084. root_srvs: l.root_srvs,
  2085. root_uavs: l.root_uavs,
  2086. root_indexed_views: Vec::new(),
  2087. };
  2088. let (root, pso) = host.compute_pipeline(&cs).unwrap();
  2089. let inputs: Vec<u32> = [
  2090. 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,
  2091. ]
  2092. .into_iter()
  2093. .map(f32::to_bits)
  2094. .collect();
  2095. let out = host
  2096. .dispatch(
  2097. &root,
  2098. &pso,
  2099. &super::host::Dispatch {
  2100. roots: vec![(0, super::host::Root::Constants(vec![0, 0, 0, 0, 0]))],
  2101. views: &[
  2102. super::host::View::Buffer {
  2103. data: &inputs,
  2104. stride: super::host::Stride::Raw,
  2105. },
  2106. super::host::View::RawUav(64),
  2107. ],
  2108. samplers: &[],
  2109. groups: [1, 1, 1],
  2110. },
  2111. )
  2112. .unwrap();
  2113. let got: Vec<f32> = out[0][..7].iter().copied().map(f32::from_bits).collect();
  2114. assert!((got[0] - (7.0f32 / 3.0)).abs() < 1e-6, "got {:?}", got);
  2115. assert_eq!(out[0][1], (-1.0f32 / 1e-40).to_bits());
  2116. assert!(
  2117. (got[2] - 1e-35).abs() <= 1e-40,
  2118. "lane 2 got {:?} ({:#x})",
  2119. got[2],
  2120. out[0][2]
  2121. );
  2122. assert!(
  2123. (got[3] - 10.0).abs() < 1e-5,
  2124. "lane 3 got {:?} ({:#x})",
  2125. got[3],
  2126. out[0][3]
  2127. );
  2128. assert_eq!(out[0][4], 0xFFC0_0000);
  2129. assert_eq!(out[0][5], (-1.0f32 / 0.0).to_bits());
  2130. assert!(
  2131. (got[6] - (-1.0)).abs() < 1e-6,
  2132. "lane 6 got {:?} ({:#x})",
  2133. got[6],
  2134. out[0][6]
  2135. );
  2136. }
  2137. }
  2138. }
  2139. #[cfg(test)]
  2140. mod atomic_tests {
  2141. use super::*;
  2142. use crate::native::{ComputeIo, RootParam, StageIo};
  2143. #[test]
  2144. fn heap_texture_atomic_widths() {
  2145. // A synthetic compute shader loads a 2D UAV from a root table,
  2146. // compares or adds at (0, 0), then uses the returned register(s).
  2147. for (opcode, mask, wide) in [
  2148. (16u32, 3, false),
  2149. (16, 15, true),
  2150. (17, 1, false),
  2151. (17, 3, true),
  2152. ] {
  2153. let words = [
  2154. 0xBE81_0380, // s_mov_b32 s1, 0 (table address high)
  2155. 0xF40C_0200,
  2156. 0xFA00_0000, // s_load_dwordx8 s[8:15], s[0:1], 0
  2157. 0x7E00_0280,
  2158. 0x7E02_0280, // v0, v1 = coordinates
  2159. 0x7E04_0281,
  2160. 0x7E06_0282,
  2161. 0x7E08_0283,
  2162. 0x7E0A_0284, // v2..v5 = 1..4
  2163. 0xF000_2008 | opcode << 18 | mask << 8,
  2164. 0x0002_0200,
  2165. // Use the old value in a second atomic at the same location.
  2166. 0xF044_0008 | (if wide { 3 } else { 1 }) << 8,
  2167. 0x0002_0200,
  2168. 0xBF81_0000,
  2169. ];
  2170. let native = NativeProgram {
  2171. stage: HwStage::Cs,
  2172. wave64: false,
  2173. vgprs: 6,
  2174. layout: vec![RootParam {
  2175. root: RootType::Table,
  2176. table_offset_dwords: 0,
  2177. sgprs: 1,
  2178. base_register: 0,
  2179. user_data: 0,
  2180. slot: 0,
  2181. }],
  2182. used: vec![],
  2183. io: StageIo::Cs(ComputeIo {
  2184. rsrc2: 2,
  2185. threads: [32, 1, 1],
  2186. }),
  2187. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  2188. };
  2189. let p = ir::build(&native.code, false, native.vgprs).unwrap();
  2190. let bytes = crate::dxbc::build(&[]);
  2191. let shader = emit(
  2192. &Container::parse(&bytes).unwrap(),
  2193. &native,
  2194. &p,
  2195. &structure::structure(&p).unwrap(),
  2196. &io::raise(&p, &native).unwrap(),
  2197. &resource::track(&p, &native.layout, native.stage, None).unwrap(),
  2198. )
  2199. .unwrap();
  2200. let container = Container::parse(&shader.dxil).unwrap();
  2201. let features = u64::from_le_bytes(
  2202. container
  2203. .part(FourCC::SFI0)
  2204. .unwrap()
  2205. .data
  2206. .try_into()
  2207. .unwrap(),
  2208. );
  2209. let required = 0x1040_8000; // heap atomics, typed atomics, Int64Ops
  2210. assert_eq!(features & required, if wide { required } else { 0 });
  2211. #[cfg(windows)]
  2212. if let Ok(mut v) =
  2213. validator::Validator::load(validator::Validator::default_path().as_deref())
  2214. {
  2215. v.validate(&mut shader.dxil.clone()).unwrap();
  2216. }
  2217. }
  2218. }
  2219. }
  2220. #[cfg(test)]
  2221. mod barycentric_tests {
  2222. use super::container::SigElement;
  2223. use super::*;
  2224. use crate::native::{PsInput, StageIo, Usage};
  2225. /// `SPI_PS_INPUT_ADDR` bits: PERSP_CENTER, LINEAR_CENTER.
  2226. const PERSP_CENTER: u32 = 1 << 1;
  2227. const LINEAR_CENTER: u32 = 1 << 5;
  2228. /// `exp mrt0, v<r>, v<r>, v<r>, v<r> done vm`.
  2229. fn exp_mrt0(r: u32) -> [u32; 2] {
  2230. [0xF800_180F, r * 0x0101_0101]
  2231. }
  2232. /// VOP2 `v_add_f32 v<dst>, v<a>, v<b>`.
  2233. fn v_add_f32(dst: u32, a: u32, b: u32) -> u32 {
  2234. 3 << 25 | dst << 17 | b << 9 | (256 + a)
  2235. }
  2236. fn element(name: &str, kind: u8, row: u32) -> SigElement {
  2237. SigElement {
  2238. name: name.into(),
  2239. index: 0,
  2240. kind,
  2241. comp: 9,
  2242. interp: 0,
  2243. row: Some(row),
  2244. col: 0,
  2245. cols: 4,
  2246. usage: 0,
  2247. half: false,
  2248. }
  2249. }
  2250. /// Translates a pixel program with the input VGPRs `input_addr`
  2251. /// enables and one float4 TEXCOORD0 attribute (attr 0, row 0).
  2252. fn pixel(words: &[u32], input_addr: u32) -> Result<HostShader, ShaderError> {
  2253. pixel_with_inputs(words, input_addr, &[element("TEXCOORD", 0, 0)])
  2254. }
  2255. fn pixel_with_inputs(words: &[u32], input_addr: u32, inputs: &[container::SigElement]) -> Result<HostShader, ShaderError> {
  2256. let native = NativeProgram {
  2257. stage: HwStage::Ps,
  2258. wave64: false,
  2259. vgprs: 8,
  2260. layout: vec![],
  2261. used: vec![],
  2262. io: StageIo::Ps {
  2263. inputs: vec![PsInput {
  2264. usage: Usage::Generic,
  2265. row: 0,
  2266. mask: 0b1111,
  2267. attr: 0,
  2268. flat: false,
  2269. fp16: false,
  2270. pack2: false,
  2271. row2: 0,
  2272. }],
  2273. input_addr,
  2274. db_shader_control: 0,
  2275. patches: vec![],
  2276. },
  2277. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  2278. };
  2279. let mut target = element("SV_Target", 16, 0);
  2280. target.usage = 15;
  2281. let isg1 = container::signature(inputs, true);
  2282. let osg1 = container::signature(&[target], false);
  2283. let bytes = crate::dxbc::build(&[(FourCC::ISG1, &isg1), (FourCC::OSG1, &osg1)]);
  2284. let c = Container::parse(&bytes).unwrap();
  2285. let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?;
  2286. let res = resource::track(&p, &native.layout, native.stage, None)?;
  2287. let io = io::raise(&p, &native)?;
  2288. let st = structure::structure(&p)?;
  2289. emit(&c, &native, &p, &st, &io, &res)
  2290. }
  2291. #[test]
  2292. fn an_unused_packed_input_matches_its_provoking_vertex_sibling() {
  2293. let [e0, e1] = exp_mrt0(3);
  2294. // v_interp_mov_f32 v3, p0, attr0.z followed by exp mrt0.
  2295. let words = [0xC80E_0202, e0, e1, 0xBF81_0000];
  2296. let xy = container::SigElement { cols: 2, ..element("TEXCOORD", 0, 0) };
  2297. let zw = container::SigElement { col: 2, cols: 2, ..element("NORMAL", 0, 0) };
  2298. let shader = pixel_with_inputs(&words, PERSP_CENTER, &[xy, zw]).unwrap();
  2299. let c = Container::parse(&shader.dxil).unwrap();
  2300. let psv = c.part(FourCC::PSV0).unwrap().data;
  2301. for columns in [0x42, 0x62] {
  2302. let record = [1, 0, columns, 0, 3, 1];
  2303. assert!(psv.windows(record.len()).any(|w| w == record));
  2304. }
  2305. let inputs = c.part(FourCC::ISG1).unwrap().data;
  2306. assert_eq!((inputs[8 + 25], inputs[8 + 32 + 25]), (0, 4));
  2307. validate(&shader);
  2308. }
  2309. /// A pixel program's first-lane loop (no table entry in it, so not a waterfall the tracker
  2310. /// knows) asks for helper lanes, which is valid DXIL (upstream #946's program).
  2311. #[test]
  2312. fn a_pixel_first_lane_loop_serves_helper_lanes() {
  2313. let shader = pixel(
  2314. &[
  2315. 0xD765_0000, 0x0001_00C1, // v_mbcnt_lo_u32_b32 v0, -1, 0
  2316. 0x7E02_0280, // v_mov_b32 v1, 0
  2317. 0xBE97_037E, // s_mov_b32 s23, exec_lo
  2318. 0x7E18_0500, // v_readfirstlane_b32 s12, v0
  2319. 0x7D84_000C, // v_cmp_eq_u32 vcc, s12, v0
  2320. 0xBE95_3C6A, // s_and_saveexec_b32 s21, vcc_lo
  2321. 0xBF80_0000, // s_nop 0
  2322. 0x7E02_02FF, 0x3F80_0000, // v_mov_b32 v1, 1.0
  2323. 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21
  2324. 0xBF89_FFF8, // s_cbranch_execnz loop
  2325. 0xBEFE_0317, // s_mov_b32 exec_lo, s23
  2326. 0xF800_180F, 0x0101_0101, // exp mrt0 v1 v1 v1 v1 done vm
  2327. 0xBF81_0000, // s_endpgm
  2328. ],
  2329. 0,
  2330. )
  2331. .unwrap();
  2332. validate(&shader);
  2333. }
  2334. /// The translation's `SFI0` features and `ISG1` rows.
  2335. fn parts(shader: &HostShader) -> (u64, Vec<SigElement>) {
  2336. let c = Container::parse(&shader.dxil).unwrap();
  2337. let sfi0 = c.part(FourCC::SFI0).unwrap().data.try_into().unwrap();
  2338. (
  2339. u64::from_le_bytes(sfi0),
  2340. signature(c.part(FourCC::ISG1).unwrap().data).unwrap(),
  2341. )
  2342. }
  2343. fn validate(shader: &HostShader) {
  2344. #[cfg(windows)]
  2345. if let Ok(mut v) =
  2346. validator::Validator::load(validator::Validator::default_path().as_deref())
  2347. {
  2348. v.validate(&mut shader.dxil.clone()).unwrap();
  2349. }
  2350. let _ = shader;
  2351. }
  2352. /// Custom interpolation reads I and J (v0, v1 with PERSP_CENTER) as
  2353. /// plain floats: they are channels y and z of `SV_Barycentrics`, the
  2354. /// weights of vertices 1 and 2.
  2355. #[test]
  2356. fn barycentrics_read_as_values_are_sv_barycentrics() {
  2357. let [e0, e1] = exp_mrt0(2);
  2358. let words = [v_add_f32(2, 0, 1), e0, e1, 0xBF81_0000];
  2359. let shader = pixel(&words, PERSP_CENTER).unwrap();
  2360. let (features, inputs) = parts(&shader);
  2361. assert_ne!(features & 0x2_0000, 0, "no Barycentrics feature");
  2362. let bary: Vec<_> = inputs.iter().filter(|e| e.kind == 28).collect();
  2363. assert_eq!(bary.len(), 1, "{inputs:?}");
  2364. assert_eq!((bary[0].index, bary[0].col, bary[0].cols), (0, 0, 3));
  2365. // Not packed: the validator wants packing location -1.
  2366. assert_eq!(bary[0].row, None);
  2367. // Only y and z (I and J) are read.
  2368. let isg1 = Container::parse(&shader.dxil).unwrap();
  2369. let isg1 = isg1.part(FourCC::ISG1).unwrap().data;
  2370. let rw: Vec<u8> = (0..2).map(|k| isg1[8 + 32 * k + 25]).collect();
  2371. assert!(rw.contains(&0b110), "{rw:?}");
  2372. validate(&shader);
  2373. }
  2374. /// Two kinds of barycentrics read directly: one element per mode.
  2375. #[test]
  2376. fn two_barycentric_modes_get_two_elements() {
  2377. // v0-v1 perspective i, j; v2-v3 linear i, j.
  2378. let [e0, e1] = exp_mrt0(4);
  2379. let words = [v_add_f32(4, 0, 3), e0, e1, 0xBF81_0000];
  2380. let shader = pixel(&words, PERSP_CENTER | LINEAR_CENTER).unwrap();
  2381. let (_, inputs) = parts(&shader);
  2382. let mut indices: Vec<u32> = inputs
  2383. .iter()
  2384. .filter(|e| e.kind == 28)
  2385. .map(|e| e.index)
  2386. .collect();
  2387. indices.sort();
  2388. assert_eq!(indices, [0, 1], "{inputs:?}");
  2389. validate(&shader);
  2390. }
  2391. /// I and J only fed to `v_interp_*` stay host interpolation: no
  2392. /// barycentrics are declared.
  2393. #[test]
  2394. fn interpolation_alone_declares_no_barycentrics() {
  2395. let [e0, e1] = exp_mrt0(2);
  2396. let words = [
  2397. 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x
  2398. 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
  2399. e0,
  2400. e1,
  2401. 0xBF81_0000,
  2402. ];
  2403. let shader = pixel(&words, PERSP_CENTER).unwrap();
  2404. let (features, inputs) = parts(&shader);
  2405. assert_eq!(features & 0x2_0000, 0);
  2406. assert!(inputs.iter().all(|e| e.kind != 28), "{inputs:?}");
  2407. validate(&shader);
  2408. }
  2409. #[test]
  2410. fn a_standalone_first_half_reads_the_vertices() {
  2411. let shader = first_half_pixel(false);
  2412. let (_, inputs) = parts(&shader);
  2413. assert_eq!(inputs.iter().filter(|e| e.kind == 28).count(), 1);
  2414. assert_eq!(texcoord_mode(&shader), 1);
  2415. validate(&shader);
  2416. }
  2417. #[test]
  2418. fn a_first_half_read_beside_its_pair_keeps_its_partial_value() {
  2419. let shader = first_half_pixel(true);
  2420. assert_eq!(texcoord_mode(&shader), 1);
  2421. validate(&shader);
  2422. }
  2423. fn first_half_pixel(paired: bool) -> HostShader {
  2424. let [e0, e1] = exp_mrt0(2);
  2425. let mut words = vec![0xC808_0000]; // v_interp_p1_f32 v2, v0, attr0.x
  2426. if paired {
  2427. words.extend([
  2428. 0x7E06_0302, // v_mov_b32 v3, v2 (keep the partial value)
  2429. 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
  2430. v_add_f32(2, 2, 3),
  2431. ]);
  2432. }
  2433. words.extend([e0, e1, 0xBF81_0000]);
  2434. pixel(&words, PERSP_CENTER).unwrap()
  2435. }
  2436. #[test]
  2437. #[cfg(windows)]
  2438. fn first_half_values_render_on_hardware_and_warp() {
  2439. use super::bitcode::{Attr, Term};
  2440. use super::host::{Draw, Host};
  2441. use super::shader::Shader;
  2442. let _one = super::valu_tests::ONE_AT_A_TIME
  2443. .lock()
  2444. .unwrap_or_else(|e| e.into_inner());
  2445. // Pass POSITION and TEXCOORD through, with TEXCOORD in the same
  2446. // output row as the translated pixel shader's input signature.
  2447. let mut s = Shader::new(false);
  2448. s.inputs = vec![element("POSITION", 0, 0), element("TEXCOORD", 0, 1)];
  2449. for e in &mut s.inputs {
  2450. e.usage = 15;
  2451. }
  2452. s.outputs = vec![element("TEXCOORD", 0, 0), element("SV_Position", 3, 1)];
  2453. for (i, e) in s.outputs.iter_mut().enumerate() {
  2454. e.usage = 15;
  2455. e.interp = if i == 1 { 4 } else { 2 };
  2456. }
  2457. for row in 0..2 {
  2458. for col in 0..4 {
  2459. let args = [s.m.i32(row), s.m.i32(0), s.m.i8(col), s.m.undef(s.t.i32)];
  2460. let v = s.op(s.entry, "loadInput.f32", Attr::ReadNone, s.t.f32, 4, &args);
  2461. let args = [s.m.i32(1 - row), s.m.i32(0), s.m.i8(col), v];
  2462. s.op(
  2463. s.entry,
  2464. "storeOutput.f32",
  2465. Attr::NoUnwind,
  2466. s.t.void,
  2467. 5,
  2468. &args,
  2469. );
  2470. }
  2471. }
  2472. s.m.terminate(s.entry, Term::Ret);
  2473. let vs = HostShader {
  2474. stage: HwStage::Vs,
  2475. dxil: s.finish(),
  2476. user_data: Vec::new(),
  2477. samplers: Vec::new(),
  2478. static_samplers: Vec::new(),
  2479. root_cbvs: Vec::new(),
  2480. root_srvs: Vec::new(),
  2481. root_uavs: Vec::new(),
  2482. root_indexed_views: Vec::new(),
  2483. };
  2484. validate(&vs);
  2485. // One triangle covers an 8x8 target, with attribute values 2, 6, 10.
  2486. let vertices = [
  2487. -1.0, 1.0, 0.5, 1.0, 2.0, 0.0, 0.0, 0.0, -1.0, -3.0, 0.5, 1.0, 6.0, 0.0, 0.0, 0.0, 3.0,
  2488. 1.0, 0.5, 1.0, 10.0, 0.0, 0.0, 0.0,
  2489. ];
  2490. let mut ran = 0;
  2491. for (backend, warp) in [("hardware", false), ("WARP", true)] {
  2492. let Ok(host) = Host::new(warp) else { continue };
  2493. let mut options =
  2494. windows::Win32::Graphics::Direct3D12::D3D12_FEATURE_DATA_D3D12_OPTIONS3::default();
  2495. // SAFETY: a correctly sized output for the feature query.
  2496. unsafe {
  2497. host.device
  2498. .CheckFeatureSupport(
  2499. windows::Win32::Graphics::Direct3D12::D3D12_FEATURE_D3D12_OPTIONS3,
  2500. (&raw mut options).cast(),
  2501. size_of_val(&options) as u32,
  2502. )
  2503. .unwrap();
  2504. }
  2505. if !options.BarycentricsSupported.as_bool() {
  2506. eprintln!("no barycentrics on {backend}; skipped");
  2507. continue;
  2508. }
  2509. for paired in [false, true] {
  2510. let ps = first_half_pixel(paired);
  2511. validate(&ps);
  2512. let (root, pso) = host.pipeline(&vs, &ps).expect("interpolation pipeline");
  2513. let out = host
  2514. .draw(
  2515. &root,
  2516. &pso,
  2517. &Draw {
  2518. roots: Vec::new(),
  2519. textures: &[],
  2520. samplers: &[],
  2521. vertices: &vertices,
  2522. stride: 32,
  2523. size: (8, 8),
  2524. mesh_groups: 0,
  2525. },
  2526. )
  2527. .expect("draw partial interpolation");
  2528. for (n, texel) in out.iter().enumerate() {
  2529. let i = (n / 8) as f32 / 16.0 + 0.5 / 16.0;
  2530. let j = (n % 8) as f32 / 16.0 + 0.5 / 16.0;
  2531. let partial = 2.0 + i * 4.0;
  2532. let want = if paired {
  2533. partial + 2.0 + i * 4.0 + j * 8.0
  2534. } else {
  2535. partial
  2536. };
  2537. for &got in texel {
  2538. assert!(
  2539. (got - want).abs() < 1e-5,
  2540. "{backend} paired={paired} pixel={n}: got {got}, want {want}"
  2541. );
  2542. }
  2543. }
  2544. }
  2545. ran += 1;
  2546. eprintln!("partial interpolation renders correctly on {backend}");
  2547. }
  2548. if ran == 0 {
  2549. eprintln!("no SM 6.6 host with barycentrics; GPU checks skipped");
  2550. }
  2551. }
  2552. /// Both: the attribute is interpolated and J is used as a value.
  2553. #[test]
  2554. fn interpolation_and_a_barycentric_value_together() {
  2555. let [e0, e1] = exp_mrt0(3);
  2556. let words = [
  2557. 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x
  2558. 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
  2559. v_add_f32(3, 2, 1), // v3 = attribute + j
  2560. e0,
  2561. e1,
  2562. 0xBF81_0000,
  2563. ];
  2564. let shader = pixel(&words, PERSP_CENTER).unwrap();
  2565. let (features, inputs) = parts(&shader);
  2566. assert_ne!(features & 0x2_0000, 0);
  2567. assert_eq!(inputs.iter().filter(|e| e.kind == 28).count(), 1);
  2568. validate(&shader);
  2569. }
  2570. /// The `PSV0` interpolation mode of TEXCOORD0 (row 0, x-w, float).
  2571. fn texcoord_mode(shader: &HostShader) -> u8 {
  2572. let c = Container::parse(&shader.dxil).unwrap();
  2573. let psv = c.part(FourCC::PSV0).unwrap().data;
  2574. let row = [1, 0, 0x44, 0, 3];
  2575. let at = psv.windows(5).position(|w| w == row).unwrap();
  2576. psv[at + 5]
  2577. }
  2578. const S_ENDPGM: u32 = 0xBF81_0000;
  2579. /// An interpolation whose i is computed (`v_mul_f32 v3, 0.5, v0`) reads
  2580. /// the attribute's vertices: TEXCOORD0 becomes constant, read with
  2581. /// `attributeAtVertex`; i and j are `SV_Barycentrics` values.
  2582. #[test]
  2583. fn computed_barycentrics_read_the_vertices() {
  2584. let [e0, e1] = exp_mrt0(2);
  2585. let words = [
  2586. 0x1006_00F0, // v_mul_f32 v3, 0.5, v0
  2587. 0xC808_0003, // v_interp_p1_f32 v2, v3, attr0.x
  2588. 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
  2589. e0,
  2590. e1,
  2591. S_ENDPGM,
  2592. ];
  2593. let shader = pixel(&words, PERSP_CENTER).unwrap();
  2594. let (features, inputs) = parts(&shader);
  2595. assert_ne!(features & 0x2_0000, 0, "no Barycentrics feature");
  2596. assert_eq!(inputs.iter().filter(|e| e.kind == 28).count(), 1);
  2597. assert_eq!(texcoord_mode(&shader), 1);
  2598. validate(&shader);
  2599. }
  2600. /// Weights from constants alone: the vertices, no `SV_Barycentrics`.
  2601. #[test]
  2602. fn constant_weights_need_no_barycentrics() {
  2603. let [e0, e1] = exp_mrt0(2);
  2604. let words = [
  2605. 0x7E06_02F0, // v_mov_b32 v3, 0.5
  2606. 0xC808_0003, // v_interp_p1_f32 v2, v3, attr0.x
  2607. 0xC809_0003, // v_interp_p2_f32 v2, v3, attr0.x
  2608. e0,
  2609. e1,
  2610. S_ENDPGM,
  2611. ];
  2612. let shader = pixel(&words, PERSP_CENTER).unwrap();
  2613. let (features, inputs) = parts(&shader);
  2614. assert_ne!(features & 0x2_0000, 0, "no Barycentrics feature");
  2615. assert!(inputs.iter().all(|e| e.kind != 28), "{inputs:?}");
  2616. assert_eq!(texcoord_mode(&shader), 1);
  2617. validate(&shader);
  2618. }
  2619. /// The same attribute interpolated with the loaded i and j and with a
  2620. /// computed j: both from its vertices, the first weighed with
  2621. /// `SV_Barycentrics`.
  2622. #[test]
  2623. fn computed_and_loaded_barycentrics_on_one_attribute() {
  2624. let [e0, e1] = exp_mrt0(2);
  2625. let words = [
  2626. 0xC810_0100, // v_interp_p1_f32 v4, v0, attr0.y
  2627. 0xC811_0101, // v_interp_p2_f32 v4, v1, attr0.y
  2628. 0x1006_02F0, // v_mul_f32 v3, 0.5, v1
  2629. 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x
  2630. 0xC809_0003, // v_interp_p2_f32 v2, v3, attr0.x
  2631. v_add_f32(2, 2, 4),
  2632. e0,
  2633. e1,
  2634. S_ENDPGM,
  2635. ];
  2636. let shader = pixel(&words, PERSP_CENTER).unwrap();
  2637. let (_, inputs) = parts(&shader);
  2638. assert_eq!(inputs.iter().filter(|e| e.kind == 28).count(), 1);
  2639. assert_eq!(texcoord_mode(&shader), 1);
  2640. validate(&shader);
  2641. }
  2642. /// P10 of an attribute the program interpolates is P1 - P0.
  2643. #[test]
  2644. fn p10_of_an_interpolated_attribute() {
  2645. let [e0, e1] = exp_mrt0(2);
  2646. let words = [
  2647. 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x
  2648. 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
  2649. 0xC812_0000, // v_interp_mov_f32 v4, p10, attr0.x
  2650. v_add_f32(2, 2, 4),
  2651. e0,
  2652. e1,
  2653. S_ENDPGM,
  2654. ];
  2655. let shader = pixel(&words, PERSP_CENTER).unwrap();
  2656. assert_eq!(texcoord_mode(&shader), 1);
  2657. validate(&shader);
  2658. // Alone, what the hardware holds is not known.
  2659. let [e0, e1] = exp_mrt0(4);
  2660. let words = [0xC812_0000, e0, e1, S_ENDPGM];
  2661. assert!(pixel(&words, PERSP_CENTER).is_err());
  2662. }
  2663. }