valu_tests.rs 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939
  1. //! End-to-end tests of synthetic GFX10 VALU shaders lowered to DXIL, validated
  2. //! by `dxil.dll` when present, and executed on the host GPU and WARP.
  3. //!
  4. //! Covers RDNA2 hardware semantics that differ from naive DXIL lowering:
  5. //! `v_med3_f32`/`v_med3_f16` with NaN operands, `v_fract_f32`/`v_fract_f16`
  6. //! near `1.0`, turn-range reduction for `v_sin_*`/`v_cos_*`, and the LDS
  7. //! float atomics `ds_min_f32`/`ds_max_f32`.
  8. use super::host::{Dispatch, Host, Root, View};
  9. use super::{HostShader, lower, validator};
  10. use crate::native::{
  11. ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource,
  12. };
  13. use crate::{io, ir, resource, structure};
  14. const S_ENDPGM: u32 = 0xBF81_0000;
  15. /// SOP1 `s_mov_b32 sdst, src0`.
  16. const fn s_mov_b32(sdst: u8, src0: u8) -> u32 {
  17. 0xBE80_0000 | (sdst as u32) << 16 | 0x03 << 8 | src0 as u32
  18. }
  19. /// SOP2 `op sdst, src0, src1`.
  20. const fn sop2(op: u8, sdst: u8, src0: u8, src1: u8) -> u32 {
  21. 0x8000_0000
  22. | (op as u32 & 0x7F) << 23
  23. | (sdst as u32 & 0x7F) << 16
  24. | (src1 as u32) << 8
  25. | src0 as u32
  26. }
  27. /// SMEM `s_load_dwordx4 s[dst:dst+3], s[base:base+1], 0` (soffset = null).
  28. const fn s_load_dwordx4(dst: u8, base: u8) -> [u32; 2] {
  29. [
  30. 0x3D << 26 | 0x02 << 18 | (dst as u32) << 6 | (base as u32 >> 1),
  31. 125 << 25,
  32. ]
  33. }
  34. /// VOP1 `op vdst, src0` (`src0`: 0..105 = SGPR, 256..511 = VGPR).
  35. const fn vop1(op: u16, vdst: u8, src0: u16) -> u32 {
  36. 0x7E00_0000 | (vdst as u32) << 17 | (op as u32) << 9 | (src0 as u32 & 0x1FF)
  37. }
  38. /// VOP3 `op vdst, src0, src1, src2` (no modifiers).
  39. const fn vop3(op: u16, vdst: u8, src0: u16, src1: u16, src2: u16) -> [u32; 2] {
  40. vop3_mod(op, vdst, src0, src1, src2, 0, 0, 0, false)
  41. }
  42. /// VOP3 `op vdst, src0, src1, src2` with explicit `abs`, `neg`, `omod`, `clamp`.
  43. #[allow(clippy::too_many_arguments)]
  44. const fn vop3_mod(
  45. op: u16,
  46. vdst: u8,
  47. src0: u16,
  48. src1: u16,
  49. src2: u16,
  50. abs: u8,
  51. neg: u8,
  52. omod: u8,
  53. clamp: bool,
  54. ) -> [u32; 2] {
  55. [
  56. 0x35 << 26
  57. | (op as u32 & 0x3FF) << 16
  58. | (clamp as u32) << 15
  59. | (abs as u32 & 7) << 8
  60. | vdst as u32,
  61. (neg as u32 & 7) << 29
  62. | (omod as u32 & 3) << 27
  63. | (src0 as u32 & 0x1FF)
  64. | (src1 as u32 & 0x1FF) << 9
  65. | (src2 as u32 & 0x1FF) << 18,
  66. ]
  67. }
  68. /// MUBUF `buffer_store_dword vdata, off, s[srsrc:srsrc+3], 0 offset:byte_off`.
  69. const fn buffer_store_dword(vdata: u8, srsrc: u8, byte_off: u16) -> [u32; 2] {
  70. [
  71. 0x38 << 26 | 0x1C << 18 | (byte_off as u32 & 0xFFF),
  72. 0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8,
  73. ]
  74. }
  75. const fn sgpr(n: u8) -> u16 {
  76. n as u16
  77. }
  78. const fn vgpr(n: u8) -> u16 {
  79. 256 + n as u16
  80. }
  81. /// Builds and lowers a 1-thread synthetic RDNA2 compute shader that receives
  82. /// 4 dwords of root constants in `s0..s3`, runs `body` (leaving its result in
  83. /// `v0`), and stores `v0` to dword 0 of the raw UAV at heap index 0.
  84. fn build_valu_cs(body: &[u32]) -> HostShader {
  85. build_cs(body, 1, 0)
  86. }
  87. /// [`build_valu_cs`] with `threads` threads in x (thread index in `v0`
  88. /// on entry, before `body`) and `lds_bytes` of LDS (a multiple of 512).
  89. fn build_cs(body: &[u32], threads: u32, lds_bytes: u32) -> HostShader {
  90. let mut words = Vec::new();
  91. // s[4:5] = descriptor table address (heap index 0 -> byte offset 0).
  92. words.push(s_mov_b32(5, 0x80)); // inline constant 0
  93. words.extend_from_slice(&s_load_dwordx4(8, 4));
  94. // Copy root constants s0..s3 into v1..v4 so VALU instructions operate on
  95. // VGPRs just as they do in real shaders.
  96. for i in 0..4u8 {
  97. words.push(vop1(0x001, i + 1, sgpr(i))); // v_mov_b32
  98. }
  99. words.extend_from_slice(body);
  100. words.extend_from_slice(&buffer_store_dword(0, 8, 0));
  101. words.push(S_ENDPGM);
  102. let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
  103. let native = NativeProgram {
  104. stage: HwStage::Cs,
  105. wave64: false,
  106. vgprs: 8,
  107. layout: vec![
  108. RootParam {
  109. root: RootType::Constants,
  110. table_offset_dwords: 0,
  111. sgprs: 4,
  112. base_register: 0,
  113. user_data: 0,
  114. slot: 0,
  115. },
  116. RootParam {
  117. root: RootType::Table,
  118. table_offset_dwords: 0,
  119. sgprs: 1,
  120. base_register: 0,
  121. user_data: 4,
  122. slot: 1,
  123. },
  124. ],
  125. used: vec![UsedResource {
  126. kind: ResourceType::Uav,
  127. root: RootType::Table,
  128. table_offset_dwords: 0,
  129. lower_bound: 0,
  130. stride: 0,
  131. dwords: 4,
  132. user_data: 4,
  133. slot: 1,
  134. }],
  135. io: StageIo::Cs(ComputeIo {
  136. rsrc2: (5 << 1) | ((lds_bytes / 512) << 15), // 5 user SGPRs: s0..s4
  137. threads: [threads, 1, 1],
  138. }),
  139. code,
  140. };
  141. let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
  142. let st = structure::structure(&p).expect("structure");
  143. let res =
  144. resource::track(&p, &native.layout, native.stage, Some(&st)).expect("resource::track");
  145. let io = io::raise(&p, &native).expect("io::raise");
  146. let lowered = lower::lower(&lower::Parts {
  147. native: &native,
  148. p: &p,
  149. st: &st,
  150. io: &io,
  151. res: &res,
  152. inputs: Vec::new(),
  153. outputs: Vec::new(),
  154. prims: Vec::new(),
  155. mesh_stride: 0,
  156. })
  157. .expect("lower");
  158. let shader = HostShader {
  159. stage: HwStage::Cs,
  160. dxil: lowered.dxil,
  161. user_data: lowered.user_data,
  162. samplers: lowered.samplers,
  163. static_samplers: Vec::new(),
  164. root_cbvs: lowered.root_cbvs,
  165. root_srvs: lowered.root_srvs,
  166. root_uavs: lowered.root_uavs,
  167. root_indexed_views: res.root_indexed_views,
  168. };
  169. if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
  170. let mut copy = shader.dxil.clone();
  171. let ours = copy[4..20].to_vec();
  172. v.validate(&mut copy).expect("DXIL validation failed");
  173. assert_eq!(copy[4..20], ours[..], "container hash mismatch");
  174. }
  175. shader
  176. }
  177. /// One GPU test at a time. With these tests on the hardware adapter and WARP
  178. /// from several test threads at once, now and then none of their dispatches
  179. /// ever completes and the test binary hangs; and two GPU tests at once on
  180. /// WARP can end the test process with an access violation. Other GPU test
  181. /// modules take this lock too.
  182. pub(super) static ONE_AT_A_TIME: std::sync::Mutex<()> = std::sync::Mutex::new(());
  183. /// Runs `shader` on every available SM 6.6 host (hardware GPU and WARP) for
  184. /// each 4-dword input set and invokes `check(backend, case_index, inputs, result_dword)`.
  185. fn run_cases(
  186. shader: &HostShader,
  187. cases: &[[u32; 4]],
  188. check: impl FnMut(&str, usize, [u32; 4], u32),
  189. ) {
  190. run_cases_on(shader, cases, &[("hardware", false), ("warp", true)], check);
  191. }
  192. fn run_cases_on(
  193. shader: &HostShader,
  194. cases: &[[u32; 4]],
  195. devices: &[(&str, bool)],
  196. mut check: impl FnMut(&str, usize, [u32; 4], u32),
  197. ) {
  198. let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
  199. let mut ran = 0;
  200. for &(label, warp) in devices {
  201. let host = match Host::new(warp) {
  202. Ok(host) => host,
  203. Err(e) => {
  204. eprintln!("no SM 6.6 {label} device ({e}); skipped");
  205. continue;
  206. }
  207. };
  208. let (root, pso) = host
  209. .compute_pipeline(shader)
  210. .unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}"));
  211. for (i, &inputs) in cases.iter().enumerate() {
  212. let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
  213. for u in &shader.user_data {
  214. ud[u.index as usize] = match (u.root, u.slot) {
  215. (RootType::Constants, 0) => inputs[u.dword as usize],
  216. (RootType::Table, 1) => 0,
  217. other => panic!("unexpected user data {other:?}"),
  218. };
  219. }
  220. let out = host
  221. .dispatch(
  222. &root,
  223. &pso,
  224. &Dispatch {
  225. roots: vec![(0, Root::Constants(ud))],
  226. views: &[View::RawUav(1)],
  227. samplers: &[],
  228. groups: [1, 1, 1],
  229. },
  230. )
  231. .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}"));
  232. check(label, i, inputs, out[0][0]);
  233. }
  234. ran += 1;
  235. }
  236. if ran == 0 && devices.iter().all(|&(_, warp)| !warp) {
  237. // A case for the hardware adapter alone, on a machine without one.
  238. eprintln!("no SM 6.6 hardware device; a hardware-only case not run");
  239. return;
  240. }
  241. assert!(ran > 0, "no SM 6.6 device available ({devices:?})");
  242. }
  243. #[test]
  244. fn scalar_quad_masks_pack_nibbles_and_set_scc() {
  245. let pack_words = |opcode: u32| {
  246. [
  247. 0xBE90_0000 | opcode << 8, // s_quadmask s16, s0 (pairs for b64)
  248. sop2(0x0a, 18, 129, 128), // s_cselect_b32 s18, 1, 0
  249. sop2(0x1e, 18, 18, 144), // s_lshl_b32 s18, s18, 16
  250. sop2(0x10, 16, 16, 18), // s_or_b32 s16, s16, s18
  251. vop1(1, 0, sgpr(16)), // v_mov_b32 v0, s16
  252. ]
  253. };
  254. let cases = [
  255. ([0, 0, 0, 0], [0, 0]),
  256. ([0x8000_0420, 0x0100_0001, 0, 0], [0x1_0086, 0x1_4186]),
  257. ([0, 0x8000_0000, 0, 0], [0, 0x1_8000]),
  258. ([u32::MAX, u32::MAX, 0, 0], [0x1_00ff, 0x1_ffff]),
  259. ];
  260. let inputs = cases.map(|(input, _)| input);
  261. for (wide, opcode) in [0x2c, 0x2d].into_iter().enumerate() {
  262. let shader = build_valu_cs(&pack_words(opcode));
  263. run_cases(&shader, &inputs, |backend, i, _, got| {
  264. assert_eq!(got, cases[i].1[wide], "{backend}, opcode {opcode:#x}");
  265. });
  266. }
  267. let high = build_valu_cs(&[
  268. 0xBE90_2D00, // s_quadmask_b64 s[16:17], s[0:1]
  269. vop1(1, 0, sgpr(17)),
  270. ]);
  271. run_cases(&high, &inputs, |backend, _, _, got| {
  272. assert_eq!(got, 0, "{backend}: high dword");
  273. });
  274. }
  275. fn is_f16_nan(bits: u16) -> bool {
  276. (bits & 0x7FFF) > 0x7C00
  277. }
  278. fn f16_to_f32(bits: u16) -> f32 {
  279. let sign = u32::from(bits >> 15) << 31;
  280. let exp = (bits >> 10) & 0x1F;
  281. let mant = bits & 0x3FF;
  282. let f32_bits = match exp {
  283. 0 => {
  284. if mant == 0 {
  285. sign
  286. } else {
  287. let mut m = u32::from(mant);
  288. let mut e = 127 - 14;
  289. while (m & 0x400) == 0 {
  290. m <<= 1;
  291. e -= 1;
  292. }
  293. sign | (e << 23) | ((m & 0x3FF) << 13)
  294. }
  295. }
  296. 0x1F => sign | (0xFF << 23) | (u32::from(mant) << 13),
  297. _ => sign | ((u32::from(exp) + 112) << 23) | (u32::from(mant) << 13),
  298. };
  299. f32::from_bits(f32_bits)
  300. }
  301. /// MTBUF `op vdata, off, s[srsrc:srsrc+3], 0 format:format` (at byte 0).
  302. const fn mtbuf(op: u8, vdata: u8, srsrc: u8, format: u8) -> [u32; 2] {
  303. [
  304. 0x3A << 26 | (format as u32 & 0x7F) << 19 | (op as u32 & 7) << 16,
  305. 0x80 << 24
  306. | (op as u32 >> 3 & 1) << 21
  307. | (srsrc as u32 >> 2 & 0x1F) << 16
  308. | (vdata as u32) << 8,
  309. ]
  310. }
  311. /// Stores `v1` to the buffer, then reads it back into `v0` with the tbuffer
  312. /// load `op` in buffer format `format`.
  313. fn tbuffer_load_of_v1(op: u8, format: u8) -> HostShader {
  314. let mut body = buffer_store_dword(1, 8, 0).to_vec();
  315. body.extend(mtbuf(op, 0, 8, format));
  316. build_valu_cs(&body)
  317. }
  318. #[test]
  319. fn tbuffer_d16_loads_pack_two_channels_per_dword() {
  320. // tbuffer_load_format_d16_x and tbuffer_load_format_d16_xy.
  321. let (x, xy) = (8, 9);
  322. // (opcode, format, dword stored, dword loaded)
  323. let cases: &[(u8, u8, u32, u32)] = &[
  324. // 16_16_FLOAT: the f16 pair (1.0, 2.0) as it was stored.
  325. (xy, 29, 0x4000_3C00, 0x4000_3C00),
  326. // 16_16_UINT: the 16-bit integers as they were stored.
  327. (xy, 27, 0xBEEF_1234, 0xBEEF_1234),
  328. // 16_16_UNORM: 0.0 and 1.0, as f16.
  329. (xy, 23, 0xFFFF_0000, 0x3C00_0000),
  330. // 16_FLOAT, one channel: the high half is 0.
  331. (x, 13, 0x4000_3C00, 0x0000_3C00),
  332. ];
  333. for &(op, format, stored, want) in cases {
  334. let shader = tbuffer_load_of_v1(op, format);
  335. run_cases(&shader, &[[stored, 0, 0, 0]], |backend, _, _, got| {
  336. assert_eq!(
  337. got, want,
  338. "{backend}: d16 opcode {op} format {format} of {stored:#010x} = {got:#010x}, want {want:#010x}",
  339. );
  340. });
  341. }
  342. }
  343. #[test]
  344. fn normalized_buffer_formats_load_their_ends_exactly() {
  345. // tbuffer_load_format_x.
  346. let x = 0;
  347. // (format, dword stored, value loaded)
  348. let cases: &[(u8, u32, f32)] = &[
  349. (1, 0xFF, 1.0), // 8_UNORM
  350. (7, 0xFFFF, 1.0), // 16_UNORM
  351. (2, 0x7F, 1.0), // 8_SNORM: the top, the one above the lowest, the lowest
  352. (2, 0x81, -1.0),
  353. (2, 0x80, -1.0),
  354. (8, 0x7FFF, 1.0), // 16_SNORM
  355. (8, 0x8001, -1.0),
  356. (8, 0x8000, -1.0),
  357. ];
  358. for &(format, stored, want) in cases {
  359. let shader = tbuffer_load_of_v1(x, format);
  360. run_cases(&shader, &[[stored, 0, 0, 0]], |backend, _, _, got| {
  361. assert_eq!(
  362. got,
  363. want.to_bits(),
  364. "{backend}: format {format} of {stored:#x} = {got:#010x}, want {want}",
  365. );
  366. });
  367. }
  368. }
  369. #[test]
  370. fn packed_add_selects_halves_of_inline_constants() {
  371. // Add the inline constant 1/(2*pi) to v1 (zero) to read back its two halves.
  372. // The same GFX10 source field (248) has a different bit pattern for a
  373. // packed floating-point and a packed integer instruction.
  374. let cases = [
  375. // v_pk_add_f16 v0, 0x3118, v1
  376. ([0xcc0f4000, 0x1a0202f8], 0x0000_3118),
  377. // v_pk_add_f16 v0, 0x3118, v1 op_sel_hi:[0,1] (use low twice)
  378. ([0xcc0f4000, 0x120202f8], 0x3118_3118),
  379. // v_pk_add_u16 v0, 0x3e22f983, v1
  380. ([0xcc0a4000, 0x1a0202f8], 0x3e22_f983),
  381. ];
  382. for (words, expected) in cases {
  383. let shader = build_valu_cs(&words);
  384. run_cases(&shader, &[[0; 4]], |backend, _, _, got| {
  385. assert_eq!(got, expected, "{backend}: {words:08x?}");
  386. });
  387. }
  388. }
  389. /// The float `v_cvt_f32_f64` gives for `x`: Rust's rounding (to nearest
  390. /// even), with results below the smallest normal float flushed to signed
  391. /// zero as the console's default float mode does.
  392. fn cvt_f32_f64_reference(x: f64) -> u32 {
  393. let r = x as f32;
  394. if r.is_subnormal() || (r == 0.0 && x != 0.0) {
  395. r.to_bits() & 0x8000_0000
  396. } else {
  397. r.to_bits()
  398. }
  399. }
  400. #[test]
  401. #[ignore = "expects results below the smallest normal float flushed to zero; the IEEE lowering (v_cvt_f32_f64_matches_ieee754) is kept until the console's mode is checked"]
  402. fn v_cvt_f32_f64_rounds_to_nearest_even() {
  403. // v_cvt_f32_f64 v0, v[1:2] (VOP1 opcode 0x0f)
  404. let shader = build_valu_cs(&[vop1(0x00f, 0, vgpr(1))]);
  405. let tie_even = 1.0f64 + f64::from(f32::EPSILON) / 2.0; // ties to 1.0
  406. let tie_odd = 1.0f64 + 1.5 * f64::from(f32::EPSILON); // ties up to 1 + 2 ulp
  407. let values = [
  408. 0.0,
  409. -0.0,
  410. 1.0,
  411. -2.5,
  412. std::f64::consts::PI,
  413. 1.0e-3,
  414. 123_456_789.123,
  415. tie_even,
  416. tie_odd,
  417. 1.0 + f64::from(f32::EPSILON) * 0.75,
  418. f64::from(f32::MAX),
  419. f64::from(f32::MAX) * 1.000_000_1, // rounds to infinity
  420. 1.0e300,
  421. -1.0e300,
  422. 1.0e-40, // a float denormal: flushed
  423. -1.0e-300,
  424. f64::from(f32::MIN_POSITIVE),
  425. f64::INFINITY,
  426. f64::NEG_INFINITY,
  427. f64::NAN,
  428. ];
  429. let inputs: Vec<[u32; 4]> = values
  430. .iter()
  431. .map(|x| {
  432. let b = x.to_bits();
  433. [b as u32, (b >> 32) as u32, 0, 0]
  434. })
  435. .collect();
  436. run_cases(&shader, &inputs, |backend, i, _, got| {
  437. let x = values[i];
  438. if x.is_nan() {
  439. assert!(f32::from_bits(got).is_nan(), "{backend}: cvt({x}) = {got:#010x}, want NaN");
  440. return;
  441. }
  442. let want = cvt_f32_f64_reference(x);
  443. assert_eq!(got, want, "{backend}: cvt({x:e}) = {got:#010x}, want {want:#010x}");
  444. });
  445. }
  446. /// The lane `v_permlane16_b32` (`cross` false) or `v_permlanex16_b32` reads
  447. /// for `lane`, with selector dwords `s1` (lanes 0-7 of a row) and `s2`.
  448. fn permlane_source(lane: u32, s1: u32, s2: u32, cross: bool) -> u32 {
  449. let sel = u64::from(s1) | u64::from(s2) << 32;
  450. let pick = (sel >> (4 * (lane & 15)) & 15) as u32;
  451. let row = if cross {
  452. (lane & !31) | ((lane & 16) ^ 16)
  453. } else {
  454. lane & !15
  455. };
  456. row | pick
  457. }
  458. #[test]
  459. fn v_permlane16_and_x16_read_the_lanes_their_selectors_pick() {
  460. // 32 lanes, each with its lane number in v0; v1 = permute(v0, s0, s1);
  461. // lane `read` of v1 into s12, then into v0 for the store.
  462. let selectors: [(u32, u32); 3] = [
  463. (0x7654_3210, 0xfedc_ba98), // identity within the row
  464. (0x89ab_cdef, 0x0123_4567), // reversed
  465. (0x1111_1111, 0xf0f0_f0f0), // repeats
  466. ];
  467. for (op, cross) in [(0x377u16, false), (0x378, true)] {
  468. for read in [0u8, 5, 15, 16, 22, 31] {
  469. let mut body = Vec::new();
  470. body.extend_from_slice(&vop3(op, 1, vgpr(0), sgpr(0), sgpr(1)));
  471. // v_readlane_b32 s12, v1, read (inline constant 128 + read)
  472. body.extend_from_slice(&vop3(0x360, 12, vgpr(1), 128 + u16::from(read), 0));
  473. body.push(vop1(0x001, 0, sgpr(12))); // v_mov_b32 v0, s12
  474. let shader = build_cs(&body, 32, 0);
  475. let inputs: Vec<[u32; 4]> = selectors.iter().map(|&(a, b)| [a, b, 0, 0]).collect();
  476. // Cross-lane code declares WaveSize(32), which WARP's pipeline
  477. // creation refuses: hardware only.
  478. run_cases_on(&shader, &inputs, &[("hardware", false)], |backend, i, inp, got| {
  479. let want = permlane_source(u32::from(read), inp[0], inp[1], cross);
  480. assert_eq!(
  481. got, want,
  482. "{backend}: op {op:#x} selectors {:08x?}, lane {read}",
  483. selectors[i]
  484. );
  485. });
  486. }
  487. }
  488. }
  489. #[test]
  490. fn v_med3_f32_matches_rdna2_with_nan() {
  491. // v_med3_f32 v0, v1, v2, v3 (VOP3 opcode 0x157)
  492. let shader = build_valu_cs(&vop3(0x157, 0, vgpr(1), vgpr(2), vgpr(3)));
  493. let nan = f32::NAN.to_bits();
  494. let f = f32::to_bits;
  495. let cases: &[([u32; 4], Option<f32>)] = &[
  496. // Normal medians (all orderings).
  497. ([f(1.0), f(2.0), f(3.0), 0], Some(2.0)),
  498. ([f(3.0), f(1.0), f(2.0), 0], Some(2.0)),
  499. ([f(-5.0), f(0.0), f(5.0), 0], Some(0.0)),
  500. ([f(1.0), f(1.0), f(2.0), 0], Some(1.0)),
  501. // One NaN: RDNA2 returns min3 of the non-NaN operands.
  502. ([f(1.0), f(2.0), nan, 0], Some(1.0)),
  503. ([nan, f(1.0), f(0.0), 0], Some(0.0)),
  504. ([nan, f(0.0), f(1.0), 0], Some(0.0)),
  505. ([f(2.0), nan, f(1.0), 0], Some(1.0)),
  506. ([f(-3.0), nan, f(4.0), 0], Some(-3.0)),
  507. // Two NaNs: returns the sole non-NaN operand.
  508. ([nan, f(5.0), nan, 0], Some(5.0)),
  509. ([nan, nan, f(-2.0), 0], Some(-2.0)),
  510. ([f(7.0), nan, nan, 0], Some(7.0)),
  511. // Three NaNs: returns NaN.
  512. ([nan, nan, nan, 0], None),
  513. ];
  514. let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect();
  515. run_cases(&shader, &inputs, |backend, i, inp, got| {
  516. let expect = cases[i].1;
  517. let got_f = f32::from_bits(got);
  518. match expect {
  519. Some(want) => assert_eq!(
  520. got_f,
  521. want,
  522. "{backend}: v_med3_f32({:?}, {:?}, {:?}) = {got_f} ({got:#010x}), want {want}",
  523. f32::from_bits(inp[0]),
  524. f32::from_bits(inp[1]),
  525. f32::from_bits(inp[2]),
  526. ),
  527. None => assert!(
  528. got_f.is_nan(),
  529. "{backend}: v_med3_f32(NaN, NaN, NaN) = {got_f} ({got:#010x}), want NaN",
  530. ),
  531. }
  532. });
  533. }
  534. /// RDNA2 orders -0 below +0 in its maximums and minimums; DXIL's FMax and
  535. /// FMin compare and select, which can give either zero.
  536. #[test]
  537. fn max_and_min_order_negative_zero_below_positive_zero() {
  538. let (pz, nz) = (0_u32, 0x8000_0000_u32);
  539. // Each case has a -0 and a +0 among its first two operands.
  540. let cases = [
  541. [nz, pz, nz, 0],
  542. [pz, nz, nz, 0],
  543. [nz, pz, pz, 0],
  544. [pz, nz, pz, 0],
  545. ];
  546. let ops = [
  547. ("v_max_f32", 0x110, pz),
  548. ("v_min_f32", 0x10F, nz),
  549. ("v_max3_f32", 0x154, pz),
  550. ("v_min3_f32", 0x151, nz),
  551. ];
  552. for (name, op, want) in ops {
  553. let shader = build_valu_cs(&vop3(op, 0, vgpr(1), vgpr(2), vgpr(3)));
  554. run_cases(&shader, &cases, |backend, _, inp, got| {
  555. assert_eq!(got, want, "{backend}: {name} {inp:x?}");
  556. });
  557. }
  558. }
  559. /// The f16 forms go through the same `max_min` helper, after widening to f32.
  560. #[test]
  561. fn f16_max_and_min_order_negative_zero_below_positive_zero() {
  562. let (pz, nz) = (0_u32, 0x8000_u32);
  563. let cases = [
  564. [nz, pz, nz, 0],
  565. [pz, nz, nz, 0],
  566. [nz, pz, pz, 0],
  567. [pz, nz, pz, 0],
  568. ];
  569. let ops = [
  570. ("v_max_f16", 0x139, pz),
  571. ("v_min_f16", 0x13A, nz),
  572. ("v_max3_f16", 0x354, pz),
  573. ("v_min3_f16", 0x351, nz),
  574. ];
  575. for (name, op, want) in ops {
  576. let shader = build_valu_cs(&vop3(op, 0, vgpr(1), vgpr(2), vgpr(3)));
  577. run_cases(&shader, &cases, |backend, _, inp, got| {
  578. // The f16 result is the low half of v0.
  579. assert_eq!(got & 0xFFFF, want, "{backend}: {name} {inp:x?}");
  580. });
  581. }
  582. }
  583. #[test]
  584. fn v_min3_max3_med3_integer_forms_match_rdna2() {
  585. // v_{min3,max3,med3}_{i32,u32} v0, v1, v2, v3 (VOP3 0x152..0x159).
  586. type Pick = fn([u32; 3]) -> u32;
  587. let ops: [(&str, u16, Pick); 6] = [
  588. ("v_min3_i32", 0x152, |t| {
  589. t.into_iter().min_by_key(|&x| x as i32).unwrap()
  590. }),
  591. ("v_min3_u32", 0x153, |t| t.into_iter().min().unwrap()),
  592. ("v_max3_i32", 0x155, |t| {
  593. t.into_iter().max_by_key(|&x| x as i32).unwrap()
  594. }),
  595. ("v_max3_u32", 0x156, |t| t.into_iter().max().unwrap()),
  596. ("v_med3_i32", 0x158, |mut t| {
  597. t.sort_by_key(|&x| x as i32);
  598. t[1]
  599. }),
  600. ("v_med3_u32", 0x159, |mut t| {
  601. t.sort_unstable();
  602. t[1]
  603. }),
  604. ];
  605. // Every ordering of three values, with the sign bit set on some so that
  606. // the signed and unsigned answers differ.
  607. let values = [0u32, 1, 0x7FFF_FFFF, 0x8000_0000, 0xFFFF_FFFF];
  608. let mut cases = Vec::new();
  609. for a in values {
  610. for b in values {
  611. for c in values {
  612. cases.push([a, b, c, 0]);
  613. }
  614. }
  615. }
  616. for (name, op, pick) in ops {
  617. let shader = build_valu_cs(&vop3(op, 0, vgpr(1), vgpr(2), vgpr(3)));
  618. run_cases(&shader, &cases, |backend, _, inp, got| {
  619. let want = pick([inp[0], inp[1], inp[2]]);
  620. assert_eq!(
  621. got, want,
  622. "{backend}: {name}({:#010x}, {:#010x}, {:#010x}) = {got:#010x}, want {want:#010x}",
  623. inp[0], inp[1], inp[2],
  624. );
  625. });
  626. }
  627. }
  628. #[test]
  629. fn v_min3_max3_med3_integer_forms_match_rdna2() {
  630. // v_{min3,max3,med3}_{i32,u32} v0, v1, v2, v3 (VOP3 0x152..0x159).
  631. let ops: [(&str, u16, fn([u32; 3]) -> u32); 6] = [
  632. ("v_min3_i32", 0x152, |t| {
  633. t.into_iter().min_by_key(|&x| x as i32).unwrap()
  634. }),
  635. ("v_min3_u32", 0x153, |t| t.into_iter().min().unwrap()),
  636. ("v_max3_i32", 0x155, |t| {
  637. t.into_iter().max_by_key(|&x| x as i32).unwrap()
  638. }),
  639. ("v_max3_u32", 0x156, |t| t.into_iter().max().unwrap()),
  640. ("v_med3_i32", 0x158, |mut t| {
  641. t.sort_by_key(|&x| x as i32);
  642. t[1]
  643. }),
  644. ("v_med3_u32", 0x159, |mut t| {
  645. t.sort_unstable();
  646. t[1]
  647. }),
  648. ];
  649. // Every ordering of three values, with the sign bit set on some so that
  650. // the signed and unsigned answers differ.
  651. let values = [0u32, 1, 0x7FFF_FFFF, 0x8000_0000, 0xFFFF_FFFF];
  652. let mut cases = Vec::new();
  653. for a in values {
  654. for b in values {
  655. for c in values {
  656. cases.push([a, b, c, 0]);
  657. }
  658. }
  659. }
  660. for (name, op, pick) in ops {
  661. let shader = build_valu_cs(&vop3(op, 0, vgpr(1), vgpr(2), vgpr(3)));
  662. run_cases(&shader, &cases, |backend, _, inp, got| {
  663. let want = pick([inp[0], inp[1], inp[2]]);
  664. assert_eq!(
  665. got, want,
  666. "{backend}: {name}({:#010x}, {:#010x}, {:#010x}) = {got:#010x}, want {want:#010x}",
  667. inp[0], inp[1], inp[2],
  668. );
  669. });
  670. }
  671. }
  672. #[test]
  673. fn v_med3_f16_matches_rdna2_with_nan() {
  674. // v_med3_f16 v0, v1, v2, v3 (VOP3 opcode 0x357)
  675. let shader = build_valu_cs(&vop3(0x357, 0, vgpr(1), vgpr(2), vgpr(3)));
  676. let h0 = 0x0000u32; // 0.0
  677. let h1 = 0x3C00u32; // 1.0
  678. let h2 = 0x4000u32; // 2.0
  679. let h3 = 0x4200u32; // 3.0
  680. let h5 = 0x4500u32; // 5.0
  681. let hn2 = 0xC000u32; // -2.0
  682. let nan = 0x7E00u32;
  683. let cases: &[([u32; 4], Option<u16>)] = &[
  684. ([h1, h2, h3, 0], Some(h2 as u16)),
  685. ([hn2, h0, h3, 0], Some(h0 as u16)),
  686. ([h1, h2, nan, 0], Some(h1 as u16)),
  687. ([nan, h1, h0, 0], Some(h0 as u16)),
  688. ([nan, h0, h1, 0], Some(h0 as u16)),
  689. ([h2, nan, h1, 0], Some(h1 as u16)),
  690. ([nan, h5, nan, 0], Some(h5 as u16)),
  691. ([nan, nan, nan, 0], None),
  692. ];
  693. let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect();
  694. run_cases(&shader, &inputs, |backend, i, inp, got| {
  695. let expect = cases[i].1;
  696. let got_h = got as u16;
  697. match expect {
  698. Some(want) => assert_eq!(
  699. got_h, want,
  700. "{backend}: v_med3_f16({:#06x}, {:#06x}, {:#06x}) = {got_h:#06x}, want {want:#06x}",
  701. inp[0], inp[1], inp[2],
  702. ),
  703. None => assert!(
  704. is_f16_nan(got_h),
  705. "{backend}: v_med3_f16(NaN, NaN, NaN) = {got_h:#06x}, want NaN",
  706. ),
  707. }
  708. });
  709. }
  710. /// `v_cmp_lg_*` is "less or greater": ordered and not equal, so false when
  711. /// either operand is a NaN (RDNA2 ISA; the same on gfx1036 hardware).
  712. #[test]
  713. fn v_cmp_lg_is_false_for_nan() {
  714. // v_cmp_lg_{f32,f16}_e64 s20, v1, v2 (VOPC 0x005 / 0x0cd in VOP3);
  715. // v_cndmask_b32_e64 v0, 0, 1, s20 (VOP3 0x101)
  716. let nan = f32::NAN.to_bits();
  717. let (inf, ninf) = (f32::INFINITY.to_bits(), f32::NEG_INFINITY.to_bits());
  718. let f = f32::to_bits;
  719. let f32_cases: &[([u32; 4], u32)] = &[
  720. ([f(1.0), f(2.0), 0, 0], 1),
  721. ([f(2.0), f(1.0), 0, 0], 1),
  722. ([f(1.0), f(1.0), 0, 0], 0),
  723. ([f(0.0), f(-0.0), 0, 0], 0),
  724. ([inf, ninf, 0, 0], 1),
  725. ([inf, inf, 0, 0], 0),
  726. ([nan, f(1.0), 0, 0], 0),
  727. ([f(1.0), nan, 0, 0], 0),
  728. ([nan, nan, 0, 0], 0),
  729. ([0x7F80_0001, f(0.0), 0, 0], 0), // a signalling NaN
  730. ];
  731. let f16_cases: &[([u32; 4], u32)] = &[
  732. ([0x3C00, 0x4000, 0, 0], 1),
  733. ([0x4000, 0x3C00, 0, 0], 1),
  734. ([0x3C00, 0x3C00, 0, 0], 0),
  735. ([0x0000, 0x8000, 0, 0], 0),
  736. ([0x7C00, 0xFC00, 0, 0], 1),
  737. ([0x7E00, 0x3C00, 0, 0], 0),
  738. ([0x3C00, 0x7E00, 0, 0], 0),
  739. ([0x7E00, 0x7E00, 0, 0], 0),
  740. ([0x7C01, 0x0000, 0, 0], 0), // a signalling NaN
  741. ([0xABCD_3C00, 0x1234_7E00, 0, 0], 0), // only the low halves are read
  742. ];
  743. for (op, what, cases) in [
  744. (0x005u16, "v_cmp_lg_f32", f32_cases),
  745. (0x0cd, "v_cmp_lg_f16", f16_cases),
  746. ] {
  747. let mut body = vop3(op, 20, vgpr(1), vgpr(2), 0x80).to_vec();
  748. body.extend_from_slice(&vop3(0x101, 0, 0x80, 0x81, sgpr(20)));
  749. let shader = build_valu_cs(&body);
  750. let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect();
  751. run_cases(&shader, &inputs, |backend, i, inp, got| {
  752. let want = cases[i].1;
  753. assert_eq!(
  754. got, want,
  755. "{backend}: {what}({:#010x}, {:#010x}) = {got}, want {want}",
  756. inp[0], inp[1],
  757. );
  758. });
  759. }
  760. }
  761. #[test]
  762. fn v_cvt_off_f32_i4_uses_the_signed_low_nibble() {
  763. // v_cvt_off_f32_i4 v0, v1 (VOP1 opcode 0x00e)
  764. let shader = build_valu_cs(&[vop1(0x00e, 0, vgpr(1))]);
  765. let nibble = |n: u32| (((n as i32) << 28) >> 28) as f32 / 16.0;
  766. let mut cases: Vec<u32> = (0..16).collect();
  767. // Bits above the low nibble are ignored.
  768. cases.extend([0xABCD_EF05, 0xFFFF_FFF8, 0x1234_5670, 0x8000_000F, 0x0000_00F7]);
  769. let inputs: Vec<[u32; 4]> = cases.iter().map(|&x| [x, 0, 0, 0]).collect();
  770. run_cases(&shader, &inputs, |backend, i, inp, got| {
  771. let want = nibble(cases[i]).to_bits();
  772. assert_eq!(
  773. got, want,
  774. "{backend}: v_cvt_off_f32_i4({:#010x}) = {got:#010x} ({:?}), want {want:#010x}",
  775. inp[0],
  776. f32::from_bits(got),
  777. );
  778. });
  779. // Spot-check the reference itself: 0x5 -> 0.3125, 0x8 -> -0.5, 0xF -> -0.0625.
  780. assert_eq!(nibble(0xABCD_EF05), 0.3125);
  781. assert_eq!(nibble(8), -0.5);
  782. assert_eq!(nibble(0xF), -0.0625);
  783. }
  784. #[test]
  785. fn v_fract_f32_never_returns_one() {
  786. // v_fract_f32 v0, v1 (VOP1 opcode 0x020)
  787. let shader = build_valu_cs(&[vop1(0x020, 0, vgpr(1))]);
  788. let f = f32::to_bits;
  789. let below_one = 0x3F7F_FFFFu32;
  790. let cases: &[(u32, Option<u32>)] = &[
  791. // Tiny negatives: must clamp strictly below 1.0 (not 0x3f800000).
  792. (f(-1e-10), Some(below_one)),
  793. (f(-1e-8), Some(below_one)),
  794. (f(-2.0f32.powi(-25)), Some(below_one)),
  795. (f(-2.0f32.powi(-24)), Some(below_one)),
  796. // Normal values.
  797. (f(0.0), Some(f(0.0))),
  798. (f(-0.0), Some(f(0.0))),
  799. (f(0.25), Some(f(0.25))),
  800. (f(3.75), Some(f(0.75))),
  801. (f(-0.25), Some(f(0.75))),
  802. (f(-3.25), Some(f(0.75))),
  803. (f(1.0), Some(f(0.0))),
  804. (f(-1.0), Some(f(0.0))),
  805. // Non-finite inputs yield NaN.
  806. (f(f32::NAN), None),
  807. (f(f32::INFINITY), None),
  808. (f(f32::NEG_INFINITY), None),
  809. ];
  810. let inputs: Vec<[u32; 4]> = cases.iter().map(|&(x, _)| [x, 0, 0, 0]).collect();
  811. run_cases(&shader, &inputs, |backend, i, inp, got| {
  812. let expect = cases[i].1;
  813. match expect {
  814. Some(want) => assert_eq!(
  815. got,
  816. want,
  817. "{backend}: v_fract_f32({:?} / {:#010x}) = {got:#010x} ({:?}), want {want:#010x}",
  818. f32::from_bits(inp[0]),
  819. inp[0],
  820. f32::from_bits(got),
  821. ),
  822. None => assert!(
  823. f32::from_bits(got).is_nan(),
  824. "{backend}: v_fract_f32({:?}) = {got:#010x}, want NaN",
  825. f32::from_bits(inp[0]),
  826. ),
  827. }
  828. });
  829. }
  830. #[test]
  831. fn v_fract_f16_never_returns_one() {
  832. // v_fract_f16 v0, v1 (VOP1 opcode 0x05f)
  833. let shader = build_valu_cs(&[vop1(0x05f, 0, vgpr(1))]);
  834. let below_one = 0x3BFFu16; // 1.0 - 2^-11
  835. assert_eq!(f16_to_f32(0x9400), -2.0f32.powi(-10));
  836. assert_eq!(f16_to_f32(0x9000), -2.0f32.powi(-11));
  837. assert_eq!(f16_to_f32(0x8C00), -2.0f32.powi(-12));
  838. let cases: &[(u16, Option<u16>)] = &[
  839. // Negatives in (-2^-11, 0): must clamp to 0x3BFF, never 0x3C00 (1.0).
  840. (0x8C00, Some(below_one)), // -2^-12
  841. (0x8400, Some(below_one)), // -2^-14
  842. (0x8001, Some(below_one)), // -2^-24 (smallest negative f16 subnormal)
  843. (0x9000, Some(below_one)), // -2^-11 (exact 1 - 2^-11 = 0x3BFF)
  844. (0x9400, Some(0x3BFE)), // -2^-10 (exact 1 - 2^-10 = 0x3BFE)
  845. // Normal values.
  846. (0x0000, Some(0x0000)), // 0.0 -> 0.0
  847. (0x3400, Some(0x3400)), // 0.25 -> 0.25
  848. (0xB400, Some(0x3A00)), // -0.25 -> 0.75
  849. (0x4300, Some(0x3800)), // 3.5 -> 0.5
  850. (0x3C00, Some(0x0000)), // 1.0 -> 0.0
  851. // Non-finite inputs yield NaN.
  852. (0x7E00, None), // NaN
  853. (0x7C00, None), // +inf
  854. (0xFC00, None), // -inf
  855. ];
  856. let inputs: Vec<[u32; 4]> = cases
  857. .iter()
  858. .map(|&(x, _)| [u32::from(x), 0, 0, 0])
  859. .collect();
  860. run_cases(&shader, &inputs, |backend, i, inp, got| {
  861. let expect = cases[i].1;
  862. let got_h = got as u16;
  863. match expect {
  864. Some(want) => assert_eq!(
  865. got_h, want,
  866. "{backend}: v_fract_f16({:#06x}) = {got_h:#06x}, want {want:#06x}",
  867. inp[0],
  868. ),
  869. None => assert!(
  870. is_f16_nan(got_h),
  871. "{backend}: v_fract_f16({:#06x}) = {got_h:#06x}, want NaN",
  872. inp[0],
  873. ),
  874. }
  875. });
  876. }
  877. /// RDNA2's flt16_to_snorm16 / flt16_to_unorm16: clamp, scale by 32767 or
  878. /// 65535, round the exact product to nearest even; NaN gives 0.
  879. fn cvt_norm16_reference(bits: u16, signed: bool) -> u16 {
  880. let x = f16_to_f32(bits);
  881. if x.is_nan() {
  882. return 0;
  883. }
  884. let (lo, scale) = if signed {
  885. (-1.0, 32767.0)
  886. } else {
  887. (0.0, 65535.0)
  888. };
  889. // f64 holds the product of an f16 and a 16-bit scale exactly.
  890. let p = f64::from(x.clamp(lo, 1.0)) * scale;
  891. p.round_ties_even() as i32 as u16
  892. }
  893. #[test]
  894. fn v_cvt_norm_i16_and_u16_f16_round_the_exact_product() {
  895. // Every 251st f16 pattern, plus the values where an f32 product would
  896. // round before the rounding to an integer, ties, and the edges.
  897. let mut bits: Vec<u16> = (0..=u16::MAX).step_by(251).collect();
  898. bits.extend([
  899. 0x0000, 0x8000, 0x0001, 0x8001, 0x03FF, 0x0400, 0x3800, 0xB800, 0x3801, 0xB801, 0x37FF,
  900. 0x3BFF, 0xBBFF, 0x3C00, 0xBC00, 0x3C01, 0x7BFF, 0x7C00, 0xFC00, 0x7E00, 0xFE00, 0x7C01,
  901. 0x3A9B, 0xBA9B, 0x2E66, 0x1400,
  902. ]);
  903. for (op, signed, what) in [
  904. (0x063u16, true, "v_cvt_norm_i16_f16"),
  905. (0x064, false, "v_cvt_norm_u16_f16"),
  906. ] {
  907. // v_cvt_norm_*16_f16 v0, v1 (VOP1); v0's high half starts at 0.
  908. let shader = build_valu_cs(&[vop1(0x001, 0, 128), vop1(op, 0, vgpr(1))]);
  909. let inputs: Vec<[u32; 4]> = bits.iter().map(|&b| [u32::from(b), 0, 0, 0]).collect();
  910. run_cases(&shader, &inputs, |backend, i, _, got| {
  911. let want = cvt_norm16_reference(bits[i], signed);
  912. assert_eq!(
  913. got,
  914. u32::from(want),
  915. "{backend}: {what}({:#06x}) = {got:#010x}, want {want:#06x}",
  916. bits[i],
  917. );
  918. });
  919. }
  920. }
  921. #[test]
  922. fn v_sin_and_v_cos_f32_reduce_large_turns() {
  923. let sin_shader = build_valu_cs(&[vop1(0x035, 0, vgpr(1))]);
  924. let cos_shader = build_valu_cs(&[vop1(0x036, 0, vgpr(1))]);
  925. let f = f32::to_bits;
  926. let half_sqrt2 = std::f32::consts::FRAC_1_SQRT_2;
  927. let sin_cases: &[(f32, Option<f32>)] = &[
  928. (0.0, Some(0.0)),
  929. (0.25, Some(1.0)),
  930. (255.0, Some(0.0)),
  931. (255.25, Some(1.0)),
  932. (255.5, Some(0.0)),
  933. (-255.25, Some(-1.0)),
  934. (10_000.125, Some(half_sqrt2)),
  935. (f32::NAN, None),
  936. (f32::INFINITY, None),
  937. (f32::NEG_INFINITY, None),
  938. ];
  939. let sin_inputs: Vec<[u32; 4]> = sin_cases.iter().map(|&(x, _)| [f(x), 0, 0, 0]).collect();
  940. run_cases(&sin_shader, &sin_inputs, |backend, i, inp, got| {
  941. let expect = sin_cases[i].1;
  942. let got_f = f32::from_bits(got);
  943. match expect {
  944. Some(want) => assert!(
  945. (got_f - want).abs() < 1e-5,
  946. "{backend}: v_sin_f32({}) = {got_f}, want {want} (err = {})",
  947. f32::from_bits(inp[0]),
  948. (got_f - want).abs(),
  949. ),
  950. None => assert!(
  951. got_f.is_nan(),
  952. "{backend}: v_sin_f32({}) = {got_f}, want NaN",
  953. f32::from_bits(inp[0]),
  954. ),
  955. }
  956. });
  957. let cos_cases: &[(f32, Option<f32>)] = &[
  958. (0.0, Some(1.0)),
  959. (0.25, Some(0.0)),
  960. (255.0, Some(1.0)),
  961. (255.25, Some(0.0)),
  962. (255.5, Some(-1.0)),
  963. (-255.5, Some(-1.0)),
  964. (10_000.125, Some(half_sqrt2)),
  965. (f32::NAN, None),
  966. (f32::INFINITY, None),
  967. (f32::NEG_INFINITY, None),
  968. ];
  969. let cos_inputs: Vec<[u32; 4]> = cos_cases.iter().map(|&(x, _)| [f(x), 0, 0, 0]).collect();
  970. run_cases(&cos_shader, &cos_inputs, |backend, i, inp, got| {
  971. let expect = cos_cases[i].1;
  972. let got_f = f32::from_bits(got);
  973. match expect {
  974. Some(want) => assert!(
  975. (got_f - want).abs() < 1e-5,
  976. "{backend}: v_cos_f32({}) = {got_f}, want {want} (err = {})",
  977. f32::from_bits(inp[0]),
  978. (got_f - want).abs(),
  979. ),
  980. None => assert!(
  981. got_f.is_nan(),
  982. "{backend}: v_cos_f32({}) = {got_f}, want NaN",
  983. f32::from_bits(inp[0]),
  984. ),
  985. }
  986. });
  987. // Main's `trig_turns` preserves sin(-0.0) = -0.0 and produces exact +0.0 at
  988. // half-turns (sin) and quarter-turns (cos).
  989. let exact_sin: &[(u32, u32)] = &[
  990. (0x8000_0000, 0x8000_0000), // sin(-0.0) = -0.0
  991. (f(255.0), 0), // sin(255.0) = +0.0
  992. (f(255.5), 0), // sin(255.5) = +0.0
  993. ];
  994. let exact_sin_in: Vec<[u32; 4]> = exact_sin.iter().map(|&(x, _)| [x, 0, 0, 0]).collect();
  995. run_cases(&sin_shader, &exact_sin_in, |backend, i, inp, got| {
  996. let want = exact_sin[i].1;
  997. assert_eq!(
  998. got, want,
  999. "{backend}: v_sin_f32({:#010x}) = {got:#010x}, want {want:#010x}",
  1000. inp[0],
  1001. );
  1002. });
  1003. let exact_cos: &[(u32, u32)] = &[
  1004. (f(0.25), 0), // cos(0.25) = +0.0
  1005. (f(255.25), 0), // cos(255.25) = +0.0
  1006. ];
  1007. let exact_cos_in: Vec<[u32; 4]> = exact_cos.iter().map(|&(x, _)| [x, 0, 0, 0]).collect();
  1008. run_cases(&cos_shader, &exact_cos_in, |backend, i, inp, got| {
  1009. let want = exact_cos[i].1;
  1010. assert_eq!(
  1011. got, want,
  1012. "{backend}: v_cos_f32({:#010x}) = {got:#010x}, want {want:#010x}",
  1013. inp[0],
  1014. );
  1015. });
  1016. }
  1017. #[test]
  1018. fn v_cvt_u16_and_i16_f16_saturate() {
  1019. // v_mov_b32 v0, 0; v_cvt_u16_f16 / v_cvt_i16_f16 v0, v1 (VOP1 0x052 / 0x053).
  1020. let cases: &[(u16, u16, u16)] = &[
  1021. // (f16 input, u16 result, i16 result)
  1022. (0x0000, 0, 0), // 0
  1023. (0x8000, 0, 0), // -0
  1024. (0x3E00, 1, 1), // 1.5 -> 1 (toward zero)
  1025. (0xBE00, 0, 0xFFFF), // -1.5 -> 0 / -1
  1026. (0x57D0, 125, 125), // 125.0
  1027. (0x7800, 32768, 32767), // 32768 saturates i16
  1028. (0x77FF, 32752, 32752), // 32752, the largest f16 below 32768
  1029. (0xF800, 0, 0x8000), // -32768 fits i16
  1030. (0xF801, 0, 0x8000), // -32800 saturates i16
  1031. (0x7BFF, 65504, 32767), // max finite f16
  1032. (0xFBFF, 0, 0x8000), // -65504
  1033. (0x7C00, 0xFFFF, 32767), // +inf
  1034. (0xFC00, 0, 0x8000), // -inf
  1035. (0x7E00, 0, 0), // NaN
  1036. (0xFE00, 0, 0), // -NaN
  1037. (0x0001, 0, 0), // smallest subnormal
  1038. ];
  1039. for (op, what, pick) in [
  1040. (0x052u16, "v_cvt_u16_f16", 0usize),
  1041. (0x053, "v_cvt_i16_f16", 1),
  1042. ] {
  1043. let shader = build_valu_cs(&[vop1(0x001, 0, 128), vop1(op, 0, vgpr(1))]);
  1044. let inputs: Vec<[u32; 4]> = cases.iter().map(|c| [u32::from(c.0), 0, 0, 0]).collect();
  1045. run_cases(&shader, &inputs, |backend, i, _, got| {
  1046. let want = if pick == 0 { cases[i].1 } else { cases[i].2 };
  1047. assert_eq!(
  1048. got,
  1049. u32::from(want),
  1050. "{backend}: {what}({:#06x}) = {got:#010x}, want {want:#06x}",
  1051. cases[i].0,
  1052. );
  1053. });
  1054. }
  1055. }
  1056. #[test]
  1057. fn v_cvt_f16_u16_and_i16_widen_the_integer_first() {
  1058. // v_mov_b32 v0, 0; v_cvt_f16_u16 / v_cvt_f16_i16 v0, v1 (VOP1 0x050 / 0x051).
  1059. // Only integers f16 holds exactly: how the others round is the narrowing's
  1060. // business, not this conversion's. `None`: the result depends on rounding.
  1061. let cases: &[(u16, Option<u16>, Option<u16>)] = &[
  1062. // (u16 / i16 input bits, f16 of the unsigned value, f16 of the signed value)
  1063. (0x0000, Some(0x0000), Some(0x0000)), // 0
  1064. (0x0001, Some(0x3C00), Some(0x3C00)), // 1.0
  1065. (0x07FF, Some(0x67FF), Some(0x67FF)), // 2047, the last integer below 2048 that f16 holds
  1066. (0x8000, Some(0x7800), Some(0xF800)), // 32768 / -32768
  1067. (0xFC00, Some(0x7BE0), Some(0xE400)), // 64512 / -1024
  1068. (0xFFFE, None, Some(0xC000)), // 65534 does not fit f16 / -2
  1069. (0xFFFF, None, Some(0xBC00)), // 65535 does not fit f16 / -1
  1070. ];
  1071. for (op, what, pick) in [
  1072. (0x050u16, "v_cvt_f16_u16", 0usize),
  1073. (0x051, "v_cvt_f16_i16", 1),
  1074. ] {
  1075. let shader = build_valu_cs(&[vop1(0x001, 0, 128), vop1(op, 0, vgpr(1))]);
  1076. let inputs: Vec<[u32; 4]> = cases.iter().map(|c| [u32::from(c.0), 0, 0, 0]).collect();
  1077. run_cases(&shader, &inputs, |backend, i, _, got| {
  1078. let want = if pick == 0 { cases[i].1 } else { cases[i].2 };
  1079. let Some(want) = want else { return };
  1080. assert_eq!(
  1081. got,
  1082. u32::from(want),
  1083. "{backend}: {what}({:#06x}) = {got:#010x}, want {want:#06x}",
  1084. cases[i].0,
  1085. );
  1086. });
  1087. }
  1088. }
  1089. #[test]
  1090. fn v_sin_and_v_cos_f16_reduce_large_turns() {
  1091. let sin_shader = build_valu_cs(&[vop1(0x060, 0, vgpr(1))]);
  1092. let cos_shader = build_valu_cs(&[vop1(0x061, 0, vgpr(1))]);
  1093. // Sanity-check the f16 bit encodings of large turns.
  1094. assert_eq!(f16_to_f32(0x5BF8), 255.0);
  1095. assert_eq!(f16_to_f32(0x5BFA), 255.25);
  1096. assert_eq!(f16_to_f32(0x5BFC), 255.5);
  1097. assert_eq!(f16_to_f32(0x7BFF), 65504.0);
  1098. let sin_cases: &[(u16, Option<f32>)] = &[
  1099. (0x5BF8, Some(0.0)), // 255.0
  1100. (0x5BFA, Some(1.0)), // 255.25
  1101. (0x5BFC, Some(0.0)), // 255.5
  1102. (0xDBFA, Some(-1.0)), // -255.25
  1103. (0x7BFF, Some(0.0)), // 65504.0 (largest finite f16, exact integer)
  1104. (0x7E00, None), // NaN
  1105. (0x7C00, None), // +inf
  1106. (0xFC00, None), // -inf
  1107. ];
  1108. let sin_inputs: Vec<[u32; 4]> = sin_cases
  1109. .iter()
  1110. .map(|&(x, _)| [u32::from(x), 0, 0, 0])
  1111. .collect();
  1112. run_cases(&sin_shader, &sin_inputs, |backend, i, inp, got| {
  1113. let expect = sin_cases[i].1;
  1114. let got_h = got as u16;
  1115. match expect {
  1116. Some(want) => {
  1117. let got_f = f16_to_f32(got_h);
  1118. assert!(
  1119. (got_f - want).abs() < 1e-3,
  1120. "{backend}: v_sin_f16({:#06x} = {}) = {got_f} ({got_h:#06x}), want {want}",
  1121. inp[0],
  1122. f16_to_f32(inp[0] as u16),
  1123. );
  1124. }
  1125. None => assert!(
  1126. is_f16_nan(got_h),
  1127. "{backend}: v_sin_f16({:#06x}) = {got_h:#06x}, want NaN",
  1128. inp[0],
  1129. ),
  1130. }
  1131. });
  1132. let cos_cases: &[(u16, Option<f32>)] = &[
  1133. (0x5BF8, Some(1.0)), // 255.0
  1134. (0x5BFA, Some(0.0)), // 255.25
  1135. (0x5BFC, Some(-1.0)), // 255.5
  1136. (0x7BFF, Some(1.0)), // 65504.0 (largest finite f16, exact integer)
  1137. (0x7E00, None), // NaN
  1138. (0x7C00, None), // +inf
  1139. (0xFC00, None), // -inf
  1140. ];
  1141. let cos_inputs: Vec<[u32; 4]> = cos_cases
  1142. .iter()
  1143. .map(|&(x, _)| [u32::from(x), 0, 0, 0])
  1144. .collect();
  1145. run_cases(&cos_shader, &cos_inputs, |backend, i, inp, got| {
  1146. let expect = cos_cases[i].1;
  1147. let got_h = got as u16;
  1148. match expect {
  1149. Some(want) => {
  1150. let got_f = f16_to_f32(got_h);
  1151. assert!(
  1152. (got_f - want).abs() < 1e-3,
  1153. "{backend}: v_cos_f16({:#06x} = {}) = {got_f} ({got_h:#06x}), want {want}",
  1154. inp[0],
  1155. f16_to_f32(inp[0] as u16),
  1156. );
  1157. }
  1158. None => assert!(
  1159. is_f16_nan(got_h),
  1160. "{backend}: v_cos_f16({:#06x}) = {got_h:#06x}, want NaN",
  1161. inp[0],
  1162. ),
  1163. }
  1164. });
  1165. }
  1166. /// A 32-bit literal in a signed 64-bit operand is sign-extended (an
  1167. /// unsigned one's is zero-extended): -100 compared with `v[1:2]`, and
  1168. /// shifted by `s_ashr_i64`.
  1169. #[test]
  1170. fn signed_64_bit_operands_sign_extend_their_literal() {
  1171. const MINUS_100: u32 = -100_i32 as u32;
  1172. let check = |name: &str, body: &[u32], cases: &[([u32; 4], u32)]| {
  1173. let shader = build_valu_cs(body);
  1174. let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect();
  1175. run_cases(&shader, &inputs, |backend, i, inp, got| {
  1176. let want = cases[i].1;
  1177. assert_eq!(got, want, "{backend}: {name} {inp:x?}");
  1178. });
  1179. };
  1180. // v_cmp_*_i64 s6, v[1:2], -100 (VOP3, literal src1), then
  1181. // v_cndmask_b32 v0, 0, 1, s6.
  1182. let compare = |op: u16| {
  1183. let [a, b] = vop3(op, 6, vgpr(1), 255, 0);
  1184. let [c, d] = vop3(0x101, 0, 0x80, 0x81, sgpr(6));
  1185. [a, b, MINUS_100, c, d]
  1186. };
  1187. // An i64 as the two input dwords of `v[1:2]`.
  1188. let pair = |n: i64| [n as u32, (n >> 32) as u32, 0, 0];
  1189. let eq = [(pair(-100), 1), ([MINUS_100, 0, 0, 0], 0), (pair(0), 0)];
  1190. check("v_cmp_eq_i64", &compare(0x0A2), &eq);
  1191. let lt = [(pair(-200), 1), (pair(-50), 0), (pair(0), 0)];
  1192. check("v_cmp_lt_i64", &compare(0x0A1), &lt);
  1193. // s_ashr_i64 s[6:7], -100, 4; v_mov_b32 v0, s7: the high dword.
  1194. let ashr = [sop2(0x23, 6, 255, 0x84), MINUS_100, vop1(0x001, 0, sgpr(7))];
  1195. check("s_ashr_i64", &ashr, &[([0; 4], u32::MAX)]);
  1196. }
  1197. #[test]
  1198. fn bfe_signed_and_unsigned_match_rdna2() {
  1199. // v_bfe_i32 v0, v1, v2, v3 (VOP3 opcode 0x149)
  1200. let v_signed = build_valu_cs(&vop3(0x149, 0, vgpr(1), vgpr(2), vgpr(3)));
  1201. // v_bfe_u32 v0, v1, v2, v3 (VOP3 opcode 0x148)
  1202. let v_unsigned = build_valu_cs(&vop3(0x148, 0, vgpr(1), vgpr(2), vgpr(3)));
  1203. // s_bfe_i32 s6, s0, s1 (SOP2 opcode 0x28: s1 = off[4:0] | width[22:16]); v_mov_b32 v0, s6
  1204. let s_signed = build_valu_cs(&[sop2(0x28, 6, 0, 1), vop1(0x001, 0, sgpr(6))]);
  1205. let signed_cases: &[([u32; 4], u32)] = &[
  1206. // Field crosses bit 31: extends from bit 31.
  1207. ([0xd2f9_0159, 28, 16, 0], 0xffff_fffd),
  1208. ([0x8000_0000, 31, 4, 0], 0xffff_ffff),
  1209. ([0x7000_0000, 28, 8, 0], 0x0000_0007),
  1210. // Normal fields inside 32 bits.
  1211. ([0x0000_0080, 4, 4, 0], 0xffff_fff8),
  1212. ([0x0000_0070, 4, 4, 0], 0x0000_0007),
  1213. // Edge widths: 0 yields 0; v_bfe masks width to 5 bits (32 -> 0),
  1214. // while 31 extracts all remaining bits from offset 4.
  1215. ([0xffff_ffff, 4, 0, 0], 0),
  1216. ([0x8000_0000, 4, 31, 0], 0xf800_0000),
  1217. ];
  1218. let v_in: Vec<[u32; 4]> = signed_cases.iter().map(|c| c.0).collect();
  1219. run_cases(&v_signed, &v_in, |backend, i, inp, got| {
  1220. let want = signed_cases[i].1;
  1221. assert_eq!(
  1222. got, want,
  1223. "{backend}: v_bfe_i32({:#010x}, {}, {}) = {got:#010x}, want {want:#010x}",
  1224. inp[0], inp[1], inp[2],
  1225. );
  1226. });
  1227. // v_bfe_i32 width is 5-bit (src2[4:0]), so width=32 wraps to 0.
  1228. run_cases(
  1229. &v_signed,
  1230. &[[0x8000_0000, 4, 32, 0]],
  1231. |backend, _, _, got| {
  1232. assert_eq!(got, 0, "{backend}: v_bfe_i32 width 32 should mask to 0");
  1233. },
  1234. );
  1235. // s_bfe_i32 width is 7-bit (src1[22:16]), so width=32 keeps all 32 bits.
  1236. let mut s_cases = signed_cases.to_vec();
  1237. s_cases.push(([0x8000_0000, 4, 32, 0], 0xf800_0000));
  1238. let s_in: Vec<[u32; 4]> = s_cases
  1239. .iter()
  1240. .map(|&(inp, _)| [inp[0], (inp[1] & 31) | ((inp[2] & 0x7F) << 16), 0, 0])
  1241. .collect();
  1242. run_cases(&s_signed, &s_in, |backend, i, inp, got| {
  1243. let want = s_cases[i].1;
  1244. assert_eq!(
  1245. got, want,
  1246. "{backend}: s_bfe_i32({:#010x}, {:#010x}) = {got:#010x}, want {want:#010x}",
  1247. inp[0], inp[1],
  1248. );
  1249. });
  1250. let unsigned_cases: &[([u32; 4], u32)] = &[
  1251. ([0xd2f9_0159, 28, 16, 0], 0x0000_000d),
  1252. ([0x8000_0000, 31, 4, 0], 0x0000_0001),
  1253. ([0xffff_ffff, 4, 0, 0], 0),
  1254. ([0x8000_0000, 4, 31, 0], 0x0800_0000),
  1255. ];
  1256. let u_in: Vec<[u32; 4]> = unsigned_cases.iter().map(|c| c.0).collect();
  1257. run_cases(&v_unsigned, &u_in, |backend, i, inp, got| {
  1258. let want = unsigned_cases[i].1;
  1259. assert_eq!(
  1260. got, want,
  1261. "{backend}: v_bfe_u32({:#010x}, {}, {}) = {got:#010x}, want {want:#010x}",
  1262. inp[0], inp[1], inp[2],
  1263. );
  1264. });
  1265. }
  1266. #[test]
  1267. fn f16_omod_applies_before_clamp() {
  1268. // VOP3 v_add_f16 (0x132 = 0x100 + VOP2 0x32): v0 = (v1 + v2) * omod [clamp]
  1269. let mul2 = build_valu_cs(&vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 1, false));
  1270. let mul4 = build_valu_cs(&vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 2, false));
  1271. let div2 = build_valu_cs(&vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 3, false));
  1272. let div2_clamp = build_valu_cs(&vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 3, true));
  1273. // f16 constants: 0.25=0x3400, 0.5=0x3800, 0.75=0x3A00, 1.0=0x3C00, 1.5=0x3E00, 2.0=0x4000, -0.5=0xB800
  1274. run_cases(
  1275. &mul2,
  1276. &[[0x3400, 0x3800, 0, 0]], // (0.25 + 0.5) * 2 = 1.5 (0x3E00)
  1277. |backend, _, _, got| {
  1278. assert_eq!(got as u16, 0x3E00, "{backend}: v_add_f16 mul:2");
  1279. },
  1280. );
  1281. run_cases(
  1282. &mul4,
  1283. &[[0x3400, 0x3400, 0, 0]], // (0.25 + 0.25) * 4 = 2.0 (0x4000)
  1284. |backend, _, _, got| {
  1285. assert_eq!(got as u16, 0x4000, "{backend}: v_add_f16 mul:4");
  1286. },
  1287. );
  1288. run_cases(
  1289. &div2,
  1290. &[[0x3E00, 0x3E00, 0, 0]], // (1.5 + 1.5) / 2 = 1.5 (0x3E00)
  1291. |backend, _, _, got| {
  1292. assert_eq!(got as u16, 0x3E00, "{backend}: v_add_f16 div:2");
  1293. },
  1294. );
  1295. // Ordering check: (0.75 + 0.75) = 1.5; div:2 before clamp gives 0.75 (0x3A00),
  1296. // whereas clamp before div:2 would give 0.5 (0x3800).
  1297. let clamp_cases: &[(u16, u16, u16)] = &[
  1298. (0x3A00, 0x3A00, 0x3A00), // (0.75 + 0.75) / 2 = 0.75 -> 0.75
  1299. (0x3E00, 0x3E00, 0x3C00), // (1.5 + 1.5) / 2 = 1.5 -> clamped to 1.0
  1300. (0xB800, 0xB800, 0x0000), // (-0.5 + -0.5) / 2 = -0.5 -> clamped to 0.0
  1301. ];
  1302. let inputs: Vec<[u32; 4]> = clamp_cases
  1303. .iter()
  1304. .map(|&(a, b, _)| [u32::from(a), u32::from(b), 0, 0])
  1305. .collect();
  1306. run_cases(&div2_clamp, &inputs, |backend, i, _, got| {
  1307. let want = clamp_cases[i].2;
  1308. assert_eq!(
  1309. got as u16, want,
  1310. "{backend}: v_add_f16 div:2 clamp case {i}: got {:#06x}, want {want:#06x}",
  1311. got as u16,
  1312. );
  1313. });
  1314. }
  1315. #[test]
  1316. fn cvt_16bit_int_from_f16_saturates_and_honors_modifiers() {
  1317. // VOP3 v_cvt_u16_f16 = 0x1D2 (0x180 + VOP1 0x52)
  1318. // VOP3 v_cvt_i16_f16 = 0x1D3 (0x180 + VOP1 0x53)
  1319. let cvt_u16 = build_valu_cs(&vop3_mod(0x1D2, 0, vgpr(1), 0, 0, 0, 0, 0, false));
  1320. let cvt_u16_abs = build_valu_cs(&vop3_mod(0x1D2, 0, vgpr(1), 0, 0, 1, 0, 0, false));
  1321. let cvt_i16 = build_valu_cs(&vop3_mod(0x1D3, 0, vgpr(1), 0, 0, 0, 0, 0, false));
  1322. let cvt_i16_neg = build_valu_cs(&vop3_mod(0x1D3, 0, vgpr(1), 0, 0, 0, 1, 0, false));
  1323. let u16_cases: &[(u16, u16)] = &[
  1324. (0xBC00, 0), // -1.0 -> 0
  1325. (0xFC00, 0), // -inf -> 0
  1326. (0x7E00, 0), // NaN -> 0
  1327. (0x57BC, 123), // 123.75 -> 123
  1328. (0x7BFF, 65504), // 65504.0 (max finite f16) -> 65504
  1329. (0x7C00, 0xFFFF), // +inf -> 65535 (saturated)
  1330. ];
  1331. let u16_in: Vec<[u32; 4]> = u16_cases.iter().map(|&(x, _)| [u32::from(x), 0, 0, 0]).collect();
  1332. run_cases(&cvt_u16, &u16_in, |backend, i, inp, got| {
  1333. let want = u16_cases[i].1;
  1334. assert_eq!(
  1335. got as u16, want,
  1336. "{backend}: v_cvt_u16_f16({:#06x}) = {:#06x}, want {want:#06x}",
  1337. inp[0], got as u16,
  1338. );
  1339. });
  1340. run_cases(
  1341. &cvt_u16_abs,
  1342. &[[0xD7BC, 0, 0, 0]], // |-123.75| -> 123
  1343. |backend, _, _, got| {
  1344. assert_eq!(got as u16, 123, "{backend}: v_cvt_u16_f16 |src0|");
  1345. },
  1346. );
  1347. let i16_cases: &[(u16, u16)] = &[
  1348. (0xFC00, 0x8000), // -inf -> -32768
  1349. (0xF8E2, 0x8000), // -40000.0 -> -32768 (saturated, not wrapped)
  1350. (0xD7BC, (-123i16) as u16), // -123.75 -> -123
  1351. (0x7E00, 0), // NaN -> 0
  1352. (0x57BC, 123), // 123.75 -> 123
  1353. (0x78E2, 0x7FFF), // +40000.0 -> 32767 (saturated, not wrapped)
  1354. (0x7C00, 0x7FFF), // +inf -> 32767
  1355. ];
  1356. let i16_in: Vec<[u32; 4]> = i16_cases.iter().map(|&(x, _)| [u32::from(x), 0, 0, 0]).collect();
  1357. run_cases(&cvt_i16, &i16_in, |backend, i, inp, got| {
  1358. let want = i16_cases[i].1;
  1359. assert_eq!(
  1360. got as u16, want,
  1361. "{backend}: v_cvt_i16_f16({:#06x}) = {:#06x}, want {want:#06x}",
  1362. inp[0], got as u16,
  1363. );
  1364. });
  1365. run_cases(
  1366. &cvt_i16_neg,
  1367. &[[0x57BC, 0, 0, 0], [0x78E2, 0, 0, 0]], // -(123.75) -> -123; -(40000.0) -> -32768
  1368. |backend, i, _, got| {
  1369. let want = [(-123i16) as u16, 0x8000][i];
  1370. assert_eq!(got as u16, want, "{backend}: v_cvt_i16_f16 -src0 case {i}");
  1371. },
  1372. );
  1373. }
  1374. const S_BARRIER: u32 = 0xBF8A_0000;
  1375. /// VOP2 `op vdst, src0, vsrc1`.
  1376. const fn vop2(op: u8, vdst: u8, src0: u16, vsrc1: u8) -> u32 {
  1377. (op as u32 & 0x3F) << 25 | (vdst as u32) << 17 | (vsrc1 as u32) << 9 | (src0 as u32 & 0x1FF)
  1378. }
  1379. /// DS `op vdst, addr, data0` at offset 0.
  1380. const fn ds(op: u8, vdst: u8, addr: u8, data0: u8) -> [u32; 2] {
  1381. [
  1382. 0x36 << 26 | (op as u32) << 18,
  1383. (vdst as u32) << 24 | (data0 as u32) << 8 | addr as u32,
  1384. ]
  1385. }
  1386. const DS_WRITE_B32: u8 = 0x0D;
  1387. const DS_MIN_F32: u8 = 0x12;
  1388. const DS_MAX_F32: u8 = 0x13;
  1389. const DS_MIN_RTN_F32: u8 = 0x32;
  1390. const DS_MAX_RTN_F32: u8 = 0x33;
  1391. const DS_READ_B32: u8 = 0x36;
  1392. /// What RDNA2 writes for `ds_max_f32` / `ds_min_f32` over a dword holding
  1393. /// `old` with `data` (bits), as measured on gfx1036 with f32 denormals kept:
  1394. /// an sNaN, data first, then memory, is written quieted; otherwise a NaN
  1395. /// loses to a number (two quiet NaNs give the data); numbers compare as
  1396. /// floats with -0 below +0.
  1397. fn lds_min_max_ref(old: u32, data: u32, max: bool) -> u32 {
  1398. let nan = |x: u32| x & 0x7FFF_FFFF > 0x7F80_0000;
  1399. let snan = |x: u32| nan(x) && x & 0x40_0000 == 0;
  1400. let key = |x: u32| {
  1401. let b = x as i32;
  1402. if b < 0 { b ^ 0x7FFF_FFFF } else { b }
  1403. };
  1404. if snan(data) {
  1405. return data | 0x40_0000;
  1406. }
  1407. if snan(old) {
  1408. return old | 0x40_0000;
  1409. }
  1410. match (nan(data), nan(old)) {
  1411. (true, true) | (false, true) => return data,
  1412. (true, false) => return old,
  1413. (false, false) => {}
  1414. }
  1415. let take = if max {
  1416. key(data) > key(old)
  1417. } else {
  1418. key(data) < key(old)
  1419. };
  1420. if take { data } else { old }
  1421. }
  1422. #[test]
  1423. fn ds_min_max_f32_order_floats_and_return_the_old_value() {
  1424. let values = [
  1425. 0.0f32,
  1426. -0.0,
  1427. 1.0,
  1428. -1.0,
  1429. 2.5,
  1430. -2.5,
  1431. 1e-30,
  1432. -1e-30,
  1433. f32::from_bits(1), // denormal
  1434. f32::from_bits(0x8000_0001),
  1435. f32::INFINITY,
  1436. f32::NEG_INFINITY,
  1437. f32::MAX,
  1438. f32::MIN,
  1439. ];
  1440. // Quiet and signalling NaNs of both signs, in memory and as data.
  1441. let nans = [
  1442. 0x7FC0_0000u32,
  1443. 0xFFC0_0000,
  1444. 0x7F80_0001,
  1445. 0xFFA0_0000,
  1446. 0x7FBF_FFFF,
  1447. ];
  1448. let bits: Vec<u32> = values.iter().map(|v| v.to_bits()).chain(nans).collect();
  1449. let mut cases: Vec<[u32; 4]> = Vec::new();
  1450. for &old in &bits {
  1451. for &data in &bits {
  1452. cases.push([old, data, 0, 0]);
  1453. }
  1454. }
  1455. for (rtn, plain, max, what) in [
  1456. (DS_MAX_RTN_F32, DS_MAX_F32, true, "ds_max"),
  1457. (DS_MIN_RTN_F32, DS_MIN_F32, false, "ds_min"),
  1458. ] {
  1459. // v5 = 0; LDS[v5] = v1; the atomic with v2; v0 = the old value
  1460. // (rtn) or the dword afterwards (read back).
  1461. let mut returns_old = vec![vop1(0x001, 5, 0x80)];
  1462. returns_old.extend(ds(DS_WRITE_B32, 0, 5, 1));
  1463. returns_old.extend(ds(rtn, 0, 5, 2));
  1464. let mut returns_new = vec![vop1(0x001, 5, 0x80)];
  1465. returns_new.extend(ds(DS_WRITE_B32, 0, 5, 1));
  1466. returns_new.extend(ds(plain, 0, 5, 2));
  1467. returns_new.extend(ds(DS_READ_B32, 0, 5, 0));
  1468. for (body, old_result) in [(returns_old, true), (returns_new, false)] {
  1469. // One thread with LDS declares WaveSize(32), which WARP's
  1470. // pipeline creation refuses: hardware only (the 64-thread test
  1471. // below runs on WARP too).
  1472. let shader = build_cs(&body, 1, 512);
  1473. run_cases_on(
  1474. &shader,
  1475. &cases,
  1476. &[("hardware", false)],
  1477. |backend, _, inp, got| {
  1478. let (old, data) = (f32::from_bits(inp[0]), f32::from_bits(inp[1]));
  1479. let want = if old_result {
  1480. inp[0]
  1481. } else {
  1482. lds_min_max_ref(inp[0], inp[1], max)
  1483. };
  1484. assert_eq!(
  1485. got,
  1486. want,
  1487. "{backend}: {what}_f32 on {old:e} [{:#010x}] with {data:e} [{:#010x}] gave {got:#010x}, want {want:#010x} ({})",
  1488. inp[0],
  1489. inp[1],
  1490. if old_result {
  1491. "old value"
  1492. } else {
  1493. "dword after"
  1494. },
  1495. );
  1496. },
  1497. );
  1498. }
  1499. }
  1500. }
  1501. #[test]
  1502. fn ds_min_max_f32_are_atomic_across_waves() {
  1503. // 64 threads (two host waves of 32 or one of 64): LDS[0] = v1, then
  1504. // every thread applies (thread - 32) as a float; v0 = LDS[0].
  1505. for (op, max, init, want) in [
  1506. (DS_MAX_F32, true, f32::NEG_INFINITY, 31.0f32),
  1507. (DS_MAX_F32, true, 100.0, 100.0),
  1508. (DS_MIN_F32, false, f32::INFINITY, -32.0),
  1509. (DS_MIN_F32, false, -0.0, -32.0),
  1510. ] {
  1511. let mut body = vec![vop1(0x001, 5, 0x80)];
  1512. body.extend(ds(DS_WRITE_B32, 0, 5, 1));
  1513. body.push(S_BARRIER);
  1514. body.push(vop2(0x26, 6, vgpr(0), 3)); // v_sub_nc_u32 v6, v0, v3
  1515. body.push(vop1(0x005, 6, vgpr(6))); // v_cvt_f32_i32
  1516. body.extend(ds(op, 0, 5, 6));
  1517. body.push(S_BARRIER);
  1518. body.extend(ds(DS_READ_B32, 0, 5, 0));
  1519. let shader = build_cs(&body, 64, 512);
  1520. run_cases(
  1521. &shader,
  1522. &[[init.to_bits(), 0, 32, 0]],
  1523. |backend, _, _, got| {
  1524. assert_eq!(
  1525. f32::from_bits(got),
  1526. want,
  1527. "{backend}: {} from {init} over 64 threads",
  1528. if max { "max" } else { "min" },
  1529. );
  1530. },
  1531. );
  1532. }
  1533. }
  1534. #[test]
  1535. fn v_cmp_class_f16_matches_rdna2() {
  1536. // v_cmp_class_f16_e64 s6, v1, v2 (VOP3 opcode 0x08f); v_cndmask_b32_e64 v0, 0, 1, s6
  1537. let cmp_lo = build_valu_cs(&[
  1538. vop3(0x08f, 6, vgpr(1), vgpr(2), 0)[0],
  1539. vop3(0x08f, 6, vgpr(1), vgpr(2), 0)[1],
  1540. vop3(0x101, 0, 0x80, 0x81, sgpr(6))[0],
  1541. vop3(0x101, 0, 0x80, 0x81, sgpr(6))[1],
  1542. ]);
  1543. // Same with op_sel:[1,0] (high half of v1) + neg on src0 (bit 29 of w1).
  1544. let [mut w0, mut w1] = vop3(0x08f, 6, vgpr(1), vgpr(2), 0);
  1545. w0 |= 1 << 11; // opsel[0] = 1 (high half)
  1546. w1 |= 1 << 29; // neg[0] = 1
  1547. let cmp_hi_neg = build_valu_cs(&[
  1548. w0,
  1549. w1,
  1550. vop3(0x101, 0, 0x80, 0x81, sgpr(6))[0],
  1551. vop3(0x101, 0, 0x80, 0x81, sgpr(6))[1],
  1552. ]);
  1553. // All 10 IEEE-754 binary16 classes: bit k corresponds to class k.
  1554. let classes: &[(u32, u32)] = &[
  1555. (0x7C01, 0), // sNaN (+sNaN, quiet bit 0x0200 clear)
  1556. (0xFDFF, 0), // -sNaN (sign ignored for NaNs)
  1557. (0x7E00, 1), // +qNaN
  1558. (0xFE01, 1), // -qNaN
  1559. (0xFC00, 2), // -inf
  1560. (0xBC00, 3), // -normal (-1.0)
  1561. (0x8001, 4), // -denormal
  1562. (0x8000, 5), // -0.0
  1563. (0x0000, 6), // +0.0
  1564. (0x0001, 7), // +denormal
  1565. (0x3C00, 8), // +normal (+1.0)
  1566. (0x7C00, 9), // +inf
  1567. ];
  1568. let mut cases = Vec::new();
  1569. for &(bits, cls) in classes {
  1570. // Exact class bit -> true; complement of class bit across all 10 bits -> false.
  1571. cases.push(([bits, 1u32 << cls, 0, 0], 1u32));
  1572. cases.push(([bits, 0x3FF & !(1u32 << cls), 0, 0], 0u32));
  1573. }
  1574. let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect();
  1575. run_cases(&cmp_lo, &inputs, |backend, i, inp, got| {
  1576. let want = cases[i].1;
  1577. assert_eq!(
  1578. got, want,
  1579. "{backend}: v_cmp_class_f16({:#06x}, {:#05x}) = {got}, want {want}",
  1580. inp[0], inp[1],
  1581. );
  1582. });
  1583. // High half with neg: high half 0x3C00 (+1.0) negated -> -normal (class 3);
  1584. // high half 0x7C01 (+sNaN) negated -> still sNaN (class 0, not quieted).
  1585. let hi_cases: &[([u32; 4], u32)] = &[
  1586. ([0x3C00_0000, 1 << 3, 0, 0], 1),
  1587. ([0x3C00_0000, 1 << 8, 0, 0], 0),
  1588. ([0x7C01_FFFF, 1 << 0, 0, 0], 1),
  1589. ([0x7C01_FFFF, 1 << 1, 0, 0], 0),
  1590. ];
  1591. let hi_in: Vec<[u32; 4]> = hi_cases.iter().map(|c| c.0).collect();
  1592. run_cases(&cmp_hi_neg, &hi_in, |backend, i, inp, got| {
  1593. let want = hi_cases[i].1;
  1594. assert_eq!(
  1595. got, want,
  1596. "{backend}: v_cmp_class_f16(-hi({:#010x}), {:#05x}) = {got}, want {want}",
  1597. inp[0], inp[1],
  1598. );
  1599. });
  1600. }
  1601. #[test]
  1602. fn v_cvt_f32_f64_matches_ieee754() {
  1603. // v_cvt_f32_f64 v0, v[1:2] (VOP1 opcode 0x00f -> VOP3 opcode 0x18f).
  1604. let plain = build_valu_cs(&[vop1(0x00f, 0, vgpr(1))]);
  1605. // Same with abs + neg on src0 (VOP3: abs[0] = bit 8 of w0, neg[0] = bit 29 of w1).
  1606. let [mut w0, mut w1] = vop3(0x18f, 0, vgpr(1), 0, 0);
  1607. w0 |= 1 << 8;
  1608. w1 |= 1 << 29;
  1609. let neg_abs = build_valu_cs(&[w0, w1]);
  1610. let values: &[f64] = &[
  1611. 0.0,
  1612. -0.0,
  1613. 1.0,
  1614. -1.0,
  1615. 3.5,
  1616. -123456.75,
  1617. // Tie-to-even: even mantissa stays, odd mantissa rounds up.
  1618. f64::from_bits(0x3FF0_0000_1000_0000), // 1.0 + 0.5 ulp(f32) -> 1.0
  1619. f64::from_bits(0x3FF0_0000_3000_0000), // (1.0 + 1 ulp) + 0.5 ulp -> 1.0 + 2 ulp
  1620. f64::from_bits(0x3FF0_0000_1000_0001), // > 0.5 ulp -> rounds up
  1621. // Largest finite f32 and overflow to +Inf / -Inf.
  1622. f64::from(f32::MAX),
  1623. f64::from(f32::MAX) * 1.000_001,
  1624. -f64::from(f32::MAX) * 1.000_001,
  1625. 1e300,
  1626. // Subnormal range (exp64 in [874, 896]), including carry into smallest normal.
  1627. f64::from(f32::MIN_POSITIVE),
  1628. f64::from(f32::MIN_POSITIVE) * 0.5,
  1629. f64::from(f32::MIN_POSITIVE) * 0.75,
  1630. f64::from(f32::from_bits(0x007F_FFFF)),
  1631. f64::from_bits(0x380F_FFFF_F000_0000), // max subnormal + 0.5 ulp -> min normal
  1632. // exp64 == 873: exact 2^-150 ties to 0; strictly greater rounds to min subnormal (1).
  1633. f64::from_bits(0x3690_0000_0000_0000),
  1634. f64::from_bits(0x3690_0000_0000_0001),
  1635. f64::from_bits(0xB690_0000_0000_0001),
  1636. // Deep underflow -> +/-0.0.
  1637. 1e-200,
  1638. -1e-200,
  1639. // Infinities and NaNs.
  1640. f64::INFINITY,
  1641. f64::NEG_INFINITY,
  1642. f64::from_bits(0x7FF8_0000_0000_0000), // +qNaN
  1643. f64::from_bits(0x7FF0_0000_0000_0001), // +sNaN -> quieted
  1644. ];
  1645. let inputs: Vec<[u32; 4]> = values
  1646. .iter()
  1647. .map(|&x| {
  1648. let b = x.to_bits();
  1649. [b as u32, (b >> 32) as u32, 0, 0]
  1650. })
  1651. .collect();
  1652. run_cases(&plain, &inputs, |backend, i, _, got| {
  1653. let x = values[i];
  1654. let want = (x as f32).to_bits();
  1655. if x.is_nan() {
  1656. assert!(
  1657. f32::from_bits(got).is_nan() && (got & 0x0040_0000) != 0,
  1658. "{backend}: v_cvt_f32_f64({:#018x}) = {got:#010x}, expected qNaN",
  1659. x.to_bits(),
  1660. );
  1661. } else {
  1662. assert_eq!(
  1663. got, want,
  1664. "{backend}: v_cvt_f32_f64({x} / {:#018x}) = {got:#010x}, want {want:#010x}",
  1665. x.to_bits(),
  1666. );
  1667. }
  1668. });
  1669. // -|x| via VOP3 abs + neg modifiers.
  1670. let mod_values: &[f64] = &[2.5, -2.5, 0.0, f64::INFINITY];
  1671. let mod_in: Vec<[u32; 4]> = mod_values
  1672. .iter()
  1673. .map(|&x| {
  1674. let b = x.to_bits();
  1675. [b as u32, (b >> 32) as u32, 0, 0]
  1676. })
  1677. .collect();
  1678. run_cases(&neg_abs, &mod_in, |backend, i, _, got| {
  1679. let x = mod_values[i];
  1680. let want = (-(x.abs()) as f32).to_bits();
  1681. assert_eq!(
  1682. got, want,
  1683. "{backend}: v_cvt_f32_f64(-|{x}|) = {got:#010x}, want {want:#010x}",
  1684. );
  1685. });
  1686. }
  1687. #[test]
  1688. fn whole_wave_f64_sum_and_cvt_f32_f64() {
  1689. let s_or_saveexec_b32 =
  1690. |sdst: u8, src0: u8| 0xBE80_0000 | (sdst as u32) << 16 | 0x3D << 8 | src0 as u32;
  1691. let v_mov_dpp8 = |vdst: u8, vsrc: u8, sel: u32| [vop1(0x001, vdst, 0xE9), vsrc as u32 | (sel << 8)];
  1692. let v_mov_row_mirror = |vdst: u8, vsrc: u8| {
  1693. [
  1694. vop1(0x001, vdst, 0xFA),
  1695. vsrc as u32 | (0x140 << 8) | (1 << 19) | (0xF << 24) | (0xF << 28),
  1696. ]
  1697. };
  1698. let mut words = Vec::new();
  1699. words.push(s_mov_b32(5, 0x80));
  1700. words.extend_from_slice(&s_load_dwordx4(8, 4));
  1701. // Per-lane f64 input in v[6:7] = (s0, s1).
  1702. words.push(vop1(0x001, 6, sgpr(0)));
  1703. words.push(vop1(0x001, 7, sgpr(1)));
  1704. // Whole-wave f64 sum over Wave32 with s_mov_b32 copy before EXEC restore.
  1705. words.push(s_or_saveexec_b32(12, 0xC1));
  1706. words.extend_from_slice(&vop3(0x101, 2, 0x80, vgpr(6), sgpr(12)));
  1707. words.extend_from_slice(&vop3(0x101, 3, 0x80, vgpr(7), sgpr(12)));
  1708. for sel in [14570689u32, 9658386, 2340] {
  1709. words.extend_from_slice(&v_mov_dpp8(4, 2, sel));
  1710. words.extend_from_slice(&v_mov_dpp8(5, 3, sel));
  1711. words.extend_from_slice(&vop3(0x164, 2, vgpr(4), vgpr(2), 0)); // v_add_f64
  1712. }
  1713. words.extend_from_slice(&v_mov_row_mirror(4, 2));
  1714. words.extend_from_slice(&v_mov_row_mirror(5, 3));
  1715. words.extend_from_slice(&vop3(0x164, 2, vgpr(4), vgpr(2), 0));
  1716. words.extend_from_slice(&vop3(0x378, 4, vgpr(2), 0x80, 0x80)); // v_permlanex16_b32
  1717. words.extend_from_slice(&vop3(0x378, 5, vgpr(3), 0x80, 0x80));
  1718. words.extend_from_slice(&vop3(0x164, 2, vgpr(4), vgpr(2), 0));
  1719. words.extend_from_slice(&vop3(0x360, 14, vgpr(2), 0x80, 0)); // v_readlane_b32 s14, v2, 0
  1720. words.extend_from_slice(&vop3(0x360, 15, vgpr(3), 0x80, 0)); // v_readlane_b32 s15, v3, 0
  1721. words.push(s_mov_b32(16, 14));
  1722. words.push(s_mov_b32(17, 15));
  1723. words.push(s_mov_b32(126, 12)); // restore exec_lo
  1724. words.push(vop1(0x00f, 0, sgpr(16))); // v_cvt_f32_f64 v0, s[16:17]
  1725. words.extend_from_slice(&buffer_store_dword(0, 8, 0));
  1726. words.push(S_ENDPGM);
  1727. let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
  1728. let native = NativeProgram {
  1729. stage: HwStage::Cs,
  1730. wave64: false,
  1731. vgprs: 12,
  1732. layout: vec![
  1733. RootParam {
  1734. root: RootType::Constants,
  1735. table_offset_dwords: 0,
  1736. sgprs: 4,
  1737. base_register: 0,
  1738. user_data: 0,
  1739. slot: 0,
  1740. },
  1741. RootParam {
  1742. root: RootType::Table,
  1743. table_offset_dwords: 0,
  1744. sgprs: 1,
  1745. base_register: 0,
  1746. user_data: 4,
  1747. slot: 1,
  1748. },
  1749. ],
  1750. used: vec![UsedResource {
  1751. kind: ResourceType::Uav,
  1752. root: RootType::Table,
  1753. table_offset_dwords: 0,
  1754. lower_bound: 0,
  1755. stride: 0,
  1756. dwords: 4,
  1757. user_data: 4,
  1758. slot: 1,
  1759. }],
  1760. io: StageIo::Cs(ComputeIo {
  1761. rsrc2: 5 << 1,
  1762. threads: [4, 1, 1],
  1763. }),
  1764. code,
  1765. };
  1766. let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
  1767. let st = structure::structure(&p).expect("structure");
  1768. let res =
  1769. resource::track(&p, &native.layout, native.stage, Some(&st)).expect("resource::track");
  1770. let io = io::raise(&p, &native).expect("io::raise");
  1771. let lowered = lower::lower(&lower::Parts {
  1772. native: &native,
  1773. p: &p,
  1774. st: &st,
  1775. io: &io,
  1776. res: &res,
  1777. inputs: Vec::new(),
  1778. outputs: Vec::new(),
  1779. prims: Vec::new(),
  1780. mesh_stride: 0,
  1781. })
  1782. .expect("lower");
  1783. let shader = HostShader {
  1784. stage: HwStage::Cs,
  1785. dxil: lowered.dxil,
  1786. user_data: lowered.user_data,
  1787. samplers: lowered.samplers,
  1788. static_samplers: Vec::new(),
  1789. root_cbvs: lowered.root_cbvs,
  1790. root_srvs: lowered.root_srvs,
  1791. root_uavs: lowered.root_uavs,
  1792. root_indexed_views: Vec::new(),
  1793. };
  1794. if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
  1795. let mut copy = shader.dxil.clone();
  1796. v.validate(&mut copy).expect("DXIL validation failed");
  1797. }
  1798. let cases: &[(f64, f32)] = &[(1.25, 5.0), (-0.75, -3.0)];
  1799. let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
  1800. for (label, warp) in [("hardware", false), ("warp", true)] {
  1801. let Ok(host) = Host::new(warp) else {
  1802. continue;
  1803. };
  1804. let (root, pso) = match host.compute_pipeline(&shader) {
  1805. Ok(p) => p,
  1806. // WARP does not support fixed WaveSize(32) on SM 6.6.
  1807. Err(e) if warp => {
  1808. eprintln!("{label}: compute_pipeline skipped ({e})");
  1809. continue;
  1810. }
  1811. Err(e) => panic!("{label}: compute_pipeline failed: {e}"),
  1812. };
  1813. for &(x, want) in cases {
  1814. let b = x.to_bits();
  1815. let inputs = [b as u32, (b >> 32) as u32, 0, 0];
  1816. let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
  1817. for u in &shader.user_data {
  1818. ud[u.index as usize] = match (u.root, u.slot) {
  1819. (RootType::Constants, 0) => inputs[u.dword as usize],
  1820. (RootType::Table, 1) => 0,
  1821. other => panic!("unexpected user data {other:?}"),
  1822. };
  1823. }
  1824. let out = host
  1825. .dispatch(
  1826. &root,
  1827. &pso,
  1828. &Dispatch {
  1829. roots: vec![(0, Root::Constants(ud))],
  1830. views: &[View::RawUav(1)],
  1831. samplers: &[],
  1832. groups: [1, 1, 1],
  1833. },
  1834. )
  1835. .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}"));
  1836. assert_eq!(
  1837. out[0][0],
  1838. want.to_bits(),
  1839. "{label}: wave f64 sum({x}) = {:#010x}, want {:#010x}",
  1840. out[0][0],
  1841. want.to_bits(),
  1842. );
  1843. }
  1844. }
  1845. }