mod.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. //! GFX10 machine code: instruction boundaries, encodings and opcodes.
  2. //!
  3. //! Instructions are found by following control flow from offset 0, not by a
  4. //! linear sweep: compilers place data (constant tables) in the code region
  5. //! after the end of the program. [`Instruction::fields`] decodes the operand
  6. //! fields and [`Instruction::text`] prints them in AMD's SP3 syntax.
  7. //!
  8. //! Encodings by the top bits of the first dword:
  9. //!
  10. //! ```text
  11. //! 0xxxxxxx VOP2; 0111111 VOP1; 0111110 VOPC
  12. //! 10 SOP2; 1011 SOPK; 101111101 SOP1; 101111110 SOPC; 101111111 SOPP
  13. //! 110010 VINTRP 110011 VOP3P 110101 VOP3 110110 DS 110111 FLAT/GLOBAL/SCRATCH
  14. //! 111000 MUBUF 111010 MTBUF 111100 MIMG 111101 SMEM 111110 EXP
  15. //! ```
  16. mod fields;
  17. mod opcodes;
  18. mod sp3;
  19. pub use fields::{Cache, Dpp, Fields, NULL, Operand, Sdwa, Valu};
  20. use std::collections::BTreeMap;
  21. use crate::ShaderError;
  22. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
  23. pub enum Encoding {
  24. Sop2,
  25. Sopk,
  26. Sop1,
  27. Sopc,
  28. Sopp,
  29. Smem,
  30. Vop2,
  31. Vop1,
  32. Vopc,
  33. Vop3,
  34. Vop3p,
  35. Vintrp,
  36. Ds,
  37. Mubuf,
  38. Mtbuf,
  39. Mimg,
  40. Exp,
  41. Flat,
  42. Global,
  43. Scratch,
  44. }
  45. #[derive(Debug, Clone, PartialEq, Eq)]
  46. pub struct Instruction {
  47. /// Byte offset in the program.
  48. pub offset: usize,
  49. pub encoding: Encoding,
  50. pub opcode: u16,
  51. /// Every dword of the instruction, including literals and extra dwords.
  52. pub words: Vec<u32>,
  53. /// [`name`] of `encoding` and `opcode`, resolved once at decode time.
  54. /// The translator asks about every instruction eight times; the table is
  55. /// a binary search.
  56. name: Option<&'static str>,
  57. }
  58. impl Instruction {
  59. /// An instruction of these words, its name resolved.
  60. pub fn new(offset: usize, encoding: Encoding, opcode: u16, words: Vec<u32>) -> Self {
  61. Self { offset, encoding, opcode, words, name: name(encoding, opcode) }
  62. }
  63. /// AMD's name for the opcode, if it is in our table.
  64. pub fn name(&self) -> Option<&'static str> {
  65. self.name
  66. }
  67. }
  68. /// Decodes every instruction reachable from offset 0, sorted by offset.
  69. pub fn decode(code: &[u8]) -> Result<Vec<Instruction>, ShaderError> {
  70. if !code.len().is_multiple_of(4) {
  71. return Err(isa(code.len(), "code size is not a multiple of 4"));
  72. }
  73. let mut found = BTreeMap::new();
  74. let mut pending = vec![0usize];
  75. while let Some(mut offset) = pending.pop() {
  76. while !found.contains_key(&offset) {
  77. let inst = instruction(code, offset)?;
  78. let next = offset + 4 * inst.words.len();
  79. let flow = control(&inst, code.len(), |at| {
  80. found.range(..at).next_back().map(|(_, i)| i)
  81. })?;
  82. found.insert(offset, inst);
  83. match flow {
  84. Flow::Next => offset = next,
  85. Flow::Stop => break,
  86. Flow::Jump(target) => offset = target,
  87. Flow::Branch(target) => {
  88. pending.push(target);
  89. offset = next;
  90. }
  91. }
  92. }
  93. }
  94. let list: Vec<Instruction> = found.into_values().collect();
  95. if let Some(w) = list
  96. .windows(2)
  97. .find(|w| w[0].offset + 4 * w[0].words.len() > w[1].offset)
  98. {
  99. return Err(isa(w[1].offset, "a branch lands inside an instruction"));
  100. }
  101. Ok(list)
  102. }
  103. /// Where execution goes after an instruction.
  104. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  105. pub(crate) enum Flow {
  106. Next,
  107. /// End of the program, or an indirect jump that is not a far jump.
  108. Stop,
  109. Jump(usize),
  110. /// Conditional: to the target or the next instruction.
  111. Branch(usize),
  112. }
  113. /// Control flow after `inst`, resolving far jumps. `before(at)` returns the
  114. /// decoded instruction with the highest offset below `at`, if any.
  115. pub(crate) fn control<'a>(
  116. inst: &Instruction,
  117. len: usize,
  118. before: impl Fn(usize) -> Option<&'a Instruction>,
  119. ) -> Result<Flow, ShaderError> {
  120. Ok(match flow(inst, inst.offset + 4 * inst.words.len(), len)? {
  121. Flow::Stop if inst.name() == Some("s_setpc_b64") => {
  122. far_jump(before, inst, len)?.map_or(Flow::Stop, Flow::Jump)
  123. }
  124. flow => flow,
  125. })
  126. }
  127. fn flow(inst: &Instruction, next: usize, len: usize) -> Result<Flow, ShaderError> {
  128. let target = || {
  129. let delta = 4 * i64::from(inst.words[0] as u16 as i16);
  130. usize::try_from(next as i64 + delta)
  131. .ok()
  132. .filter(|&t| t < len)
  133. .ok_or(isa(inst.offset, "branch target outside the code"))
  134. };
  135. Ok(match (inst.encoding, inst.name().unwrap_or("")) {
  136. (
  137. Encoding::Sopp,
  138. "s_endpgm" | "s_endpgm_saved" | "s_endpgm_ordered_ps_done" | "s_code_end",
  139. ) => Flow::Stop,
  140. (Encoding::Sopp, "s_branch") => Flow::Jump(target()?),
  141. (Encoding::Sopp, name) if name.starts_with("s_cbranch_") => Flow::Branch(target()?),
  142. (Encoding::Sopk, "s_call_b64") => Flow::Branch(target()?),
  143. // Indirect jump; `decode` resolves the compiler's far-jump form.
  144. (Encoding::Sop1, "s_setpc_b64") => Flow::Stop,
  145. _ => Flow::Next,
  146. })
  147. }
  148. /// Resolves the far jump compilers emit beyond the reach of a branch offset:
  149. /// `s_getpc_b64 s[n:n+1]`, `s_add_u32|s_sub_u32 sn, sn, literal`, a carry
  150. /// into s(n+1), `s_setpc_b64 s[n:n+1]`, looking back over the straight-line
  151. /// run just decoded. Any other `s_setpc_b64` (e.g. a handover to the next
  152. /// merged stage through registers) gives `None`.
  153. fn far_jump<'a>(
  154. before: impl Fn(usize) -> Option<&'a Instruction>,
  155. setpc: &Instruction,
  156. len: usize,
  157. ) -> Result<Option<usize>, ShaderError> {
  158. let n = setpc.words[0] & 0xFF;
  159. let mut delta = None;
  160. let mut at = setpc.offset;
  161. for _ in 0..4 {
  162. let Some(prev) = before(at) else {
  163. break;
  164. };
  165. if prev.offset + 4 * prev.words.len() != at {
  166. break;
  167. }
  168. let w = prev.words[0];
  169. let (sdst, ssrc0, ssrc1) = ((w >> 16) & 0x7F, w & 0xFF, (w >> 8) & 0xFF);
  170. match (prev.encoding, prev.name()) {
  171. (Encoding::Sop2, Some(op @ ("s_add_u32" | "s_sub_u32")))
  172. if sdst == n && ssrc0 == n && ssrc1 == 0xFF && delta.is_none() =>
  173. {
  174. // The low dword of a signed 64-bit offset: a backward jump
  175. // adds a negative one (its high dword is -1).
  176. let literal = i64::from(prev.words[1] as i32);
  177. delta = Some(if op == "s_add_u32" { literal } else { -literal });
  178. }
  179. (Encoding::Sop1, Some("s_getpc_b64")) if sdst == n => {
  180. let Some(delta) = delta else { break };
  181. // s_getpc_b64 yields the address of the instruction after it.
  182. return usize::try_from(prev.offset as i64 + 4 + delta)
  183. .ok()
  184. .filter(|&t| t < len)
  185. .map(Some)
  186. .ok_or(isa(setpc.offset, "far jump target outside the code"));
  187. }
  188. _ => {}
  189. }
  190. at = prev.offset;
  191. }
  192. Ok(None)
  193. }
  194. fn instruction(code: &[u8], offset: usize) -> Result<Instruction, ShaderError> {
  195. let word = |i: usize| {
  196. code.get(offset + 4 * i..offset + 4 * i + 4)
  197. .map(|b| u32::from_le_bytes(b.try_into().expect("4 bytes")))
  198. .ok_or(isa(offset, "instruction runs past the end of the code"))
  199. };
  200. let w = word(0)?;
  201. let (encoding, opcode, len) = if w >> 31 == 0 {
  202. let src0 = w & 0x1FF;
  203. // Literal constant, SDWA, DPP16, DPP8, DPP8 with fetch-inactive.
  204. let extra = usize::from(matches!(src0, 0xFF | 0xF9 | 0xFA | 0xE9 | 0xEA));
  205. match w >> 25 {
  206. 0x3F => (Encoding::Vop1, (w >> 9) & 0xFF, 1 + extra),
  207. 0x3E => (Encoding::Vopc, (w >> 17) & 0xFF, 1 + extra),
  208. op => {
  209. let mk_ak = name(Encoding::Vop2, op as u16).is_some_and(|n| {
  210. matches!(
  211. n,
  212. "v_madmk_f32"
  213. | "v_madak_f32"
  214. | "v_fmamk_f32"
  215. | "v_fmaak_f32"
  216. | "v_madmk_f16"
  217. | "v_madak_f16"
  218. | "v_fmamk_f16"
  219. | "v_fmaak_f16"
  220. )
  221. });
  222. (Encoding::Vop2, op, 1 + extra.max(usize::from(mk_ak)))
  223. }
  224. }
  225. } else if w >> 30 == 0b10 {
  226. let literal = |srcs: &[u32]| 1 + usize::from(srcs.contains(&0xFF));
  227. match w >> 23 {
  228. 0x17D => (Encoding::Sop1, (w >> 8) & 0xFF, literal(&[w & 0xFF])),
  229. 0x17E => (
  230. Encoding::Sopc,
  231. (w >> 16) & 0x7F,
  232. literal(&[w & 0xFF, (w >> 8) & 0xFF]),
  233. ),
  234. 0x17F => (Encoding::Sopp, (w >> 16) & 0x7F, 1),
  235. _ if w >> 28 == 0b1011 => {
  236. let op = (w >> 23) & 0x1F;
  237. let imm32 = name(Encoding::Sopk, op as u16) == Some("s_setreg_imm32_b32");
  238. (Encoding::Sopk, op, 1 + usize::from(imm32))
  239. }
  240. _ => (
  241. Encoding::Sop2,
  242. (w >> 23) & 0x7F,
  243. literal(&[w & 0xFF, (w >> 8) & 0xFF]),
  244. ),
  245. }
  246. } else {
  247. let vop3 =
  248. |w1: u32| 2 + usize::from([w1, w1 >> 9, w1 >> 18].iter().any(|s| s & 0x1FF == 0xFF));
  249. match w >> 26 {
  250. 0x32 => (Encoding::Vintrp, (w >> 16) & 0x3, 1),
  251. 0x33 => (Encoding::Vop3p, (w >> 16) & 0x7F, vop3(word(1)?)),
  252. 0x35 => (Encoding::Vop3, (w >> 16) & 0x3FF, vop3(word(1)?)),
  253. 0x36 => (Encoding::Ds, (w >> 18) & 0xFF, 2),
  254. 0x37 => {
  255. let encoding = match (w >> 14) & 3 {
  256. 0 => Encoding::Flat,
  257. 1 => Encoding::Scratch,
  258. 2 => Encoding::Global,
  259. _ => return Err(isa(offset, "reserved FLAT segment")),
  260. };
  261. (encoding, (w >> 18) & 0x7F, 2)
  262. }
  263. 0x38 => (Encoding::Mubuf, (w >> 18) & 0x7F | (w >> 25 & 1) << 7, 2),
  264. 0x3A => (
  265. Encoding::Mtbuf,
  266. (w >> 16) & 0x7 | (word(1)? >> 21 & 1) << 3,
  267. 2,
  268. ),
  269. // Bits 2:1 count extra dwords of non-sequential address registers.
  270. 0x3C => (
  271. Encoding::Mimg,
  272. (w >> 18) & 0x7F | (w & 1) << 7,
  273. 2 + (w as usize >> 1 & 3),
  274. ),
  275. 0x3D => (Encoding::Smem, (w >> 18) & 0xFF, 2),
  276. 0x3E => (Encoding::Exp, 0, 2),
  277. _ => return Err(isa(offset, "unknown encoding")),
  278. }
  279. };
  280. let opcode = opcode as u16;
  281. Ok(Instruction {
  282. offset,
  283. encoding,
  284. opcode,
  285. words: (0..len).map(word).collect::<Result<_, _>>()?,
  286. name: name(encoding, opcode),
  287. })
  288. }
  289. fn name(encoding: Encoding, opcode: u16) -> Option<&'static str> {
  290. use opcodes as t;
  291. let (table, op) = match encoding {
  292. Encoding::Sop2 => (t::SOP2, opcode),
  293. Encoding::Sopk => (t::SOPK, opcode),
  294. Encoding::Sop1 => (t::SOP1, opcode),
  295. Encoding::Sopc => (t::SOPC, opcode),
  296. Encoding::Sopp => (t::SOPP, opcode),
  297. Encoding::Smem => (t::SMEM, opcode),
  298. Encoding::Vop2 => (t::VOP2, opcode),
  299. Encoding::Vop1 => (t::VOP1, opcode),
  300. Encoding::Vopc => (t::VOPC, opcode),
  301. // VOP3 also encodes the VOPC, VOP2 and VOP1 opcodes at fixed bases.
  302. Encoding::Vop3 => match opcode {
  303. 0x000..0x100 => (t::VOPC, opcode),
  304. 0x100..0x140 => (t::VOP2, opcode - 0x100),
  305. 0x180..0x200 => (t::VOP1, opcode - 0x180),
  306. _ => (t::VOP3, opcode),
  307. },
  308. Encoding::Vop3p => (t::VOP3P, opcode),
  309. Encoding::Vintrp => (t::VINTRP, opcode),
  310. Encoding::Ds => (t::DS, opcode),
  311. Encoding::Mubuf => (t::MUBUF, opcode),
  312. Encoding::Mtbuf => (t::MTBUF, opcode),
  313. Encoding::Mimg => (t::MIMG, opcode),
  314. Encoding::Exp => return Some("exp"),
  315. Encoding::Flat => (t::FLAT, opcode),
  316. Encoding::Global => (t::GLOBAL, opcode),
  317. Encoding::Scratch => (t::SCRATCH, opcode),
  318. };
  319. table
  320. .binary_search_by_key(&op, |&(o, _)| o)
  321. .ok()
  322. .map(|i| table[i].1)
  323. }
  324. fn isa(offset: usize, reason: &'static str) -> ShaderError {
  325. ShaderError::Isa { offset, reason }
  326. }
  327. #[cfg(test)]
  328. mod tests {
  329. use super::*;
  330. const S_ENDPGM: u32 = 0xBF81_0000;
  331. /// s_branch / s_cbranch_scc0 with a dword offset relative to the next instruction.
  332. const fn sopp(op: u32, simm16: i16) -> u32 {
  333. 0xBF80_0000 | op << 16 | simm16 as u16 as u32
  334. }
  335. fn bytes(words: &[u32]) -> Vec<u8> {
  336. words.iter().flat_map(|w| w.to_le_bytes()).collect()
  337. }
  338. fn summary(code: &[u32]) -> Vec<(usize, usize, &'static str)> {
  339. decode(&bytes(code))
  340. .unwrap()
  341. .iter()
  342. .map(|i| (i.offset, i.words.len(), i.name().unwrap_or("?")))
  343. .collect()
  344. }
  345. #[test]
  346. fn flat_offsets_ignore_bit_eleven() {
  347. let offset = |word0: u32| {
  348. let code = bytes(&[word0, 0x0000_0001, S_ENDPGM]);
  349. match decode(&code).unwrap()[0].fields(false) {
  350. Fields::Flat { offset, .. } => offset,
  351. fields => panic!("{fields:?}"),
  352. }
  353. };
  354. // flat_load_dword v0, v[1:2]: the FLAT offset is 11-bit and
  355. // unsigned, so bit 11 is ignored (0x800 -> 0, 0xfff -> 0x7ff).
  356. assert_eq!(offset(0xDC30_0800), 0);
  357. assert_eq!(offset(0xDC30_0FFF), 0x7FF);
  358. }
  359. #[test]
  360. fn tables_are_sorted() {
  361. for t in [
  362. opcodes::SOP2,
  363. opcodes::SOPK,
  364. opcodes::SOP1,
  365. opcodes::SOPC,
  366. opcodes::SOPP,
  367. opcodes::SMEM,
  368. opcodes::VOP2,
  369. opcodes::VOP1,
  370. opcodes::VOPC,
  371. opcodes::VOP3,
  372. opcodes::VOP3P,
  373. opcodes::VINTRP,
  374. opcodes::DS,
  375. opcodes::MUBUF,
  376. opcodes::MTBUF,
  377. opcodes::MIMG,
  378. opcodes::FLAT,
  379. opcodes::GLOBAL,
  380. opcodes::SCRATCH,
  381. ] {
  382. assert!(t.windows(2).all(|w| w[0].0 < w[1].0));
  383. }
  384. }
  385. #[test]
  386. fn lengths_and_names() {
  387. let code = [
  388. 0xBE80_03FF,
  389. 0x3F80_0000, // s_mov_b32 s0, literal
  390. 0x0600_0000, // v_add_f32 v0, s0, v0
  391. 0xD54B_0000,
  392. 0x03FE_0000,
  393. 0x4000_0000, // v_fma_f32 with a literal src2
  394. 0xF080_0F0A,
  395. 0,
  396. 0, // image_sample (2D) with one extra address dword
  397. 0xF800_080F,
  398. 0, // exp
  399. S_ENDPGM,
  400. ];
  401. assert_eq!(
  402. summary(&code),
  403. [
  404. (0, 2, "s_mov_b32"),
  405. (8, 1, "v_add_f32"),
  406. (12, 3, "v_fma_f32"),
  407. (24, 3, "image_sample"),
  408. (36, 2, "exp"),
  409. (44, 1, "s_endpgm"),
  410. ]
  411. );
  412. }
  413. #[test]
  414. fn follows_branches_and_skips_data() {
  415. let code = [
  416. sopp(0x04, 1), // s_cbranch_scc0 -> 8
  417. sopp(0x02, 1), // s_branch -> 12
  418. S_ENDPGM,
  419. S_ENDPGM,
  420. S_ENDPGM, // data follows the program end
  421. 0xFFFF_FFFF,
  422. ];
  423. let found: Vec<_> = summary(&code).iter().map(|i| i.0).collect();
  424. assert_eq!(found, [0, 4, 8, 12]);
  425. }
  426. #[test]
  427. fn follows_far_jumps() {
  428. let code = [
  429. 0xBE88_1F00, // s_getpc_b64 s[8:9]
  430. 0x8008_FF08,
  431. 20, // s_add_u32 s8, s8, 20 -> 4 + 20 = 24
  432. 0x8209_8009, // s_addc_u32 s9, s9, 0
  433. 0xBE80_2008, // s_setpc_b64 s[8:9]
  434. 0xFFFF_FFFF, // not code
  435. S_ENDPGM,
  436. ];
  437. let found: Vec<_> = summary(&code).iter().map(|i| (i.0, i.2)).collect();
  438. assert_eq!(
  439. found,
  440. [
  441. (0, "s_getpc_b64"),
  442. (4, "s_add_u32"),
  443. (12, "s_addc_u32"),
  444. (16, "s_setpc_b64"),
  445. (24, "s_endpgm"),
  446. ]
  447. );
  448. // Through other registers (a handover to another stage): the path ends.
  449. assert_eq!(summary(&[0xBE80_2018, S_ENDPGM]).len(), 1);
  450. }
  451. #[test]
  452. fn follows_far_jumps_backward() {
  453. // The compiler's backward far jump adds a negative offset: the low
  454. // dword as a 32-bit literal, the high dword as -1 with the carry.
  455. let code = [
  456. sopp(0x02, 1), // s_branch -> 8, past the jump target
  457. S_ENDPGM, // the far jump's target: only it reaches here
  458. 0xBE88_1F00, // s_getpc_b64 s[8:9]
  459. 0x8008_FF08,
  460. 0xFFFF_FFF8, // s_add_u32 s8, s8, -8 -> 12 - 8 = 4
  461. 0x8209_C109, // s_addc_u32 s9, s9, -1
  462. 0xBE80_2008, // s_setpc_b64 s[8:9]
  463. ];
  464. let found: Vec<_> = summary(&code).iter().map(|i| (i.0, i.2)).collect();
  465. assert_eq!(
  466. found,
  467. [
  468. (0, "s_branch"),
  469. (4, "s_endpgm"),
  470. (8, "s_getpc_b64"),
  471. (12, "s_add_u32"),
  472. (20, "s_addc_u32"),
  473. (24, "s_setpc_b64"),
  474. ]
  475. );
  476. }
  477. #[test]
  478. fn rejects_bad_code() {
  479. assert!(decode(&[0; 3]).is_err(), "size not a multiple of 4");
  480. assert!(
  481. decode(&bytes(&[sopp(0x02, 100)])).is_err(),
  482. "branch out of range"
  483. );
  484. assert!(
  485. decode(&bytes(&[0xBE80_03FF])).is_err(),
  486. "literal past the end"
  487. );
  488. assert!(
  489. decode(&bytes(&[0xE400_0000, 0])).is_err(),
  490. "unknown encoding"
  491. );
  492. // s_cbranch_scc0 into the literal of the s_mov_b32 at 4.
  493. assert!(decode(&bytes(&[sopp(0x04, 1), 0xBE80_03FF, S_ENDPGM, S_ENDPGM])).is_err());
  494. }
  495. }