io.rs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  1. //! I/O raising (decision 0003): what a program's input registers, its
  2. //! interpolation and its exports mean.
  3. //!
  4. //! Pixel shaders get the VGPRs `SPI_PS_INPUT_ADDR` enables, in a fixed
  5. //! order (barycentrics, then position, front face...). `v_interp_p1` and
  6. //! `v_interp_p2` (and their f16 forms) evaluate an attribute from a pair of
  7. //! barycentrics; `v_interp_mov` reads one vertex's value. After the 32-bit
  8. //! export patch ([`NativeProgram::patched_code`]) exports carry plain
  9. //! 32-bit values: `mrt<n>` is render target n, `mrtz` depth, stencil and
  10. //! sample mask, `null` nothing. A lane whose EXEC bit is clear at the
  11. //! export that ends the program (`done`) is discarded: that export's guard
  12. //! after structurisation.
  13. //!
  14. //! Vertex shaders that run as the hardware VS get the vertex id in v0, the
  15. //! primitive id in v2 and the instance id in v3; the fetch shader loads
  16. //! channel k of each attribute into its VGPR + k. `exp pos0` is the
  17. //! position, `exp param<n>` the output with parameter n.
  18. //!
  19. //! Attributes and outputs are named by their row: a register of the
  20. //! container's signature part.
  21. //!
  22. //! Compute programs get the thread id in the group in v0-v2 and the group
  23. //! id in the SGPRs after the user data, as `COMPUTE_PGM_RSRC2` enables them.
  24. //!
  25. //! Mesh programs run as one NGG stage. The program computes its thread
  26. //! index from the wave index (s3 bits 24-27) and the lane (`v_mbcnt`), and
  27. //! its group id from v5 of the first lane (`v_readfirstlane`: the group
  28. //! times the group size). Lane n exports vertex n (`exp pos`, `exp param`)
  29. //! and primitive n (`exp prim`: 10-bit vertex indices at bits 0, 10, 20,
  30. //! bit 31 culls); `param` entries with bit 7 are per-primitive outputs. One
  31. //! lane sends the output counts (`s_sendmsg` GS_ALLOC_REQ, m0 = vertices |
  32. //! primitives << 12).
  33. use crate::ShaderError;
  34. use crate::gfx10::{Fields, Operand};
  35. use crate::ir::{Inst, Program, Reg, Value};
  36. use crate::native::{HwStage, NativeProgram, PsInput, StageIo, Usage};
  37. use crate::resource::Site;
  38. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  39. pub enum Input {
  40. VertexId,
  41. PrimitiveId,
  42. InstanceId,
  43. /// A vertex attribute the fetch shader loads.
  44. Attribute {
  45. row: u8,
  46. channel: u8,
  47. },
  48. /// `index` 0 is i, 1 is j (2 the pull model's w).
  49. Barycentric {
  50. kind: Barycentric,
  51. index: u8,
  52. },
  53. /// Pixel position channel (0-3: x, y, z, w).
  54. Position(u8),
  55. FrontFace,
  56. /// Sample id and other bits.
  57. Ancillary,
  58. SampleCoverage,
  59. FixedPosition,
  60. LineStipple,
  61. /// Compute: thread-group id component (an SGPR).
  62. GroupId(u8),
  63. /// Compute: thread id within the group, component (a VGPR).
  64. ThreadIdInGroup(u8),
  65. /// Compute: the thread-group info SGPR (wave index and count).
  66. GroupInfo,
  67. /// Mesh: v5, the group id times the group size (read as uniform).
  68. MeshGroup,
  69. /// Mesh: s3, the wave's index in the group in bits 24-27.
  70. MergedWaveInfo,
  71. }
  72. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  73. pub enum Barycentric {
  74. PerspectiveSample,
  75. PerspectiveCenter,
  76. PerspectiveCentroid,
  77. PerspectivePullModel,
  78. LinearSample,
  79. LinearCenter,
  80. LinearCentroid,
  81. }
  82. /// The pixel input VGPRs in hardware order: one entry per
  83. /// `SPI_PS_INPUT_ADDR` bit.
  84. const PS_VGPRS: [(u8, Option<Barycentric>); 16] = [
  85. (2, Some(Barycentric::PerspectiveSample)),
  86. (2, Some(Barycentric::PerspectiveCenter)),
  87. (2, Some(Barycentric::PerspectiveCentroid)),
  88. (3, Some(Barycentric::PerspectivePullModel)),
  89. (2, Some(Barycentric::LinearSample)),
  90. (2, Some(Barycentric::LinearCenter)),
  91. (2, Some(Barycentric::LinearCentroid)),
  92. (1, None), // line stipple
  93. (1, None), // position x
  94. (1, None), // y
  95. (1, None), // z
  96. (1, None), // w
  97. (1, None), // front face
  98. (1, None), // ancillary
  99. (1, None), // sample coverage
  100. (1, None), // fixed-point position
  101. ];
  102. fn ps_system(bit: usize) -> Input {
  103. match bit {
  104. 7 => Input::LineStipple,
  105. 8..=11 => Input::Position(bit as u8 - 8),
  106. 12 => Input::FrontFace,
  107. 13 => Input::Ancillary,
  108. 14 => Input::SampleCoverage,
  109. _ => Input::FixedPosition,
  110. }
  111. }
  112. /// An attribute channel of the input signature.
  113. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  114. pub struct Attribute {
  115. pub usage: Usage,
  116. pub row: u8,
  117. pub channel: u8,
  118. /// The upper f16 half of the channel (packed fp16 inputs).
  119. pub high: bool,
  120. }
  121. #[derive(Debug, Clone, PartialEq, Eq)]
  122. pub enum Interp {
  123. /// This site's result (`v_interp_p2*`) is the attribute interpolated
  124. /// with `barycentric`; `first` are the `v_interp_p1*` halves it
  125. /// completes (one per path where the compiler shares a first half).
  126. Interpolated {
  127. attribute: Attribute,
  128. barycentric: Barycentric,
  129. first: Vec<Site>,
  130. },
  131. /// One vertex's value (`v_interp_mov_f32`), as encoded: 0 for P10,
  132. /// 1 for P20, 2 for P0 (the provoking vertex).
  133. Vertex { attribute: Attribute, vertex: u8 },
  134. }
  135. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  136. pub enum Target {
  137. Color(u8),
  138. /// Depth, stencil, sample mask (channels as `DB_SHADER_CONTROL` enables).
  139. Depth,
  140. Null,
  141. Position(u8),
  142. Param {
  143. usage: Usage,
  144. row: u8,
  145. },
  146. /// `param0` of a vertex shader without outputs: the hardware wants one
  147. /// parameter export regardless.
  148. Unread,
  149. /// The primitive export of a merged or mesh stage.
  150. Primitive,
  151. /// A mesh program's per-primitive output (a row of `PSG1`).
  152. PrimitiveParam {
  153. usage: Usage,
  154. row: u8,
  155. },
  156. }
  157. #[derive(Debug, Clone, PartialEq, Eq)]
  158. pub struct Export {
  159. pub site: Site,
  160. pub target: Target,
  161. /// Per channel, as the instruction enables them.
  162. pub values: [Option<Value>; 4],
  163. /// Two f16 values per dword.
  164. pub compressed: bool,
  165. /// The program's last export (for pixels: kills the lanes not in EXEC).
  166. pub done: bool,
  167. }
  168. #[derive(Debug, Clone, Default, PartialEq, Eq)]
  169. pub struct Io {
  170. /// Input values the hardware loads, with their meaning; other VGPRs
  171. /// read before written hold undefined values.
  172. pub inputs: Vec<(Value, Input)>,
  173. pub interps: Vec<(Site, Interp)>,
  174. pub exports: Vec<Export>,
  175. }
  176. /// Raises the I/O of `p`, built from `native`'s patched code. Fails for
  177. /// stages whose stage data is not read and on constructs not covered yet.
  178. pub fn raise(p: &Program, native: &NativeProgram) -> Result<Io, ShaderError> {
  179. let unsupported = |offset, what| ShaderError::Unsupported { offset, what };
  180. let (loaded, ps_inputs, params) = match (&native.io, native.stage) {
  181. (
  182. StageIo::Ps {
  183. inputs, input_addr, ..
  184. },
  185. HwStage::Ps,
  186. ) => {
  187. // A pixel shader exports no parameters; `[]` never reaches `Unread`.
  188. let loaded = ps_vgprs(*input_addr)
  189. .into_iter()
  190. .map(|(r, i)| (Reg::V(r), i))
  191. .collect();
  192. (loaded, &inputs[..], &[][..])
  193. }
  194. (StageIo::Vs { inputs, outputs }, HwStage::Vs) => {
  195. let mut loaded = vec![
  196. (Reg::V(0), Input::VertexId),
  197. (Reg::V(2), Input::PrimitiveId),
  198. (Reg::V(3), Input::InstanceId),
  199. ];
  200. for i in inputs {
  201. for channel in (0..4).filter(|c| i.mask >> c & 1 != 0) {
  202. let input = Input::Attribute {
  203. row: i.row,
  204. channel,
  205. };
  206. loaded.push((Reg::V(i.vgpr + channel), input));
  207. }
  208. }
  209. (loaded, &[][..], &outputs[..])
  210. }
  211. // Compute: thread ids in v0-v2, group ids and the group info in the
  212. // SGPRs after the user data.
  213. (StageIo::Cs(cs), HwStage::Cs) => {
  214. let (ids, info) = cs.system_sgprs();
  215. let mut loaded: Vec<(Reg, Input)> = (0..cs.thread_id_vgprs())
  216. .map(|c| (Reg::V(c), Input::ThreadIdInGroup(c)))
  217. .collect();
  218. for (c, s) in ids.into_iter().enumerate() {
  219. if let Some(s) = s {
  220. loaded.push((Reg::S(s), Input::GroupId(c as u8)));
  221. }
  222. }
  223. loaded.extend(info.map(|s| (Reg::S(s), Input::GroupInfo)));
  224. (loaded, &[][..], &[][..])
  225. }
  226. (StageIo::Ms(ms), HwStage::Ms) => {
  227. let group = p.inputs.iter().find(|i| i.0 == Reg::V(5)).map(|i| i.1);
  228. // The group input holds the same value in every lane only as the
  229. // first lane reads it; a VGPR write reads its old value too.
  230. let per_lane = p.blocks.iter().flat_map(|b| &b.insts).find(|i| {
  231. group.is_some_and(|g| i.reads.contains(&(Reg::V(5), g)))
  232. && i.name() != "v_readfirstlane_b32"
  233. && i.write(Reg::V(5)).is_none()
  234. });
  235. if let Some(i) = per_lane {
  236. return Err(unsupported(
  237. i.machine.offset,
  238. "the mesh group input read per lane",
  239. ));
  240. }
  241. let loaded = vec![
  242. (Reg::V(5), Input::MeshGroup),
  243. (Reg::S(3), Input::MergedWaveInfo),
  244. ];
  245. (loaded, &[][..], &ms.outputs[..])
  246. }
  247. _ => return Err(unsupported(0, "I/O of this stage")),
  248. };
  249. let inputs: Vec<(Value, Input)> = p
  250. .inputs
  251. .iter()
  252. .filter_map(|&(reg, v)| loaded.iter().find(|l| l.0 == reg).map(|l| (v, l.1)))
  253. .collect();
  254. let input_of = |v: Value| inputs.iter().find(|i| i.0 == v).map(|i| i.1);
  255. let attribute = |inst: &Inst, attr: &Operand| match *attr {
  256. Operand::Attr { index, chan, high } => ps_inputs
  257. .iter()
  258. .find(|i: &&PsInput| i.attr == index)
  259. .map(|i| Attribute {
  260. usage: i.usage,
  261. row: i.row,
  262. channel: chan,
  263. high,
  264. })
  265. .ok_or(unsupported(
  266. inst.machine.offset,
  267. "an interpolated attribute the stage data does not list",
  268. )),
  269. _ => Err(unsupported(inst.machine.offset, "an interpolation operand")),
  270. };
  271. // A VGPR value's barycentric kind and index, if it is one as loaded.
  272. let barycentric = |v: Option<Value>| match v.and_then(input_of) {
  273. Some(Input::Barycentric { kind, index }) => Some((kind, index)),
  274. _ => None,
  275. };
  276. let mut io = Io {
  277. inputs: inputs.clone(),
  278. ..Io::default()
  279. };
  280. let defs: std::collections::HashMap<Value, Site> = p
  281. .blocks
  282. .iter()
  283. .enumerate()
  284. .flat_map(|(b, block)| {
  285. block
  286. .insts
  287. .iter()
  288. .enumerate()
  289. .flat_map(move |(i, inst)| inst.writes.iter().map(move |w| (w.1, (b, i))))
  290. })
  291. .collect();
  292. let phis: std::collections::HashMap<Value, (usize, usize)> = p
  293. .blocks
  294. .iter()
  295. .enumerate()
  296. .flat_map(|(b, block)| {
  297. block
  298. .phis
  299. .iter()
  300. .enumerate()
  301. .map(move |(i, phi)| (phi.value, (b, i)))
  302. })
  303. .collect();
  304. let halves = Halves {
  305. p,
  306. defs: &defs,
  307. phis: &phis,
  308. };
  309. for (b, block) in p.blocks.iter().enumerate() {
  310. for (i, inst) in block.insts.iter().enumerate() {
  311. let site = (b, i);
  312. let at = inst.machine.offset;
  313. let name = inst.name();
  314. match &inst.fields {
  315. Fields::Vintrp { dst, src, attr } => {
  316. let attribute = attribute(inst, attr)?;
  317. match (name, *src) {
  318. ("v_interp_mov_f32", Operand::Const(vertex)) => {
  319. io.interps
  320. .push((site, Interp::Vertex { attribute, vertex }));
  321. }
  322. ("v_interp_p1_f32", _) => {}
  323. ("v_interp_p2_f32", Operand::Vector { reg, .. }) => {
  324. let Operand::Vector { reg: d, .. } = *dst else {
  325. return Err(unsupported(at, "an interpolation operand"));
  326. };
  327. // The first half's result is this one's old dst.
  328. let interp = halves
  329. .pair(
  330. attr,
  331. inst.read(Reg::V(d)),
  332. inst.read(Reg::V(reg)),
  333. &barycentric,
  334. )
  335. .map_err(|what| unsupported(at, what))?;
  336. io.interps.push((site, interp.with(attribute)));
  337. }
  338. _ => return Err(unsupported(at, "an interpolation form")),
  339. }
  340. }
  341. Fields::Valu(v) if name.starts_with("v_interp_") => match name {
  342. "v_interp_p1ll_f16" => {}
  343. "v_interp_p2_f16" => {
  344. let attribute = attribute(inst, &v.src[0])?;
  345. let read = |k: usize| match v.src.get(k) {
  346. Some(&Operand::Vector { reg, .. }) => inst.read(Reg::V(reg)),
  347. _ => None,
  348. };
  349. let interp = halves
  350. .pair(&v.src[0], read(2), read(1), &barycentric)
  351. .map_err(|what| unsupported(at, what))?;
  352. io.interps.push((site, interp.with(attribute)));
  353. }
  354. _ => return Err(unsupported(at, "an interpolation form")),
  355. },
  356. Fields::Exp {
  357. target,
  358. src,
  359. compr,
  360. done,
  361. ..
  362. } => {
  363. let target = match *target {
  364. t @ 0..=7 => Target::Color(t),
  365. 8 => Target::Depth,
  366. 9 => Target::Null,
  367. t @ 12..=16 => Target::Position(t - 12),
  368. 20 => Target::Primitive,
  369. 32 if params.is_empty() => Target::Unread,
  370. t @ 32..=63 => {
  371. // Bit 7: a mesh program's per-primitive output.
  372. let o = params.iter().find(|o| o.param & 0x7F == t - 32).ok_or(
  373. unsupported(at, "a parameter export the stage data does not list"),
  374. )?;
  375. let (usage, row) = (o.usage, o.row);
  376. if o.param & 0x80 != 0 {
  377. Target::PrimitiveParam { usage, row }
  378. } else {
  379. Target::Param { usage, row }
  380. }
  381. }
  382. _ => return Err(unsupported(at, "an export target")),
  383. };
  384. let values = src.map(|s| match s {
  385. Some(Operand::Vector { reg, .. }) => inst.read(Reg::V(reg)),
  386. _ => None,
  387. });
  388. io.exports.push(Export {
  389. site,
  390. target,
  391. values,
  392. compressed: *compr,
  393. done: *done,
  394. });
  395. }
  396. _ => {}
  397. }
  398. }
  399. }
  400. Ok(io)
  401. }
  402. /// The pixel input VGPRs that `addr` enables, with their meaning.
  403. fn ps_vgprs(addr: u32) -> Vec<(u8, Input)> {
  404. let mut out = Vec::new();
  405. let mut next = 0u8;
  406. for (bit, &(count, kind)) in PS_VGPRS.iter().enumerate() {
  407. if addr >> bit & 1 == 0 {
  408. continue;
  409. }
  410. for index in 0..count {
  411. let input = match kind {
  412. Some(kind) => Input::Barycentric { kind, index },
  413. None => ps_system(bit),
  414. };
  415. out.push((next + index, input));
  416. }
  417. next += count;
  418. }
  419. out
  420. }
  421. /// An interpolation before its attribute is known.
  422. struct Pair {
  423. barycentric: Barycentric,
  424. first: Vec<Site>,
  425. }
  426. impl Pair {
  427. fn with(self, attribute: Attribute) -> Interp {
  428. Interp::Interpolated {
  429. attribute,
  430. barycentric: self.barycentric,
  431. first: self.first,
  432. }
  433. }
  434. }
  435. /// Finds the first halves of interpolations.
  436. struct Halves<'a> {
  437. p: &'a Program,
  438. defs: &'a std::collections::HashMap<Value, Site>,
  439. phis: &'a std::collections::HashMap<Value, (usize, usize)>,
  440. }
  441. impl Halves<'_> {
  442. /// The interpolation whose second half reads the first half's result
  443. /// `acc`, the barycentric `j`, and attribute `attr`: every first half
  444. /// must read the same attribute channel and the same kind's i.
  445. fn pair(
  446. &self,
  447. attr: &Operand,
  448. acc: Option<Value>,
  449. j: Option<Value>,
  450. barycentric: &impl Fn(Option<Value>) -> Option<(Barycentric, u8)>,
  451. ) -> Result<Pair, &'static str> {
  452. let mut first = Vec::new();
  453. self.sites(
  454. acc.ok_or("an interpolation without its first half")?,
  455. &mut Vec::new(),
  456. &mut first,
  457. )?;
  458. let Some((kind, 1)) = barycentric(j) else {
  459. return Err("an interpolation with computed barycentrics");
  460. };
  461. for &(b, i) in &first {
  462. let inst = &self.p.blocks[b].insts[i];
  463. let (a, i) = match &inst.fields {
  464. Fields::Vintrp {
  465. src: Operand::Vector { reg, .. },
  466. attr,
  467. ..
  468. } if inst.name() == "v_interp_p1_f32" => (*attr, inst.read(Reg::V(*reg))),
  469. Fields::Valu(v) if inst.name() == "v_interp_p1ll_f16" => match v.src.get(1) {
  470. Some(&Operand::Vector { reg, .. }) => (v.src[0], inst.read(Reg::V(reg))),
  471. _ => return Err("an interpolation without its first half"),
  472. },
  473. _ => return Err("an interpolation without its first half"),
  474. };
  475. if a != *attr {
  476. return Err("interpolation halves of different attributes");
  477. }
  478. if barycentric(i) != Some((kind, 0)) {
  479. return Err("an interpolation with computed barycentrics");
  480. }
  481. }
  482. Ok(Pair {
  483. barycentric: kind,
  484. first,
  485. })
  486. }
  487. /// The instructions `v` comes from, through phis (`seen`: phis on the
  488. /// way; a loop back to one adds nothing).
  489. fn sites(
  490. &self,
  491. v: Value,
  492. seen: &mut Vec<Value>,
  493. out: &mut Vec<Site>,
  494. ) -> Result<(), &'static str> {
  495. if let Some(&site) = self.defs.get(&v) {
  496. if !out.contains(&site) {
  497. out.push(site);
  498. }
  499. return Ok(());
  500. }
  501. let &(b, i) = self
  502. .phis
  503. .get(&v)
  504. .ok_or("an interpolation without its first half")?;
  505. if !seen.contains(&v) {
  506. seen.push(v);
  507. for &a in &self.p.blocks[b].phis[i].args {
  508. self.sites(a, seen, out)?;
  509. }
  510. }
  511. Ok(())
  512. }
  513. }
  514. #[cfg(test)]
  515. mod tests {
  516. use super::*;
  517. use crate::native::ExportPatch;
  518. const S_ENDPGM: u32 = 0xBF81_0000;
  519. fn program(words: &[u32]) -> Program {
  520. let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
  521. crate::ir::build(&code, false, 256).unwrap()
  522. }
  523. fn pixel(inputs: Vec<PsInput>, input_addr: u32) -> NativeProgram {
  524. NativeProgram {
  525. stage: HwStage::Ps,
  526. wave64: false,
  527. vgprs: 256,
  528. layout: vec![],
  529. used: vec![],
  530. io: StageIo::Ps {
  531. inputs,
  532. input_addr,
  533. db_shader_control: 0,
  534. patches: Vec::<ExportPatch>::new(),
  535. },
  536. code: vec![],
  537. }
  538. }
  539. const TEXCOORD: PsInput = PsInput {
  540. usage: Usage::Generic,
  541. row: 1,
  542. mask: 3,
  543. attr: 0,
  544. flat: false,
  545. fp16: false,
  546. pack2: false,
  547. row2: 1,
  548. };
  549. #[test]
  550. fn interpolation_pairs_and_color_exports() {
  551. // Blit's pixel shader: TEXCOORD.xy from the perspective-center i/j
  552. // in v0/v1, then exported unconverted to MRT0.
  553. let p = program(&[
  554. 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x
  555. 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
  556. 0xF800_180F,
  557. 0x0302_0102, // exp mrt0, v2, v1, v2, v3 done vm
  558. S_ENDPGM,
  559. ]);
  560. let io = raise(&p, &pixel(vec![TEXCOORD], 2)).unwrap();
  561. let input = |reg| p.inputs.iter().find(|i| i.0 == Reg::V(reg)).unwrap().1;
  562. let center = |index| Input::Barycentric {
  563. kind: Barycentric::PerspectiveCenter,
  564. index,
  565. };
  566. assert!(io.inputs.contains(&(input(0), center(0))));
  567. assert!(io.inputs.contains(&(input(1), center(1))));
  568. // v2 and v3 are read before written but hold nothing.
  569. assert!(!io.inputs.iter().any(|i| i.0 == input(3)));
  570. assert_eq!(
  571. io.interps,
  572. [(
  573. (0, 1),
  574. Interp::Interpolated {
  575. attribute: Attribute {
  576. usage: Usage::Generic,
  577. row: 1,
  578. channel: 0,
  579. high: false
  580. },
  581. barycentric: Barycentric::PerspectiveCenter,
  582. first: vec![(0, 0)],
  583. }
  584. )]
  585. );
  586. let [e] = &io.exports[..] else {
  587. panic!("{:?}", io.exports)
  588. };
  589. assert_eq!(
  590. (e.target, e.done, e.compressed),
  591. (Target::Color(0), true, false)
  592. );
  593. assert_eq!(e.values[0], p.blocks[0].insts[1].write(Reg::V(2)));
  594. }
  595. #[test]
  596. fn unpaired_or_unknown_interpolation_fails() {
  597. // p2 alone: its old dst is no p1's result.
  598. let lone = program(&[0xC809_0001, S_ENDPGM]); // v_interp_p2_f32 v2, v1, attr0.x
  599. assert!(raise(&lone, &pixel(vec![TEXCOORD], 2)).is_err());
  600. // attr1 is not in the stage data.
  601. let other = program(&[0xC808_0400, S_ENDPGM]); // v_interp_p1_f32 v2, v0, attr1.x
  602. assert!(raise(&other, &pixel(vec![TEXCOORD], 2)).is_err());
  603. }
  604. #[test]
  605. fn mesh_inputs_and_primitive_export() {
  606. let mesh = |words: &[u32]| {
  607. let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
  608. let p = crate::ir::build(&code, true, 256).unwrap();
  609. let native = NativeProgram {
  610. stage: HwStage::Ms,
  611. wave64: true,
  612. vgprs: 256,
  613. layout: vec![],
  614. used: vec![],
  615. io: StageIo::Ms(crate::native::MeshIo {
  616. outputs: vec![],
  617. clip_cntl: 0,
  618. threads: 128,
  619. max_vertices: 128,
  620. max_primitives: 128,
  621. topology: 2,
  622. lds_bytes: 0,
  623. }),
  624. code,
  625. };
  626. raise(&p, &native)
  627. };
  628. let io = mesh(&[
  629. 0x7E04_0505, // v_readfirstlane_b32 s2, v5
  630. 0xF800_0941,
  631. 0x0000_0009, // exp prim, v9, off, off, off done
  632. S_ENDPGM,
  633. ])
  634. .unwrap();
  635. assert!(io.inputs.iter().any(|i| i.1 == Input::MeshGroup));
  636. assert_eq!(io.exports[0].target, Target::Primitive);
  637. // The group input is uniform only as the first lane reads it.
  638. assert!(mesh(&[0x7E02_0305, S_ENDPGM]).is_err()); // v_mov_b32 v1, v5
  639. }
  640. #[test]
  641. fn pixel_vgprs_follow_the_input_address() {
  642. // Linear center (bit 5), then position x and y (bits 8, 9).
  643. let v = ps_vgprs(1 << 5 | 1 << 8 | 1 << 9);
  644. assert_eq!(
  645. v,
  646. [
  647. (
  648. 0,
  649. Input::Barycentric {
  650. kind: Barycentric::LinearCenter,
  651. index: 0
  652. }
  653. ),
  654. (
  655. 1,
  656. Input::Barycentric {
  657. kind: Barycentric::LinearCenter,
  658. index: 1
  659. }
  660. ),
  661. (2, Input::Position(0)),
  662. (3, Input::Position(1)),
  663. ]
  664. );
  665. }
  666. }