ir.rs 78 KB

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