structure.rs 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890
  1. //! Control-flow structurisation (decision 0003): the program as one lane
  2. //! runs it, without EXEC.
  3. //!
  4. //! Lane masks (EXEC, compare and carry results, the SGPRs they are saved
  5. //! in) become per-lane booleans ([`Bools`]). A branch on a wave-wide test of
  6. //! a mask (`s_cbranch_execz`, `vccz`, SCC of a mask operation) becomes a
  7. //! branch on the lane's own bit: compiled code only skips work that lanes
  8. //! outside the mask would not change, or tests a value that is the same in
  9. //! every lane, so either way each lane can decide alone. A path-sensitive
  10. //! pass then proves, for each vector instruction, that EXEC holds in every
  11. //! lane that reaches it; what it cannot prove stays as the instruction's
  12. //! guard, a per-lane `if` around it.
  13. //!
  14. //! The control-flow graph keeps its shape and must be reducible (DXIL's
  15. //! only requirement). Helper lanes of a pixel shader count as live: on PC
  16. //! their side effects are dropped too, and what they compute is only read
  17. //! through derivatives.
  18. use std::collections::{HashMap, HashSet};
  19. use std::hash::{BuildHasherDefault, Hasher};
  20. use crate::ShaderError;
  21. use crate::gfx10::{Fields, NULL, Operand};
  22. use crate::ir::{EXEC, Exit, Inst, Program, Reg, VCC, Value};
  23. /// A per-lane boolean: a node of [`Bools`]. Equal functions are equal nodes.
  24. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
  25. pub struct Bool(u32);
  26. impl Bool {
  27. pub const FALSE: Bool = Bool(0);
  28. pub const TRUE: Bool = Bool(1);
  29. }
  30. /// What a variable of [`Bools`] stands for.
  31. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
  32. pub enum Atom {
  33. /// The lane's bit of the compare or carry result in this VALU-written
  34. /// value, before EXEC masking.
  35. Lane(Value),
  36. /// An SCC value, the same in every lane.
  37. Uniform(Value),
  38. /// A lane mask joined at a block entry, by its low dword's phi.
  39. Phi(Value),
  40. /// `s_wqm` result: some lane of the quad is in the source mask.
  41. Quad(Value),
  42. /// A mask the pass cannot see into (loaded, built from scalars, an
  43. /// EXEC write it does not follow): the lane's bit of the register pair
  44. /// this value is a dword of.
  45. Opaque(Value),
  46. /// A constant mask other than all lanes or none.
  47. Constant(u64),
  48. }
  49. /// Reduced ordered binary decision diagrams over [`Atom`]s.
  50. #[derive(Debug, Clone)]
  51. pub struct Bools {
  52. /// (variable, low, high); nodes 0 and 1 are the constants.
  53. nodes: Vec<(u32, Bool, Bool)>,
  54. unique: Map<(u32, Bool, Bool), Bool>,
  55. memo: Map<(Bool, Bool, Bool), Bool>,
  56. atoms: Vec<Atom>,
  57. /// Reverse-postorder index of the block that defines each atom.
  58. born: Vec<usize>,
  59. ids: Map<Atom, u32>,
  60. overflow: bool,
  61. }
  62. /// The tables below have small integer keys; SipHash dominated run time.
  63. type Map<K, V> = HashMap<K, V, BuildHasherDefault<Fx>>;
  64. /// FxHash's multiply-rotate step.
  65. #[derive(Default)]
  66. struct Fx(u64);
  67. impl Hasher for Fx {
  68. fn finish(&self) -> u64 {
  69. self.0
  70. }
  71. fn write(&mut self, bytes: &[u8]) {
  72. for &b in bytes {
  73. self.write_u64(u64::from(b));
  74. }
  75. }
  76. fn write_u32(&mut self, n: u32) {
  77. self.write_u64(u64::from(n));
  78. }
  79. fn write_u64(&mut self, n: u64) {
  80. self.0 = (self.0.rotate_left(5) ^ n).wrapping_mul(0x517c_c1b7_2722_0a95);
  81. }
  82. fn write_usize(&mut self, n: usize) {
  83. self.write_u64(n as u64);
  84. }
  85. }
  86. const TERMINAL: u32 = u32::MAX;
  87. const MAX_NODES: usize = 1 << 21;
  88. /// Case splits [`Bools::meet`] makes before it gives up.
  89. const MAX_MEET: usize = 1 << 16;
  90. /// Conditions [`Meets`] keeps; past that, they are searched anew.
  91. const MAX_MEETS: usize = 1 << 18;
  92. /// What [`Bools::meet`] found out about one [`Bools`], for its later calls:
  93. /// the conditions no lane satisfies, and the case splits it took to find
  94. /// that out of each.
  95. #[derive(Debug, Default)]
  96. pub struct Meets {
  97. none: Map<Box<[u32]>, usize>,
  98. }
  99. impl Bools {
  100. fn new() -> Self {
  101. Bools {
  102. nodes: vec![
  103. (TERMINAL, Bool::FALSE, Bool::FALSE),
  104. (TERMINAL, Bool::TRUE, Bool::TRUE),
  105. ],
  106. unique: Map::default(),
  107. memo: Map::default(),
  108. atoms: Vec::new(),
  109. born: Vec::new(),
  110. ids: Map::default(),
  111. overflow: false,
  112. }
  113. }
  114. /// The atom tested at the top of `b` and the results when it is false
  115. /// and true; `None` for the constants.
  116. pub fn node(&self, b: Bool) -> Option<(Atom, Bool, Bool)> {
  117. let (v, lo, hi) = self.nodes[b.0 as usize];
  118. (v != TERMINAL).then(|| (self.atoms[v as usize], lo, hi))
  119. }
  120. /// The atoms `b` depends on, in variable order.
  121. pub fn support(&self, b: Bool) -> Vec<Atom> {
  122. let mut vars = self.vars(b);
  123. vars.sort_unstable();
  124. vars.into_iter().map(|v| self.atoms[v as usize]).collect()
  125. }
  126. fn vars(&self, b: Bool) -> Vec<u32> {
  127. let (mut seen, mut vars, mut stack) = (Vec::new(), Vec::new(), vec![b]);
  128. while let Some(b) = stack.pop() {
  129. let (v, lo, hi) = self.nodes[b.0 as usize];
  130. if v == TERMINAL || seen.contains(&b) {
  131. continue;
  132. }
  133. seen.push(b);
  134. if !vars.contains(&v) {
  135. vars.push(v);
  136. }
  137. stack.extend([lo, hi]);
  138. }
  139. vars
  140. }
  141. fn atom(&mut self, atom: Atom, born: usize) -> Bool {
  142. let v = *self.ids.entry(atom).or_insert_with(|| {
  143. self.atoms.push(atom);
  144. self.born.push(born);
  145. (self.atoms.len() - 1) as u32
  146. });
  147. self.mk(v, Bool::FALSE, Bool::TRUE)
  148. }
  149. fn mk(&mut self, v: u32, lo: Bool, hi: Bool) -> Bool {
  150. if lo == hi {
  151. return lo;
  152. }
  153. if let Some(&b) = self.unique.get(&(v, lo, hi)) {
  154. return b;
  155. }
  156. if self.nodes.len() >= MAX_NODES {
  157. // The caller fails once it sees `overflow`.
  158. self.overflow = true;
  159. return Bool::FALSE;
  160. }
  161. let b = Bool(self.nodes.len() as u32);
  162. self.nodes.push((v, lo, hi));
  163. self.unique.insert((v, lo, hi), b);
  164. b
  165. }
  166. /// Cofactors of `b` for `v`, which is `b`'s top variable or above it.
  167. fn split(&self, b: Bool, v: u32) -> (Bool, Bool) {
  168. match self.nodes[b.0 as usize] {
  169. (bv, lo, hi) if bv == v => (lo, hi),
  170. _ => (b, b),
  171. }
  172. }
  173. fn ite(&mut self, f: Bool, g: Bool, h: Bool) -> Bool {
  174. if f == Bool::TRUE || g == h {
  175. return g;
  176. }
  177. if f == Bool::FALSE {
  178. return h;
  179. }
  180. if (g, h) == (Bool::TRUE, Bool::FALSE) {
  181. return f;
  182. }
  183. if let Some(&r) = self.memo.get(&(f, g, h)) {
  184. return r;
  185. }
  186. let top = |b: Bool| self.nodes[b.0 as usize].0;
  187. let v = top(f).min(top(g)).min(top(h));
  188. let ((f0, f1), (g0, g1), (h0, h1)) = (self.split(f, v), self.split(g, v), self.split(h, v));
  189. let lo = self.ite(f0, g0, h0);
  190. let hi = self.ite(f1, g1, h1);
  191. let r = self.mk(v, lo, hi);
  192. self.memo.insert((f, g, h), r);
  193. r
  194. }
  195. fn and(&mut self, a: Bool, b: Bool) -> Bool {
  196. self.ite(a, b, Bool::FALSE)
  197. }
  198. fn or(&mut self, a: Bool, b: Bool) -> Bool {
  199. self.ite(a, Bool::TRUE, b)
  200. }
  201. fn not(&mut self, a: Bool) -> Bool {
  202. self.ite(a, Bool::FALSE, Bool::TRUE)
  203. }
  204. fn xor(&mut self, a: Bool, b: Bool) -> Bool {
  205. let nb = self.not(b);
  206. self.ite(a, nb, b)
  207. }
  208. /// Whether some lane can satisfy every `(b, holds)` of `all` at once:
  209. /// `b` where `holds`, its negation where not. Yes when the search grows
  210. /// too large to finish.
  211. pub fn meet(&self, all: &[(Bool, bool)]) -> bool {
  212. self.meet_seen(all, &mut Meets::default())
  213. }
  214. /// [`Self::meet`], which looks up in `seen` what earlier calls on these
  215. /// `Bools` found out and adds what it finds. The answer is the one
  216. /// `meet` gives.
  217. pub fn meet_seen(&self, all: &[(Bool, bool)], seen: &mut Meets) -> bool {
  218. self.meet_within(all, MAX_MEET, seen)
  219. }
  220. /// [`Self::meet_seen`] with `budget` case splits.
  221. fn meet_within(&self, all: &[(Bool, bool)], mut budget: usize, seen: &mut Meets) -> bool {
  222. let mut work = all
  223. .iter()
  224. .map(|&(b, holds)| b.0 << 1 | u32::from(holds))
  225. .collect();
  226. self.meet_in(0, &mut work, &mut budget, seen)
  227. }
  228. /// The search of [`Self::meet`] for the conditions `work[at..]` (a node
  229. /// doubled, plus one where it must hold), which it takes off `work`.
  230. ///
  231. /// The search is a case split on the top variable, and the cofactors of
  232. /// a few large functions come down to the same conditions over and over
  233. /// (a block's reach under a mask and under its negation share most of
  234. /// their nodes), so splitting each anew is exponential where the
  235. /// distinct conditions are few. `seen` keeps the conditions that no lane
  236. /// satisfies with the case splits it took to find that out: meeting
  237. /// them again takes those splits off the budget at once. A search
  238. /// therefore gives up exactly where one that split everything anew
  239. /// would (nothing below such conditions ends it early, so it either
  240. /// makes all those splits or runs out among them), and gives the same
  241. /// answer.
  242. fn meet_in(
  243. &self,
  244. at: usize,
  245. work: &mut Vec<u32>,
  246. budget: &mut usize,
  247. seen: &mut Meets,
  248. ) -> bool {
  249. // Constants either fail or say nothing.
  250. let mut kept = at;
  251. for i in at..work.len() {
  252. let (b, holds) = (work[i] >> 1, work[i] & 1 != 0);
  253. if b > Bool::TRUE.0 {
  254. work[kept] = work[i];
  255. kept += 1;
  256. } else if (b == Bool::TRUE.0) != holds {
  257. work.truncate(at);
  258. return false;
  259. }
  260. }
  261. work.truncate(kept);
  262. if kept == at || *budget == 0 {
  263. work.truncate(at);
  264. return true;
  265. }
  266. // As a set: neither order nor repeats change the search.
  267. work[at..].sort_unstable();
  268. let mut end = at + 1;
  269. for i in at + 1..kept {
  270. if work[i] != work[end - 1] {
  271. work[end] = work[i];
  272. end += 1;
  273. }
  274. }
  275. work.truncate(end);
  276. if let Some(&splits) = seen.none.get(&work[at..]) {
  277. let within = splits <= *budget;
  278. *budget = budget.saturating_sub(splits);
  279. work.truncate(at);
  280. return !within;
  281. }
  282. let before = *budget;
  283. *budget -= 1;
  284. let top = |code: u32| self.nodes[(code >> 1) as usize].0;
  285. let v = work[at..].iter().map(|&c| top(c)).min().expect("not empty");
  286. let mut found = false;
  287. for value in [false, true] {
  288. for i in at..end {
  289. let (lo, hi) = self.split(Bool(work[i] >> 1), v);
  290. work.push((if value { hi } else { lo }).0 << 1 | work[i] & 1);
  291. }
  292. if self.meet_in(end, work, budget, seen) {
  293. found = true;
  294. break;
  295. }
  296. }
  297. if !found && seen.none.len() < MAX_MEETS {
  298. seen.none.insert(work[at..end].into(), before - *budget);
  299. }
  300. work.truncate(at);
  301. found
  302. }
  303. fn implies(&mut self, a: Bool, b: Bool) -> bool {
  304. let nb = self.not(b);
  305. self.and(a, nb) == Bool::FALSE
  306. }
  307. /// `b` with every atom born at reverse-postorder index `from` or later
  308. /// existentially quantified: what still holds once those are redefined.
  309. fn forget(&mut self, b: Bool, from: usize, memo: &mut Map<Bool, Bool>) -> Bool {
  310. let (v, lo, hi) = self.nodes[b.0 as usize];
  311. if v == TERMINAL {
  312. return b;
  313. }
  314. if let Some(&r) = memo.get(&b) {
  315. return r;
  316. }
  317. let lo = self.forget(lo, from, memo);
  318. let hi = self.forget(hi, from, memo);
  319. let r = if self.born[v as usize] >= from {
  320. self.or(lo, hi)
  321. } else {
  322. self.mk(v, lo, hi)
  323. };
  324. memo.insert(b, r);
  325. r
  326. }
  327. fn restrict(&mut self, b: Bool, v: u32, value: bool, memo: &mut Map<Bool, Bool>) -> Bool {
  328. let (bv, lo, hi) = self.nodes[b.0 as usize];
  329. if bv == TERMINAL || bv > v {
  330. return b;
  331. }
  332. if bv == v {
  333. return if value { hi } else { lo };
  334. }
  335. if let Some(&r) = memo.get(&b) {
  336. return r;
  337. }
  338. let l = self.restrict(lo, v, value, memo);
  339. let h = self.restrict(hi, v, value, memo);
  340. let r = self.mk(bv, l, h);
  341. memo.insert(b, r);
  342. r
  343. }
  344. /// `b` with each atom that `known` decides replaced by its value.
  345. fn given(&mut self, mut b: Bool, known: Bool) -> Bool {
  346. for v in self.vars(b) {
  347. let x = self.mk(v, Bool::FALSE, Bool::TRUE);
  348. let nx = self.not(x);
  349. if self.implies(known, x) {
  350. b = self.restrict(b, v, true, &mut Map::default());
  351. } else if self.implies(known, nx) {
  352. b = self.restrict(b, v, false, &mut Map::default());
  353. }
  354. }
  355. b
  356. }
  357. }
  358. /// How a lane leaves a block.
  359. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  360. pub enum LaneExit {
  361. Jump(usize),
  362. /// To `taken` in lanes where `when` holds. A condition over
  363. /// [`Atom::Uniform`]s only is a uniform branch.
  364. Branch {
  365. when: Bool,
  366. taken: usize,
  367. not_taken: usize,
  368. },
  369. End,
  370. Indirect,
  371. }
  372. /// A [`Program`] as one lane runs it: same blocks, per-lane branches.
  373. #[derive(Debug, Clone)]
  374. pub struct Structured {
  375. pub bools: Bools,
  376. /// Per block.
  377. pub exits: Vec<LaneExit>,
  378. /// Per block and instruction: the condition, beyond reaching it, under
  379. /// which a lane runs a vector instruction; `None` when reaching it is
  380. /// enough (lanes outside EXEC then never get there, so a VGPR write
  381. /// needs no old value). Always `None` for scalar instructions.
  382. pub guards: Vec<Vec<Option<Bool>>>,
  383. /// Per block: what holds in every lane that enters it (over forward
  384. /// edges; a loop header forgets what its loop redefines).
  385. pub reach: Vec<Bool>,
  386. /// The lane's bit of each lane-mask value, by its low dword's value.
  387. pub masks: HashMap<Value, Bool>,
  388. /// Exact Wave64 pairs for checking masks at their uses.
  389. paired_masks: Map<Key, Bool>,
  390. /// Wave64 masks: low dword's value by the high dword's.
  391. pub highs: HashMap<Value, Value>,
  392. /// Masks (low dwords) set only in lanes whose EXEC bit is set where
  393. /// they are written: every such lane reaches the writing block, so a
  394. /// ballot there gives the mask as data. No split low dword, as in
  395. /// `masks`.
  396. pub active: HashSet<Value>,
  397. /// Incoming lane boolean per predecessor edge (in block predecessor order)
  398. /// for each [`Atom::Phi`] id.
  399. pub phi_masks: HashMap<Value, Vec<Bool>>,
  400. /// Blocks whose closing branch the whole wave takes together ([`structure_wide`]): its
  401. /// `when` is still the lane's own bit; the wave goes by all of them.
  402. pub wide: HashSet<usize>,
  403. /// Per block closed by a branch on a lane mask: whether the console takes it when some
  404. /// lane's `when` holds (`true`) or when every lane's does (`false`).
  405. pub wave_any: Vec<Option<bool>>,
  406. /// SCC values a mask operation sets when some lane's bit of its result is set, with that
  407. /// lane bit: as data such an SCC is "some lane of the wave has it".
  408. pub scc_some: HashMap<Value, Bool>,
  409. }
  410. impl Structured {
  411. pub(crate) fn mask_bits(&self, low: Value, high: Option<Value>) -> Option<Bool> {
  412. match high {
  413. Some(high) => self.paired_masks.get(&(low, high)),
  414. None => self.masks.get(&low),
  415. }
  416. .copied()
  417. }
  418. }
  419. /// Builds the per-lane form of `program`.
  420. pub fn structure(program: &Program) -> Result<Structured, ShaderError> {
  421. structure_wide(program, &HashSet::new())
  422. }
  423. /// [`structure`], with the branches that close the blocks of `wide` kept as the console has
  424. /// them: one decision for the whole wave (`s_cbranch_execz` and `vccz`: taken when no lane's
  425. /// bit is set; `execnz` and `vccnz`: when some lane's is; SCC of a mask operation likewise,
  426. /// [`Structured::wave_any`]), which every lane follows. A lane
  427. /// then learns nothing about its own bit from the way it went, so past such a branch EXEC
  428. /// stays a guard on every vector instruction, as it is on the console. For a console wave
  429. /// run as two host waves, which exchange that decision and can then meet (a group barrier)
  430. /// inside the branch.
  431. pub fn structure_wide(program: &Program, wide: &HashSet<usize>) -> Result<Structured, ShaderError> {
  432. let mut l = Lanes::new(program)?;
  433. l.wide = wide.clone();
  434. loop {
  435. let execs = l.masks_in_order();
  436. let cond = l.paths()?;
  437. let (wrong, new_derived) = l.check_joins(&cond);
  438. if l.b.overflow {
  439. return Err(TOO_LARGE);
  440. }
  441. if wrong.is_empty() && new_derived.is_empty() {
  442. return l.finish(&execs, &cond);
  443. }
  444. l.unresolved.extend(wrong);
  445. l.derived_phis.extend(new_derived);
  446. l.reset();
  447. }
  448. }
  449. /// A lane mask by the values of its low and high dword (both the low one in
  450. /// wave32).
  451. type Key = (Value, Value);
  452. struct Lanes<'a> {
  453. p: &'a Program,
  454. order: Vec<usize>,
  455. /// Reverse-postorder index per block.
  456. index: Vec<usize>,
  457. /// Per block, in predecessor order: (block, over its taken edge).
  458. incoming: Vec<Vec<(usize, bool)>>,
  459. /// Block and instruction index writing each value.
  460. defs: Map<Value, (usize, usize)>,
  461. /// Block and index of each phi value.
  462. phis: Map<Value, (usize, usize)>,
  463. /// Mask joins found wrong when resolved to a constant: atoms instead.
  464. unresolved: HashSet<Value>,
  465. /// Phi ids whose joins depend on EXEC or VALU results (including along
  466. /// back edges), carried across resets so their joins stay in `masks`.
  467. derived_phis: HashSet<Value>,
  468. b: Bools,
  469. /// Masks derived from EXEC and VALU results.
  470. masks: Map<Key, Bool>,
  471. /// Other values read as masks: constants, uniform selects, opaque ones.
  472. other: Map<Key, Bool>,
  473. /// Pairs read as masks that `mask` does not see: carry-ins, and pairs
  474. /// joins take over back edges.
  475. seen: Vec<Key>,
  476. /// For branches: SCC of a mask operation ("some lane is set") as the
  477. /// lane's own bit.
  478. scc_lane: Map<Value, Bool>,
  479. /// Joins resolved to a constant, to check once all edges are known.
  480. joins: Vec<Join>,
  481. /// [`Atom::Phi`] joins created in the current pass, resolved in
  482. /// `check_joins` and exported in `finish`.
  483. phi_joins: Vec<PhiJoin>,
  484. phi_join_ids: HashSet<Value>,
  485. /// Per block: what a lane knows on entry, over forward edges only.
  486. first: Vec<Bool>,
  487. /// Per block ending in a branch: when a lane takes it.
  488. when: Vec<Option<Bool>>,
  489. /// See [`Structured::active`].
  490. active: HashSet<Value>,
  491. /// See [`Structured::wide`].
  492. wide: HashSet<usize>,
  493. /// SCC values of [`Self::scc_lane`] that are set when EVERY lane's bit is (`s_cmp_eq` of
  494. /// two masks: "no lane differs"); the others are set when some lane's is.
  495. scc_every: HashSet<Value>,
  496. /// See [`Structured::wave_any`].
  497. wave_any: Vec<Option<bool>>,
  498. }
  499. /// A mask join taken as `value` in every lane that reaches `block`: each
  500. /// incoming mask held (or failed) on its edge.
  501. struct Join {
  502. block: usize,
  503. /// The phi value naming the join.
  504. id: Value,
  505. value: bool,
  506. derived: bool,
  507. args: Vec<Key>,
  508. }
  509. /// A mask join represented as [`Atom::Phi`], whose incoming edge masks are
  510. /// resolved once every block (including loop back edges) has been visited.
  511. struct PhiJoin {
  512. block: usize,
  513. id: Value,
  514. derived: bool,
  515. args: Vec<Key>,
  516. }
  517. struct SopMasks {
  518. dst: Option<(Key, Bool)>,
  519. exec: Option<(Key, Bool)>,
  520. /// Some operand derives from EXEC or a VALU result.
  521. derived: bool,
  522. /// For branches: SCC ("result is not zero") per lane.
  523. scc: Option<Bool>,
  524. }
  525. const MAX_ROUNDS: usize = 256;
  526. impl<'a> Lanes<'a> {
  527. fn new(p: &'a Program) -> Result<Self, ShaderError> {
  528. let blocks = &p.blocks;
  529. let order = crate::ir::reverse_postorder(blocks);
  530. let mut index = vec![usize::MAX; blocks.len()];
  531. for (i, &b) in order.iter().enumerate() {
  532. index[b] = i;
  533. }
  534. check_reducible(p, &order, &index)?;
  535. let mut incoming = vec![Vec::new(); blocks.len()];
  536. let (mut defs, mut phis) = (Map::default(), Map::default());
  537. for (b, block) in blocks.iter().enumerate() {
  538. for (k, s) in block.exit.successors().into_iter().enumerate() {
  539. incoming[s].push((b, k == 0));
  540. }
  541. for (i, phi) in block.phis.iter().enumerate() {
  542. phis.insert(phi.value, (b, i));
  543. }
  544. for (i, inst) in block.insts.iter().enumerate() {
  545. for &(_, v) in &inst.writes {
  546. defs.insert(v, (b, i));
  547. }
  548. }
  549. }
  550. Ok(Lanes {
  551. p,
  552. order,
  553. index,
  554. incoming,
  555. defs,
  556. phis,
  557. unresolved: HashSet::new(),
  558. derived_phis: HashSet::new(),
  559. b: Bools::new(),
  560. masks: Map::default(),
  561. other: Map::default(),
  562. seen: Vec::new(),
  563. scc_lane: Map::default(),
  564. joins: Vec::new(),
  565. phi_joins: Vec::new(),
  566. phi_join_ids: HashSet::new(),
  567. first: vec![Bool::FALSE; blocks.len()],
  568. when: vec![None; blocks.len()],
  569. active: HashSet::new(),
  570. wide: HashSet::new(),
  571. scc_every: HashSet::new(),
  572. wave_any: vec![None; blocks.len()],
  573. })
  574. }
  575. fn reset(&mut self) {
  576. self.b = Bools::new();
  577. self.masks.clear();
  578. self.other.clear();
  579. self.seen.clear();
  580. self.scc_lane.clear();
  581. self.scc_every.clear();
  582. self.wave_any.fill(None);
  583. self.joins.clear();
  584. self.phi_joins.clear();
  585. self.phi_join_ids.clear();
  586. self.first.fill(Bool::FALSE);
  587. self.when.fill(None);
  588. self.active.clear();
  589. }
  590. /// Lane masks, branch conditions and forward-edge knowledge, block by
  591. /// block in reverse postorder; returns EXEC at each instruction reading it.
  592. fn masks_in_order(&mut self) -> Vec<Vec<Option<Bool>>> {
  593. let p = self.p;
  594. let input = |reg| p.inputs.iter().find(|i| i.0 == reg).map(|i| i.1);
  595. if let Some(lo) = input(Reg::S(EXEC)) {
  596. let hi = if p.wave64 {
  597. input(Reg::S(EXEC + 1)).unwrap_or(lo)
  598. } else {
  599. lo
  600. };
  601. self.masks.insert((lo, hi), Bool::TRUE);
  602. self.active.insert(lo);
  603. }
  604. let mut execs: Vec<Vec<Option<Bool>>> =
  605. p.blocks.iter().map(|b| vec![None; b.insts.len()]).collect();
  606. for n in 0..self.order.len() {
  607. let b = self.order[n];
  608. let mut c = if n == 0 { Bool::TRUE } else { Bool::FALSE };
  609. for k in 0..self.incoming[b].len() {
  610. let (q, taken) = self.incoming[b][k];
  611. if self.index[q] < n {
  612. let e = self.edge(self.first[q], q, taken);
  613. c = self.b.or(c, e);
  614. }
  615. }
  616. self.first[b] = c;
  617. // EXEC joined at the block's entry holds the lanes that arrive.
  618. for phi in &p.blocks[b].phis {
  619. if phi.reg == Reg::S(EXEC) {
  620. self.active.insert(phi.value);
  621. }
  622. }
  623. // EXEC where known in this block (read or written so far).
  624. let mut now = None;
  625. for (i, inst) in p.blocks[b].insts.iter().enumerate() {
  626. if inst.read(Reg::S(EXEC)).is_some() {
  627. let e = self.exec(inst);
  628. execs[b][i] = Some(e);
  629. now = Some(e);
  630. }
  631. self.step(inst, now);
  632. if let Some(k) = self.key(|r| inst.write(r), EXEC) {
  633. now = self.masks.get(&k).or(self.other.get(&k)).copied();
  634. }
  635. }
  636. if let Exit::Branch { .. } = p.blocks[b].exit
  637. && let Some(last) = p.blocks[b].insts.last()
  638. {
  639. self.when[b] = Some(self.branch(last));
  640. self.wave_any[b] = self.wave_kind(last);
  641. }
  642. }
  643. execs
  644. }
  645. /// `c` narrowed by the branch at the end of `q` towards one successor.
  646. fn edge(&mut self, c: Bool, q: usize, taken: bool) -> Bool {
  647. if self.wide.contains(&q) {
  648. // the wave's decision: it says nothing about this lane's own bit
  649. return c;
  650. }
  651. match self.when[q] {
  652. Some(w) if taken => self.b.and(c, w),
  653. Some(w) => {
  654. let nw = self.b.not(w);
  655. self.b.and(c, nw)
  656. }
  657. None => c,
  658. }
  659. }
  660. /// Joins whose constant fails on some edge, and joins that need another
  661. /// pass because a later edge turned out to derive from EXEC or VALU.
  662. fn check_joins(&mut self, cond: &[Bool]) -> (Vec<Value>, Vec<Value>) {
  663. let mut wrong = Vec::new();
  664. let mut new_derived = Vec::new();
  665. let mut seen_derived = HashSet::new();
  666. let mut j = 0;
  667. let mut p = 0;
  668. // Checking an argument can resolve another join; it is checked too.
  669. while j < self.joins.len() || p < self.phi_joins.len() {
  670. while j < self.joins.len() {
  671. let (block, id, value, was_derived) = (
  672. self.joins[j].block,
  673. self.joins[j].id,
  674. self.joins[j].value,
  675. self.joins[j].derived,
  676. );
  677. let mut failed = false;
  678. for (n, a) in self.joins[j].args.clone().into_iter().enumerate() {
  679. let (q, taken) = self.incoming[block][n];
  680. let e = self.edge(cond[q], q, taken);
  681. let (mut m, d) = self.mask(a);
  682. if !was_derived
  683. && d
  684. && !self.derived_phis.contains(&id)
  685. && seen_derived.insert(id)
  686. {
  687. new_derived.push(id);
  688. }
  689. if !value {
  690. m = self.b.not(m);
  691. }
  692. if !failed && !self.b.implies(e, m) {
  693. wrong.push(id);
  694. failed = true;
  695. }
  696. }
  697. j += 1;
  698. }
  699. while p < self.phi_joins.len() {
  700. let (id, was_derived) = (self.phi_joins[p].id, self.phi_joins[p].derived);
  701. for a in self.phi_joins[p].args.clone() {
  702. let (_, d) = self.mask(a);
  703. if !was_derived
  704. && d
  705. && !self.derived_phis.contains(&id)
  706. && seen_derived.insert(id)
  707. {
  708. new_derived.push(id);
  709. }
  710. }
  711. p += 1;
  712. }
  713. }
  714. (wrong, new_derived)
  715. }
  716. fn finish(
  717. mut self,
  718. execs: &[Vec<Option<Bool>>],
  719. cond: &[Bool],
  720. ) -> Result<Structured, ShaderError> {
  721. let phi_joins = std::mem::take(&mut self.phi_joins);
  722. let mut phi_masks = HashMap::with_capacity(phi_joins.len());
  723. for pj in phi_joins {
  724. let incoming: Vec<Bool> = pj
  725. .args
  726. .into_iter()
  727. .enumerate()
  728. .map(|(n, a)| {
  729. let (q, taken) = self.incoming[pj.block][n];
  730. let e = self.edge(cond[q], q, taken);
  731. let m = self.mask(a).0;
  732. self.b.given(m, e)
  733. })
  734. .collect();
  735. phi_masks.insert(pj.id, incoming);
  736. }
  737. let blocks = &self.p.blocks;
  738. let b = &mut self.b;
  739. let guards = blocks
  740. .iter()
  741. .enumerate()
  742. .map(|(n, block)| {
  743. // Reachability is fixed within the block. Vector instructions
  744. // with the same EXEC therefore need the same guard.
  745. let mut last_guard = None;
  746. block
  747. .insts
  748. .iter()
  749. .zip(&execs[n])
  750. .map(|(inst, exec)| match (exec, &inst.fields) {
  751. (None, _)
  752. | (_, Fields::Sop { .. } | Fields::Sopp { .. } | Fields::Smem { .. }) => {
  753. None
  754. }
  755. (&Some(e), _) => {
  756. if let Some((prev, guard)) = last_guard
  757. && prev == e
  758. {
  759. return guard;
  760. }
  761. let guard = (!b.implies(cond[n], e)).then(|| b.given(e, cond[n]));
  762. last_guard = Some((e, guard));
  763. guard
  764. }
  765. })
  766. .collect()
  767. })
  768. .collect();
  769. let exits = blocks
  770. .iter()
  771. .enumerate()
  772. .map(|(n, block)| match block.exit {
  773. Exit::Jump(t) => LaneExit::Jump(t),
  774. Exit::End => LaneExit::End,
  775. Exit::Indirect => LaneExit::Indirect,
  776. Exit::Branch { taken, not_taken } => LaneExit::Branch {
  777. when: b.given(self.when[n].unwrap_or(Bool::FALSE), cond[n]),
  778. taken,
  779. not_taken,
  780. },
  781. })
  782. .collect();
  783. if self.b.overflow {
  784. return Err(TOO_LARGE);
  785. }
  786. // Exports go by low dword. A low dword read with two high dwords
  787. // (one rewritten alone) names no one mask: it is left out, so
  788. // lowering refuses what reads it instead of taking the other
  789. // pair's lanes 32-63. Not where the low dword holds a number: see
  790. // the shortcut in `mask`.
  791. let (mut high, mut split) = (Map::default(), HashSet::new());
  792. let keys = self.masks.keys().chain(self.other.keys());
  793. for &(lo, hi) in keys.chain(&self.seen) {
  794. if *high.entry(lo).or_insert(hi) != hi {
  795. split.insert(lo);
  796. }
  797. }
  798. self.masks.retain(|k, _| !split.contains(&k.0));
  799. self.active.retain(|lo| !split.contains(lo));
  800. Ok(Structured {
  801. masks: self.masks.iter().map(|(&(lo, _), &m)| (lo, m)).collect(),
  802. highs: self
  803. .masks
  804. .keys()
  805. .filter(|(lo, hi)| lo != hi)
  806. .map(|&(lo, hi)| (hi, lo))
  807. .collect(),
  808. paired_masks: if self.p.wave64 { self.masks } else { Map::default() },
  809. active: self.active,
  810. wide: self.wide,
  811. wave_any: self.wave_any,
  812. scc_some: self
  813. .scc_lane
  814. .iter()
  815. .filter(|(scc, _)| !self.scc_every.contains(scc))
  816. .map(|(&scc, &m)| (scc, m))
  817. .collect(),
  818. phi_masks,
  819. bools: self.b,
  820. exits,
  821. guards,
  822. reach: cond.to_vec(),
  823. })
  824. }
  825. fn key(&self, value: impl Fn(Reg) -> Option<Value>, code: u8) -> Option<Key> {
  826. let lo = value(Reg::S(code))?;
  827. let hi = if self.p.wave64 {
  828. value(Reg::S(code + 1))?
  829. } else {
  830. lo
  831. };
  832. Some((lo, hi))
  833. }
  834. fn born(&self, v: Value) -> usize {
  835. match (self.defs.get(&v), self.phis.get(&v)) {
  836. (Some(&(b, _)), _) | (_, Some(&(b, _))) => self.index[b],
  837. _ => 0,
  838. }
  839. }
  840. fn exec(&mut self, inst: &Inst) -> Bool {
  841. match self.key(|r| inst.read(r), EXEC) {
  842. Some(k) => self.mask(k).0,
  843. None => Bool::TRUE,
  844. }
  845. }
  846. /// The mask a value pair holds, and whether it derives from EXEC or a
  847. /// VALU result.
  848. fn mask(&mut self, k: Key) -> (Bool, bool) {
  849. if let Some(&m) = self.masks.get(&k) {
  850. return (m, true);
  851. }
  852. if let Some(&m) = self.other.get(&k) {
  853. return (m, false);
  854. }
  855. let p = self.p;
  856. let (m, derived) = match self.join(k) {
  857. Some(join) => join,
  858. None => {
  859. let (lo, hi) = (self.defs.get(&k.0).copied(), self.defs.get(&k.1).copied());
  860. let def = |d: Option<(usize, usize)>| d.map(|(b, i)| &p.blocks[b].insts[i]);
  861. let m = match (lo, hi) {
  862. (Some(at), Some(hi)) if at == hi => def(lo)
  863. .and_then(|i| self.sop(i))
  864. .and_then(|r| r.dst)
  865. .map(|d| d.1),
  866. _ => None,
  867. };
  868. // What an EXEC write the pass does not follow leaves there.
  869. let exec_write = |d: Option<(usize, usize)>, v: Value| {
  870. def(d).is_some_and(|i| {
  871. i.write(Reg::S(EXEC)) == Some(v) || i.write(Reg::S(EXEC + 1)) == Some(v)
  872. })
  873. };
  874. let derived = exec_write(lo, k.0) || exec_write(hi, k.1);
  875. // shortcut: the atom names the pair by its low dword, and
  876. // lowering takes the high dword written beside it. For halves
  877. // written apart (two `s_mov_b32`) lanes 32-63 are wrong unless
  878. // lowering has no value for the low dword (EXEC, compares)
  879. // and refuses. Give the atom both dwords when such code
  880. // turns up.
  881. let m = m.unwrap_or_else(|| {
  882. let born = self.born(k.0);
  883. self.b.atom(Atom::Opaque(k.0), born)
  884. });
  885. (m, derived)
  886. }
  887. };
  888. let cache = if derived {
  889. &mut self.masks
  890. } else {
  891. &mut self.other
  892. };
  893. cache.insert(k, m);
  894. (m, derived)
  895. }
  896. /// A mask joined by phis at a block entry, and whether a mask coming in
  897. /// on a forward edge derives from EXEC or a VALU result. Where every
  898. /// lane arriving so far has the incoming mask set (or clear), the join
  899. /// is that constant, for a lane can only read it after arriving.
  900. fn join(&mut self, k: Key) -> Option<(Bool, bool)> {
  901. let p = self.p;
  902. let (lo, hi) = (self.phis.get(&k.0).copied(), self.phis.get(&k.1).copied());
  903. let block = match (lo, hi) {
  904. (Some((a, _)), Some((b, _))) if a != b => return None,
  905. (Some((b, _)), _) | (_, Some((b, _))) => b,
  906. _ => return None,
  907. };
  908. let target = &p.blocks[block];
  909. let arg = |phi: Option<(usize, usize)>, own: Value, n: usize| {
  910. phi.map_or(own, |(_, i)| target.phis[i].args[n])
  911. };
  912. let args: Vec<Key> = (0..target.preds.len())
  913. .map(|n| (arg(lo, k.0, n), arg(hi, k.1, n)))
  914. .collect();
  915. let id = lo.map_or(k.1, |_| k.0);
  916. let mut derived = self.derived_phis.contains(&id);
  917. // (edge condition, mask) per forward edge; back edges come later.
  918. let mut forward = Vec::new();
  919. for (n, &a) in args.iter().enumerate() {
  920. let (q, taken) = self.incoming[block][n];
  921. if self.index[q] < self.index[block] {
  922. let (m, d) = self.mask(a);
  923. derived |= d;
  924. let e = self.edge(self.first[q], q, taken);
  925. forward.push((e, m));
  926. } else {
  927. self.seen.push(a);
  928. }
  929. }
  930. if forward.len() == args.len()
  931. && let Some(&(_, m)) = forward.first()
  932. && forward.iter().all(|f| f.1 == m)
  933. {
  934. return Some((m, derived));
  935. }
  936. if !self.unresolved.contains(&id) {
  937. for value in [true, false] {
  938. let b = &mut self.b;
  939. let holds = forward.iter().all(|&(e, m)| {
  940. let m = if value { m } else { b.not(m) };
  941. b.implies(e, m)
  942. });
  943. if holds {
  944. self.joins.push(Join {
  945. block,
  946. id,
  947. value,
  948. derived,
  949. args,
  950. });
  951. let m = if value { Bool::TRUE } else { Bool::FALSE };
  952. return Some((m, derived));
  953. }
  954. }
  955. }
  956. if self.phi_join_ids.insert(id) {
  957. self.phi_joins.push(PhiJoin {
  958. block,
  959. id,
  960. derived,
  961. args,
  962. });
  963. }
  964. let born = self.index[block];
  965. Some((self.b.atom(Atom::Phi(id), born), derived))
  966. }
  967. fn operand(&mut self, inst: &Inst, op: &Operand) -> Option<(Bool, bool)> {
  968. let wave64 = self.p.wave64;
  969. let constant = |b: &mut Bools, v: u64| {
  970. let v = if wave64 { v } else { v & 0xFFFF_FFFF };
  971. match v {
  972. 0 => Bool::FALSE,
  973. _ if v == u64::MAX >> (32 * u8::from(!wave64)) => Bool::TRUE,
  974. _ => b.atom(Atom::Constant(v), 0),
  975. }
  976. };
  977. Some(match *op {
  978. Operand::Scalar { code, .. } if code != NULL => {
  979. let k = self.key(|r| inst.read(r), code)?;
  980. self.mask(k)
  981. }
  982. Operand::Const(c @ 128..=208) => {
  983. let v = if c <= 192 {
  984. i64::from(c) - 128
  985. } else {
  986. 192 - i64::from(c)
  987. };
  988. (constant(&mut self.b, v as u64), false)
  989. }
  990. Operand::Literal(x) => (constant(&mut self.b, u64::from(x)), false),
  991. _ => return None,
  992. })
  993. }
  994. /// Lane-mask meaning of a lane-width scalar operation.
  995. fn sop(&mut self, inst: &Inst) -> Option<SopMasks> {
  996. let Fields::Sop { dst, src, .. } = &inst.fields else {
  997. return None;
  998. };
  999. let width = if self.p.wave64 { "_b64" } else { "_b32" };
  1000. let op = inst.name().strip_prefix("s_")?.strip_suffix(width)?;
  1001. let dst = match dst {
  1002. Some(Operand::Scalar { code, .. }) if *code != NULL => {
  1003. self.key(|r| inst.write(r), *code)
  1004. }
  1005. _ => None,
  1006. };
  1007. let exec_out = self.key(|r| inst.write(r), EXEC);
  1008. let (save, f) = match (op.strip_suffix("_saveexec"), op.strip_suffix("_wrexec")) {
  1009. (Some(f), _) => (Some(true), f),
  1010. (_, Some(f)) => (Some(false), f),
  1011. _ => (None, op),
  1012. };
  1013. let mut derived = exec_out.is_some() || save.is_some();
  1014. let mut arg = |n: usize, l: &mut Self| {
  1015. let (m, d) = l.operand(inst, src.get(n)?)?;
  1016. derived |= d;
  1017. Some(m)
  1018. };
  1019. if let Some(saveexec) = save {
  1020. let s = arg(0, self)?;
  1021. let exec = self.exec(inst);
  1022. let new = self.combine(f, s, exec)?;
  1023. let saved = if saveexec { exec } else { new };
  1024. return Some(SopMasks {
  1025. dst: dst.map(|d| (d, saved)),
  1026. exec: exec_out.map(|e| (e, new)),
  1027. derived,
  1028. scc: Some(new),
  1029. });
  1030. }
  1031. let (result, scc) = match op {
  1032. "mov" => (arg(0, self)?, None),
  1033. "not" => {
  1034. let a = arg(0, self)?;
  1035. let r = self.b.not(a);
  1036. (r, Some(r))
  1037. }
  1038. "wqm" => {
  1039. let a = arg(0, self)?;
  1040. let lo = dst.or(exec_out)?.0;
  1041. let born = self.born(lo);
  1042. let q = self.b.atom(Atom::Quad(lo), born);
  1043. let r = self.b.or(a, q);
  1044. (r, Some(r))
  1045. }
  1046. "cselect" => {
  1047. let (a, c) = (arg(0, self)?, arg(1, self)?);
  1048. let scc = inst.read(Reg::Scc)?;
  1049. if self.clear_after_loop(scc) {
  1050. (c, None)
  1051. } else {
  1052. let born = self.born(scc);
  1053. let u = self.b.atom(Atom::Uniform(scc), born);
  1054. (self.b.ite(u, a, c), None)
  1055. }
  1056. }
  1057. _ => {
  1058. let (a, c) = (arg(0, self)?, arg(1, self)?);
  1059. let r = self.combine(op, a, c)?;
  1060. (r, Some(r))
  1061. }
  1062. };
  1063. Some(SopMasks {
  1064. dst: dst.map(|d| (d, result)),
  1065. exec: exec_out.map(|e| (e, result)),
  1066. derived,
  1067. scc,
  1068. })
  1069. }
  1070. /// Whether SCC value `scc` is clear wherever it is read: the instruction before an
  1071. /// `s_cbranch_execnz` that closes a loop wrote it as "the EXEC it leaves is not
  1072. /// empty" (`s_andn2_wrexec`, say), and the wave leaves `do { .. } while (EXEC)`
  1073. /// with EXEC empty. A read inside the loop or behind another way out of it sees a
  1074. /// join of this value, not the value itself.
  1075. fn clear_after_loop(&self, scc: Value) -> bool {
  1076. let Some(&(b, i)) = self.defs.get(&scc) else {
  1077. return false;
  1078. };
  1079. let block = &self.p.blocks[b];
  1080. let (Some(writer), Some(last)) = (block.insts.get(i), block.insts.last()) else {
  1081. return false;
  1082. };
  1083. let exec = writer.write(Reg::S(EXEC));
  1084. let back = match block.exit {
  1085. Exit::Branch { taken, .. } => self.index[taken] <= self.index[b],
  1086. _ => false,
  1087. };
  1088. back && i + 2 == block.insts.len()
  1089. && exec.is_some()
  1090. && last.name() == "s_cbranch_execnz"
  1091. && last.read(Reg::S(EXEC)) == exec
  1092. && (!self.p.wave64 || last.read(Reg::S(EXEC + 1)) == writer.write(Reg::S(EXEC + 1)))
  1093. }
  1094. fn combine(&mut self, f: &str, a: Bool, c: Bool) -> Option<Bool> {
  1095. let b = &mut self.b;
  1096. Some(match f {
  1097. "and" => b.and(a, c),
  1098. "or" => b.or(a, c),
  1099. "xor" => b.xor(a, c),
  1100. "andn2" => {
  1101. let nc = b.not(c);
  1102. b.and(a, nc)
  1103. }
  1104. "orn2" => {
  1105. let nc = b.not(c);
  1106. b.or(a, nc)
  1107. }
  1108. "andn1" => {
  1109. let na = b.not(a);
  1110. b.and(na, c)
  1111. }
  1112. "orn1" => {
  1113. let na = b.not(a);
  1114. b.or(na, c)
  1115. }
  1116. "nand" => {
  1117. let r = b.and(a, c);
  1118. b.not(r)
  1119. }
  1120. "nor" => {
  1121. let r = b.or(a, c);
  1122. b.not(r)
  1123. }
  1124. "xnor" => {
  1125. let r = b.xor(a, c);
  1126. b.not(r)
  1127. }
  1128. _ => return None,
  1129. })
  1130. }
  1131. /// Records the masks `inst` defines; `exec` is EXEC there, if known.
  1132. fn step(&mut self, inst: &Inst, exec: Option<Bool>) {
  1133. let name = inst.name();
  1134. match &inst.fields {
  1135. Fields::Sop { src, .. } => {
  1136. let mut takes_mask = false;
  1137. for s in src {
  1138. if let Operand::Scalar { code, .. } = *s
  1139. && code != NULL
  1140. && let Some(k) = self.key(|r| inst.read(r), code)
  1141. {
  1142. let phi = self.phis.contains_key(&k.0) || self.phis.contains_key(&k.1);
  1143. takes_mask |= self.masks.contains_key(&k) || phi && self.mask(k).1;
  1144. }
  1145. }
  1146. let touches_exec =
  1147. inst.write(Reg::S(EXEC)).is_some() || inst.read(Reg::S(EXEC)).is_some();
  1148. if (takes_mask || touches_exec)
  1149. && let Some(r) = self.sop(inst).filter(|r| r.derived)
  1150. {
  1151. for (k, m) in r.dst.into_iter().chain(r.exec) {
  1152. self.masks.insert(k, m);
  1153. // EXEC itself holds the lanes that run here.
  1154. if r.exec.is_some_and(|e| e.0 == k)
  1155. || exec.is_some_and(|e| self.b.implies(m, e))
  1156. {
  1157. self.active.insert(k.0);
  1158. }
  1159. }
  1160. if let (Some(scc), Some(m)) = (inst.write(Reg::Scc), r.scc) {
  1161. self.scc_lane.insert(scc, m);
  1162. }
  1163. }
  1164. // `s_cmp_eq/lg` of a mask: "no lane differs" per lane.
  1165. let width = if self.p.wave64 { "64" } else { "32" };
  1166. if takes_mask
  1167. && let (Some(rest), Some(scc)) =
  1168. (name.strip_prefix("s_cmp_"), inst.write(Reg::Scc))
  1169. && rest
  1170. .strip_suffix(width)
  1171. .is_some_and(|r| r == "eq_u" || r == "lg_u")
  1172. && let [a, c] = &src[..]
  1173. && let (Some((a, _)), Some((c, _))) =
  1174. (self.operand(inst, a), self.operand(inst, c))
  1175. {
  1176. let ne = self.b.xor(a, c);
  1177. let m = if rest.starts_with("eq") {
  1178. self.b.not(ne)
  1179. } else {
  1180. ne
  1181. };
  1182. self.scc_lane.insert(scc, m);
  1183. if rest.starts_with("eq") {
  1184. self.scc_every.insert(scc);
  1185. }
  1186. }
  1187. // `s_bcnt1` of a mask every running lane sees alike (EXEC under a scalar
  1188. // condition, or EXEC itself): its SCC, "some lane is set", is each lane's own
  1189. // bit. A branch on it then reads no ballot.
  1190. if takes_mask
  1191. && name.starts_with("s_bcnt1_i32_b")
  1192. && let Some(scc) = inst.write(Reg::Scc)
  1193. && let [a] = &src[..]
  1194. && let Some((m, true)) = self.operand(inst, a)
  1195. {
  1196. let e = exec.unwrap_or(Bool::TRUE);
  1197. let own = self.b.given(m, e);
  1198. if self.b.implies(m, e)
  1199. && self.b.support(own).iter().all(|a| matches!(a, Atom::Uniform(_)))
  1200. {
  1201. self.scc_lane.insert(scc, own);
  1202. }
  1203. }
  1204. }
  1205. Fields::Valu(v) => {
  1206. let exec = self.exec(inst);
  1207. let lane = |l: &mut Self, k: Key| {
  1208. let born = l.born(k.0);
  1209. let a = l.b.atom(Atom::Lane(k.0), born);
  1210. let m = l.b.and(exec, a);
  1211. l.masks.insert(k, m);
  1212. l.active.insert(k.0);
  1213. };
  1214. // A select reads a mask nothing else may: a join of compare
  1215. // results is resolved here, as for EXEC. A carry-in is only
  1216. // recorded for `finish`: resolving its join would turn a
  1217. // refusal into a per-lane phi, wrong after a divergent branch.
  1218. if (name == "v_cndmask_b32" || name.contains("_co_ci_"))
  1219. && let Some(&Operand::Scalar { code, .. }) = v.src.get(2)
  1220. && code != NULL
  1221. && let Some(k) = self.key(|r| inst.read(r), code)
  1222. {
  1223. if name == "v_cndmask_b32" {
  1224. self.mask(k);
  1225. } else {
  1226. self.seen.push(k);
  1227. }
  1228. }
  1229. if matches!(name, "v_div_fmas_f32" | "v_div_fmas_f64")
  1230. && let Some(k) = self.key(|r| inst.read(r), VCC)
  1231. {
  1232. self.mask(k);
  1233. }
  1234. if name.starts_with("v_cmpx") {
  1235. if let Some(k) = self.key(|r| inst.write(r), EXEC) {
  1236. lane(self, k);
  1237. }
  1238. } else {
  1239. let compare = v.dst.filter(|_| name.starts_with("v_cmp"));
  1240. for op in compare.iter().chain(&v.carry) {
  1241. if let Operand::Scalar { code, .. } = *op
  1242. && let Some(k) = self.key(|r| inst.write(r), code)
  1243. {
  1244. lane(self, k);
  1245. }
  1246. }
  1247. }
  1248. }
  1249. _ => {}
  1250. }
  1251. }
  1252. /// The per-lane condition under which a block's closing branch is taken.
  1253. /// How the console decides the branch `inst` on a lane mask, in terms of the lanes' own
  1254. /// `when` ([`Self::branch`]): taken when some lane's holds (`true`) or when every lane's
  1255. /// does (`false`). `execnz`/`vccnz` ask for some set bit, `execz`/`vccz` for none; SCC
  1256. /// of a mask operation is "some lane's bit is set", SCC of `s_cmp_eq` of two masks is
  1257. /// "every lane's is" ([`Self::scc_every`]), and `scc0` branches on the opposite. None
  1258. /// for a branch on a scalar condition.
  1259. fn wave_kind(&self, inst: &Inst) -> Option<bool> {
  1260. match inst.name() {
  1261. "s_cbranch_execnz" | "s_cbranch_vccnz" => Some(true),
  1262. "s_cbranch_execz" | "s_cbranch_vccz" => Some(false),
  1263. n @ ("s_cbranch_scc0" | "s_cbranch_scc1") => {
  1264. let scc = inst.read(Reg::Scc)?;
  1265. self.scc_lane.get(&scc)?;
  1266. // set: SCC is 1 when some lane's bit is set (every lane's, for a compare)
  1267. let every = self.scc_every.contains(&scc);
  1268. Some((n == "s_cbranch_scc1") != every)
  1269. }
  1270. _ => None,
  1271. }
  1272. }
  1273. fn branch(&mut self, inst: &Inst) -> Bool {
  1274. let exec = self.exec(inst);
  1275. match inst.name() {
  1276. "s_cbranch_execz" => self.b.not(exec),
  1277. "s_cbranch_execnz" => exec,
  1278. n @ ("s_cbranch_vccz" | "s_cbranch_vccnz") => {
  1279. let vcc = match self.key(|r| inst.read(r), VCC) {
  1280. Some(k) => self.mask(k).0,
  1281. None => Bool::FALSE,
  1282. };
  1283. let any = self.b.and(vcc, exec);
  1284. if n.ends_with("nz") {
  1285. any
  1286. } else {
  1287. self.b.not(any)
  1288. }
  1289. }
  1290. n => {
  1291. let Some(scc) = inst.read(Reg::Scc) else {
  1292. return Bool::FALSE;
  1293. };
  1294. let set = match self.scc_lane.get(&scc) {
  1295. Some(&m) => m,
  1296. None => {
  1297. let born = self.born(scc);
  1298. self.b.atom(Atom::Uniform(scc), born)
  1299. }
  1300. };
  1301. if n == "s_cbranch_scc1" {
  1302. set
  1303. } else {
  1304. self.b.not(set)
  1305. }
  1306. }
  1307. }
  1308. }
  1309. /// What a lane knows on entering each block, to a fixpoint. A loop
  1310. /// header forgets what the back edge says about atoms the loop redefines.
  1311. fn paths(&mut self) -> Result<Vec<Bool>, ShaderError> {
  1312. let n = self.p.blocks.len();
  1313. let mut cond = vec![Bool::FALSE; n];
  1314. if let Some(&entry) = self.order.first() {
  1315. cond[entry] = Bool::TRUE;
  1316. }
  1317. for _ in 0..MAX_ROUNDS {
  1318. let mut changed = false;
  1319. for i in 1..self.order.len() {
  1320. let s = self.order[i];
  1321. let mut c = Bool::FALSE;
  1322. for k in 0..self.incoming[s].len() {
  1323. let (q, taken) = self.incoming[s][k];
  1324. let mut e = self.edge(cond[q], q, taken);
  1325. if i <= self.index[q] {
  1326. e = self.b.forget(e, i, &mut Map::default());
  1327. }
  1328. c = self.b.or(c, e);
  1329. }
  1330. if c != cond[s] {
  1331. cond[s] = c;
  1332. changed = true;
  1333. }
  1334. }
  1335. if self.b.overflow {
  1336. return Err(TOO_LARGE);
  1337. }
  1338. if !changed {
  1339. return Ok(cond);
  1340. }
  1341. }
  1342. Err(ShaderError::Isa {
  1343. offset: 0,
  1344. reason: "lane conditions do not settle",
  1345. })
  1346. }
  1347. }
  1348. const TOO_LARGE: ShaderError = ShaderError::Isa {
  1349. offset: 0,
  1350. reason: "lane conditions too large",
  1351. };
  1352. /// `ir::build` splits irreducible loops; checked again because everything
  1353. /// here assumes a reducible graph.
  1354. fn check_reducible(p: &Program, order: &[usize], index: &[usize]) -> Result<(), ShaderError> {
  1355. match crate::ir::irreducible_edge(&p.blocks, order, index) {
  1356. Some((from, _)) => Err(ShaderError::Unsupported {
  1357. offset: p.blocks[from].offset,
  1358. what: "irreducible control flow",
  1359. }),
  1360. None => Ok(()),
  1361. }
  1362. }
  1363. #[cfg(test)]
  1364. mod tests {
  1365. use super::*;
  1366. use crate::ir;
  1367. const S_ENDPGM: u32 = 0xBF81_0000;
  1368. fn build(words: &[u32], wave64: bool) -> Program {
  1369. let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
  1370. ir::build(&code, wave64, 256).unwrap()
  1371. }
  1372. fn guarded(s: &Structured) -> usize {
  1373. s.guards.iter().flatten().filter(|g| g.is_some()).count()
  1374. }
  1375. /// The search of [`Bools::meet`] with every case split made anew, as it
  1376. /// was before [`Meets`].
  1377. fn meet_anew(b: &Bools, mut all: Vec<(Bool, bool)>, budget: &mut usize) -> bool {
  1378. let fails = |&(b, holds): &(Bool, bool)| b == if holds { Bool::FALSE } else { Bool::TRUE };
  1379. if all.iter().any(fails) {
  1380. return false;
  1381. }
  1382. all.retain(|&(b, _)| b != Bool::FALSE && b != Bool::TRUE);
  1383. if all.is_empty() || *budget == 0 {
  1384. return true;
  1385. }
  1386. *budget -= 1;
  1387. let top = |x: Bool| b.nodes[x.0 as usize].0;
  1388. let v = all.iter().map(|&(x, _)| top(x)).min().expect("not empty");
  1389. [false, true].into_iter().any(|value| {
  1390. let next = all
  1391. .iter()
  1392. .map(|&(x, holds)| {
  1393. let (lo, hi) = b.split(x, v);
  1394. (if value { hi } else { lo }, holds)
  1395. })
  1396. .collect();
  1397. meet_anew(b, next, budget)
  1398. })
  1399. }
  1400. #[test]
  1401. fn a_search_that_remembers_answers_as_one_made_anew() {
  1402. // Functions of 12 variables put together at random, and conditions
  1403. // of two to five of them (repeats and constants among them), under
  1404. // budgets that run out early, late and never: the answer, and where
  1405. // no lane is found the budget left, are those of the search that
  1406. // remembers nothing; with what one `Meets` gathered over all of
  1407. // them, and with an empty one.
  1408. let mut b = Bools::new();
  1409. let mut state = 0x9E37_79B9_7F4A_7C15_u64;
  1410. let mut random = move |n: usize| {
  1411. state ^= state << 13;
  1412. state ^= state >> 7;
  1413. state ^= state << 17;
  1414. (state % n as u64) as usize
  1415. };
  1416. let mut f: Vec<Bool> = (0..12).map(|i| b.atom(Atom::Constant(i + 2), 0)).collect();
  1417. f.extend([Bool::FALSE, Bool::TRUE]);
  1418. for _ in 0..120 {
  1419. let (x, y) = (f[random(f.len())], f[random(f.len())]);
  1420. let made = match random(4) {
  1421. 0 => b.and(x, y),
  1422. 1 => b.or(x, y),
  1423. 2 => b.xor(x, y),
  1424. _ => b.not(x),
  1425. };
  1426. f.push(made);
  1427. }
  1428. let mut seen = Meets::default();
  1429. let (mut none, mut some, mut gave_up) = (0, 0, 0);
  1430. for _ in 0..1500 {
  1431. let all: Vec<(Bool, bool)> = (0..2 + random(4))
  1432. .map(|_| (f[random(f.len())], random(2) == 0))
  1433. .collect();
  1434. for budget in [0, 1, 2, 3, 5, 9, 20, 60, 250, 1000, MAX_MEET] {
  1435. let mut left = budget;
  1436. let anew = meet_anew(&b, all.clone(), &mut left);
  1437. for fresh in [false, true] {
  1438. let mut empty = Meets::default();
  1439. let seen = if fresh { &mut empty } else { &mut seen };
  1440. let mut work = all
  1441. .iter()
  1442. .map(|&(x, holds)| x.0 << 1 | u32::from(holds))
  1443. .collect();
  1444. let mut mine = budget;
  1445. let found = b.meet_in(0, &mut work, &mut mine, seen);
  1446. assert_eq!(found, anew, "{all:?} within {budget}");
  1447. assert!(work.is_empty());
  1448. if !found {
  1449. assert_eq!(mine, left, "{all:?} within {budget}");
  1450. }
  1451. }
  1452. assert_eq!(b.meet_within(&all, budget, &mut seen), anew);
  1453. if !anew {
  1454. none += 1;
  1455. } else if meet_anew(&b, all.clone(), &mut usize::MAX.clone()) {
  1456. some += 1;
  1457. } else {
  1458. gave_up += 1;
  1459. }
  1460. }
  1461. }
  1462. // All three outcomes came up, and searches were remembered.
  1463. assert!(
  1464. none > 100 && some > 100 && gave_up > 100,
  1465. "{none} {some} {gave_up}"
  1466. );
  1467. assert!(seen.none.len() > 100);
  1468. }
  1469. #[test]
  1470. fn divergent_if_becomes_a_lane_branch() {
  1471. let p = build(
  1472. &[
  1473. 0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0
  1474. 0xBE80_3C6A, // s_and_saveexec_b32 s0, vcc_lo
  1475. 0xBF88_0001, // s_cbranch_execz -> 16
  1476. 0x7E02_0280, // v_mov_b32 v1, 0
  1477. 0x887E_007E, // 16: s_or_b32 exec_lo, exec_lo, s0
  1478. 0x7E04_0280, // v_mov_b32 v2, 0
  1479. S_ENDPGM,
  1480. ],
  1481. false,
  1482. );
  1483. let s = structure(&p).unwrap();
  1484. let LaneExit::Branch {
  1485. when,
  1486. taken: 2,
  1487. not_taken: 1,
  1488. } = s.exits[0]
  1489. else {
  1490. panic!("{:?}", s.exits)
  1491. };
  1492. // Skipped exactly where the compare fails.
  1493. let cmp = p.blocks[0].insts[0].write(Reg::S(VCC)).unwrap();
  1494. assert_eq!(
  1495. s.bools.node(when),
  1496. Some((Atom::Lane(cmp), Bool::TRUE, Bool::FALSE))
  1497. );
  1498. assert_eq!(guarded(&s), 0, "{:?}", s.guards);
  1499. }
  1500. #[test]
  1501. fn exec_narrowed_without_a_branch_leaves_a_guard() {
  1502. let p = build(
  1503. &[
  1504. 0x7DA4_0080, // v_cmpx_eq_u32 exec, 0, v0
  1505. 0x7E02_0280, // v_mov_b32 v1, 0
  1506. S_ENDPGM,
  1507. ],
  1508. true,
  1509. );
  1510. let s = structure(&p).unwrap();
  1511. assert_eq!(s.guards[0][0], None, "the compare runs in every lane");
  1512. let g = s.guards[0][1].expect("guard");
  1513. assert!(matches!(s.bools.support(g)[..], [Atom::Lane(_)]));
  1514. }
  1515. #[test]
  1516. fn guards_follow_exec_and_block_reachability() {
  1517. let p = build(
  1518. &[
  1519. 0x7DA4_0080, // v_cmpx_eq_u32 exec, 0, v0
  1520. 0x7E02_0280, // v_mov_b32 v1, 0
  1521. 0x7E04_0280, // v_mov_b32 v2, 0
  1522. 0xBF88_0005, // s_cbranch_execz -> end
  1523. 0x7E06_0280, // v_mov_b32 v3, 0
  1524. 0x7DA4_0880, // v_cmpx_eq_u32 exec, 0, v4
  1525. 0x7E06_0280, // v_mov_b32 v3, 0
  1526. 0xBE82_0480, // s_mov_b64 s[2:3], 0
  1527. 0x7E0A_0280, // v_mov_b32 v5, 0
  1528. S_ENDPGM,
  1529. ],
  1530. true,
  1531. );
  1532. let s = structure(&p).unwrap();
  1533. let lane = |block: usize, i: usize| {
  1534. Atom::Lane(p.blocks[block].insts[i].write(Reg::S(EXEC)).unwrap())
  1535. };
  1536. let a = s.guards[0][1].unwrap();
  1537. let b = s.guards[1][2].unwrap();
  1538. assert_eq!(s.bools.node(a), Some((lane(0, 0), Bool::FALSE, Bool::TRUE)));
  1539. assert_eq!(s.guards[0], [None, Some(a), Some(a), None]);
  1540. // The fallthrough already implies the first compare. Only the second
  1541. // compare needs testing, and the scalar move never needs a guard.
  1542. assert_eq!(s.bools.node(b), Some((lane(1, 1), Bool::FALSE, Bool::TRUE)));
  1543. assert_eq!(s.guards[1], [None, None, Some(b), None, Some(b)]);
  1544. }
  1545. #[test]
  1546. fn divergent_loop_exits_per_lane() {
  1547. let p = build(
  1548. &[
  1549. 0xBE82_0480, // s_mov_b64 s[2:3], 0
  1550. 0x4A00_0081, // 4: v_add_nc_u32 v0, 1, v0
  1551. 0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0
  1552. 0x8882_026A, // s_or_b64 s[2:3], vcc, s[2:3]
  1553. 0x8AFE_027E, // s_andn2_b64 exec, exec, s[2:3]
  1554. 0xBF89_FFFB, // s_cbranch_execnz -> 4
  1555. 0x88FE_027E, // s_or_b64 exec, exec, s[2:3]
  1556. 0x7E02_0280, // v_mov_b32 v1, 0
  1557. S_ENDPGM,
  1558. ],
  1559. true,
  1560. );
  1561. let s = structure(&p).unwrap();
  1562. assert_eq!(guarded(&s), 0, "{:?}", s.guards);
  1563. let LaneExit::Branch {
  1564. when,
  1565. taken: 1,
  1566. not_taken: 2,
  1567. } = s.exits[1]
  1568. else {
  1569. panic!("{:?}", s.exits)
  1570. };
  1571. // Back while the lane's compare fails.
  1572. assert!(matches!(
  1573. s.bools.node(when),
  1574. Some((Atom::Lane(_), Bool::TRUE, Bool::FALSE))
  1575. ));
  1576. }
  1577. /// `s_cselect` on the SCC a lane loop ended with (the blend-shape skinning
  1578. /// programs): the loop is left when no lane remains, so the select takes
  1579. /// its second operand; it was a uniform atom whose value no lane has.
  1580. #[test]
  1581. fn a_select_on_the_condition_a_lane_loop_ended_with_takes_its_second_operand() {
  1582. let cnd = 256 | (256 << 9) | (3 << 18);
  1583. let p = build(
  1584. &[
  1585. 0xBE83_037E, // 0: s_mov_b32 s3, exec_lo
  1586. 0xBE9C_037E, // s_mov_b32 s28, exec_lo
  1587. 0x7E3A_0507, // 8: v_readfirstlane_b32 s29, v7
  1588. 0x7DA4_0E1D, // v_cmpx_eq_u32 exec_lo, s29, v7
  1589. 0xBE9C_471C, // s_andn2_wrexec_b32 s28, s28
  1590. 0xBF89_FFFC, // s_cbranch_execnz -> 8
  1591. 0xBEFE_0303, // s_mov_b32 exec_lo, s3
  1592. 0x8503_807E, // s_cselect_b32 s3, exec_lo, 0
  1593. 0xD501_0001,
  1594. cnd, // v_cndmask_b32 v1, v0, v0, s3
  1595. S_ENDPGM,
  1596. ],
  1597. false,
  1598. );
  1599. let s = structure(&p).unwrap();
  1600. let select = p
  1601. .blocks
  1602. .iter()
  1603. .flat_map(|b| &b.insts)
  1604. .find(|i| i.name() == "s_cselect_b32")
  1605. .expect("the select");
  1606. let mask = select.write(Reg::S(3)).unwrap();
  1607. assert_eq!(s.masks.get(&mask), Some(&Bool::FALSE));
  1608. }
  1609. #[test]
  1610. fn scalar_branches_stay_uniform() {
  1611. let p = build(
  1612. &[
  1613. 0xBF06_0100, // s_cmp_eq_u32 s0, s1
  1614. 0xBF85_0001, // s_cbranch_scc1 -> 12
  1615. 0x7E02_0280, // v_mov_b32 v1, 0
  1616. S_ENDPGM, // 12
  1617. ],
  1618. true,
  1619. );
  1620. let s = structure(&p).unwrap();
  1621. let LaneExit::Branch { when, .. } = s.exits[0] else {
  1622. panic!()
  1623. };
  1624. assert!(matches!(s.bools.support(when)[..], [Atom::Uniform(_)]));
  1625. assert_eq!(guarded(&s), 0);
  1626. }
  1627. #[test]
  1628. fn a_mask_whose_high_dword_is_rewritten_is_not_the_compare() {
  1629. for reader in [
  1630. 0x0202_0480, // v_cndmask_b32 v1, 0, v2, vcc
  1631. 0x5002_0480, // v_add_co_ci_u32 v1, vcc, 0, v2, vcc
  1632. ] {
  1633. let p = build(
  1634. &[
  1635. 0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0
  1636. 0xBEEB_0380, // s_mov_b32 vcc_hi, 0
  1637. reader,
  1638. S_ENDPGM,
  1639. ],
  1640. true,
  1641. );
  1642. let s = structure(&p).unwrap();
  1643. let lo = p.blocks[0].insts[2].read(Reg::S(VCC)).unwrap();
  1644. assert_eq!(p.blocks[0].insts[0].write(Reg::S(VCC)), Some(lo));
  1645. // The reader sees (compare low dword, 0): lanes 32-63 are clear.
  1646. // The mask exported for that low dword must not be the compare.
  1647. assert_ne!(
  1648. s.masks.get(&lo).and_then(|&m| s.bools.node(m)),
  1649. Some((Atom::Lane(lo), Bool::FALSE, Bool::TRUE)),
  1650. "{reader:#x}: vcc_hi was zeroed after the compare"
  1651. );
  1652. }
  1653. }
  1654. #[test]
  1655. fn a_mask_joined_over_a_back_edge_with_a_rewritten_high_dword_is_not_the_compare() {
  1656. let p = build(
  1657. &[
  1658. 0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0
  1659. 0x0202_0480, // 4: v_cndmask_b32 v1, 0, v2, vcc
  1660. 0x7D84_0280, // v_cmp_eq_u32 vcc, 0, v1
  1661. 0xBEEB_0380, // s_mov_b32 vcc_hi, 0
  1662. 0xBF85_FFFC, // s_cbranch_scc1 -> 4
  1663. S_ENDPGM,
  1664. ],
  1665. true,
  1666. );
  1667. let s = structure(&p).unwrap();
  1668. // The select reads the loop header's join; over the back edge it
  1669. // takes (compare low dword, 0), which only the join sees.
  1670. let lo = p.blocks[1].insts[1].write(Reg::S(VCC)).unwrap();
  1671. assert_ne!(
  1672. s.masks.get(&lo).and_then(|&m| s.bools.node(m)),
  1673. Some((Atom::Lane(lo), Bool::FALSE, Bool::TRUE))
  1674. );
  1675. }
  1676. #[test]
  1677. fn irreducible_loops_are_split() {
  1678. let p = build(
  1679. &[
  1680. 0xBF06_0100, // s_cmp_eq_u32 s0, s1
  1681. 0xBF85_0001, // s_cbranch_scc1 -> 12, into the loop's middle
  1682. 0x8002_8102, // 8: s_add_u32 s2, s2, 1
  1683. 0xBF84_FFFE, // 12: s_cbranch_scc0 -> 8
  1684. S_ENDPGM,
  1685. ],
  1686. false,
  1687. );
  1688. // The loop keeps 12 as its header; the entry into 8 gets a copy of it.
  1689. let copy = &p.blocks[4];
  1690. assert_eq!((copy.offset, copy.exit), (8, ir::Exit::Jump(2)));
  1691. assert_eq!(p.blocks[0].exit.successors(), [2, 4]);
  1692. assert_eq!(p.blocks[1].preds, [2]);
  1693. assert!(structure(&p).is_ok());
  1694. }
  1695. #[test]
  1696. fn mask_phi_joining_constant_and_compare_records_edge_bools() {
  1697. let cnd = 258 | (259 << 9) | (2 << 18);
  1698. let p = build(
  1699. &[
  1700. 0xBF06_8000, // 0: s_cmp_eq_u32 s0, 0
  1701. 0xBF85_0002, // 4: s_cbranch_scc1 -> 16
  1702. 0xBE82_0380, // 8: s_mov_b32 s2, 0
  1703. 0xBF82_0002, // 12: s_branch -> 24
  1704. 0xD4C2_0002,
  1705. 0x0002_0080, // 16: v_cmp_eq_u32 s2, 0, v0
  1706. 0xD501_0001,
  1707. cnd, // 24: v_cndmask_b32 v1, v2, v3, s2
  1708. S_ENDPGM,
  1709. ],
  1710. false,
  1711. );
  1712. let s = structure(&p).unwrap();
  1713. let phi = p
  1714. .blocks
  1715. .iter()
  1716. .flat_map(|b| &b.phis)
  1717. .find(|phi| phi.reg == Reg::S(2))
  1718. .expect("mask phi for s2");
  1719. assert_eq!(
  1720. s.masks.get(&phi.value).and_then(|&m| s.bools.node(m)),
  1721. Some((Atom::Phi(phi.value), Bool::FALSE, Bool::TRUE))
  1722. );
  1723. let edges = &s.phi_masks[&phi.value];
  1724. assert_eq!(edges.len(), 2);
  1725. assert!(edges.contains(&Bool::FALSE), "{edges:?}");
  1726. assert!(
  1727. edges
  1728. .iter()
  1729. .any(|&e| matches!(s.bools.support(e)[..], [Atom::Lane(_)])),
  1730. "{edges:?}"
  1731. );
  1732. }
  1733. #[test]
  1734. fn loop_mask_accumulator_from_zero_tracks_phi_and_edges() {
  1735. let cnd = 258 | (259 << 9) | (2 << 18);
  1736. let p = build(
  1737. &[
  1738. 0xBE82_0480, // 0: s_mov_b64 s[2:3], 0
  1739. 0xBE84_0380, // 4: s_mov_b32 s4, 0
  1740. 0xD501_0001,
  1741. cnd, // 8: v_cndmask_b32 v1, v2, v3, s[2:3]
  1742. 0x7D84_0080, // 16: v_cmp_eq_u32 vcc, 0, v0
  1743. 0x8882_026A, // 20: s_or_b64 s[2:3], vcc, s[2:3]
  1744. 0x8004_8104, // 24: s_add_u32 s4, s4, 1
  1745. 0xBF0A_8404, // 28: s_cmp_lt_u32 s4, 4
  1746. 0xBF85_FFF9, // 32: s_cbranch_scc1 -> 8
  1747. 0xD501_0004,
  1748. cnd, // 36: v_cndmask_b32 v4, v2, v3, s[2:3]
  1749. S_ENDPGM,
  1750. ],
  1751. true,
  1752. );
  1753. let s = structure(&p).unwrap();
  1754. let phi = p
  1755. .blocks
  1756. .iter()
  1757. .flat_map(|b| &b.phis)
  1758. .find(|phi| phi.reg == Reg::S(2))
  1759. .expect("loop mask phi for s[2:3]");
  1760. assert!(s.masks.contains_key(&phi.value));
  1761. let edges = &s.phi_masks[&phi.value];
  1762. assert_eq!(edges.len(), 2);
  1763. assert!(edges.contains(&Bool::FALSE), "{edges:?}");
  1764. assert!(edges.iter().any(|&e| {
  1765. let sup = s.bools.support(e);
  1766. sup.contains(&Atom::Phi(phi.value)) && sup.iter().any(|a| matches!(a, Atom::Lane(_)))
  1767. }));
  1768. }
  1769. #[test]
  1770. fn loop_mask_phi_reset_to_constant_on_back_edge() {
  1771. let cnd = 258 | (259 << 9) | (2 << 18);
  1772. let p = build(
  1773. &[
  1774. 0xD4C2_0002,
  1775. 0x0002_0080, // 0: v_cmp_eq_u32 s2, 0, v0
  1776. 0xBE84_0380, // 8: s_mov_b32 s4, 0
  1777. 0xD501_0001,
  1778. cnd, // 12: v_cndmask_b32 v1, v2, v3, s2
  1779. 0xBE82_0380, // 20: s_mov_b32 s2, 0
  1780. 0x8004_8104, // 24: s_add_u32 s4, s4, 1
  1781. 0xBF0A_8404, // 28: s_cmp_lt_u32 s4, 4
  1782. 0xBF85_FFFA, // 32: s_cbranch_scc1 -> 12
  1783. S_ENDPGM,
  1784. ],
  1785. false,
  1786. );
  1787. let s = structure(&p).unwrap();
  1788. let phi = p
  1789. .blocks
  1790. .iter()
  1791. .flat_map(|b| &b.phis)
  1792. .find(|phi| phi.reg == Reg::S(2))
  1793. .expect("loop mask phi for s2");
  1794. assert!(s.masks.contains_key(&phi.value));
  1795. let edges = &s.phi_masks[&phi.value];
  1796. assert_eq!(edges.len(), 2);
  1797. assert!(edges.contains(&Bool::FALSE), "{edges:?}");
  1798. assert!(
  1799. edges
  1800. .iter()
  1801. .any(|&e| matches!(s.bools.support(e)[..], [Atom::Lane(_)])),
  1802. "{edges:?}"
  1803. );
  1804. }
  1805. }