ir.rs 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791
  1. //! One-to-one SSA form of a native program (decision 0003, step 1).
  2. //!
  3. //! Every machine instruction becomes one [`Inst`], except scheduling-only
  4. //! ones (`s_nop`, `s_waitcnt*`, `s_inst_prefetch`...), which are dropped.
  5. //! Each register dword is a variable: a read names the [`Value`] it sees, a
  6. //! write defines a new one, and [`Phi`]s merge values where control flow
  7. //! joins. Nothing is raised: an instruction keeps its opcode and decoded
  8. //! fields, so its exact semantics stay with it.
  9. //!
  10. //! Implicit operands are explicit: SCC, M0, and EXEC, which every vector
  11. //! instruction reads. A write to a VGPR also reads the register's old value,
  12. //! because lanes disabled in EXEC keep it.
  13. //!
  14. //! M0-relative VGPR access (`v_movrels/d/sd_b32`, `v_swaprel_b32`) names its
  15. //! operand's whole possible range: from the encoded register up to the
  16. //! program's VGPR count, all read (and all written, for a destination).
  17. use crate::ShaderError;
  18. use crate::gfx10::{self, Fields, Flow, Instruction, Operand};
  19. /// One register dword. Scalar codes as in [`Operand::Scalar`]: 0-105 SGPRs,
  20. /// 106/107 VCC, 108-123 trap temporaries, 124 M0, 126/127 EXEC. Codes from
  21. /// [`PARKED`] up are scalars the compiler parked in VGPR lanes (`unspill`):
  22. /// no machine instruction names them.
  23. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
  24. pub enum Reg {
  25. S(u8),
  26. Scc,
  27. V(u8),
  28. }
  29. pub const VCC: u8 = 106;
  30. pub const M0: u8 = 124;
  31. pub const EXEC: u8 = 126;
  32. /// The first scalar code past the machine's (0-127): see [`Reg`].
  33. pub const PARKED: u8 = 128;
  34. /// An SSA value: the content of one register dword (SCC: one bit).
  35. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
  36. pub struct Value(pub u32);
  37. #[derive(Debug, Clone, PartialEq, Eq)]
  38. pub struct Program {
  39. pub wave64: bool,
  40. /// VGPRs v0 up to this exist; bounds M0-relative access.
  41. pub vgprs: u16,
  42. /// In code order, then copies made to give every loop one entry; block 0
  43. /// is the entry.
  44. pub blocks: Vec<Block>,
  45. /// Registers read before any write, with their value on entry: what the
  46. /// hardware or a called fetch routine set up (user SGPRs, system values,
  47. /// vertex inputs).
  48. pub inputs: Vec<(Reg, Value)>,
  49. }
  50. #[derive(Debug, Clone, PartialEq, Eq)]
  51. pub struct Block {
  52. /// Byte offset of the block's first machine instruction (shared by a
  53. /// block and its copies).
  54. pub offset: usize,
  55. pub preds: Vec<usize>,
  56. pub phis: Vec<Phi>,
  57. pub insts: Vec<Inst>,
  58. pub exit: Exit,
  59. }
  60. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  61. pub enum Exit {
  62. Jump(usize),
  63. /// `s_cbranch_*`, the block's last instruction.
  64. Branch {
  65. taken: usize,
  66. not_taken: usize,
  67. },
  68. /// `s_endpgm` and its variants.
  69. End,
  70. /// `s_setpc_b64` to an address held in registers, e.g. the handover to
  71. /// the next half of a merged hardware stage.
  72. Indirect,
  73. }
  74. impl Exit {
  75. pub fn successors(&self) -> Vec<usize> {
  76. match *self {
  77. Exit::Jump(b) => vec![b],
  78. Exit::Branch { taken, not_taken } => vec![taken, not_taken],
  79. Exit::End | Exit::Indirect => vec![],
  80. }
  81. }
  82. }
  83. #[derive(Debug, Clone, PartialEq, Eq)]
  84. pub struct Phi {
  85. pub reg: Reg,
  86. pub value: Value,
  87. /// One per predecessor, in [`Block::preds`] order.
  88. pub args: Vec<Value>,
  89. }
  90. #[derive(Debug, Clone, PartialEq, Eq)]
  91. pub struct Inst {
  92. pub machine: Instruction,
  93. pub fields: Fields,
  94. /// Every register dword read, with the value it holds.
  95. pub reads: Vec<(Reg, Value)>,
  96. /// Every register dword written, with the value it receives.
  97. pub writes: Vec<(Reg, Value)>,
  98. }
  99. impl Inst {
  100. pub fn name(&self) -> &'static str {
  101. self.machine.name().unwrap_or("")
  102. }
  103. /// The value `reg` holds when this instruction reads it.
  104. pub fn read(&self, reg: Reg) -> Option<Value> {
  105. self.reads.iter().find(|r| r.0 == reg).map(|r| r.1)
  106. }
  107. /// The value this instruction writes to `reg`.
  108. pub fn write(&self, reg: Reg) -> Option<Value> {
  109. self.writes.iter().find(|w| w.0 == reg).map(|w| w.1)
  110. }
  111. }
  112. /// Decodes `code` and builds its SSA form; `vgprs` is the program's VGPR
  113. /// count. Fails on instructions the IR cannot express yet
  114. /// ([`ShaderError::Unsupported`]).
  115. pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result<Program, ShaderError> {
  116. let mut list = gfx10::decode(code)?;
  117. let lanes = 1 + u8::from(wave64);
  118. let isa = |offset, reason| ShaderError::Isa { offset, reason };
  119. let mut flows = Vec::with_capacity(list.len());
  120. let mut leaders = vec![0];
  121. for (i, inst) in list.iter().enumerate() {
  122. let flow = gfx10::control(inst, code.len(), |at| {
  123. list[..list.partition_point(|i| i.offset < at)].last()
  124. })?;
  125. if let Flow::Jump(t) | Flow::Branch(t) = flow {
  126. leaders.push(t);
  127. }
  128. if flow != Flow::Next
  129. && let Some(next) = list.get(i + 1)
  130. {
  131. leaders.push(next.offset);
  132. }
  133. flows.push(flow);
  134. }
  135. leaders.sort_unstable();
  136. leaders.dedup();
  137. let parked = unspill(&mut list, &leaders, wave64, lanes, vgprs);
  138. let block_at = |offset: usize| {
  139. leaders
  140. .binary_search(&offset)
  141. .map_err(|_| isa(offset, "jump into a block"))
  142. };
  143. let mut blocks: Vec<Block> = leaders
  144. .iter()
  145. .map(|&offset| Block {
  146. offset,
  147. preds: Vec::new(),
  148. phis: Vec::new(),
  149. insts: Vec::new(),
  150. exit: Exit::End,
  151. })
  152. .collect();
  153. let next_offsets: Vec<Option<usize>> = (0..list.len())
  154. .map(|i| list.get(i + 1).map(|n| n.offset))
  155. .collect();
  156. for (n, ((machine, flow), next)) in list.into_iter().zip(flows).zip(next_offsets).enumerate() {
  157. let b = leaders.partition_point(|&l| l <= machine.offset) - 1;
  158. let name = machine.name().ok_or(ShaderError::Unsupported {
  159. offset: machine.offset,
  160. what: "unknown opcode",
  161. })?;
  162. let mut fields = machine.fields(wave64);
  163. // A move to or from a scalar parked in a VGPR lane (`unspill`): its register
  164. // codes may be ones the machine word cannot hold.
  165. if let Ok(k) = parked.binary_search_by_key(&n, |m| m.0)
  166. && let Fields::Sop { dst: Some(Operand::Scalar { code: to, .. }), src, .. } = &mut fields
  167. && let Some(Operand::Scalar { code: from, .. }) = src.first_mut()
  168. {
  169. (*to, *from) = (parked[k].1, parked[k].2);
  170. }
  171. let fallthrough = || block_at(next.ok_or(isa(machine.offset, "falls off the code"))?);
  172. let ends = flow != Flow::Next || next.is_none_or(|n| leaders.binary_search(&n).is_ok());
  173. if ends {
  174. blocks[b].exit = match flow {
  175. Flow::Next => Exit::Jump(fallthrough()?),
  176. Flow::Jump(t) => Exit::Jump(block_at(t)?),
  177. Flow::Branch(t) => Exit::Branch {
  178. taken: block_at(t)?,
  179. not_taken: fallthrough()?,
  180. },
  181. Flow::Stop if name == "s_setpc_b64" => Exit::Indirect,
  182. Flow::Stop => Exit::End,
  183. };
  184. }
  185. if let Some((mut reads, writes)) = effects(&machine, &fields, name, lanes, vgprs)? {
  186. // Lanes disabled in EXEC keep the old value.
  187. for w in writes.iter().filter(|w| matches!(w, Reg::V(_))) {
  188. if !reads.contains(w) {
  189. reads.push(*w);
  190. }
  191. }
  192. let unset = |regs: Vec<Reg>| regs.into_iter().map(|r| (r, NONE)).collect();
  193. blocks[b].insts.push(Inst {
  194. machine,
  195. fields,
  196. reads: unset(reads),
  197. writes: unset(writes),
  198. });
  199. }
  200. }
  201. link(&mut blocks);
  202. if !blocks[0].preds.is_empty() {
  203. return Err(ShaderError::Unsupported {
  204. offset: 0,
  205. what: "a branch to the program entry",
  206. });
  207. }
  208. split_irreducible(&mut blocks)?;
  209. Ok(rename(blocks, wave64, vgprs))
  210. }
  211. /// Scalar registers the compiler parked in lanes of a VGPR, as scalar moves.
  212. ///
  213. /// When it runs out of SGPRs the console compiler saves one in a lane of a
  214. /// spare VGPR (`v_writelane_b32 vN, sX, K`) and takes it back later
  215. /// (`v_readlane_b32 sX, vN, K`). A VGPR whose every use in the program is one
  216. /// of those two forms with a constant lane is such a store: lane K of it is a
  217. /// scalar register by another name. Each (VGPR, lane) gets a register code
  218. /// the program does not use (the trap temporaries first, then SGPRs it never
  219. /// names, then codes from [`PARKED`] up, which no machine word can hold), and
  220. /// the save and the restore become `s_mov_b32` to and from it. Returns those
  221. /// moves (index in `list`, destination code, source code) in order, for
  222. /// `build` to put the codes into the decoded fields. They are then copies for
  223. /// every later stage: a parked descriptor is traced to its load, and nothing
  224. /// is left of a cross-lane operation, which a console wave run as two host
  225. /// waves could not do where not every lane runs (the lane may be in the other
  226. /// wave, or not running).
  227. /// A register pair parked in two neighbouring lanes (a lane mask, a 64-bit
  228. /// address) moves as a pair (`s_mov_b64`) when every save and every restore
  229. /// of the two lanes come together, so a parked lane mask comes back as the
  230. /// mask it is; otherwise its halves come back as two scalars.
  231. fn unspill(
  232. list: &mut [gfx10::Instruction],
  233. leaders: &[usize],
  234. wave64: bool,
  235. lanes: u8,
  236. vgprs: u16,
  237. ) -> Vec<(usize, u8, u8)> {
  238. /// `v_writelane_b32 vN, sX, K` / `v_readlane_b32 sX, vN, K`: (save, N, X, K).
  239. fn parked(inst: &gfx10::Instruction, fields: &Fields) -> Option<(bool, u8, u8, u32)> {
  240. let Fields::Valu(v) = fields else { return None };
  241. if v.abs != 0 || v.neg != 0 || v.opsel != 0 || v.clamp || v.omod != 0 || v.sdwa.is_some() || v.dpp.is_some() {
  242. return None;
  243. }
  244. let lane = |op: &Operand| match *op {
  245. Operand::Const(c @ 128..=191) => Some(u32::from(c) - 128),
  246. _ => None,
  247. };
  248. match (inst.name()?, v.dst?, v.src.as_slice()) {
  249. ("v_writelane_b32", Operand::Vector { reg, .. }, [Operand::Scalar { code, .. }, k]) if *code < 105 => {
  250. Some((true, reg, *code, lane(k)?))
  251. }
  252. ("v_readlane_b32", Operand::Scalar { code, .. }, [Operand::Vector { reg, .. }, k]) if code < 105 => {
  253. Some((false, *reg, code, lane(k)?))
  254. }
  255. _ => None,
  256. }
  257. }
  258. // VGPRs used by parking alone, the scalar codes the program uses, and
  259. // per instruction the scalar codes it writes.
  260. let mut stores = [false; 256];
  261. let mut other = [false; 256];
  262. let mut used = [false; 128];
  263. let mut parks: Vec<Option<(bool, u8, u8, u32)>> = Vec::with_capacity(list.len());
  264. let mut written: Vec<Vec<u8>> = Vec::with_capacity(list.len());
  265. let mut read: Vec<Vec<u8>> = Vec::with_capacity(list.len());
  266. for inst in list.iter() {
  267. let Some(name) = inst.name() else { return Vec::new() };
  268. let fields = inst.fields(wave64);
  269. let park = parked(inst, &fields);
  270. let Ok(effects) = effects(inst, &fields, name, lanes, vgprs) else {
  271. return Vec::new();
  272. };
  273. let mut codes = Vec::new();
  274. let mut from = Vec::new();
  275. if let Some((reads, writes)) = effects {
  276. for &reg in &writes {
  277. if let Reg::S(c) = reg {
  278. codes.push(c);
  279. }
  280. }
  281. for &reg in &reads {
  282. if let Reg::S(c) = reg {
  283. from.push(c);
  284. }
  285. }
  286. // An M0-relative read (`v_movrels_b32`) names every VGPR from its
  287. // base up; the compiler indexes a small array with it, never the
  288. // lanes it parks scalars in, so it does not make those VGPRs
  289. // ordinary ones. (Relative writes still do.)
  290. let relative = name == "v_movrels_b32";
  291. let n_reads = reads.len();
  292. for (k, reg) in reads.into_iter().chain(writes).enumerate() {
  293. if relative && k < n_reads && matches!(reg, Reg::V(_)) {
  294. continue;
  295. }
  296. match reg {
  297. Reg::S(c) => used[usize::from(c)] = true,
  298. Reg::V(r) if park.is_some_and(|p| p.1 == r) => stores[usize::from(r)] = true,
  299. Reg::V(r) => other[usize::from(r)] = true,
  300. Reg::Scc => {}
  301. }
  302. }
  303. }
  304. parks.push(park);
  305. written.push(codes);
  306. read.push(from);
  307. }
  308. for (i, park) in parks.iter_mut().enumerate() {
  309. if park.is_some_and(|p| other[usize::from(p.1)]) {
  310. *park = None;
  311. }
  312. let _ = i;
  313. }
  314. if parks.iter().all(Option::is_none) {
  315. return Vec::new();
  316. }
  317. let leader = |i: usize| leaders.binary_search(&list[i].offset).is_ok();
  318. // Lane pairs (register, lower lane) that always move together: each
  319. // save of the lower lane is followed, in the same block and before its
  320. // register changes, by the save of the next register into the next
  321. // lane; each restore of the lower lane is followed at once by the
  322. // restore of the next lane into the next register.
  323. // The second save may come any number of instructions after the first (the
  324. // compiler puts loads and constants between the two: five instructions later
  325. // in the ped mesh programs). Only wave64 programs have pairs: a wave32 mask
  326. // is one dword, and a pair move of it with its neighbour would hide it.
  327. let mut slots: Vec<(u8, u32)> = parks.iter().flatten().map(|p| (p.1, p.3)).collect();
  328. slots.sort_unstable();
  329. slots.dedup();
  330. // instruction -> the instruction that completes its pair
  331. let partner = |i: usize| -> Option<usize> {
  332. let (save, reg, code, lane) = parks[i]?;
  333. if save {
  334. let mut j = i + 1;
  335. while j < list.len() && !leader(j) {
  336. if parks[j] == Some((true, reg, code + 1, lane + 1)) {
  337. return Some(j);
  338. }
  339. if parks[j].is_some_and(|p| p.1 == reg && (p.3 == lane || p.3 == lane + 1))
  340. || written[j].contains(&code)
  341. || written[j].contains(&(code + 1))
  342. {
  343. return None;
  344. }
  345. j += 1;
  346. }
  347. None
  348. } else {
  349. // The second restore may come a few instructions later (the
  350. // compiler schedules other work between the two): the pair is
  351. // restored at the first, so nothing between may read or write
  352. // the second register, write the first, or save into the lanes.
  353. let mut j = i + 1;
  354. while j < list.len() && !leader(j) {
  355. if parks[j] == Some((false, reg, code + 1, lane + 1)) {
  356. return Some(j);
  357. }
  358. if parks[j].is_some_and(|p| p.0 && p.1 == reg && (p.3 == lane || p.3 == lane + 1))
  359. || written[j].contains(&code)
  360. || written[j].contains(&(code + 1))
  361. || read[j].contains(&(code + 1))
  362. {
  363. return None;
  364. }
  365. j += 1;
  366. }
  367. None
  368. }
  369. };
  370. let mut pairs: Vec<(u8, u32)> = Vec::new();
  371. for &(reg, lane) in &slots {
  372. if !wave64 || pairs.iter().any(|&(r, l)| r == reg && l + 1 == lane) || !slots.contains(&(reg, lane + 1)) {
  373. continue;
  374. }
  375. let lower: Vec<usize> = (0..list.len()).filter(|&i| parks[i].is_some_and(|p| (p.1, p.3) == (reg, lane))).collect();
  376. let upper = parks.iter().flatten().filter(|p| (p.1, p.3) == (reg, lane + 1)).count();
  377. let partners: Vec<Option<usize>> = lower.iter().map(|&i| partner(i)).collect();
  378. let mut distinct: Vec<usize> = partners.iter().flatten().copied().collect();
  379. distinct.sort_unstable();
  380. distinct.dedup();
  381. if partners.iter().all(Option::is_some) && distinct.len() == lower.len() && upper == lower.len() {
  382. pairs.push((reg, lane));
  383. }
  384. }
  385. // Codes for the parked scalars: the trap temporaries (108..=123), then
  386. // user SGPRs the program never names, from the top, then the codes past
  387. // the machine's (`PARKED`..=254; 255 stays unused so that the code after a
  388. // parked one always exists). A material resolve program parks up to 63
  389. // scalars and leaves about 20 machine codes unused.
  390. let past = usize::from(PARKED);
  391. let mut free = [false; 256];
  392. for c in (0..105).chain(108..=123) {
  393. free[c] = !used[c];
  394. }
  395. free[past..255].fill(true);
  396. let mut codes: Vec<((u8, u32), u8)> = Vec::new();
  397. for &(reg, lane) in &pairs {
  398. let at = (108..123).chain((0..104).rev()).chain(past..254).find(|&c| free[c] && free[c + 1]);
  399. // Not enough spare codes: leave the program as it is.
  400. let Some(c) = at else { return Vec::new() };
  401. (free[c], free[c + 1]) = (false, false);
  402. codes.push(((reg, lane), c as u8));
  403. codes.push(((reg, lane + 1), c as u8 + 1));
  404. }
  405. for &slot in &slots {
  406. if codes.iter().any(|c| c.0 == slot) {
  407. continue;
  408. }
  409. let Some(c) = (108..=123).chain((0..105).rev()).chain(past..255).find(|&c| free[c]) else {
  410. return Vec::new();
  411. };
  412. free[c] = false;
  413. codes.push((slot, c as u8));
  414. }
  415. let code_of = |reg: u8, lane: u32| codes.iter().find(|c| c.0 == (reg, lane)).map(|c| c.1);
  416. let put = |list: &mut [gfx10::Instruction], i: usize, encoding, opcode: u16, word: u32| {
  417. list[i] = gfx10::Instruction {
  418. offset: list[i].offset,
  419. encoding,
  420. opcode,
  421. words: vec![word],
  422. };
  423. };
  424. // `s_mov_b32` / `s_mov_b64 dst, src` (SOP1, opcodes 3 and 4); `s_nop`. A code
  425. // from `PARKED` up does not fit the word: s0 stands in for it there.
  426. let field = |code: u8| if code < PARKED { u32::from(code) } else { 0 };
  427. let mov = |wide: bool, dst: u8, src: u8| 0xBE80_0000 | field(dst) << 16 | (3 + u32::from(wide)) << 8 | field(src);
  428. const NOP: u32 = 0xBF80_0000;
  429. let mut edits: Vec<(usize, Option<(bool, u8, u8)>)> = Vec::new();
  430. for i in 0..list.len() {
  431. let Some((save, reg, code, lane)) = parks[i] else {
  432. continue;
  433. };
  434. let Some(slot) = code_of(reg, lane) else { return Vec::new() };
  435. if pairs.contains(&(reg, lane)) {
  436. let Some(j) = partner(i) else { return Vec::new() };
  437. // A save moves the pair where its second half is saved; a
  438. // restore where its first half is restored.
  439. let (at, gone) = if save { (j, i) } else { (i, j) };
  440. let (dst, src) = if save { (slot, code) } else { (code, slot) };
  441. edits.push((at, Some((true, dst, src))));
  442. edits.push((gone, None));
  443. } else if lane > 0 && pairs.contains(&(reg, lane - 1)) {
  444. // the upper half of a pair: moved with the lower
  445. } else {
  446. let (dst, src) = if save { (slot, code) } else { (code, slot) };
  447. edits.push((i, Some((false, dst, src))));
  448. }
  449. }
  450. let mut moves = Vec::new();
  451. for (i, edit) in edits {
  452. match edit {
  453. Some((wide, dst, src)) => {
  454. put(list, i, gfx10::Encoding::Sop1, 3 + u16::from(wide), mov(wide, dst, src));
  455. moves.push((i, dst, src));
  456. }
  457. None => put(list, i, gfx10::Encoding::Sopp, 0, NOP),
  458. }
  459. }
  460. moves.sort_unstable();
  461. moves
  462. }
  463. /// Rename register reads and writes after changing edges in a reducible graph.
  464. fn rename(mut blocks: Vec<Block>, wave64: bool, vgprs: u16) -> Program {
  465. let order = reverse_postorder(&blocks);
  466. let (live_in, live_out) = liveness(&blocks, &order);
  467. let mut values = 0u32;
  468. let mut new_value = || {
  469. values += 1;
  470. Value(values - 1)
  471. };
  472. let mut inputs = Vec::new();
  473. let mut outs: Vec<Vec<(Reg, Value)>> = vec![Vec::new(); blocks.len()];
  474. let mut current = [NONE; REGS];
  475. for &b in &order {
  476. current.fill(NONE);
  477. let block = &mut blocks[b];
  478. for reg in members(&live_in[b]) {
  479. current[index(reg)] = match block.preds[..] {
  480. [] => {
  481. let v = new_value();
  482. inputs.push((reg, v));
  483. v
  484. }
  485. // A single predecessor comes earlier in reverse postorder.
  486. [p] => lookup(&outs[p], reg),
  487. _ => {
  488. let value = new_value();
  489. block.phis.push(Phi {
  490. reg,
  491. value,
  492. args: Vec::new(),
  493. });
  494. value
  495. }
  496. };
  497. }
  498. for inst in &mut block.insts {
  499. for (reg, v) in &mut inst.reads {
  500. *v = current[index(*reg)];
  501. debug_assert_ne!(*v, NONE, "{reg:?} read at {:#x}", inst.machine.offset);
  502. }
  503. for (reg, v) in &mut inst.writes {
  504. *v = new_value();
  505. current[index(*reg)] = *v;
  506. }
  507. }
  508. outs[b] = members(&live_out[b])
  509. .map(|reg| (reg, current[index(reg)]))
  510. .collect();
  511. }
  512. for block in &mut blocks {
  513. for phi in &mut block.phis {
  514. phi.args = block
  515. .preds
  516. .iter()
  517. .map(|&p| lookup(&outs[p], phi.reg))
  518. .collect();
  519. debug_assert!(!phi.args.contains(&NONE), "{phi:?}");
  520. }
  521. }
  522. remove_trivial_phis(&mut blocks, values);
  523. Program {
  524. wave64,
  525. vgprs,
  526. blocks,
  527. inputs,
  528. }
  529. }
  530. /// Duplicate a join for each proven (predecessor, join, destination) edge.
  531. /// The instructions still execute on that path and define fresh SSA values.
  532. pub(crate) fn thread_edges(
  533. p: &Program,
  534. edges: &[(usize, usize, usize)],
  535. ) -> Result<Program, ShaderError> {
  536. let mut blocks = p.blocks.clone();
  537. for block in &mut blocks {
  538. block.phis.clear();
  539. }
  540. for &(pred, join, dest) in edges {
  541. let mut copy = blocks[join].clone();
  542. copy.exit = Exit::Jump(dest);
  543. let target = blocks.len();
  544. match &mut blocks[pred].exit {
  545. Exit::Jump(t) => *t = target,
  546. Exit::Branch { taken, not_taken } => {
  547. if *taken == join {
  548. *taken = target;
  549. }
  550. if *not_taken == join {
  551. *not_taken = target;
  552. }
  553. }
  554. _ => unreachable!("threading an incoming edge"),
  555. }
  556. blocks.push(copy);
  557. }
  558. link(&mut blocks);
  559. split_irreducible(&mut blocks)?;
  560. Ok(rename(blocks, p.wave64, p.vgprs))
  561. }
  562. /// The program without its early-outs: an `s_cbranch_execz` to a block that
  563. /// only ends the program (`if (!inBounds) return;`, the outermost branch of
  564. /// most compute programs) is left out, so the lanes that would have left
  565. /// walk the body with EXEC clear. Vector instructions and every effect are
  566. /// masked by EXEC already, as on the console, where the branch is taken
  567. /// only when no lane of the wave is left; scalar code has no effects. The
  568. /// body is then code every lane runs, which a console wave run as two host
  569. /// waves needs for the barriers of its exchanges and LDS accesses.
  570. /// `None` if the program has no such branch.
  571. pub(crate) fn without_early_outs(p: &Program) -> Option<Program> {
  572. let ends = |b: usize| {
  573. p.blocks[b].exit == Exit::End
  574. && p.blocks[b].insts.iter().all(|i| matches!(i.fields, crate::gfx10::Fields::Sopp { .. }))
  575. };
  576. let mut blocks = p.blocks.clone();
  577. let mut any = false;
  578. for block in &mut blocks {
  579. let Exit::Branch { taken, not_taken } = block.exit else {
  580. continue;
  581. };
  582. if ends(taken) && block.insts.last().is_some_and(|i| i.name() == "s_cbranch_execz") {
  583. block.insts.pop();
  584. block.exit = Exit::Jump(not_taken);
  585. any = true;
  586. }
  587. }
  588. if !any {
  589. return None;
  590. }
  591. for block in &mut blocks {
  592. block.phis.clear();
  593. }
  594. link(&mut blocks);
  595. split_irreducible(&mut blocks).ok()?;
  596. Some(rename(blocks, p.wave64, p.vgprs))
  597. }
  598. /// As [`without_early_outs`], and also without the branches that only skip a
  599. /// region when no lane is left for it: an `s_cbranch_execz` whose target is
  600. /// where the skipped code ends up anyway (`if (c) { ... }` with nothing
  601. /// else leaving the region). Every lane then walks the region with EXEC
  602. /// clear for those that would have skipped it, and LDS accesses and
  603. /// exchanges inside it are in code every lane runs.
  604. /// The console takes such a branch only when no lane of the wave is left,
  605. /// and then its scalar code does not run: a branch is kept if the code
  606. /// after it could see that (a scalar register or SCC that the region
  607. /// changes and the join merges with the value from before; EXEC aside,
  608. /// which is empty either way). `None` if nothing changes.
  609. ///
  610. /// `deep` looks closer at what the code after the branch can see. A scalar the region moves
  611. /// away and back (the compiler parks scalars in VGPR lanes around a branch and takes them
  612. /// back before the join, `unspill`) is the value it copies; a join nothing reads shows no
  613. /// one the difference (a restore of EXEC that the next one overwrites reads nothing); and
  614. /// the join may have other ways in (an inner branch that ends together with an outer one).
  615. /// That leaves out most of the skips of the title's large lighting programs, whose bodies
  616. /// are then code every lane runs.
  617. pub(crate) fn without_skips(p: &Program, deep: bool) -> Option<Program> {
  618. let n = p.blocks.len();
  619. let ends = |b: usize| {
  620. p.blocks[b].exit == Exit::End
  621. && p.blocks[b].insts.iter().all(|i| matches!(i.fields, crate::gfx10::Fields::Sopp { .. }))
  622. };
  623. // Scalars moved from register to register (a scalar the compiler parked in a VGPR lane
  624. // comes back by such a move, `unspill`) are the value they copy.
  625. let mut copy: std::collections::HashMap<Value, Value> = Default::default();
  626. // Values something reads, directly or through joins. A scalar operation none of whose
  627. // results is read reads nothing either (the compiler restores EXEC from a saved mask
  628. // and overwrites it at once where two branches end together).
  629. let mut live: std::collections::HashSet<Value> = Default::default();
  630. let idle = |inst: &Inst, live: &std::collections::HashSet<Value>| {
  631. let name = inst.name();
  632. matches!(inst.fields, crate::gfx10::Fields::Sop { .. })
  633. && !(name.starts_with("s_setpc")
  634. || name.starts_with("s_swappc")
  635. || name.starts_with("s_call")
  636. || name.starts_with("s_rfe")
  637. || name.starts_with("s_movrel")
  638. || name.starts_with("s_subvector"))
  639. && inst.writes.iter().all(|w| !live.contains(&w.1))
  640. };
  641. for block in &p.blocks {
  642. for inst in &block.insts {
  643. if matches!(inst.name(), "s_mov_b32" | "s_mov_b64")
  644. && inst.reads.len() == inst.writes.len()
  645. && inst.reads.iter().chain(&inst.writes).all(|r| matches!(r.0, Reg::S(_)))
  646. {
  647. copy.extend(inst.writes.iter().zip(&inst.reads).map(|(w, r)| (w.1, r.1)));
  648. }
  649. }
  650. }
  651. let mut changed = true;
  652. while changed {
  653. changed = false;
  654. for block in &p.blocks {
  655. for inst in &block.insts {
  656. if !idle(inst, &live) {
  657. for r in &inst.reads {
  658. changed |= live.insert(r.1);
  659. }
  660. }
  661. }
  662. for phi in &block.phis {
  663. if live.contains(&phi.value) {
  664. for &a in &phi.args {
  665. changed |= live.insert(a);
  666. }
  667. }
  668. }
  669. }
  670. }
  671. let root = |mut v: Value| {
  672. while deep && let Some(&c) = copy.get(&v) {
  673. v = c;
  674. }
  675. v
  676. };
  677. // The region a skip of `b` to `target` leaves out, if it is a pure skip.
  678. let skipped = |b: usize, target: usize, first: usize| -> Option<Vec<bool>> {
  679. let mut inside = vec![false; n];
  680. let mut stack = vec![first];
  681. while let Some(x) = stack.pop() {
  682. if x == target || inside[x] {
  683. continue;
  684. }
  685. if x == b {
  686. return None; // a loop back to the branch
  687. }
  688. inside[x] = true;
  689. match p.blocks[x].exit {
  690. Exit::End | Exit::Indirect => return None,
  691. exit => stack.extend(exit.successors()),
  692. }
  693. }
  694. // entered only through the branch
  695. for x in (0..n).filter(|&x| inside[x]) {
  696. if p.blocks[x].preds.iter().any(|&q| q != b && !inside[q]) {
  697. return None;
  698. }
  699. }
  700. // the join sees no scalar the region changed
  701. let join = &p.blocks[target];
  702. for phi in &join.phis {
  703. let scalar = match phi.reg {
  704. Reg::S(c) => c != 126 && c != 127,
  705. Reg::Scc => true,
  706. Reg::V(_) => false,
  707. };
  708. // (a join nothing reads shows no one the difference)
  709. if !scalar || deep && !live.contains(&phi.value) {
  710. continue;
  711. }
  712. let before: Vec<Value> =
  713. join.preds.iter().zip(&phi.args).filter(|(q, _)| **q == b).map(|(_, a)| root(*a)).collect();
  714. let within = join.preds.iter().zip(&phi.args).filter(|(q, _)| inside[**q]).map(|(_, a)| root(*a));
  715. if within.into_iter().any(|a| !before.contains(&a)) {
  716. return None;
  717. }
  718. }
  719. // Other ways into the join than the branch and the region (an inner branch that ends
  720. // together with an outer one) change nothing in that: the lanes that would have
  721. // skipped arrive from the region instead, with the same scalars.
  722. if !deep && join.preds.iter().any(|&q| q != b && !inside[q]) {
  723. return None;
  724. }
  725. Some(inside)
  726. };
  727. let mut blocks = p.blocks.clone();
  728. let mut any = false;
  729. for b in 0..n {
  730. let Exit::Branch { taken, not_taken } = p.blocks[b].exit else {
  731. continue;
  732. };
  733. if !p.blocks[b].insts.last().is_some_and(|i| i.name() == "s_cbranch_execz") {
  734. continue;
  735. }
  736. if ends(taken) || skipped(b, taken, not_taken).is_some() {
  737. blocks[b].insts.pop();
  738. blocks[b].exit = Exit::Jump(not_taken);
  739. any = true;
  740. }
  741. }
  742. if !any {
  743. return None;
  744. }
  745. for block in &mut blocks {
  746. block.phis.clear();
  747. }
  748. link(&mut blocks);
  749. split_irreducible(&mut blocks).ok()?;
  750. Some(rename(blocks, p.wave64, p.vgprs))
  751. }
  752. /// Placeholder before renaming.
  753. const NONE: Value = Value(u32::MAX);
  754. /// Scalar codes 0-255 (from [`PARKED`] up: parked scalars), SCC, VGPRs 0-255.
  755. const REGS: usize = 256 + 1 + 256;
  756. type RegSet = [u64; REGS.div_ceil(64)];
  757. fn index(reg: Reg) -> usize {
  758. match reg {
  759. Reg::S(c) => usize::from(c),
  760. Reg::Scc => 256,
  761. Reg::V(r) => 257 + usize::from(r),
  762. }
  763. }
  764. fn reg_at(i: usize) -> Reg {
  765. match i {
  766. 0..256 => Reg::S(i as u8),
  767. 256 => Reg::Scc,
  768. _ => Reg::V((i - 257) as u8),
  769. }
  770. }
  771. fn insert(set: &mut RegSet, reg: Reg) {
  772. let i = index(reg);
  773. set[i / 64] |= 1 << (i % 64);
  774. }
  775. fn contains(set: &RegSet, reg: Reg) -> bool {
  776. let i = index(reg);
  777. set[i / 64] >> (i % 64) & 1 != 0
  778. }
  779. /// In [`Reg`] order, which is also index order.
  780. fn members(set: &RegSet) -> impl Iterator<Item = Reg> + '_ {
  781. (0..REGS)
  782. .filter(|&i| set[i / 64] >> (i % 64) & 1 != 0)
  783. .map(reg_at)
  784. }
  785. /// `outs` is sorted by register, and holds every register live out.
  786. fn lookup(outs: &[(Reg, Value)], reg: Reg) -> Value {
  787. outs.binary_search_by_key(&reg, |&(r, _)| r)
  788. .map_or(NONE, |i| outs[i].1)
  789. }
  790. pub(crate) fn reverse_postorder(blocks: &[Block]) -> Vec<usize> {
  791. let mut seen = vec![false; blocks.len()];
  792. let mut post = Vec::with_capacity(blocks.len());
  793. let mut stack = vec![(0, 0)];
  794. seen[0] = true;
  795. while let Some(top) = stack.last_mut() {
  796. let (b, i) = *top;
  797. top.1 += 1;
  798. match blocks[b].exit.successors().get(i) {
  799. Some(&s) if !seen[s] => {
  800. seen[s] = true;
  801. stack.push((s, 0));
  802. }
  803. Some(_) => {}
  804. None => {
  805. post.push(b);
  806. stack.pop();
  807. }
  808. }
  809. }
  810. post.reverse();
  811. post
  812. }
  813. /// Recomputes every block's predecessors from the exits.
  814. fn link(blocks: &mut [Block]) {
  815. for block in blocks.iter_mut() {
  816. block.preds.clear();
  817. }
  818. for b in 0..blocks.len() {
  819. for s in blocks[b].exit.successors() {
  820. blocks[s].preds.push(b);
  821. }
  822. }
  823. }
  824. /// An edge to an earlier block in reverse postorder whose target does not
  825. /// dominate its source, if any: there the control flow is irreducible.
  826. /// `index` is each block's position in `order`.
  827. pub(crate) fn irreducible_edge(
  828. blocks: &[Block],
  829. order: &[usize],
  830. index: &[usize],
  831. ) -> Option<(usize, usize)> {
  832. let &entry = order.first()?;
  833. let idom = idoms(blocks, order, index);
  834. for &b in order {
  835. for s in blocks[b].exit.successors() {
  836. if index[s] > index[b] {
  837. continue;
  838. }
  839. let mut d = b;
  840. while d != s && d != entry {
  841. d = idom[d];
  842. }
  843. if d != s {
  844. return Some((b, s));
  845. }
  846. }
  847. }
  848. None
  849. }
  850. /// Each block's immediate dominator (the entry's is itself, unreachable
  851. /// blocks' `usize::MAX`); `order` is reverse postorder, `index` each
  852. /// block's position in it.
  853. pub(crate) fn idoms(blocks: &[Block], order: &[usize], index: &[usize]) -> Vec<usize> {
  854. let mut idom = vec![usize::MAX; blocks.len()];
  855. let Some(&entry) = order.first() else {
  856. return idom;
  857. };
  858. idom[entry] = entry;
  859. let intersect = |idom: &[usize], mut a: usize, mut b: usize| {
  860. while a != b {
  861. while index[a] > index[b] {
  862. a = idom[a];
  863. }
  864. while index[b] > index[a] {
  865. b = idom[b];
  866. }
  867. }
  868. a
  869. };
  870. let mut changed = true;
  871. while changed {
  872. changed = false;
  873. for &b in &order[1..] {
  874. let mut new = usize::MAX;
  875. for &q in blocks[b].preds.iter().filter(|&&q| idom[q] != usize::MAX) {
  876. new = if new == usize::MAX {
  877. q
  878. } else {
  879. intersect(&idom, q, new)
  880. };
  881. }
  882. if idom[b] != new {
  883. idom[b] = new;
  884. changed = true;
  885. }
  886. }
  887. }
  888. idom
  889. }
  890. /// Node splitting, before SSA. While a loop is entered at several blocks
  891. /// (a compiler-rotated loop whose peeled first test jumps into its body),
  892. /// the entry first in reverse postorder stays the header, and another
  893. /// entry's outside predecessors move to a copy of everything that entry
  894. /// reaches in the loop before the header. The copies run the same
  895. /// instructions, so behaviour is unchanged.
  896. fn split_irreducible(blocks: &mut Vec<Block>) -> Result<(), ShaderError> {
  897. let limit = 4 * blocks.len() + 64;
  898. loop {
  899. let order = reverse_postorder(blocks);
  900. let mut index = vec![usize::MAX; blocks.len()];
  901. for (i, &b) in order.iter().enumerate() {
  902. index[b] = i;
  903. }
  904. let Some((from, _)) = irreducible_edge(blocks, &order, &index) else {
  905. return Ok(());
  906. };
  907. let found = multi_entry_loop(blocks, &vec![true; blocks.len()]);
  908. let Some((region, mut entries)) = found.filter(|_| blocks.len() < limit) else {
  909. return Err(ShaderError::Unsupported {
  910. offset: blocks[from].offset,
  911. what: "irreducible control flow",
  912. });
  913. };
  914. entries.sort_by_key(|&e| index[e]);
  915. let (header, entry) = (entries[0], entries[1]);
  916. // What `entry` reaches in the loop before the header, and its copies.
  917. let mut copy = vec![usize::MAX; blocks.len()];
  918. let mut copied = Vec::new();
  919. let mut stack = vec![entry];
  920. while let Some(b) = stack.pop() {
  921. if copy[b] != usize::MAX {
  922. continue;
  923. }
  924. copy[b] = blocks.len() + copied.len();
  925. copied.push(b);
  926. for s in blocks[b].exit.successors() {
  927. if region[s] && s != header {
  928. stack.push(s);
  929. }
  930. }
  931. }
  932. let retarget = |exit: &mut Exit, to: &dyn Fn(usize) -> usize| match exit {
  933. Exit::Jump(s) => *s = to(*s),
  934. Exit::Branch { taken, not_taken } => {
  935. *taken = to(*taken);
  936. *not_taken = to(*not_taken);
  937. }
  938. Exit::End | Exit::Indirect => {}
  939. };
  940. for &b in &copied {
  941. let mut block = blocks[b].clone();
  942. retarget(&mut block.exit, &|s| {
  943. if copy[s] == usize::MAX { s } else { copy[s] }
  944. });
  945. blocks.push(block);
  946. }
  947. let outside: Vec<usize> = blocks[entry]
  948. .preds
  949. .iter()
  950. .copied()
  951. .filter(|&p| !region[p])
  952. .collect();
  953. for p in outside {
  954. retarget(&mut blocks[p].exit, &|s| {
  955. if s == entry { copy[entry] } else { s }
  956. });
  957. }
  958. link(blocks);
  959. }
  960. }
  961. /// A loop among the `inside` blocks entered at more than one block, with
  962. /// its entries. Loops nested in a single-entry loop are searched with its
  963. /// header removed, so one is found whenever the control flow is irreducible.
  964. fn multi_entry_loop(blocks: &[Block], inside: &[bool]) -> Option<(Vec<bool>, Vec<usize>)> {
  965. let reach = |from: usize, forward: bool| {
  966. let mut seen = vec![false; blocks.len()];
  967. let mut stack = vec![from];
  968. while let Some(b) = stack.pop() {
  969. let next = if forward {
  970. blocks[b].exit.successors()
  971. } else {
  972. blocks[b].preds.clone()
  973. };
  974. for n in next {
  975. if inside[n] && !seen[n] {
  976. seen[n] = true;
  977. stack.push(n);
  978. }
  979. }
  980. }
  981. seen
  982. };
  983. let mut done = vec![false; blocks.len()];
  984. for v in (0..blocks.len()).filter(|&v| inside[v]) {
  985. if done[v] {
  986. continue;
  987. }
  988. // Blocks on a cycle through `v`; `v` itself only if there is one.
  989. let (ahead, behind) = (reach(v, true), reach(v, false));
  990. let region: Vec<bool> = ahead.iter().zip(&behind).map(|(a, b)| a & b).collect();
  991. if !region[v] {
  992. continue;
  993. }
  994. let members = (0..blocks.len()).filter(|&b| region[b]);
  995. for b in members.clone() {
  996. done[b] = true;
  997. }
  998. let entries: Vec<usize> = members
  999. .filter(|&b| blocks[b].preds.iter().any(|&p| !region[p]))
  1000. .collect();
  1001. match entries[..] {
  1002. [] => {}
  1003. [header] => {
  1004. let mut nested = region;
  1005. nested[header] = false;
  1006. if let Some(found) = multi_entry_loop(blocks, &nested) {
  1007. return Some(found);
  1008. }
  1009. }
  1010. _ => return Some((region, entries)),
  1011. }
  1012. }
  1013. None
  1014. }
  1015. /// Registers live into and out of each block.
  1016. fn liveness(blocks: &[Block], order: &[usize]) -> (Vec<RegSet>, Vec<RegSet>) {
  1017. let empty = [0; REGS.div_ceil(64)];
  1018. let mut uses = vec![empty; blocks.len()];
  1019. let mut defs = vec![empty; blocks.len()];
  1020. for (b, block) in blocks.iter().enumerate() {
  1021. for inst in &block.insts {
  1022. for &(reg, _) in &inst.reads {
  1023. if !contains(&defs[b], reg) {
  1024. insert(&mut uses[b], reg);
  1025. }
  1026. }
  1027. for &(reg, _) in &inst.writes {
  1028. insert(&mut defs[b], reg);
  1029. }
  1030. }
  1031. }
  1032. let mut live_in = vec![empty; blocks.len()];
  1033. let mut live_out = vec![empty; blocks.len()];
  1034. let mut changed = true;
  1035. while changed {
  1036. changed = false;
  1037. for &b in order.iter().rev() {
  1038. let mut out = empty;
  1039. for s in blocks[b].exit.successors() {
  1040. for (o, i) in out.iter_mut().zip(&live_in[s]) {
  1041. *o |= i;
  1042. }
  1043. }
  1044. let mut inn = empty;
  1045. for w in 0..inn.len() {
  1046. inn[w] = uses[b][w] | out[w] & !defs[b][w];
  1047. }
  1048. if inn != live_in[b] || out != live_out[b] {
  1049. (live_in[b], live_out[b]) = (inn, out);
  1050. changed = true;
  1051. }
  1052. }
  1053. }
  1054. (live_in, live_out)
  1055. }
  1056. /// Phis are placed for every live register at every join; those whose
  1057. /// arguments are all one value (or the phi itself) are replaced by it.
  1058. fn remove_trivial_phis(blocks: &mut [Block], values: u32) {
  1059. let mut replaced: Vec<Value> = (0..values).map(Value).collect();
  1060. let find = |replaced: &[Value], mut v: Value| {
  1061. while replaced[v.0 as usize] != v {
  1062. v = replaced[v.0 as usize];
  1063. }
  1064. v
  1065. };
  1066. let mut changed = true;
  1067. while changed {
  1068. changed = false;
  1069. for block in blocks.iter_mut() {
  1070. block.phis.retain(|phi| {
  1071. let mut only = None;
  1072. for &a in &phi.args {
  1073. let a = find(&replaced, a);
  1074. if a == phi.value || Some(a) == only {
  1075. continue;
  1076. }
  1077. if only.is_some() {
  1078. return true;
  1079. }
  1080. only = Some(a);
  1081. }
  1082. let Some(v) = only else { return true };
  1083. replaced[phi.value.0 as usize] = v;
  1084. changed = true;
  1085. false
  1086. });
  1087. }
  1088. }
  1089. for block in blocks {
  1090. for phi in &mut block.phis {
  1091. for a in &mut phi.args {
  1092. *a = find(&replaced, *a);
  1093. }
  1094. }
  1095. for inst in &mut block.insts {
  1096. for (_, v) in &mut inst.reads {
  1097. *v = find(&replaced, *v);
  1098. }
  1099. }
  1100. }
  1101. }
  1102. /// Scheduling hints, performance counters and tracing: no effect on results.
  1103. const DROPPED: &[&str] = &[
  1104. "s_nop",
  1105. "s_waitcnt",
  1106. "s_waitcnt_vscnt",
  1107. "s_waitcnt_vmcnt",
  1108. "s_waitcnt_expcnt",
  1109. "s_waitcnt_lgkmcnt",
  1110. "s_waitcnt_depctr",
  1111. "s_wait_idle",
  1112. "s_inst_prefetch",
  1113. "s_clause",
  1114. "s_setprio",
  1115. "s_sleep",
  1116. "s_ttracedata",
  1117. "s_ttracedata_imm",
  1118. "s_incperflevel",
  1119. "s_decperflevel",
  1120. "v_nop",
  1121. "v_pipeflush",
  1122. "v_clrexcp",
  1123. ];
  1124. /// Registers read, registers written.
  1125. type Effects = (Vec<Reg>, Vec<Reg>);
  1126. /// The registers `inst` of `p` reads as operands: its reads without the old
  1127. /// value of a VGPR it only writes.
  1128. pub(crate) fn operand_reads(p: &Program, inst: &Inst) -> Vec<Reg> {
  1129. let lanes = 1 + u8::from(p.wave64);
  1130. effects(&inst.machine, &inst.fields, inst.name(), lanes, p.vgprs)
  1131. .ok()
  1132. .flatten()
  1133. .map_or_else(Vec::new, |e| e.0)
  1134. }
  1135. /// Registers an instruction reads and writes, one per dword, or `None` if
  1136. /// the IR drops it.
  1137. fn effects(
  1138. inst: &Instruction,
  1139. fields: &Fields,
  1140. name: &'static str,
  1141. lanes: u8,
  1142. vgprs: u16,
  1143. ) -> Result<Option<Effects>, ShaderError> {
  1144. if DROPPED.contains(&name) {
  1145. return Ok(None);
  1146. }
  1147. let unsupported = || ShaderError::Unsupported {
  1148. offset: inst.offset,
  1149. what: name,
  1150. };
  1151. let mask = |code: u8| (0..lanes).map(move |i| Reg::S(code + i));
  1152. let (mut r, mut w) = (Vec::new(), Vec::new());
  1153. let regs = |op: &Operand, out: &mut Vec<Reg>| {
  1154. add_regs(op, lanes, out).map_err(|_| ShaderError::Isa {
  1155. offset: inst.offset,
  1156. reason: "register range out of bounds",
  1157. })
  1158. };
  1159. let vector = !matches!(
  1160. fields,
  1161. Fields::Sop { .. } | Fields::Sopp { .. } | Fields::Smem { .. }
  1162. );
  1163. match fields {
  1164. Fields::Sop { dst, src, .. } => {
  1165. if name.starts_with("s_movrel")
  1166. || name.starts_with("s_subvector_loop")
  1167. || matches!(name, "s_call_b64" | "s_rfe_b64")
  1168. {
  1169. return Err(unsupported());
  1170. }
  1171. for s in src {
  1172. regs(s, &mut r)?;
  1173. }
  1174. if let Some(d) = dst {
  1175. regs(d, &mut w)?;
  1176. // These change (or may keep) the destination's old value.
  1177. if name.starts_with("s_bitset")
  1178. || name.starts_with("s_cmov")
  1179. || matches!(name, "s_addk_i32" | "s_mulk_i32")
  1180. {
  1181. regs(d, &mut r)?;
  1182. }
  1183. }
  1184. if matches!(name, "s_addc_u32" | "s_subb_u32" | "s_cmovk_i32")
  1185. || name.starts_with("s_cselect_")
  1186. || name.starts_with("s_cmov_")
  1187. {
  1188. r.push(Reg::Scc);
  1189. }
  1190. if name.contains("saveexec") || name.contains("wrexec") {
  1191. r.extend(mask(EXEC));
  1192. w.extend(mask(EXEC));
  1193. }
  1194. if writes_scc(inst.encoding, name) {
  1195. w.push(Reg::Scc);
  1196. }
  1197. }
  1198. Fields::Sopp { .. } => match name {
  1199. "s_cbranch_scc0" | "s_cbranch_scc1" => r.push(Reg::Scc),
  1200. "s_cbranch_vccz" | "s_cbranch_vccnz" => r.extend(mask(VCC)),
  1201. "s_cbranch_execz" | "s_cbranch_execnz" => r.extend(mask(EXEC)),
  1202. "s_sendmsg" | "s_sendmsghalt" => r.push(Reg::S(M0)),
  1203. "s_endpgm"
  1204. | "s_endpgm_saved"
  1205. | "s_endpgm_ordered_ps_done"
  1206. | "s_code_end"
  1207. | "s_branch"
  1208. | "s_barrier"
  1209. | "s_icache_inv"
  1210. | "s_wakeup"
  1211. | "s_round_mode"
  1212. | "s_denorm_mode" => {}
  1213. _ => return Err(unsupported()),
  1214. },
  1215. Fields::Smem {
  1216. data,
  1217. base,
  1218. soffset,
  1219. ..
  1220. } => match name {
  1221. "s_memtime" | "s_memrealtime" | "s_get_waveid_in_workgroup" => {
  1222. regs(data.as_ref().ok_or_else(unsupported)?, &mut w)?;
  1223. }
  1224. "s_gl1_inv" | "s_dcache_inv" | "s_dcache_wb" => {}
  1225. _ if name.contains("_load_") || name.contains("_store_") => {
  1226. regs(base, &mut r)?;
  1227. regs(soffset, &mut r)?;
  1228. let data = data.as_ref().ok_or_else(unsupported)?;
  1229. regs(
  1230. data,
  1231. if name.contains("_load_") {
  1232. &mut w
  1233. } else {
  1234. &mut r
  1235. },
  1236. )?;
  1237. }
  1238. _ => return Err(unsupported()),
  1239. },
  1240. Fields::Valu(v) => {
  1241. let (src_indexed, dst_indexed) = match name {
  1242. "v_movrels_b32" => (true, false),
  1243. "v_movreld_b32" => (false, true),
  1244. "v_movrelsd_b32" | "v_movrelsd_2_b32" | "v_swaprel_b32" => (true, true),
  1245. _ => (false, false),
  1246. };
  1247. // v[reg + M0] for any M0 that stays inside the program's VGPRs.
  1248. let indexed = |op: &Operand, out: &mut Vec<Reg>| match *op {
  1249. Operand::Vector { reg, .. } if u16::from(reg) < vgprs => {
  1250. out.extend((u16::from(reg)..vgprs).map(|r| Reg::V(r as u8)));
  1251. Ok(())
  1252. }
  1253. _ => Err(ShaderError::Isa {
  1254. offset: inst.offset,
  1255. reason: "relative VGPR base outside the program's VGPRs",
  1256. }),
  1257. };
  1258. for (i, s) in v.src.iter().enumerate() {
  1259. if i == 0 && src_indexed {
  1260. indexed(s, &mut r)?;
  1261. } else {
  1262. regs(s, &mut r)?;
  1263. }
  1264. }
  1265. // GFX10 compares into EXEC write nothing else.
  1266. if name.starts_with("v_cmpx") {
  1267. w.extend(mask(EXEC));
  1268. } else if let Some(d) = &v.dst {
  1269. if dst_indexed {
  1270. indexed(d, &mut w)?;
  1271. } else {
  1272. regs(d, &mut w)?;
  1273. }
  1274. }
  1275. if let Some(c) = &v.carry {
  1276. regs(c, &mut w)?;
  1277. }
  1278. match name {
  1279. "v_swap_b32" => {
  1280. regs(&v.src[0], &mut w)?;
  1281. if let Some(d) = &v.dst {
  1282. regs(d, &mut r)?;
  1283. }
  1284. }
  1285. "v_swaprel_b32" => {
  1286. indexed(&v.src[0], &mut w)?;
  1287. if let Some(d) = &v.dst {
  1288. indexed(d, &mut r)?;
  1289. }
  1290. }
  1291. "v_div_fmas_f32" | "v_div_fmas_f64" => r.extend(mask(VCC)),
  1292. _ => {}
  1293. }
  1294. if name.starts_with("v_interp_") || src_indexed || dst_indexed {
  1295. r.push(Reg::S(M0));
  1296. }
  1297. }
  1298. Fields::Vintrp { dst, src, .. } => {
  1299. regs(src, &mut r)?;
  1300. r.push(Reg::S(M0));
  1301. regs(dst, &mut w)?;
  1302. }
  1303. Fields::Ds {
  1304. dst,
  1305. addr,
  1306. data,
  1307. gds,
  1308. ..
  1309. } => {
  1310. for o in addr.iter().chain(data) {
  1311. regs(o, &mut r)?;
  1312. }
  1313. if let Some(d) = dst {
  1314. regs(d, &mut w)?;
  1315. }
  1316. if *gds
  1317. || name.starts_with("ds_gws")
  1318. || name.contains("addtid")
  1319. || matches!(name, "ds_ordered_count" | "ds_append" | "ds_consume")
  1320. {
  1321. r.push(Reg::S(M0));
  1322. }
  1323. }
  1324. Fields::Buffer {
  1325. data,
  1326. addr,
  1327. rsrc,
  1328. soffset,
  1329. offen,
  1330. idxen,
  1331. lds,
  1332. cache,
  1333. ..
  1334. } => {
  1335. if *offen || *idxen {
  1336. regs(addr, &mut r)?;
  1337. }
  1338. regs(rsrc, &mut r)?;
  1339. regs(soffset, &mut r)?;
  1340. if *lds {
  1341. r.push(Reg::S(M0));
  1342. }
  1343. if let Some(d) = data {
  1344. if name.contains("_load_") {
  1345. if !lds {
  1346. regs(d, &mut w)?;
  1347. }
  1348. } else if name.contains("_store_") {
  1349. regs(d, &mut r)?;
  1350. } else if name.contains("_atomic_") {
  1351. regs(d, &mut r)?;
  1352. if cache.glc {
  1353. regs(&atomic_result(d, name), &mut w)?;
  1354. }
  1355. } else {
  1356. return Err(unsupported());
  1357. }
  1358. }
  1359. }
  1360. Fields::Image {
  1361. data,
  1362. addr,
  1363. rsrc,
  1364. sampler,
  1365. cache,
  1366. ..
  1367. } => {
  1368. for a in addr.iter().chain([rsrc]).chain(sampler) {
  1369. regs(a, &mut r)?;
  1370. }
  1371. if name.contains("_store") {
  1372. regs(data, &mut r)?;
  1373. } else if name.contains("_atomic_") {
  1374. regs(data, &mut r)?;
  1375. if cache.glc {
  1376. regs(&atomic_result(data, name), &mut w)?;
  1377. }
  1378. } else {
  1379. regs(data, &mut w)?;
  1380. }
  1381. }
  1382. Fields::Flat {
  1383. dst,
  1384. addr,
  1385. data,
  1386. saddr,
  1387. ..
  1388. } => {
  1389. for o in [addr, data, saddr].into_iter().flatten() {
  1390. regs(o, &mut r)?;
  1391. }
  1392. if let Some(d) = dst {
  1393. regs(d, &mut w)?;
  1394. }
  1395. }
  1396. Fields::Exp { src, .. } => {
  1397. for s in src.iter().flatten() {
  1398. regs(s, &mut r)?;
  1399. }
  1400. }
  1401. }
  1402. if vector {
  1403. r.extend(mask(EXEC));
  1404. }
  1405. let mut seen = Vec::with_capacity(r.len());
  1406. r.retain(|reg| {
  1407. let new = !seen.contains(reg);
  1408. seen.push(*reg);
  1409. new
  1410. });
  1411. Ok(Some((r, w)))
  1412. }
  1413. /// Scalar ALU opcodes that set SCC (carry, overflow, comparison, or "result
  1414. /// is not zero").
  1415. fn writes_scc(encoding: gfx10::Encoding, name: &str) -> bool {
  1416. use gfx10::Encoding::*;
  1417. match encoding {
  1418. Sopc => true,
  1419. Sopk => name.starts_with("s_cmpk_") || name == "s_addk_i32",
  1420. _ => {
  1421. let stem = name.split('_').nth(1).unwrap_or("");
  1422. name.contains("saveexec")
  1423. || name.contains("wrexec")
  1424. || matches!(
  1425. stem,
  1426. "add"
  1427. | "sub"
  1428. | "addc"
  1429. | "subb"
  1430. | "min"
  1431. | "max"
  1432. | "and"
  1433. | "or"
  1434. | "xor"
  1435. | "andn2"
  1436. | "orn2"
  1437. | "nand"
  1438. | "nor"
  1439. | "xnor"
  1440. | "lshl"
  1441. | "lshr"
  1442. | "ashr"
  1443. | "bfe"
  1444. | "absdiff"
  1445. | "lshl1"
  1446. | "lshl2"
  1447. | "lshl3"
  1448. | "lshl4"
  1449. | "not"
  1450. | "wqm"
  1451. | "bcnt0"
  1452. | "bcnt1"
  1453. | "quadmask"
  1454. | "abs"
  1455. )
  1456. }
  1457. }
  1458. }
  1459. /// What an atomic with `glc` returns: the old value (for compare-and-swap,
  1460. /// half the data operand).
  1461. fn atomic_result(data: &Operand, name: &str) -> Operand {
  1462. match *data {
  1463. Operand::Vector { reg, dwords } if name.contains("cmpswap") => Operand::Vector {
  1464. reg,
  1465. dwords: dwords / 2,
  1466. },
  1467. op => op,
  1468. }
  1469. }
  1470. /// Appends the register dwords an operand names; reading `vccz`, `execz`,
  1471. /// `scc` or `lds_direct` reads the register behind it.
  1472. fn add_regs(op: &Operand, lanes: u8, out: &mut Vec<Reg>) -> Result<(), ()> {
  1473. match *op {
  1474. Operand::Scalar { code, .. } if code == gfx10::NULL => {}
  1475. Operand::Scalar { code, dwords } => {
  1476. let end = u16::from(code) + u16::from(dwords);
  1477. // A machine operand ends within the machine's codes, a parked
  1478. // scalar (`unspill`) within those past them.
  1479. let limit = if code < PARKED { 128 } else { 256 };
  1480. if end > limit {
  1481. return Err(());
  1482. }
  1483. out.extend((u16::from(code)..end).map(|c| Reg::S(c as u8)));
  1484. }
  1485. Operand::Vector { reg, dwords } => {
  1486. if u16::from(reg) + u16::from(dwords) > 256 {
  1487. return Err(());
  1488. }
  1489. out.extend((0..dwords).map(|i| Reg::V(reg + i)));
  1490. }
  1491. Operand::Const(251) => out.extend((0..lanes).map(|i| Reg::S(VCC + i))),
  1492. Operand::Const(252) => out.extend((0..lanes).map(|i| Reg::S(EXEC + i))),
  1493. Operand::Const(253) => out.push(Reg::Scc),
  1494. Operand::Const(254) => out.push(Reg::S(M0)),
  1495. Operand::Const(_) | Operand::Literal(_) | Operand::Attr { .. } => {}
  1496. }
  1497. Ok(())
  1498. }
  1499. #[cfg(test)]
  1500. mod tests {
  1501. use super::*;
  1502. const S_ENDPGM: u32 = 0xBF81_0000;
  1503. fn build_words(words: &[u32], wave64: bool) -> Program {
  1504. let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
  1505. build(&code, wave64, 256).unwrap()
  1506. }
  1507. fn input(p: &Program, reg: Reg) -> Value {
  1508. p.inputs.iter().find(|i| i.0 == reg).expect("input").1
  1509. }
  1510. /// `if (v0 < s0) { ... }` whose body changes s6: `body` are its words, `after` what
  1511. /// follows the join.
  1512. fn skip(body: &[u32], after: &[u32]) -> Program {
  1513. let mut w = vec![
  1514. 0xBE94_0306, // s_mov_b32 s20, s6
  1515. 0x7D88_0000, // v_cmp_gt_u32 vcc, s0, v0
  1516. 0xBE8C_246A, // s_and_saveexec_b64 s[12:13], vcc
  1517. 0xBF88_0000 | body.len() as u32, // s_cbranch_execz past the body
  1518. ];
  1519. w.extend_from_slice(body);
  1520. w.push(0xBEFE_040C); // s_mov_b64 exec, s[12:13]
  1521. w.extend_from_slice(after);
  1522. w.push(S_ENDPGM);
  1523. build_words(&w, true)
  1524. }
  1525. fn skips(p: &Program) -> usize {
  1526. p.blocks
  1527. .iter()
  1528. .filter(|b| b.insts.last().is_some_and(|i| i.name() == "s_cbranch_execz"))
  1529. .count()
  1530. }
  1531. #[test]
  1532. fn a_skip_is_left_out_when_the_scalars_it_changes_come_back_or_are_not_read() {
  1533. const SET: u32 = 0xBE86_0385; // s_mov_b32 s6, 5
  1534. const USE: u32 = 0x7E02_0206; // v_mov_b32 v1, s6
  1535. const BACK: u32 = 0xBE86_0314; // s_mov_b32 s6, s20
  1536. const READ: u32 = 0x7E04_0206; // v_mov_b32 v2, s6
  1537. // s6 is changed in the body and read after the join: the branch stays
  1538. let kept = skip(&[SET, USE], &[READ]);
  1539. assert_eq!(skips(&kept), 1);
  1540. assert!(without_skips(&kept, false).is_none());
  1541. assert!(without_skips(&kept, true).is_none());
  1542. // ... put back by a copy of what it held (as a scalar parked in a VGPR lane comes
  1543. // back): every lane may walk the body
  1544. let back = skip(&[SET, USE, BACK], &[READ]);
  1545. assert!(without_skips(&back, false).is_none());
  1546. assert_eq!(skips(&without_skips(&back, true).expect("left out")), 0);
  1547. // ... or not read after the join at all
  1548. let unread = skip(&[SET, USE], &[]);
  1549. assert_eq!(skips(&without_skips(&unread, false).expect("left out")), 0);
  1550. assert_eq!(skips(&without_skips(&unread, true).expect("left out")), 0);
  1551. // ... or read only by a restore of EXEC that nothing uses before the next one
  1552. // (s_mov_b64 exec, s[6:7]; s_mov_b64 exec, s[12:13]; v_mov_b32 v2, s0)
  1553. let idle = skip(&[SET, USE], &[0xBEFE_0406, 0xBEFE_040C, 0x7E04_0200]);
  1554. assert!(without_skips(&idle, false).is_none());
  1555. assert_eq!(skips(&without_skips(&idle, true).expect("left out")), 0);
  1556. }
  1557. #[test]
  1558. fn joins_get_phis_only_where_values_differ() {
  1559. let code = [
  1560. 0xBF06_0100, // s_cmp_eq_u32 s0, s1
  1561. 0xBF85_0001, // s_cbranch_scc1 -> 12
  1562. 0xBE82_0380, // s_mov_b32 s2, 0
  1563. 0x7E00_0202, // 12: v_mov_b32 v0, s2
  1564. 0x7E02_0200, // v_mov_b32 v1, s0
  1565. S_ENDPGM,
  1566. ];
  1567. for wave64 in [false, true] {
  1568. let p = build_words(&code, wave64);
  1569. let [b0, b1, b2] = &p.blocks[..] else {
  1570. panic!("{:?}", p.blocks)
  1571. };
  1572. assert_eq!(
  1573. b0.exit,
  1574. Exit::Branch {
  1575. taken: 2,
  1576. not_taken: 1
  1577. }
  1578. );
  1579. assert_eq!(b1.exit, Exit::Jump(2));
  1580. assert_eq!(b2.preds, [0, 1]);
  1581. assert_eq!(b0.insts[1].read(Reg::Scc), b0.insts[0].write(Reg::Scc));
  1582. // s2 differs per path; s0, EXEC, v0 and v1 do not.
  1583. let [phi] = &b2.phis[..] else {
  1584. panic!("{:?}", b2.phis)
  1585. };
  1586. assert_eq!(phi.reg, Reg::S(2));
  1587. assert_eq!(
  1588. phi.args,
  1589. [input(&p, Reg::S(2)), b1.insts[0].write(Reg::S(2)).unwrap()]
  1590. );
  1591. let [mov0, mov1, end] = &b2.insts[..] else {
  1592. panic!()
  1593. };
  1594. assert_eq!(mov0.read(Reg::S(2)), Some(phi.value));
  1595. assert_eq!(mov1.read(Reg::S(0)), Some(input(&p, Reg::S(0))));
  1596. // The old v1 is read: lanes outside EXEC keep it.
  1597. assert_eq!(mov1.read(Reg::V(1)), Some(input(&p, Reg::V(1))));
  1598. assert_eq!(mov1.read(Reg::S(EXEC)), Some(input(&p, Reg::S(EXEC))));
  1599. assert_eq!(mov1.read(Reg::S(EXEC + 1)).is_some(), wave64);
  1600. assert_eq!((end.name(), b2.exit), ("s_endpgm", Exit::End));
  1601. }
  1602. }
  1603. #[test]
  1604. fn in_place_scalar_ops_read_their_destination() {
  1605. let p = build_words(
  1606. &[
  1607. 0xBE8D_1D94, // s_bitset1_b32 s13, 20
  1608. 0xB78E_0010, // s_addk_i32 s14, 0x10
  1609. 0xBE8F_0380, // s_mov_b32 s15, 0
  1610. S_ENDPGM,
  1611. ],
  1612. false,
  1613. );
  1614. let [bitset, addk, mov, _] = &p.blocks[0].insts[..] else {
  1615. panic!("{:?}", p.blocks[0].insts)
  1616. };
  1617. assert_eq!(bitset.read(Reg::S(13)), Some(input(&p, Reg::S(13))));
  1618. assert_eq!(addk.read(Reg::S(14)), Some(input(&p, Reg::S(14))));
  1619. assert_eq!(mov.read(Reg::S(15)), None);
  1620. }
  1621. #[test]
  1622. fn loops_carry_values_through_phis() {
  1623. let p = build_words(
  1624. &[
  1625. 0xBE80_0380, // s_mov_b32 s0, 0
  1626. 0x8000_8100, // 4: s_add_u32 s0, s0, 1
  1627. 0xBF07_8400, // s_cmp_lg_u32 s0, 4
  1628. 0xBF85_FFFD, // s_cbranch_scc1 -> 4
  1629. S_ENDPGM,
  1630. ],
  1631. true,
  1632. );
  1633. assert!(p.inputs.is_empty(), "{:?}", p.inputs);
  1634. let [b0, b1, b2] = &p.blocks[..] else {
  1635. panic!()
  1636. };
  1637. assert_eq!(b1.preds, [0, 1]);
  1638. assert_eq!(
  1639. b1.exit,
  1640. Exit::Branch {
  1641. taken: 1,
  1642. not_taken: 2
  1643. }
  1644. );
  1645. let [phi] = &b1.phis[..] else {
  1646. panic!("{:?}", b1.phis)
  1647. };
  1648. let add = &b1.insts[0];
  1649. assert_eq!(phi.reg, Reg::S(0));
  1650. assert_eq!(
  1651. phi.args,
  1652. [
  1653. b0.insts[0].write(Reg::S(0)).unwrap(),
  1654. add.write(Reg::S(0)).unwrap()
  1655. ]
  1656. );
  1657. assert_eq!(add.read(Reg::S(0)), Some(phi.value));
  1658. assert_eq!(b1.insts[1].read(Reg::S(0)), add.write(Reg::S(0)));
  1659. assert_eq!(b2.insts[0].name(), "s_endpgm");
  1660. }
  1661. #[test]
  1662. fn drops_scheduling_and_follows_far_jumps() {
  1663. let p = build_words(
  1664. &[
  1665. 0xBF80_0000, // s_nop 0
  1666. 0xBE88_1F00, // s_getpc_b64 s[8:9]
  1667. 0x8008_FF08,
  1668. 20, // s_add_u32 s8, s8, 20 -> 8 + 20 = 28
  1669. 0x8209_8009, // s_addc_u32 s9, s9, 0
  1670. 0xBE80_2008, // s_setpc_b64 s[8:9]
  1671. 0xFFFF_FFFF, // not code
  1672. S_ENDPGM,
  1673. ],
  1674. false,
  1675. );
  1676. let names: Vec<_> = p.blocks[0].insts.iter().map(Inst::name).collect();
  1677. assert_eq!(
  1678. names,
  1679. ["s_getpc_b64", "s_add_u32", "s_addc_u32", "s_setpc_b64"]
  1680. );
  1681. assert_eq!(p.blocks[0].exit, Exit::Jump(1));
  1682. assert_eq!(p.blocks[1].offset, 28);
  1683. // s_addc_u32 reads the carry s_add_u32 left in SCC.
  1684. let i = &p.blocks[0].insts;
  1685. assert_eq!(i[2].read(Reg::Scc), i[1].write(Reg::Scc));
  1686. }
  1687. #[test]
  1688. fn reports_what_it_cannot_express() {
  1689. let code: Vec<u8> = [0xBE80_2E01_u32, S_ENDPGM] // s_movrels_b32 s0, s1
  1690. .iter()
  1691. .flat_map(|w| w.to_le_bytes())
  1692. .collect();
  1693. assert_eq!(
  1694. build(&code, false, 256),
  1695. Err(ShaderError::Unsupported {
  1696. offset: 0,
  1697. what: "s_movrels_b32"
  1698. })
  1699. );
  1700. }
  1701. #[test]
  1702. fn relative_vgpr_access_spans_up_to_the_vgpr_count() {
  1703. let code: Vec<u8> = [
  1704. 0x7E04_8501_u32, // v_movreld_b32 v2, v1: v[2 + m0] = v1
  1705. 0x7E00_8704, // v_movrels_b32 v0, v4: v0 = v[4 + m0]
  1706. S_ENDPGM,
  1707. ]
  1708. .iter()
  1709. .flat_map(|w| w.to_le_bytes())
  1710. .collect();
  1711. let p = build(&code, false, 6).unwrap();
  1712. let [movreld, movrels, _] = &p.blocks[0].insts[..] else {
  1713. panic!()
  1714. };
  1715. let vgprs = |regs: &[(Reg, Value)]| -> Vec<u8> {
  1716. regs.iter()
  1717. .filter_map(|r| match r.0 {
  1718. Reg::V(v) => Some(v),
  1719. _ => None,
  1720. })
  1721. .collect()
  1722. };
  1723. assert_eq!(vgprs(&movreld.writes), [2, 3, 4, 5]);
  1724. // v1 is the source; v2-v5 are read for the lanes and indices not written.
  1725. assert_eq!(vgprs(&movreld.reads), [1, 2, 3, 4, 5]);
  1726. assert!(movreld.read(Reg::S(M0)).is_some());
  1727. assert_eq!(vgprs(&movrels.writes), [0]);
  1728. assert_eq!(vgprs(&movrels.reads), [4, 5, 0]);
  1729. assert_eq!(movrels.read(Reg::V(4)), movreld.write(Reg::V(4)));
  1730. assert!(build(&code, false, 4).is_err(), "v4 is past 4 VGPRs");
  1731. }
  1732. }