resource.rs 157 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012
  1. //! Resource tracking (decision 0003): where each descriptor a program uses
  2. //! comes from, in terms of the root signature.
  3. //!
  4. //! Root parameters arrive in user SGPRs ([`RootParam`]): a descriptor table
  5. //! as the 32-bit heap address of its range (the code sets the high half to
  6. //! 0), a root descriptor as a 64-bit buffer address, root constants as
  7. //! themselves. A root signature with dynamic resources (SM 6.6) adds the
  8. //! 32-bit base addresses of both heaps; a descriptor is then loaded from
  9. //! one of them at an index the code computes (from a root constant, say). The code loads table descriptors from heap memory with
  10. //! `s_load_dword*`, and builds a buffer descriptor around a root
  11. //! descriptor's address itself. Each descriptor operand and each scalar
  12. //! memory address is traced through the SSA values back to those
  13. //! parameters, by data flow: copies, phis that agree, and additions.
  14. use crate::ShaderError;
  15. use crate::gfx10::{Fields, NULL, Operand};
  16. use crate::ir::{EXEC, Exit, Inst, Program, Reg, Value};
  17. use crate::native::{HwStage, RootParam, RootType};
  18. use crate::structure::{Bool, LaneExit, Meets, Structured};
  19. /// An instruction: block and index in [`crate::ir::Block::insts`].
  20. pub type Site = (usize, usize);
  21. /// A byte address: a root parameter's, plus a constant and at most one
  22. /// value the program computes (an index times a stride, say).
  23. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  24. pub struct Address {
  25. /// Index into the layout, or [`CODE`].
  26. pub param: usize,
  27. /// Added modulo 2^32 (with carry into the high half of a root
  28. /// descriptor's address).
  29. pub offset: u32,
  30. pub dynamic: Option<Value>,
  31. }
  32. /// [`Address::param`] of the program's own code: a constant table the
  33. /// compiler appends after the code and reads through `s_getpc_b64`; the
  34. /// offset is then the byte offset in the code.
  35. pub const CODE: usize = usize::MAX;
  36. /// [`Address::param`] of title memory at an address no root parameter
  37. /// gives: one the code computes from root constants, reads out of a
  38. /// descriptor or loads from other memory (compute programs only: the
  39. /// ray-tracing structure builder and the programs that walk its
  40. /// structures). Offset and computed term are not used: lowering takes the
  41. /// 64-bit address from the instruction's operands.
  42. pub const MEMORY: usize = usize::MAX - 1;
  43. /// The reasons an address traces to no root parameter for which the
  44. /// address is then taken as it stands ([`MEMORY`]).
  45. const RAW: [&str; 5] = [
  46. "an address not from a root parameter",
  47. "an address from a root parameter that is no address",
  48. "an address in an SGPR that is no root parameter",
  49. "an address loaded from memory",
  50. "an address from a phi",
  51. ];
  52. #[derive(Debug, Clone, PartialEq, Eq)]
  53. pub enum Source {
  54. /// Dwords `first..` of what the scalar load at `load` reads (see
  55. /// [`Resources::scalar`] for its address).
  56. Loaded { load: Site, first: u8 },
  57. /// A buffer descriptor built around an address: `bits` OR-ed into
  58. /// dword 1 (stride, swizzle), dwords 2 and 3 as given.
  59. Built {
  60. address: Address,
  61. bits: u32,
  62. words: [u32; 2],
  63. },
  64. /// Fixed in the code (an immediate sampler, say).
  65. Constant(Vec<u32>),
  66. /// Chosen by control flow: one source per predecessor of `block`, in
  67. /// [`crate::ir::Block::preds`] order.
  68. Phi { block: usize, args: Vec<Source> },
  69. /// Chosen by SCC (`scc`, the value an `s_cselect` or `s_cmov` of each
  70. /// dword reads): the source when it is set, then when it is clear.
  71. Select { scc: Value, args: Vec<Source> },
  72. /// Dwords `first..` of what the vector load at `load` (`global_load_*`)
  73. /// reads, each lane at its own address (see [`Resources::scalar`]); the
  74. /// dwords past that load come from loads of the bytes that follow. A
  75. /// descriptor that differs between lanes.
  76. Fetched { load: Site, first: u8 },
  77. /// Picked per lane by `v_cndmask_b32` reading the lane mask whose low
  78. /// dword is `mask`: the source where the lane's bit is set, then where it
  79. /// is clear.
  80. Lanes { mask: Value, args: Vec<Source> },
  81. /// Per-lane dwords chosen by control flow (VGPRs joined where lanes
  82. /// that took different paths meet): one source per predecessor of
  83. /// `block`, in [`crate::ir::Block::preds`] order, `None` on an edge no
  84. /// lane that accesses the descriptor takes. A descriptor that differs
  85. /// between lanes.
  86. LanePhi {
  87. block: usize,
  88. args: Vec<Option<Source>>,
  89. },
  90. }
  91. impl Source {
  92. /// The sources this one picks from (itself unless a phi).
  93. pub fn leaves(&self) -> Vec<&Source> {
  94. match self {
  95. Source::Phi { args, .. } | Source::Select { args, .. } | Source::Lanes { args, .. } => {
  96. args.iter().flat_map(Source::leaves).collect()
  97. }
  98. Source::LanePhi { args, .. } => {
  99. args.iter().flatten().flat_map(Source::leaves).collect()
  100. }
  101. s => vec![s],
  102. }
  103. }
  104. }
  105. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  106. pub enum Role {
  107. /// Image, buffer or `s_buffer_load` resource.
  108. Resource,
  109. Sampler,
  110. }
  111. #[derive(Debug, Clone, PartialEq, Eq)]
  112. pub struct Descriptor {
  113. pub site: Site,
  114. pub role: Role,
  115. pub source: Source,
  116. }
  117. /// A view-heap descriptor whose byte address can be evaluated when binding
  118. /// the draw, using a table base and a root constant.
  119. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  120. pub struct RootIndexedView {
  121. pub table_slot: u8,
  122. pub constant_slot: u8,
  123. pub constant_dword: u32,
  124. pub byte_offset: u32,
  125. pub shift: u8,
  126. }
  127. #[derive(Debug, Clone, Default, PartialEq, Eq)]
  128. pub struct Resources {
  129. /// Every scalar memory access by address (`s_load_*`, `s_store_*`), and
  130. /// every global memory access (`global_*`, the dynamic term per lane).
  131. pub scalar: Vec<(Site, Address)>,
  132. pub descriptors: Vec<Descriptor>,
  133. /// Direct descriptor sources with a draw-evaluable index.
  134. pub root_indexed_views: Vec<RootIndexedView>,
  135. /// User SGPRs holding root parameters: value on entry, layout index,
  136. /// dword within the parameter.
  137. pub params: Vec<(Value, usize, u32)>,
  138. /// Scalar loads of one descriptor the code keeps per lane in VGPRs
  139. /// ([`Tracer::lane_copies`]): they read one address, so their dwords
  140. /// stand in for each other.
  141. pub lane_copied: Vec<Site>,
  142. pub waterfall: Waterfall,
  143. /// Every `image_bvh_intersect_ray` and `image_bvh64_intersect_ray`: where
  144. /// its nodes are.
  145. pub bvh: Vec<(Site, BvhNodes)>,
  146. }
  147. /// Where a ray-tracing node test ([`crate::bvh`]) reads its nodes. Its
  148. /// descriptor operand names a range of memory, not a texture.
  149. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  150. pub enum BvhNodes {
  151. /// A buffer of the host: the descriptor is loaded from a table (it is
  152. /// among [`Resources::descriptors`]), and node pointers count from the
  153. /// buffer's start. Its flags are not known to the shader: boxes are
  154. /// sorted and triangles return barycentrics, as every descriptor
  155. /// the title builds asks.
  156. Resource,
  157. /// Title memory by address: the code makes the descriptor from numbers
  158. /// (the title: the whole address space, or one structure's address in
  159. /// dword 0). Dwords 1 and 3, which hold its flags.
  160. Memory { word1: u32, word3: u32 },
  161. }
  162. /// Waterfall loops over descriptors that differ between lanes: each pass
  163. /// reads the first active lane's descriptor with `v_readfirstlane_b32`,
  164. /// compares it with every lane's own (`v_cmp_eq`), and runs the access with
  165. /// the lanes that match. Their accesses take each lane's own descriptor
  166. /// ([`Source::Fetched`], [`Source::Lanes`]), so the first lane's dwords are
  167. /// each lane's own too: the compares hold in every lane and one pass serves
  168. /// all lanes.
  169. #[derive(Debug, Clone, Default, PartialEq, Eq)]
  170. pub struct Waterfall {
  171. /// The compares, true in every lane.
  172. pub compares: Vec<Site>,
  173. /// The `v_readfirstlane_b32` results they compare, each the lane's own
  174. /// source dword.
  175. pub reads: Vec<Value>,
  176. /// Descriptor loads at a table offset among `reads` (the console
  177. /// compiler's form): each lane loads its own entry.
  178. pub loads: Vec<Site>,
  179. }
  180. /// Traces every descriptor and scalar address of `p`, which runs as
  181. /// `stage`, to the root parameters in `layout`. Fails on the first one it
  182. /// cannot trace. `lanes`, `p` as one lane runs it, tells which paths the
  183. /// lanes that access a per-lane descriptor took and which writes they ran;
  184. /// without it, per-lane descriptors chosen by control flow are refused and
  185. /// per-lane writes are taken to run in every lane.
  186. pub fn track(
  187. p: &Program,
  188. layout: &[RootParam],
  189. stage: HwStage,
  190. lanes: Option<&Structured>,
  191. ) -> Result<Resources, ShaderError> {
  192. let t = Tracer::new(p, layout, stage, lanes)?;
  193. let mut out = Resources {
  194. params: p
  195. .inputs
  196. .iter()
  197. .filter_map(|&(reg, v)| {
  198. let (param, dword) = t.param_of(reg)?;
  199. Some((v, param, dword))
  200. })
  201. .collect(),
  202. ..Resources::default()
  203. };
  204. // Group accesses in the same loop so a shared mask can select several
  205. // descriptors together.
  206. let mut first_lane_at = std::collections::BTreeMap::<usize, (Vec<usize>, Vec<Value>)>::new();
  207. // The console compiler's waterfall reads the first lane's table offset
  208. // and loads that entry: accesses, offset reads and loads by block.
  209. let mut offset_at =
  210. std::collections::BTreeMap::<usize, (Vec<usize>, Vec<Value>, Vec<Site>)>::new();
  211. for (b, block) in p.blocks.iter().enumerate() {
  212. t.at.set(Some(b));
  213. for (i, inst) in block.insts.iter().enumerate() {
  214. let site = (b, i);
  215. let fail = |what| ShaderError::Unsupported {
  216. offset: inst.machine.offset,
  217. what,
  218. };
  219. let mut first_lane = Vec::new();
  220. let mut offset = Vec::new();
  221. let mut descriptor = |op: &Operand, role| -> Result<(), ShaderError> {
  222. let source = t.descriptor(inst, op, b).map_err(fail)?;
  223. // A descriptor the code keeps per lane ([`Tracer::lane_copies`])
  224. // is the same in every lane: its loop is lowered as it stands
  225. // and needs no proof.
  226. if !t.kept_per_lane(inst, op) {
  227. first_lane.extend(t.first_lane_words(inst, op).unwrap_or_default());
  228. }
  229. if let Source::Loaded { load, .. } = source
  230. && out.scalar.iter().any(|s| s.0 == load)
  231. && let Some(v) = t.first_lane_offset(load)
  232. {
  233. offset.push((v, load));
  234. }
  235. out.descriptors.push(Descriptor { site, role, source });
  236. Ok(())
  237. };
  238. match &inst.fields {
  239. Fields::Image { rsrc, .. } if inst.name().starts_with("image_bvh") => {
  240. // The ray and node test names no texture. A descriptor
  241. // whose flag dwords the code sets as numbers and whose
  242. // type is a ray-tracing structure is a range of title
  243. // memory (the title: all of it, or from one structure's
  244. // address on), and the node's address is among the
  245. // operands; any other descriptor must be a resource of
  246. // the host.
  247. let word = |k: u8| match *rsrc {
  248. Operand::Scalar { code, dwords } if k < dwords => {
  249. inst.read(Reg::S(code + k)).map(|v| t.origin(v))
  250. }
  251. _ => None,
  252. };
  253. match (word(1), word(3)) {
  254. (Some(Term::Const(word1)), Some(Term::Const(word3)))
  255. if word3 >> 28 == crate::bvh::DESCRIPTOR_TYPE =>
  256. {
  257. out.bvh.push((site, BvhNodes::Memory { word1, word3 }));
  258. }
  259. _ => {
  260. descriptor(rsrc, Role::Resource)?;
  261. out.bvh.push((site, BvhNodes::Resource));
  262. }
  263. }
  264. }
  265. Fields::Image { rsrc, sampler, .. } => {
  266. descriptor(rsrc, Role::Resource)?;
  267. if let Some(s) = sampler {
  268. descriptor(s, Role::Sampler)?;
  269. }
  270. }
  271. // Cache invalidations name a buffer's address space but do
  272. // not read its descriptor; the host has no cache to drop.
  273. Fields::Buffer { rsrc, .. } if !inst.name().ends_with("_inv") => {
  274. descriptor(rsrc, Role::Resource)?
  275. }
  276. Fields::Buffer { .. } => {}
  277. Fields::Smem { base, .. } if inst.name().starts_with("s_buffer_") => {
  278. descriptor(base, Role::Resource)?;
  279. }
  280. Fields::Smem {
  281. base,
  282. offset,
  283. soffset,
  284. ..
  285. } if inst.name().contains("_load_") || inst.name().contains("_store_") => {
  286. let address = t
  287. .smem_address(inst, base, *offset, soffset)
  288. .or_else(|why| t.by_address(why))
  289. .map_err(fail)?;
  290. out.scalar.push((site, address));
  291. }
  292. Fields::Flat {
  293. addr,
  294. saddr,
  295. offset,
  296. ..
  297. } if inst.name().starts_with("global_") => {
  298. let address = t
  299. .flat_address(inst, addr.as_ref(), saddr.as_ref(), *offset)
  300. .or_else(|why| t.by_address(why))
  301. .map_err(fail)?;
  302. out.scalar.push((site, address));
  303. }
  304. _ => {}
  305. }
  306. if !first_lane.is_empty() {
  307. let (accesses, reads) = first_lane_at.entry(b).or_default();
  308. accesses.push(i);
  309. reads.extend(first_lane);
  310. }
  311. if !offset.is_empty() {
  312. let (accesses, reads, loads) = offset_at.entry(b).or_default();
  313. accesses.push(i);
  314. for (v, load) in offset {
  315. reads.push(v);
  316. loads.push(load);
  317. }
  318. }
  319. }
  320. }
  321. // What follows traces no access of one block.
  322. t.at.set(None);
  323. // The proof needs the per-lane form. Without it nothing is emitted, and
  324. // its failure is the one to report, so the reads stay unproven here.
  325. if t.lanes.is_none() {
  326. return Ok(out);
  327. }
  328. for (block, (accesses, mut reads)) in first_lane_at {
  329. reads.sort_unstable();
  330. reads.dedup();
  331. let proof = t
  332. .waterfall(block, &accesses, &reads)
  333. .map_err(|what| ShaderError::Unsupported {
  334. offset: t.inst((block, accesses[0])).machine.offset,
  335. what,
  336. })?;
  337. out.waterfall.compares.extend(proof.compares);
  338. out.waterfall.reads.extend(proof.reads);
  339. }
  340. // Unproven, an offset read stays the first lane's (one uniform entry),
  341. // which is what the hardware reads outside a waterfall loop.
  342. for (block, (accesses, mut reads, loads)) in offset_at {
  343. reads.sort_unstable();
  344. reads.dedup();
  345. if let Ok(proof) = t.waterfall(block, &accesses, &reads) {
  346. out.waterfall.compares.extend(proof.compares);
  347. out.waterfall.reads.extend(proof.reads);
  348. out.waterfall.loads.extend(loads);
  349. }
  350. }
  351. out.lane_copied = t.lane_copied.take();
  352. out.lane_copied.sort_unstable();
  353. out.lane_copied.dedup();
  354. out.root_indexed_views = out
  355. .descriptors
  356. .iter()
  357. .filter_map(|d| t.root_indexed_view(d, &out.scalar))
  358. .collect();
  359. Ok(out)
  360. }
  361. /// A dword after copy propagation.
  362. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  363. enum Term {
  364. Const(u32),
  365. Value(Value),
  366. }
  367. /// A 32-bit sum: optional root parameter (as its first dword), constant,
  368. /// optional computed term.
  369. struct Sum {
  370. base: Option<Value>,
  371. offset: u32,
  372. dynamic: Option<Value>,
  373. }
  374. struct Tracer<'a> {
  375. p: &'a Program,
  376. layout: &'a [RootParam],
  377. stage: HwStage,
  378. /// Defining instruction per value (phis and inputs have none).
  379. defs: Vec<Option<Site>>,
  380. /// Block and index of each phi value.
  381. phis: Vec<Option<(usize, usize)>>,
  382. /// Register per input value.
  383. inputs: Vec<Option<Reg>>,
  384. origin: Vec<Term>,
  385. /// See [`Resources::lane_copied`].
  386. lane_copied: std::cell::RefCell<Vec<Site>>,
  387. lanes: Option<&'a Structured>,
  388. /// While set, [`Self::sum`] keeps the first-lane read of an index as
  389. /// the computed term instead of what the lanes hold.
  390. read_first_lane: std::cell::Cell<bool>,
  391. /// What the conditions asked of `lanes` so far came down to: the proofs
  392. /// of one program ask about the same blocks and masks again and again.
  393. meets: std::cell::RefCell<Meets>,
  394. /// Reverse-postorder index per block.
  395. rpo: Vec<usize>,
  396. /// The block of the access being traced ([`Self::live`]).
  397. at: std::cell::Cell<Option<usize>>,
  398. }
  399. /// What lanes are known to satisfy: each [`Bool`] where its flag is set,
  400. /// its negation where not.
  401. type Known = Vec<(Bool, bool)>;
  402. const MAX_ROUNDS: usize = 64;
  403. const MAX_JOINS: usize = 8;
  404. /// VGPR values followed for one dword of a descriptor kept per lane.
  405. const MAX_COPIES: usize = 64;
  406. impl<'a> Tracer<'a> {
  407. fn new(
  408. p: &'a Program,
  409. layout: &'a [RootParam],
  410. stage: HwStage,
  411. lanes: Option<&'a Structured>,
  412. ) -> Result<Self, ShaderError> {
  413. let all = || {
  414. p.inputs
  415. .iter()
  416. .map(|i| i.1)
  417. .chain(p.blocks.iter().flat_map(|b| {
  418. b.phis
  419. .iter()
  420. .map(|phi| phi.value)
  421. .chain(b.insts.iter().flat_map(|i| i.writes.iter().map(|w| w.1)))
  422. }))
  423. };
  424. let n = all().map(|v| v.0 as usize + 1).max().unwrap_or(0);
  425. let mut defs = vec![None; n];
  426. let mut phis = vec![None; n];
  427. let mut inputs = vec![None; n];
  428. for &(reg, v) in &p.inputs {
  429. inputs[v.0 as usize] = Some(reg);
  430. }
  431. for (b, block) in p.blocks.iter().enumerate() {
  432. for (i, phi) in block.phis.iter().enumerate() {
  433. phis[phi.value.0 as usize] = Some((b, i));
  434. }
  435. for (i, inst) in block.insts.iter().enumerate() {
  436. for &(_, v) in &inst.writes {
  437. defs[v.0 as usize] = Some((b, i));
  438. }
  439. }
  440. }
  441. let mut rpo = vec![usize::MAX; p.blocks.len()];
  442. for (n, b) in crate::ir::reverse_postorder(&p.blocks)
  443. .into_iter()
  444. .enumerate()
  445. {
  446. rpo[b] = n;
  447. }
  448. let mut t = Tracer {
  449. p,
  450. layout,
  451. stage,
  452. defs,
  453. phis,
  454. inputs,
  455. origin: Vec::new(),
  456. lane_copied: Default::default(),
  457. lanes,
  458. read_first_lane: Default::default(),
  459. meets: Default::default(),
  460. rpo,
  461. at: Default::default(),
  462. };
  463. t.origin = t.propagate_copies(n)?;
  464. Ok(t)
  465. }
  466. /// Optimistic copy propagation: a move's result is its source's
  467. /// origin, a phi's the one origin its arguments agree on.
  468. fn propagate_copies(&self, n: usize) -> Result<Vec<Term>, ShaderError> {
  469. let mut o: Vec<Option<Term>> = vec![None; n];
  470. for &(_, v) in &self.p.inputs {
  471. o[v.0 as usize] = Some(Term::Value(v));
  472. }
  473. let order = crate::ir::reverse_postorder(&self.p.blocks);
  474. for _ in 0..MAX_ROUNDS {
  475. let mut changed = false;
  476. for &b in &order {
  477. let block = &self.p.blocks[b];
  478. for phi in &block.phis {
  479. let own = Term::Value(phi.value);
  480. let mut args = phi
  481. .args
  482. .iter()
  483. .filter_map(|a| o[a.0 as usize])
  484. .filter(|&t| t != own);
  485. let new = args
  486. .next()
  487. .map(|first| if args.all(|t| t == first) { first } else { own });
  488. if new.is_some() && new != o[phi.value.0 as usize] {
  489. o[phi.value.0 as usize] = new;
  490. changed = true;
  491. }
  492. }
  493. for inst in &block.insts {
  494. for (k, &(_, v)) in inst.writes.iter().enumerate() {
  495. let new = match copy_source(inst, k).or_else(|| self.restored(inst)) {
  496. Some(Moved::Const(c)) => Some(Term::Const(c)),
  497. Some(Moved::Value(s)) => o[s.0 as usize],
  498. None => Some(Term::Value(v)),
  499. };
  500. if new.is_some() && new != o[v.0 as usize] {
  501. o[v.0 as usize] = new;
  502. changed = true;
  503. }
  504. }
  505. }
  506. }
  507. if !changed {
  508. return Ok(o
  509. .into_iter()
  510. .enumerate()
  511. .map(|(v, t)| t.unwrap_or(Term::Value(Value(v as u32))))
  512. .collect());
  513. }
  514. }
  515. Err(ShaderError::Unsupported {
  516. offset: 0,
  517. what: "copies that do not settle",
  518. })
  519. }
  520. /// Whether some lane can satisfy all of `conditions` ([`Bools::meet`]).
  521. ///
  522. /// [`Bools::meet`]: crate::structure::Bools::meet
  523. fn meet(&self, lanes: &Structured, conditions: &[(Bool, bool)]) -> bool {
  524. lanes
  525. .bools
  526. .meet_seen(conditions, &mut self.meets.borrow_mut())
  527. }
  528. fn inst(&self, (b, i): Site) -> &'a Inst {
  529. &self.p.blocks[b].insts[i]
  530. }
  531. fn def(&self, v: Value) -> Option<&'a Inst> {
  532. self.defs[v.0 as usize].map(|s| self.inst(s))
  533. }
  534. fn origin(&self, v: Value) -> Term {
  535. self.origin[v.0 as usize]
  536. }
  537. /// The origin of a one-dword operand as `inst` reads it.
  538. fn term(&self, inst: &Inst, op: &Operand) -> Option<Term> {
  539. match *op {
  540. Operand::Scalar { code: NULL, .. } => Some(Term::Const(0)),
  541. Operand::Scalar { code, .. } => Some(self.origin(inst.read(Reg::S(code))?)),
  542. Operand::Const(c) => inline(c).map(Term::Const),
  543. Operand::Literal(x) => Some(Term::Const(x)),
  544. _ => None,
  545. }
  546. }
  547. /// Layout index and dword of the root parameter `reg` holds on entry.
  548. fn param_of(&self, reg: Reg) -> Option<(usize, u32)> {
  549. let Reg::S(code) = reg else { return None };
  550. self.layout.iter().enumerate().find_map(|(i, p)| {
  551. let first = self.stage.user_sgpr(p.user_data);
  552. let dword = u32::from(code).checked_sub(first.into())?;
  553. (dword < p.sgprs).then_some((i, dword))
  554. })
  555. }
  556. /// The SOP2 operands of `v` if an instruction with one of `names` wrote it.
  557. fn sop2(&self, v: Value, names: &[&str]) -> Option<(&'a Inst, [Term; 2])> {
  558. let inst = self.def(v)?;
  559. if !names.contains(&inst.name()) || inst.writes.first()?.1 != v {
  560. return None;
  561. }
  562. let Fields::Sop { src, .. } = &inst.fields else {
  563. return None;
  564. };
  565. Some((
  566. inst,
  567. [
  568. self.term(inst, src.first()?)?,
  569. self.term(inst, src.get(1)?)?,
  570. ],
  571. ))
  572. }
  573. fn root_indexed_view(
  574. &self,
  575. descriptor: &Descriptor,
  576. scalar: &[(Site, Address)],
  577. ) -> Option<RootIndexedView> {
  578. if descriptor.role != Role::Resource {
  579. return None;
  580. }
  581. let Source::Loaded { load, first } = descriptor.source else {
  582. return None;
  583. };
  584. let i = scalar.binary_search_by_key(&load, |(site, _)| *site).ok()?;
  585. let address = scalar[i].1;
  586. let base = self.layout.get(address.param)?;
  587. if base.root != RootType::Table {
  588. return None;
  589. }
  590. let dynamic = address.dynamic?;
  591. let (input, shift) = match self.sop2(dynamic, &["s_lshl_b32"]) {
  592. Some((_, [Term::Value(input), Term::Const(shift)])) => (input, (shift & 31) as u8),
  593. _ => (dynamic, 0),
  594. };
  595. let (param, constant_dword) = self.param_of(self.inputs[input.0 as usize]?)?;
  596. let constant = self.layout.get(param)?;
  597. if constant.root != RootType::Constants {
  598. return None;
  599. }
  600. Some(RootIndexedView {
  601. table_slot: base.slot,
  602. constant_slot: constant.slot,
  603. constant_dword,
  604. byte_offset: address.offset.wrapping_add(u32::from(first) * 4),
  605. shift,
  606. })
  607. }
  608. fn sum(&self, t: Term) -> Sum {
  609. let v = match t {
  610. Term::Const(c) => {
  611. return Sum {
  612. base: None,
  613. offset: c,
  614. dynamic: None,
  615. };
  616. }
  617. Term::Value(v) => v,
  618. };
  619. let dynamic = Sum {
  620. base: None,
  621. offset: 0,
  622. dynamic: Some(v),
  623. };
  624. if let Some(reg) = self.inputs[v.0 as usize] {
  625. return match self.param_of(reg) {
  626. Some((_, 0)) => Sum {
  627. base: Some(v),
  628. offset: 0,
  629. dynamic: None,
  630. },
  631. _ => dynamic,
  632. };
  633. }
  634. if self.getpc(v).is_some() {
  635. return Sum {
  636. base: Some(v),
  637. offset: 0,
  638. dynamic: None,
  639. };
  640. }
  641. // Paths that each add an index to a table in the code and meet before one
  642. // load: the join itself is the computed term. Lowering gives every
  643. // `s_getpc_b64` its own offset in the code as its value, so the join is the
  644. // byte in the code whichever table a path took ([`Self::address`] adds no
  645. // base to it).
  646. if let Some(pc) = self.code_join(v) {
  647. return Sum {
  648. base: Some(pc),
  649. offset: 0,
  650. dynamic: Some(v),
  651. };
  652. }
  653. // An address computed in VGPRs and taken from the first lane (a
  654. // table in the code indexed by a value held per lane, or a table
  655. // offset held per lane, the console's waterfall): the sum of what
  656. // the lanes hold. Loads at one offset in different loops (each with
  657. // its own `v_readfirstlane_b32`) then have one address, which is
  658. // what tells lowering that they read one descriptor. With
  659. // `read_first_lane` a first-lane read of an index alone stays the
  660. // computed term ([`Self::first_lane_offset`]).
  661. if let Some(lane) = self.first_lane(v) {
  662. let per_lane = self.sum(self.vorigin(lane));
  663. return if per_lane.base.is_some() || !self.read_first_lane.get() {
  664. per_lane
  665. } else {
  666. dynamic
  667. };
  668. }
  669. let Some([a, b]) = self
  670. .sop2(v, &["s_add_u32", "s_add_i32"])
  671. .map(|(_, t)| t)
  672. .or_else(|| self.vadd(v))
  673. else {
  674. return dynamic;
  675. };
  676. let (x, y) = (self.sum(a), self.sum(b));
  677. if x.base.is_some() && y.base.is_some() || x.dynamic.is_some() && y.dynamic.is_some() {
  678. return dynamic;
  679. }
  680. Sum {
  681. base: x.base.or(y.base),
  682. offset: x.offset.wrapping_add(y.offset),
  683. dynamic: x.dynamic.or(y.dynamic),
  684. }
  685. }
  686. /// For a join `v` whose every incoming value adds to an `s_getpc_b64` low
  687. /// dword: the first of those (one level of joins only). The paths may add
  688. /// to different ones: two tables in the code, one picked by control flow
  689. /// (the title's fog reconstruction reads its sample offsets from
  690. /// one of two tables, by the sample's number; refused, the lit frame was
  691. /// multiplied by a fog transmittance nothing had written).
  692. fn code_join(&self, v: Value) -> Option<Value> {
  693. let (b, i) = self.phis[v.0 as usize]?;
  694. let mut base = None;
  695. for &a in &self.p.blocks[b].phis[i].args {
  696. let Term::Value(x) = self.vorigin(a) else {
  697. return None;
  698. };
  699. if x == v {
  700. continue;
  701. }
  702. let pc = self.code_base(x, 4)?;
  703. base = base.or(Some(pc));
  704. }
  705. base
  706. }
  707. /// `t` is the high dword of an `s_getpc_b64`, or `s_addc_u32`s of one:
  708. /// the carry may be added in steps (the counter's high dword plus 0
  709. /// where the table's offset is added, then plus the index's high dword).
  710. fn code_high(&self, t: Term) -> bool {
  711. self.code_high_in(t, 4)
  712. }
  713. /// [`Self::code_high`], at most `depth` additions deep.
  714. fn code_high_in(&self, t: Term, depth: u32) -> bool {
  715. let Term::Value(x) = t else { return false };
  716. if self.def(x).is_some_and(|i| {
  717. i.name() == "s_getpc_b64" && i.writes.get(1).is_some_and(|w| w.1 == x)
  718. }) {
  719. return true;
  720. }
  721. depth > 0
  722. && self.sop2(x, &["s_addc_u32"]).is_some_and(|(_, [p, q])| {
  723. self.code_high_in(p, depth - 1) || self.code_high_in(q, depth - 1)
  724. })
  725. }
  726. /// The `s_getpc_b64` low dword among the terms `v` adds up (`depth`
  727. /// additions deep; joins are not followed).
  728. fn code_base(&self, v: Value, depth: u32) -> Option<Value> {
  729. if self.getpc(v).is_some() {
  730. return Some(v);
  731. }
  732. // Computed in VGPRs and taken from the first lane.
  733. if let Some(lane) = self.first_lane(v) {
  734. return match self.vorigin(lane) {
  735. Term::Value(x) => self.code_base(x, depth),
  736. Term::Const(_) => None,
  737. };
  738. }
  739. if depth == 0 || self.phis[v.0 as usize].is_some() {
  740. return None;
  741. }
  742. let terms = self
  743. .sop2(v, &["s_add_u32", "s_add_i32"])
  744. .map(|(_, t)| t)
  745. .or_else(|| self.vadd(v))?;
  746. terms.into_iter().find_map(|t| match t {
  747. Term::Value(x) => self.code_base(x, depth - 1),
  748. Term::Const(_) => None,
  749. })
  750. }
  751. /// `t` is `high` or an `s_addc_u32` of it.
  752. fn is_high(&self, t: Term, high: Value) -> bool {
  753. match t {
  754. Term::Value(x) => {
  755. x == high
  756. || self
  757. .sop2(x, &["s_addc_u32"])
  758. .is_some_and(|(_, [p, q])| p == Term::Value(high) || q == Term::Value(high))
  759. }
  760. Term::Const(_) => false,
  761. }
  762. }
  763. /// The VGPR value `v_readfirstlane_b32` reads to write the scalar `v`.
  764. fn first_lane(&self, v: Value) -> Option<Value> {
  765. let inst = self.def(v)?;
  766. if inst.name() != "v_readfirstlane_b32" || inst.writes.first()?.1 != v {
  767. return None;
  768. }
  769. let Fields::Valu(f) = &inst.fields else {
  770. return None;
  771. };
  772. if f.abs != 0 || f.neg != 0 || f.sdwa.is_some() || f.dpp.is_some() {
  773. return None;
  774. }
  775. match *f.src.first()? {
  776. Operand::Vector { reg, .. } => inst.read(Reg::V(reg)),
  777. _ => None,
  778. }
  779. }
  780. /// The `s_getpc_b64` writing `lo` as its low dword.
  781. fn getpc(&self, lo: Value) -> Option<&'a Inst> {
  782. let inst = self.def(lo)?;
  783. (inst.name() == "s_getpc_b64" && inst.writes.first().is_some_and(|w| w.1 == lo))
  784. .then_some(inst)
  785. }
  786. /// The operands of a VALU addition (`v_add_co_u32`, `v_add_nc_u32`)
  787. /// writing `v`, through VGPR copies of scalars.
  788. fn vadd(&self, v: Value) -> Option<[Term; 2]> {
  789. let inst = self.def(v)?;
  790. let Fields::Valu(f) = &inst.fields else {
  791. return None;
  792. };
  793. if !matches!(inst.name(), "v_add_co_u32" | "v_add_nc_u32")
  794. || f.dst.is_none_or(|d| !matches!(d, Operand::Vector { .. }))
  795. || inst.write(Reg::V(match f.dst? {
  796. Operand::Vector { reg, .. } => reg,
  797. _ => return None,
  798. })) != Some(v)
  799. || f.abs != 0
  800. || f.neg != 0
  801. || f.sdwa.is_some()
  802. || f.dpp.is_some()
  803. {
  804. return None;
  805. }
  806. Some([
  807. self.vterm(inst, f.src.first()?)?,
  808. self.vterm(inst, f.src.get(1)?)?,
  809. ])
  810. }
  811. /// The origin of a VALU operand.
  812. fn vterm(&self, inst: &Inst, op: &Operand) -> Option<Term> {
  813. match *op {
  814. Operand::Vector { reg, .. } => Some(self.vorigin(inst.read(Reg::V(reg))?)),
  815. op => self.term(inst, &op),
  816. }
  817. }
  818. /// A VGPR value's origin through `v_mov_b32` copies.
  819. fn vorigin(&self, v: Value) -> Term {
  820. if let Some(inst) = self.def(v)
  821. && inst.name() == "v_mov_b32"
  822. && let Fields::Valu(f) = &inst.fields
  823. && f.abs == 0
  824. && f.neg == 0
  825. && f.sdwa.is_none()
  826. && f.dpp.is_none()
  827. && let Some(t) = f.src.first().and_then(|s| self.vterm(inst, s))
  828. {
  829. return t;
  830. }
  831. self.origin(v)
  832. }
  833. /// The address of an access that traces to no root parameter (`why`
  834. /// says how it failed): title memory at the address as it stands, in a
  835. /// compute program.
  836. fn by_address(&self, why: &'static str) -> Result<Address, &'static str> {
  837. if self.stage == HwStage::Cs && RAW.contains(&why) {
  838. Ok(Address {
  839. param: MEMORY,
  840. offset: 0,
  841. dynamic: None,
  842. })
  843. } else {
  844. Err(why)
  845. }
  846. }
  847. /// A global memory address: an SGPR pair plus a VGPR offset, or a VGPR
  848. /// pair.
  849. fn flat_address(
  850. &self,
  851. inst: &Inst,
  852. addr: Option<&Operand>,
  853. saddr: Option<&Operand>,
  854. offset: i16,
  855. ) -> Result<Address, &'static str> {
  856. let Some(&Operand::Vector { reg, .. }) = addr else {
  857. return Err("a global address not in VGPRs");
  858. };
  859. let off = offset as i32 as u32;
  860. match saddr {
  861. Some(&Operand::Scalar { code, .. }) if code != NULL => {
  862. let word = |k| Some(self.origin(inst.read(Reg::S(code + k))?));
  863. let (Some(lo), Some(hi)) = (word(0), word(1)) else {
  864. return Err("an address not in SGPRs");
  865. };
  866. let v = inst.read(Reg::V(reg)).ok_or("a global address")?;
  867. let mut extra = self.sum(self.vorigin(v));
  868. if extra.base.is_some() {
  869. return Err("an offset from a root parameter");
  870. }
  871. extra.offset = extra.offset.wrapping_add(off);
  872. self.address(lo, hi, extra)
  873. }
  874. _ => {
  875. let word = |k| inst.read(Reg::V(reg + k)).map(|v| self.vorigin(v));
  876. let (Some(lo), Some(hi)) = (word(0), word(1)) else {
  877. return Err("a global address");
  878. };
  879. self.address(
  880. lo,
  881. hi,
  882. Sum {
  883. base: None,
  884. offset: off,
  885. dynamic: None,
  886. },
  887. )
  888. }
  889. }
  890. }
  891. /// The address `lo` and `hi` hold, plus `extra` (an instruction's
  892. /// immediate and offset register).
  893. fn address(&self, lo: Term, hi: Term, extra: Sum) -> Result<Address, &'static str> {
  894. // The high half as the lanes that read through the address hold
  895. // it, where that is a constant or what a register held on entry
  896. // (the code clears a table address's high half inside a branch
  897. // and uses the address after the join).
  898. let hi = match self.live(hi) {
  899. t @ Term::Const(_) => t,
  900. Term::Value(v) if self.inputs[v.0 as usize].is_some() => Term::Value(v),
  901. _ => hi,
  902. };
  903. let s = self.sum(lo);
  904. if s.dynamic.is_some() && extra.dynamic.is_some() {
  905. return Err("an address with two computed terms");
  906. }
  907. let base = s.base.ok_or_else(|| self.why_no_base(s.dynamic))?;
  908. if let Some(pc) = self.getpc(base) {
  909. // A table in the code: the base is the next instruction's offset.
  910. let high = pc.writes.get(1).map(|w| w.1);
  911. if !self.high_half(hi, high) && !high.is_some_and(|h| self.carried(hi, h)) {
  912. return Err("an address with an untracked high half");
  913. }
  914. // A join of paths into tables in the code is the byte in the code
  915. // already: each path's `s_getpc_b64` counts as its own offset.
  916. let joined = s.dynamic.is_some_and(|d| self.code_join(d).is_some());
  917. let first = if joined { 0 } else { pc.machine.offset as u32 + 4 };
  918. return Ok(Address {
  919. param: CODE,
  920. offset: first.wrapping_add(s.offset).wrapping_add(extra.offset),
  921. dynamic: s.dynamic.or(extra.dynamic),
  922. });
  923. }
  924. let reg = self.inputs[base.0 as usize].ok_or("an address not from a root parameter")?;
  925. let (param, _) = self
  926. .param_of(reg)
  927. .ok_or("an address not from a root parameter")?;
  928. let high = match self.layout[param].root {
  929. RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap => None,
  930. RootType::Descriptor => {
  931. let high = Reg::S(self.stage.user_sgpr(self.layout[param].user_data) + 1);
  932. let input = self.p.inputs.iter().find(|i| i.0 == high);
  933. Some(input.ok_or("a root descriptor without its high half")?.1)
  934. }
  935. _ => return Err("an address from a root parameter that is no address"),
  936. };
  937. // shortcut: with a computed term, a high half that adds anything to the
  938. // base's is taken as the carry of that term (offsets below 4 GB).
  939. let dynamic = s.dynamic.or(extra.dynamic);
  940. if !self.high_half(hi, high)
  941. && !(dynamic.is_some() && high.is_some_and(|h| self.carried(hi, h)))
  942. {
  943. return Err("an address with an untracked high half");
  944. }
  945. Ok(Address {
  946. param,
  947. offset: s.offset.wrapping_add(extra.offset),
  948. dynamic: s.dynamic.or(extra.dynamic),
  949. })
  950. }
  951. /// `hi` is `high` (0 for a table), possibly plus a carry.
  952. fn high_half(&self, hi: Term, high: Option<Value>) -> bool {
  953. let want = high.map_or(Term::Const(0), Term::Value);
  954. hi == want
  955. || matches!(hi, Term::Value(v) if self.sop2(v, &["s_addc_u32"]).is_some_and(
  956. |(_, [a, b])| a == want && b == Term::Const(0) || b == want && a == Term::Const(0)
  957. ))
  958. }
  959. /// `hi` adds something (with carry) to `high`: `s_addc_u32` or
  960. /// `v_add_co_ci_u32` with `high` as an operand.
  961. fn carried(&self, hi: Term, high: Value) -> bool {
  962. let Term::Value(v) = hi else { return false };
  963. if v == high {
  964. return true;
  965. }
  966. // A join ([`Self::code_join`]): every path carries into the table's high half.
  967. if let Some((b, i)) = self.phis[v.0 as usize] {
  968. // A path may carry into another table's high half ([`Self::code_join`]).
  969. let high_of = |t: Term| self.is_high(t, high) || self.code_high(t);
  970. return self.p.blocks[b].phis[i].args.iter().all(|&a| {
  971. let t = self.vorigin(a);
  972. if t == Term::Value(v) || high_of(t) {
  973. return true;
  974. }
  975. let Term::Value(x) = t else {
  976. return false;
  977. };
  978. // Computed in VGPRs and taken from the first lane.
  979. let x = match self.first_lane(x).map(|lane| self.vorigin(lane)) {
  980. Some(Term::Value(y)) => y,
  981. Some(Term::Const(_)) => return false,
  982. None => x,
  983. };
  984. let Some(inst) = self.def(x) else {
  985. return false;
  986. };
  987. let Fields::Valu(f) = &inst.fields else {
  988. return false;
  989. };
  990. inst.name() == "v_add_co_ci_u32"
  991. && f.src[..2.min(f.src.len())]
  992. .iter()
  993. .any(|o| self.vterm(inst, o).is_some_and(high_of))
  994. });
  995. }
  996. if let Some(lane) = self.first_lane(v) {
  997. return self.carried(self.vorigin(lane), high);
  998. }
  999. if let Some((_, [a, b])) = self.sop2(v, &["s_addc_u32"]) {
  1000. return self.carried(a, high) || self.carried(b, high);
  1001. }
  1002. let Some(inst) = self.def(v) else {
  1003. return false;
  1004. };
  1005. let Fields::Valu(f) = &inst.fields else {
  1006. return false;
  1007. };
  1008. inst.name() == "v_add_co_ci_u32"
  1009. && f.src[..2.min(f.src.len())]
  1010. .iter()
  1011. .any(|o| self.vterm(inst, o).is_some_and(|t| self.carried(t, high)))
  1012. }
  1013. fn why_no_base(&self, dynamic: Option<Value>) -> &'static str {
  1014. let Some(v) = dynamic else {
  1015. return "a constant address";
  1016. };
  1017. if self.inputs[v.0 as usize].is_some() {
  1018. return "an address in an SGPR that is no root parameter";
  1019. }
  1020. if self
  1021. .leaves(v)
  1022. .any(|l| self.def(l).is_some_and(|i| i.name() == "s_getpc_b64"))
  1023. {
  1024. return "an address relative to the program counter";
  1025. }
  1026. match self.def(v).map(|i| i.name()) {
  1027. Some(n) if n.starts_with("s_load_") => "an address loaded from memory",
  1028. None => "an address from a phi",
  1029. _ => "an address not from a root parameter",
  1030. }
  1031. }
  1032. /// The terms of the additions that compute `v`.
  1033. fn leaves(&self, v: Value) -> Box<dyn Iterator<Item = Value> + '_> {
  1034. match self.sop2(v, &["s_add_u32", "s_add_i32"]) {
  1035. Some((_, terms)) => Box::new(terms.into_iter().flat_map(move |t| match t {
  1036. Term::Value(x) => self.leaves(x),
  1037. Term::Const(_) => Box::new(std::iter::empty()),
  1038. })),
  1039. None => Box::new(std::iter::once(v)),
  1040. }
  1041. }
  1042. fn smem_address(
  1043. &self,
  1044. inst: &Inst,
  1045. base: &Operand,
  1046. offset: i32,
  1047. soffset: &Operand,
  1048. ) -> Result<Address, &'static str> {
  1049. let Operand::Scalar { code, .. } = *base else {
  1050. return Err("an address not in SGPRs");
  1051. };
  1052. let word = |k| Some(self.origin(inst.read(Reg::S(code + k))?));
  1053. let (Some(lo), Some(hi)) = (word(0), word(1)) else {
  1054. return Err("an address not in SGPRs");
  1055. };
  1056. let mut extra = self.sum(
  1057. self.term(inst, soffset)
  1058. .ok_or("an unknown offset operand")?,
  1059. );
  1060. if extra.base.is_some() {
  1061. return Err("an offset from a root parameter");
  1062. }
  1063. extra.offset = extra.offset.wrapping_add(offset as u32);
  1064. self.address(lo, hi, extra)
  1065. }
  1066. /// The source of the descriptor operand `op` of `inst`, in block `at`.
  1067. fn descriptor(&self, inst: &Inst, op: &Operand, at: usize) -> Result<Source, &'static str> {
  1068. let Operand::Scalar { code, dwords } = *op else {
  1069. return Err("a descriptor not in SGPRs");
  1070. };
  1071. let mut words = (0..dwords)
  1072. .map(|k| inst.read(Reg::S(code + k)).map(|v| self.origin(v)))
  1073. .collect::<Option<Vec<_>>>()
  1074. .ok_or("a descriptor not in SGPRs")?;
  1075. // A byte access through a buffer descriptor made raw reads what the
  1076. // descriptor's view does with a raw host view (VIctory upstream 0b35b7f).
  1077. if !inst.name().contains("format")
  1078. && let Some(raw) = self.made_raw(&words)
  1079. {
  1080. words = raw.to_vec();
  1081. }
  1082. // Only the lanes that reach the access read the descriptor.
  1083. let mut known = Vec::from_iter(self.lanes.map(|l| (l.reach[at], true)));
  1084. self.classify(&words, &mut Vec::new(), &mut known)
  1085. }
  1086. /// The source of a descriptor's words; `joins` are the phi blocks
  1087. /// being resolved, `known` holds in every lane that reads them.
  1088. fn classify(
  1089. &self,
  1090. words: &[Term],
  1091. joins: &mut Vec<usize>,
  1092. known: &mut Known,
  1093. ) -> Result<Source, &'static str> {
  1094. if let Some(source) = self.phi(words, joins, known)? {
  1095. return Ok(source);
  1096. }
  1097. if let Some(source) = self.select(words, joins, known)? {
  1098. return Ok(source);
  1099. }
  1100. let read = |w: &Term| match *w {
  1101. Term::Value(v) => self.first_lane_source(v),
  1102. Term::Const(_) => None,
  1103. };
  1104. if let Some(sources) = words.iter().map(read).collect::<Option<Vec<_>>>() {
  1105. // One descriptor the code keeps per lane: the lanes agree.
  1106. if let Some(source) = self.lane_copies(words) {
  1107. return Ok(source);
  1108. }
  1109. // Read from the first active lane, as a waterfall loop does: the
  1110. // dwords each lane holds.
  1111. let lanes: Vec<Term> = sources.into_iter().map(Term::Value).collect();
  1112. return self.per_lane(&lanes, joins, known);
  1113. }
  1114. if words.iter().any(|w| read(w).is_some()) {
  1115. return Err("a descriptor partly read from the first lane");
  1116. }
  1117. if let Some(consts) = words
  1118. .iter()
  1119. .map(|w| match *w {
  1120. Term::Const(c) => Some(c),
  1121. Term::Value(_) => None,
  1122. })
  1123. .collect::<Option<Vec<_>>>()
  1124. {
  1125. return Ok(Source::Constant(consts));
  1126. }
  1127. if let Some(source) = self.loaded(words) {
  1128. return Ok(source);
  1129. }
  1130. if let [lo, hi, Term::Const(w2), Term::Const(w3)] = *words {
  1131. let (mut hi, mut bits) = (hi, 0);
  1132. while let Term::Value(v) = hi
  1133. && let Some((x, more)) = self.set_bits(v)
  1134. {
  1135. (hi, bits) = (x, bits | more);
  1136. }
  1137. let address = self.address(
  1138. lo,
  1139. hi,
  1140. Sum {
  1141. base: None,
  1142. offset: 0,
  1143. dynamic: None,
  1144. },
  1145. )?;
  1146. return Ok(Source::Built {
  1147. address,
  1148. bits,
  1149. words: [w2, w3],
  1150. });
  1151. }
  1152. let loaded = |w: &Term| {
  1153. matches!(*w, Term::Value(v)
  1154. if self.def(v).is_some_and(|i| i.name().starts_with("s_load_")))
  1155. };
  1156. Err(if words.iter().any(loaded) {
  1157. "a descriptor changed after loading"
  1158. } else {
  1159. "a descriptor neither loaded nor built"
  1160. })
  1161. }
  1162. /// The one edge into the join `block` that lanes satisfying `known`
  1163. /// can have taken, if the lanes' paths ([`Structured`]) rule out every
  1164. /// other: the console compiler loads a descriptor (or clears an
  1165. /// address's high half) inside a branch that skips code when no lane
  1166. /// is left for it, and uses it after the join, where only lanes that
  1167. /// ran the branch are left (the title's
  1168. /// `CS_Alpha_Schedule`: the registers' values from before the branch,
  1169. /// which the join also sees, are what a wave with no such lane holds).
  1170. /// None at loop headers and without the lanes' paths.
  1171. fn only_edge(&self, block: usize, known: &mut Known) -> Option<usize> {
  1172. let lanes = self.lanes?;
  1173. let preds = &self.p.blocks[block].preds;
  1174. if preds.len() < 2 || preds.iter().any(|&q| self.rpo[q] >= self.rpo[block]) {
  1175. return None;
  1176. }
  1177. let mut only = None;
  1178. for (j, &q) in preds.iter().enumerate() {
  1179. let n = known.len();
  1180. known.push((lanes.reach[q], true));
  1181. if let LaneExit::Branch {
  1182. when,
  1183. taken,
  1184. not_taken,
  1185. } = lanes.exits[q]
  1186. && taken != not_taken
  1187. {
  1188. known.push((when, taken == block));
  1189. }
  1190. let possible = self.meet(lanes, known);
  1191. known.truncate(n);
  1192. if possible {
  1193. if only.is_some() {
  1194. return None;
  1195. }
  1196. only = Some(j);
  1197. }
  1198. }
  1199. only
  1200. }
  1201. /// Whether lowering can make a handle for `source` in any block: its
  1202. /// heap index comes from root parameters and constants alone (a table
  1203. /// offset the code computes exists only where the load is).
  1204. fn anywhere(&self, source: &Source) -> bool {
  1205. match source {
  1206. Source::Constant(_) => true,
  1207. Source::Built { address, .. } => address.dynamic.is_none(),
  1208. Source::Loaded { load, .. } => {
  1209. let inst = self.inst(*load);
  1210. match &inst.fields {
  1211. Fields::Smem {
  1212. base,
  1213. offset,
  1214. soffset,
  1215. ..
  1216. } => self
  1217. .smem_address(inst, base, *offset, soffset)
  1218. .is_ok_and(|a| a.dynamic.is_none()),
  1219. _ => false,
  1220. }
  1221. }
  1222. _ => false,
  1223. }
  1224. }
  1225. /// `t` as the lanes that reach the access being traced hold it: through
  1226. /// joins they can have entered by one edge only ([`Self::only_edge`]).
  1227. fn live(&self, mut t: Term) -> Term {
  1228. let (Some(at), Some(lanes)) = (self.at.get(), self.lanes) else {
  1229. return t;
  1230. };
  1231. let mut known = vec![(lanes.reach[at], true)];
  1232. for _ in 0..MAX_JOINS {
  1233. let Term::Value(v) = t else { break };
  1234. let Some((block, i)) = self.phis[v.0 as usize] else {
  1235. break;
  1236. };
  1237. let Some(j) = self.only_edge(block, &mut known) else {
  1238. break;
  1239. };
  1240. t = self.origin(self.p.blocks[block].phis[i].args[j]);
  1241. }
  1242. t
  1243. }
  1244. /// Words that phis of one block join, traced per predecessor (words
  1245. /// defined before the join hold on every edge).
  1246. fn phi(
  1247. &self,
  1248. words: &[Term],
  1249. joins: &mut Vec<usize>,
  1250. known: &mut Known,
  1251. ) -> Result<Option<Source>, &'static str> {
  1252. let phi_of = |w: &Term| match *w {
  1253. Term::Value(v) => self.phis[v.0 as usize],
  1254. Term::Const(_) => None,
  1255. };
  1256. let Some((block, _)) = words.iter().find_map(phi_of) else {
  1257. return Ok(None);
  1258. };
  1259. if words.iter().filter_map(phi_of).any(|(b, _)| b != block) {
  1260. return Err("a descriptor joined in several blocks");
  1261. }
  1262. if joins.contains(&block) {
  1263. return Err("a descriptor that changes in a loop");
  1264. }
  1265. // Each level multiplies the sources by the predecessor count.
  1266. if joins.len() >= MAX_JOINS {
  1267. return Err("a descriptor joined too often");
  1268. }
  1269. joins.push(block);
  1270. let phis = &self.p.blocks[block].phis;
  1271. let edge = |j: usize| -> Vec<Term> {
  1272. words
  1273. .iter()
  1274. .map(|w| match phi_of(w) {
  1275. Some((_, i)) => self.origin(phis[i].args[j]),
  1276. None => *w,
  1277. })
  1278. .collect()
  1279. };
  1280. let args = (0..self.p.blocks[block].preds.len())
  1281. .map(|j| self.classify(&edge(j), joins, known))
  1282. .collect::<Result<_, _>>();
  1283. let source = match args {
  1284. Ok(args) => Ok(Source::Phi { block, args }),
  1285. // An edge holds no descriptor. With only one edge the lanes
  1286. // that read the descriptor can have come by, it is what the
  1287. // registers hold on that one (a wave that took another edge
  1288. // has no lane left that reads it), if that can be named where
  1289. // it is read.
  1290. Err(e) => match self.only_edge(block, known) {
  1291. Some(j) => match self.classify(&edge(j), joins, known) {
  1292. Ok(source) if self.anywhere(&source) => Ok(source),
  1293. _ => Err(e),
  1294. },
  1295. None => Err(e),
  1296. },
  1297. };
  1298. joins.pop();
  1299. source.map(Some)
  1300. }
  1301. /// Words that `s_cselect` (or `s_cmov`) picks by one SCC value, traced
  1302. /// per outcome (other words are the same for both).
  1303. fn select(
  1304. &self,
  1305. words: &[Term],
  1306. joins: &mut Vec<usize>,
  1307. known: &mut Known,
  1308. ) -> Result<Option<Source>, &'static str> {
  1309. let picks: Vec<_> = words
  1310. .iter()
  1311. .map(|w| match *w {
  1312. Term::Value(v) => self.picked(v),
  1313. Term::Const(_) => None,
  1314. })
  1315. .collect();
  1316. let Some(scc) = picks.iter().flatten().map(|p| p.0).next() else {
  1317. return Ok(None);
  1318. };
  1319. if picks.iter().flatten().any(|p| p.0 != scc) {
  1320. return Err("a descriptor chosen by several conditions");
  1321. }
  1322. // Each level doubles the sources; selects count like joins (a
  1323. // marker no block index reaches).
  1324. if joins.len() >= MAX_JOINS {
  1325. return Err("a descriptor joined too often");
  1326. }
  1327. joins.push(usize::MAX);
  1328. let side = |set: bool| -> Vec<Term> {
  1329. words
  1330. .iter()
  1331. .zip(&picks)
  1332. .map(|(w, p)| match p {
  1333. Some((_, t, f)) => {
  1334. if set {
  1335. *t
  1336. } else {
  1337. *f
  1338. }
  1339. }
  1340. None => *w,
  1341. })
  1342. .collect()
  1343. };
  1344. let args = [true, false]
  1345. .into_iter()
  1346. .map(|set| self.classify(&side(set), joins, known))
  1347. .collect::<Result<_, _>>();
  1348. joins.pop();
  1349. Ok(Some(Source::Select { scc, args: args? }))
  1350. }
  1351. /// For `v` written by `s_cselect_b32`/`_b64` or `s_cmov_b32`/`_b64`:
  1352. /// the SCC it reads and the dword it is when SCC is set, then clear.
  1353. fn picked(&self, v: Value) -> Option<(Value, Term, Term)> {
  1354. let inst = self.def(v)?;
  1355. let Fields::Sop { dst, src, .. } = &inst.fields else {
  1356. return None;
  1357. };
  1358. let k = inst.writes.iter().position(|w| w.1 == v)? as u8;
  1359. let wide = match inst.name() {
  1360. "s_cselect_b32" | "s_cmov_b32" => false,
  1361. "s_cselect_b64" | "s_cmov_b64" => true,
  1362. _ => return None,
  1363. };
  1364. // A dword of a 32- or 64-bit operand: 64-bit inline integers are
  1365. // sign-extended; 64-bit literals and float constants are not
  1366. // followed.
  1367. let dword = |op: &Operand| match *op {
  1368. Operand::Scalar { code: NULL, .. } => Some(Term::Const(0)),
  1369. Operand::Scalar { code, .. } => Some(self.origin(inst.read(Reg::S(code + k))?)),
  1370. Operand::Const(c) if !wide => inline(c).map(Term::Const),
  1371. Operand::Const(c @ 128..=208) => {
  1372. let low = inline(c)?;
  1373. Some(Term::Const(if k == 0 {
  1374. low
  1375. } else {
  1376. ((low as i32) >> 31) as u32
  1377. }))
  1378. }
  1379. Operand::Literal(x) if !wide => Some(Term::Const(x)),
  1380. _ => None,
  1381. };
  1382. let set = dword(src.first()?)?;
  1383. let clear = if inst.name().starts_with("s_cmov") {
  1384. dword(dst.as_ref()?)?
  1385. } else {
  1386. dword(src.get(1)?)?
  1387. };
  1388. Some((inst.read(Reg::Scc)?, set, clear))
  1389. }
  1390. /// `v` as some other dword with constant bits set.
  1391. fn set_bits(&self, v: Value) -> Option<(Term, u32)> {
  1392. if let Some((_, [x, Term::Const(bits)] | [Term::Const(bits), x])) =
  1393. self.sop2(v, &["s_or_b32"])
  1394. {
  1395. return Some((x, bits));
  1396. }
  1397. let inst = self.def(v)?;
  1398. let Fields::Sop {
  1399. dst: Some(Operand::Scalar { code, .. }),
  1400. src,
  1401. ..
  1402. } = &inst.fields
  1403. else {
  1404. return None;
  1405. };
  1406. match (inst.name(), self.term(inst, src.first()?)?) {
  1407. ("s_bitset1_b32", Term::Const(bit)) => {
  1408. Some((self.origin(inst.read(Reg::S(*code))?), 1 << (bit & 31)))
  1409. }
  1410. _ => None,
  1411. }
  1412. }
  1413. /// The words of a buffer descriptor that `words` makes raw, as the
  1414. /// FidelityFX upscaler's compiler does before byte accesses: the stride
  1415. /// (dword 1 bits 16-29) cleared, the record count times max(stride, 1),
  1416. /// out-of-bounds checking by bytes (dword 3 bits 28-29 set). The bounds
  1417. /// are then the view's size in bytes either way.
  1418. fn made_raw(&self, words: &[Term]) -> Option<[Term; 4]> {
  1419. let [w0, Term::Value(w1), Term::Value(w2), Term::Value(w3)] = *words else {
  1420. return None;
  1421. };
  1422. // `x op c` with `c` either side.
  1423. let with = |v: Value, name: &str, c: u32| match self.sop2(v, &[name])?.1 {
  1424. [x, Term::Const(k)] | [Term::Const(k), x] if k == c => Some(x),
  1425. _ => None,
  1426. };
  1427. let d1 = with(w1, "s_and_b32", 0xC000_FFFF)?;
  1428. let Term::Value(m3) = with(w3, "s_or_b32", 0x3000_0000)? else {
  1429. return None;
  1430. };
  1431. let d3 = with(m3, "s_and_b32", 0xCFFF_FFFF)?;
  1432. let [a, b] = self.sop2(w2, &["s_mul_i32"])?.1;
  1433. let max = |t: Term| match t {
  1434. Term::Value(s) => with(s, "s_max_u32", 1),
  1435. Term::Const(_) => None,
  1436. };
  1437. let (d2, field) = match (max(a), max(b)) {
  1438. (_, Some(f)) => (a, f),
  1439. (Some(f), None) => (b, f),
  1440. (None, None) => return None,
  1441. };
  1442. let Term::Value(field) = field else {
  1443. return None;
  1444. };
  1445. // s_bfe_u32: offset 16, width 14.
  1446. let (_, [x, Term::Const(0x000E_0010)]) = self.sop2(field, &["s_bfe_u32"])? else {
  1447. return None;
  1448. };
  1449. (x == d1).then_some([w0, d1, d2, d3])
  1450. }
  1451. /// For a `v_readfirstlane_b32` result: the VGPR value it reads.
  1452. fn first_lane_source(&self, v: Value) -> Option<Value> {
  1453. let inst = self.def(v)?;
  1454. let Fields::Valu(f) = &inst.fields else {
  1455. return None;
  1456. };
  1457. if inst.name() != "v_readfirstlane_b32" || f.sdwa.is_some() || f.dpp.is_some() {
  1458. return None;
  1459. }
  1460. let Some(&Operand::Vector { reg, .. }) = f.src.first() else {
  1461. return None;
  1462. };
  1463. inst.read(Reg::V(reg))
  1464. }
  1465. /// The `v_readfirstlane_b32` result the scalar load at `load` adds to
  1466. /// its address as a table offset (the console's waterfall,
  1467. /// `s_load_dwordx8 .., s[4:5], s20`): `track` proves the waterfall from
  1468. /// it, and lowering reads it per lane there.
  1469. fn first_lane_offset(&self, load: Site) -> Option<Value> {
  1470. let inst = self.inst(load);
  1471. let Fields::Smem {
  1472. base,
  1473. offset,
  1474. soffset,
  1475. ..
  1476. } = &inst.fields
  1477. else {
  1478. return None;
  1479. };
  1480. self.read_first_lane.set(true);
  1481. let address = self.smem_address(inst, base, *offset, soffset);
  1482. self.read_first_lane.set(false);
  1483. match self.origin(address.ok()?.dynamic?) {
  1484. Term::Value(v) if self.first_lane_source(v).is_some() => Some(v),
  1485. _ => None,
  1486. }
  1487. }
  1488. /// Whether the descriptor operand `op` of `inst` is one the code keeps
  1489. /// per lane ([`Self::lane_copies`]).
  1490. fn kept_per_lane(&self, inst: &Inst, op: &Operand) -> bool {
  1491. let Operand::Scalar { code, dwords } = *op else {
  1492. return false;
  1493. };
  1494. (0..dwords)
  1495. .map(|k| inst.read(Reg::S(code + k)).map(|v| self.origin(v)))
  1496. .collect::<Option<Vec<_>>>()
  1497. .is_some_and(|words| self.lane_copies(&words).is_some())
  1498. }
  1499. /// The `v_readfirstlane_b32` results the descriptor operand `op` of
  1500. /// `inst` is, when every dword is one.
  1501. fn first_lane_words(&self, inst: &Inst, op: &Operand) -> Option<Vec<Value>> {
  1502. let Operand::Scalar { code, dwords } = *op else {
  1503. return None;
  1504. };
  1505. (0..dwords)
  1506. .map(|k| match self.origin(inst.read(Reg::S(code + k))?) {
  1507. Term::Value(v) => self.first_lane_source(v).map(|_| v),
  1508. Term::Const(_) => None,
  1509. })
  1510. .collect()
  1511. }
  1512. /// `t` through VGPR copies (of VGPRs or of scalars) and copies.
  1513. fn lane_term(&self, mut t: Term) -> Term {
  1514. for _ in 0..MAX_JOINS * 2 {
  1515. let Term::Value(v) = t else { break };
  1516. let next = self.vorigin(v);
  1517. if next == t {
  1518. break;
  1519. }
  1520. t = next;
  1521. }
  1522. t
  1523. }
  1524. /// Whether `t` is a value each lane holds its own of (one in VGPRs).
  1525. fn varies(&self, t: Term) -> bool {
  1526. let Term::Value(v) = t else { return false };
  1527. let reg = match (self.inputs[v.0 as usize], self.phis[v.0 as usize]) {
  1528. (Some(reg), _) => Some(reg),
  1529. (None, Some((b, i))) => Some(self.p.blocks[b].phis[i].reg),
  1530. (None, None) => self
  1531. .def(v)
  1532. .and_then(|i| i.writes.iter().find(|w| w.1 == v))
  1533. .map(|w| w.0),
  1534. };
  1535. matches!(reg, Some(Reg::V(_)))
  1536. }
  1537. /// [`Self::lane_term`], where every lane in `known` runs each VGPR copy
  1538. /// it follows.
  1539. fn lane_value(&self, mut t: Term, known: &Known) -> Result<Term, &'static str> {
  1540. for _ in 0..MAX_JOINS * 2 {
  1541. let Term::Value(v) = t else { break };
  1542. let next = self.vstep(v);
  1543. if next == t {
  1544. break;
  1545. }
  1546. if self.varies(t)
  1547. && let Some(site) = self.defs[v.0 as usize]
  1548. {
  1549. self.runs(site, known)?;
  1550. }
  1551. t = next;
  1552. }
  1553. Ok(t)
  1554. }
  1555. /// One copy of [`Self::vorigin`]: what the `v_mov_b32` writing `v`
  1556. /// reads, or `v`'s origin.
  1557. fn vstep(&self, v: Value) -> Term {
  1558. if let Some(inst) = self.def(v)
  1559. && inst.name() == "v_mov_b32"
  1560. && let Fields::Valu(f) = &inst.fields
  1561. && f.abs == 0
  1562. && f.neg == 0
  1563. && f.sdwa.is_none()
  1564. && f.dpp.is_none()
  1565. && let Some(t) = f.src.first().and_then(|s| self.raw(inst, s))
  1566. {
  1567. return t;
  1568. }
  1569. self.origin(v)
  1570. }
  1571. /// A VALU operand as `inst` reads it: a VGPR's value itself, other
  1572. /// operands' origins.
  1573. fn raw(&self, inst: &Inst, op: &Operand) -> Option<Term> {
  1574. match *op {
  1575. Operand::Vector { reg, .. } => Some(Term::Value(inst.read(Reg::V(reg))?)),
  1576. op => self.term(inst, &op),
  1577. }
  1578. }
  1579. /// Fails unless every lane in `known` that reaches the vector
  1580. /// instruction at `site` runs it: one with its EXEC bit clear there
  1581. /// keeps what the registers held before.
  1582. fn runs(&self, site: Site, known: &Known) -> Result<(), &'static str> {
  1583. let Some(lanes) = self.lanes else {
  1584. return Ok(());
  1585. };
  1586. let Some(&Some(guard)) = lanes.guards.get(site.0).and_then(|g| g.get(site.1)) else {
  1587. return Ok(());
  1588. };
  1589. let mut skips = known.clone();
  1590. skips.extend([(lanes.reach[site.0], true), (guard, false)]);
  1591. if self.meet(lanes, &skips) {
  1592. return Err("a per-lane descriptor written where some lanes may keep the old one");
  1593. }
  1594. Ok(())
  1595. }
  1596. /// The source of descriptor dwords each lane holds its own of (a
  1597. /// waterfall loop reads them from the first active lane): the same in
  1598. /// every lane, loaded per lane from memory a heap address points to, or
  1599. /// picked per lane between such sources, by a lane mask or by the path
  1600. /// the lane took. `known` holds in every lane that accesses them.
  1601. fn per_lane(
  1602. &self,
  1603. words: &[Term],
  1604. joins: &mut Vec<usize>,
  1605. known: &mut Known,
  1606. ) -> Result<Source, &'static str> {
  1607. let words = words
  1608. .iter()
  1609. .map(|&w| self.lane_value(w, known))
  1610. .collect::<Result<Vec<_>, _>>()?;
  1611. let words = &words[..];
  1612. let Some(&lane) = words.iter().find(|&&w| self.varies(w)) else {
  1613. return self.classify(words, joins, known);
  1614. };
  1615. if let Some(source) = self.fetched(words, known)? {
  1616. return Ok(source);
  1617. }
  1618. if let Some(source) = self.lane_select(words, joins, known)? {
  1619. return Ok(source);
  1620. }
  1621. if let Some(source) = self.lane_phi(words, joins, known)? {
  1622. return Ok(source);
  1623. }
  1624. let Term::Value(v) = lane else { unreachable!() };
  1625. let name = self.def(v).map(|i| i.name());
  1626. Err(match name {
  1627. _ if self.inputs[v.0 as usize].is_some() => {
  1628. "a descriptor read from the first lane of an input VGPR"
  1629. }
  1630. None => "a descriptor read from the first lane of a phi",
  1631. Some(n) if n.starts_with("ds_read") => {
  1632. "a descriptor read from the first lane of an LDS read"
  1633. }
  1634. Some(n) if n.starts_with("buffer_load") => {
  1635. "a descriptor read from the first lane of a buffer load"
  1636. }
  1637. Some(n) if n.starts_with("global_load") || n.starts_with("flat_load") => {
  1638. "a descriptor read from the first lane of a partial or mixed load"
  1639. }
  1640. Some(_) => "a descriptor read from the first lane of computed VGPRs",
  1641. })
  1642. }
  1643. /// Dwords of `global_load_dword*` that line up: `first..` of one load,
  1644. /// then the bytes that follow (an image descriptor takes two
  1645. /// `global_load_dwordx4`).
  1646. fn fetched(&self, words: &[Term], known: &Known) -> Result<Option<Source>, &'static str> {
  1647. let at = |w: &Term| -> Option<(Site, usize)> {
  1648. let Term::Value(v) = *w else { return None };
  1649. let site = self.defs[v.0 as usize]?;
  1650. let inst = self.inst(site);
  1651. if !inst.name().starts_with("global_load_dword") {
  1652. return None;
  1653. }
  1654. let k = inst
  1655. .writes
  1656. .iter()
  1657. .filter(|w| matches!(w.0, Reg::V(_)))
  1658. .position(|w| w.1 == v)?;
  1659. Some((site, k))
  1660. };
  1661. let Some(sites) = words.iter().map(at).collect::<Option<Vec<_>>>() else {
  1662. return Ok(None);
  1663. };
  1664. let address = |site: Site| {
  1665. let inst = self.inst(site);
  1666. let Fields::Flat {
  1667. addr,
  1668. saddr,
  1669. offset,
  1670. ..
  1671. } = &inst.fields
  1672. else {
  1673. return Err("a global load");
  1674. };
  1675. self.flat_address(inst, addr.as_ref(), saddr.as_ref(), *offset)
  1676. };
  1677. let (load, first) = sites[0];
  1678. let a0 = address(load)?;
  1679. for (k, &(site, dword)) in sites.iter().enumerate() {
  1680. self.runs(site, known)?;
  1681. let a = address(site)?;
  1682. let want = a0.offset.wrapping_add(4 * (first + k) as u32);
  1683. if (a.param, a.dynamic) != (a0.param, a0.dynamic)
  1684. || a.offset.wrapping_add(4 * dword as u32) != want
  1685. {
  1686. return Err("a descriptor read from the first lane of loads that do not line up");
  1687. }
  1688. }
  1689. Ok(Some(Source::Fetched {
  1690. load,
  1691. first: first as u8,
  1692. }))
  1693. }
  1694. /// Words that `v_cndmask_b32` picks by one lane mask, traced per outcome
  1695. /// (other words are the same for both).
  1696. fn lane_select(
  1697. &self,
  1698. words: &[Term],
  1699. joins: &mut Vec<usize>,
  1700. known: &mut Known,
  1701. ) -> Result<Option<Source>, &'static str> {
  1702. let picks: Vec<_> = words
  1703. .iter()
  1704. .map(|w| match *w {
  1705. Term::Value(v) => self.lane_picked(v),
  1706. Term::Const(_) => None,
  1707. })
  1708. .collect();
  1709. let Some(mask) = picks.iter().flatten().map(|p| p.0).next() else {
  1710. return Ok(None);
  1711. };
  1712. if picks.iter().flatten().any(|p| p.0 != mask) {
  1713. return Err("a descriptor chosen per lane by several masks");
  1714. }
  1715. for (w, p) in words.iter().zip(&picks) {
  1716. if let (Term::Value(v), Some(_)) = (*w, p)
  1717. && let Some(site) = self.defs[v.0 as usize]
  1718. {
  1719. self.runs(site, known)?;
  1720. }
  1721. }
  1722. if joins.len() >= MAX_JOINS {
  1723. return Err("a descriptor joined too often");
  1724. }
  1725. joins.push(usize::MAX);
  1726. // Each side holds where the lane's bit of the mask is set, or clear.
  1727. let bit = self.lanes.and_then(|l| l.masks.get(&mask).copied());
  1728. let side = |set: bool| -> Vec<Term> {
  1729. words
  1730. .iter()
  1731. .zip(&picks)
  1732. .map(|(w, p)| match p {
  1733. Some((_, t, f)) => {
  1734. if set {
  1735. *t
  1736. } else {
  1737. *f
  1738. }
  1739. }
  1740. None => *w,
  1741. })
  1742. .collect()
  1743. };
  1744. let args = [true, false]
  1745. .into_iter()
  1746. .map(|set| {
  1747. let n = known.len();
  1748. known.extend(bit.map(|b| (b, set)));
  1749. let arg = self.per_lane(&side(set), joins, known);
  1750. known.truncate(n);
  1751. arg
  1752. })
  1753. .collect::<Result<_, _>>();
  1754. joins.pop();
  1755. Ok(Some(Source::Lanes { mask, args: args? }))
  1756. }
  1757. /// For `v` written by a plain `v_cndmask_b32`: the low dword of the
  1758. /// lane mask it reads, and the dword it is where the lane's bit is set
  1759. /// (src1), then clear (src0).
  1760. fn lane_picked(&self, v: Value) -> Option<(Value, Term, Term)> {
  1761. let inst = self.def(v)?;
  1762. let Fields::Valu(f) = &inst.fields else {
  1763. return None;
  1764. };
  1765. let Some(Operand::Vector { reg, .. }) = f.dst else {
  1766. return None;
  1767. };
  1768. if inst.name() != "v_cndmask_b32"
  1769. || inst.write(Reg::V(reg)) != Some(v)
  1770. || f.abs != 0
  1771. || f.neg != 0
  1772. || f.clamp
  1773. || f.omod != 0
  1774. || f.sdwa.is_some()
  1775. || f.dpp.is_some()
  1776. {
  1777. return None;
  1778. }
  1779. let [clear, set, Operand::Scalar { code, .. }] = f.src[..] else {
  1780. return None;
  1781. };
  1782. let mask = inst.read(Reg::S(code))?;
  1783. Some((mask, self.raw(inst, &set)?, self.raw(inst, &clear)?))
  1784. }
  1785. /// Per-lane words that phis of one block join, as an if/else on a
  1786. /// per-lane condition leaves them: traced on each edge into the block
  1787. /// that lanes in `known` can take (other words hold on every edge).
  1788. /// Lanes take their own paths ([`Structured`]), so each gets the value
  1789. /// of the edge it came by; an edge they cannot take is `None` (a flow
  1790. /// block's phi joins an arm's dwords with what lanes that skipped the
  1791. /// arm held before, which only they read).
  1792. fn lane_phi(
  1793. &self,
  1794. words: &[Term],
  1795. joins: &mut Vec<usize>,
  1796. known: &mut Known,
  1797. ) -> Result<Option<Source>, &'static str> {
  1798. let phi_of = |w: &Term| match *w {
  1799. Term::Value(v) => self.phis[v.0 as usize],
  1800. Term::Const(_) => None,
  1801. };
  1802. let Some((block, _)) = words.iter().find_map(phi_of) else {
  1803. return Ok(None);
  1804. };
  1805. if words.iter().filter_map(phi_of).any(|(b, _)| b != block) {
  1806. return Err("a descriptor joined in several blocks");
  1807. }
  1808. if joins.contains(&block) {
  1809. return Err("a descriptor that changes in a loop");
  1810. }
  1811. let preds = &self.p.blocks[block].preds;
  1812. if preds.iter().any(|&q| self.rpo[q] >= self.rpo[block]) {
  1813. // shortcut: what a lane holds after some passes is not traced.
  1814. return Err("a descriptor read from the first lane of a phi at a loop header");
  1815. }
  1816. let Some(lanes) = self.lanes else {
  1817. return Err("a descriptor read from the first lane of a phi, without the lanes' paths");
  1818. };
  1819. // The other words must be there before the join: defined in a
  1820. // block that dominates it, which (both dominating the access) is
  1821. // one the join does not reach.
  1822. for w in words {
  1823. if let Term::Value(v) = *w
  1824. && phi_of(w).is_none()
  1825. && let Some((d, _)) = self.defs[v.0 as usize]
  1826. && (d == block || self.reaches(block, d))
  1827. {
  1828. return Err("a descriptor partly joined by control flow");
  1829. }
  1830. }
  1831. if joins.len() >= MAX_JOINS {
  1832. return Err("a descriptor joined too often");
  1833. }
  1834. joins.push(block);
  1835. let phis = &self.p.blocks[block].phis;
  1836. let mut args = Vec::new();
  1837. for (j, &q) in preds.iter().enumerate() {
  1838. let n = known.len();
  1839. known.push((lanes.reach[q], true));
  1840. if let LaneExit::Branch {
  1841. when,
  1842. taken,
  1843. not_taken,
  1844. } = lanes.exits[q]
  1845. && taken != not_taken
  1846. {
  1847. known.push((when, taken == block));
  1848. }
  1849. let arg = if self.meet(lanes, known) {
  1850. let edge: Vec<Term> = words
  1851. .iter()
  1852. .map(|w| match phi_of(w) {
  1853. Some((_, i)) => Term::Value(phis[i].args[j]),
  1854. None => *w,
  1855. })
  1856. .collect();
  1857. self.per_lane(&edge, joins, known).map(Some)
  1858. } else {
  1859. Ok(None)
  1860. };
  1861. known.truncate(n);
  1862. match arg {
  1863. Ok(a) => args.push(a),
  1864. Err(e) => {
  1865. joins.pop();
  1866. return Err(e);
  1867. }
  1868. }
  1869. }
  1870. joins.pop();
  1871. Ok(Some(Source::LanePhi { block, args }))
  1872. }
  1873. /// Whether a path leads from block `from` to block `to` (to `from`
  1874. /// itself only through a back edge).
  1875. fn reaches(&self, from: usize, to: usize) -> bool {
  1876. let mut seen = vec![false; self.p.blocks.len()];
  1877. let mut stack = self.p.blocks[from].exit.successors();
  1878. while let Some(x) = stack.pop() {
  1879. if x == to {
  1880. return true;
  1881. }
  1882. if std::mem::replace(&mut seen[x], true) {
  1883. continue;
  1884. }
  1885. stack.extend(self.p.blocks[x].exit.successors());
  1886. }
  1887. false
  1888. }
  1889. /// Prove a single-block waterfall at the descriptor access. In each
  1890. /// iteration the access serves exactly the matching lanes, and the
  1891. /// back edge keeps exactly the other lanes active. Otherwise, why not.
  1892. ///
  1893. // shortcut: only the accesses are proven. Any other per-lane work in the
  1894. // loop is taken to run once for each lane, as the access does; a body
  1895. // whose effect adds up over the passes a lane waits through (a counter
  1896. // before the mask is narrowed) would differ. Compilers put nothing but
  1897. // the reads, the compares and the access in these loops.
  1898. fn waterfall(
  1899. &self,
  1900. b: usize,
  1901. accesses: &[usize],
  1902. reads: &[Value],
  1903. ) -> Result<Waterfall, &'static str> {
  1904. const LOOP: &str = "a descriptor read from the first lane outside a waterfall loop";
  1905. const SPLIT: &str = "a waterfall loop nested in another or split over blocks";
  1906. const SELECT: &str = "a waterfall loop whose compares do not select the access's lanes";
  1907. const RETRY: &str = "a waterfall loop whose retry does not keep the lanes still waiting";
  1908. let access = accesses[0];
  1909. let block = &self.p.blocks[b];
  1910. let lanes = self.lanes.ok_or(LOOP)?;
  1911. let exit = block.insts.last().ok_or(LOOP)?;
  1912. if !matches!(block.exit, Exit::Branch { taken, not_taken } if taken == b && not_taken != b)
  1913. || exit.name() != "s_cbranch_execnz"
  1914. {
  1915. return Err(LOOP);
  1916. }
  1917. let mask = |low: Option<Value>, high: Option<Value>| {
  1918. let high = if self.p.wave64 { Some(high?) } else { None };
  1919. lanes.mask_bits(low?, high)
  1920. };
  1921. let exec = |inst: &Inst| mask(inst.read(Reg::S(EXEC)), inst.read(Reg::S(EXEC + 1)));
  1922. // The reads belong to this loop's own block: a loop around this one
  1923. // (one per operand, as LLVM nests them for a per-lane image and
  1924. // sampler) is not followed.
  1925. if reads
  1926. .iter()
  1927. .any(|v| self.defs[v.0 as usize].is_none_or(|at| at.0 != b))
  1928. {
  1929. return Err(SPLIT);
  1930. }
  1931. let selected = exec(&block.insts[access]).ok_or(SELECT)?;
  1932. if accesses
  1933. .iter()
  1934. .any(|&i| exec(&block.insts[i]) != Some(selected))
  1935. {
  1936. return Err(SELECT);
  1937. }
  1938. let retry = exec(exit).ok_or(RETRY)?;
  1939. let first = self.defs[reads[0].0 as usize].ok_or(LOOP)?;
  1940. let remaining = exec(self.inst(first)).ok_or(SELECT)?;
  1941. if reads.iter().any(|v| {
  1942. self.defs[v.0 as usize]
  1943. .is_none_or(|at| at.1 >= access || exec(self.inst(at)) != Some(remaining))
  1944. }) {
  1945. return Err(SELECT);
  1946. }
  1947. let reach = (lanes.reach[b], true);
  1948. let meet = |conditions: &[(Bool, bool)]| self.meet(lanes, conditions);
  1949. let mut out = Waterfall::default();
  1950. let mut required = vec![(remaining, true)];
  1951. for (i, inst) in block.insts[..access].iter().enumerate() {
  1952. let Fields::Valu(f) = &inst.fields else {
  1953. continue;
  1954. };
  1955. let Some(ty) = inst
  1956. .name()
  1957. .strip_prefix("v_cmp_eq_")
  1958. .or(inst.name().strip_prefix("v_cmpx_eq_"))
  1959. else {
  1960. continue;
  1961. };
  1962. let dwords = match ty {
  1963. "u32" | "i32" => 1,
  1964. "u64" | "i64" => 2,
  1965. _ => continue,
  1966. };
  1967. if f.abs != 0 || f.neg != 0 || f.sdwa.is_some() || f.dpp.is_some() {
  1968. continue;
  1969. }
  1970. // The first lane's dwords on one side, the lane's own on the
  1971. // other.
  1972. let pair = |first: &Operand, own: &Operand| -> Option<Vec<Value>> {
  1973. let (&Operand::Scalar { code, .. }, &Operand::Vector { reg, .. }) = (first, own)
  1974. else {
  1975. return None;
  1976. };
  1977. (0..dwords)
  1978. .map(|k| {
  1979. let Term::Value(x) = self.origin(inst.read(Reg::S(code + k))?) else {
  1980. return None;
  1981. };
  1982. let lane = inst.read(Reg::V(reg + k))?;
  1983. let (_, read) = self.defs[x.0 as usize]?;
  1984. let same = reads.contains(&x)
  1985. && read < i
  1986. && self.lane_term(Term::Value(self.first_lane_source(x)?))
  1987. == self.lane_term(Term::Value(lane));
  1988. same.then_some(x)
  1989. })
  1990. .collect()
  1991. };
  1992. let (Some(a), Some(c)) = (f.src.first(), f.src.get(1)) else {
  1993. continue;
  1994. };
  1995. if let Some(xs) = pair(a, c).or_else(|| pair(c, a)) {
  1996. let code = if inst.name().starts_with("v_cmpx_") {
  1997. EXEC
  1998. } else if let Some(Operand::Scalar { code, .. }) = f.dst {
  1999. code
  2000. } else {
  2001. continue;
  2002. };
  2003. let Some(matched) = mask(inst.write(Reg::S(code)), inst.write(Reg::S(code + 1))) else {
  2004. continue;
  2005. };
  2006. if meet(&[reach, (selected, true), (matched, false)]) {
  2007. continue;
  2008. }
  2009. required.push((matched, true));
  2010. out.compares.push((b, i));
  2011. for x in xs {
  2012. if !out.reads.contains(&x) {
  2013. out.reads.push(x);
  2014. }
  2015. }
  2016. }
  2017. }
  2018. if reads.iter().any(|v| !out.reads.contains(v))
  2019. || meet(&[reach, (selected, true), (remaining, false)])
  2020. {
  2021. return Err(SELECT);
  2022. }
  2023. // The access must take every match.
  2024. required.extend([reach, (selected, false)]);
  2025. if meet(&required) {
  2026. return Err(SELECT);
  2027. }
  2028. // The retry must keep exactly the lanes that were eligible but did
  2029. // not perform the access.
  2030. if meet(&[reach, (retry, true), (remaining, false)])
  2031. || meet(&[reach, (retry, true), (selected, true)])
  2032. || meet(&[reach, (remaining, true), (selected, false), (retry, false)])
  2033. {
  2034. return Err(RETRY);
  2035. }
  2036. Ok(out)
  2037. }
  2038. /// Consecutive dwords of one scalar load.
  2039. fn loaded(&self, words: &[Term]) -> Option<Source> {
  2040. let Term::Value(v0) = words[0] else {
  2041. return None;
  2042. };
  2043. let load = self.defs[v0.0 as usize]?;
  2044. let inst = self.inst(load);
  2045. if !inst.name().starts_with("s_load_") {
  2046. return None;
  2047. }
  2048. let first = inst.writes.iter().position(|w| w.1 == v0)?;
  2049. let same = words.iter().enumerate().all(|(k, w)| {
  2050. inst.writes
  2051. .get(first + k)
  2052. .is_some_and(|x| *w == Term::Value(x.1))
  2053. });
  2054. same.then_some(Source::Loaded {
  2055. load,
  2056. first: first as u8,
  2057. })
  2058. }
  2059. /// A descriptor the code keeps per lane: every dword of `words` is the
  2060. /// first lane (`v_readfirstlane_b32`) of a VGPR that `v_mov_b32` filled
  2061. /// from SGPRs. The console compiler does this to a descriptor loaded on
  2062. /// both sides of a per-lane branch: the join is per lane, so it lives in
  2063. /// VGPRs, and the instruction that needs it in SGPRs runs in a loop over
  2064. /// the distinct values (the first lane's, the lanes holding the same,
  2065. /// then the rest). When every scalar those moves copy is the same dword
  2066. /// of loads from one constant address, the lanes agree and the
  2067. /// descriptor is any of those loads.
  2068. // shortcut: what else the VGPRs held (numbers, on paths or in lanes that
  2069. // never read them as a descriptor) is ignored, and a move is taken to
  2070. // leave either its source or what a move before it wrote; a descriptor
  2071. // read per lane from memory (`global_load_*`) refuses.
  2072. fn lane_copies(&self, words: &[Term]) -> Option<Source> {
  2073. let mut loads: Vec<Site> = Vec::new();
  2074. let mut first = None;
  2075. for (k, w) in words.iter().enumerate() {
  2076. let Term::Value(v) = *w else { return None };
  2077. let mut copies = Vec::new();
  2078. if !self.scalar_copies(self.first_lane(v)?, &mut copies) {
  2079. return None;
  2080. }
  2081. let mut found = false;
  2082. for c in copies {
  2083. let Term::Value(c) = c else { continue };
  2084. let Some(site) = self.defs[c.0 as usize] else {
  2085. continue;
  2086. };
  2087. let load = self.inst(site);
  2088. if !load.name().starts_with("s_load_") {
  2089. continue;
  2090. }
  2091. // Dword k of the operand is dword `first + k` of each load.
  2092. let dword = load.writes.iter().position(|x| x.1 == c)?;
  2093. let f = dword.checked_sub(k)?;
  2094. if *first.get_or_insert(f) != f {
  2095. return None;
  2096. }
  2097. if !loads.contains(&site) {
  2098. loads.push(site);
  2099. }
  2100. found = true;
  2101. }
  2102. if !found {
  2103. return None;
  2104. }
  2105. }
  2106. let address = |site: Site| {
  2107. let inst = self.inst(site);
  2108. match &inst.fields {
  2109. Fields::Smem {
  2110. base,
  2111. offset,
  2112. soffset,
  2113. ..
  2114. } => self.smem_address(inst, base, *offset, soffset).ok(),
  2115. _ => None,
  2116. }
  2117. };
  2118. let a = address(*loads.first()?)?;
  2119. if a.dynamic.is_some() || loads.iter().any(|&l| address(l) != Some(a)) {
  2120. return None;
  2121. }
  2122. // The handle is made where the descriptor is used, from the load's
  2123. // operands: take a load whose base is the root parameter's own SGPR.
  2124. loads.sort_unstable();
  2125. let load = *loads.iter().find(|&&l| self.base_from_entry(l))?;
  2126. self.lane_copied.borrow_mut().extend(&loads);
  2127. Some(Source::Loaded {
  2128. load,
  2129. first: first? as u8,
  2130. })
  2131. }
  2132. /// The scalars (as origins) that `v_mov_b32` copies put in VGPR value
  2133. /// `v`, through joins, moves between VGPRs and per-lane selects; a move
  2134. /// keeps what it wrote over in the lanes it does not run. False if the
  2135. /// VGPR may hold something read per lane from memory.
  2136. fn scalar_copies(&self, v: Value, out: &mut Vec<Term>) -> bool {
  2137. let (mut seen, mut work) = (Vec::new(), vec![v]);
  2138. while let Some(v) = work.pop() {
  2139. if seen.contains(&v) {
  2140. continue;
  2141. }
  2142. if seen.len() == MAX_COPIES {
  2143. return false;
  2144. }
  2145. seen.push(v);
  2146. if let Some((b, i)) = self.phis[v.0 as usize] {
  2147. work.extend(&self.p.blocks[b].phis[i].args);
  2148. continue;
  2149. }
  2150. // An entry value, or a number some instruction computed.
  2151. let Some(inst) = self.def(v) else { continue };
  2152. if inst.name().starts_with("global_load_") {
  2153. return false;
  2154. }
  2155. let Fields::Valu(f) = &inst.fields else {
  2156. continue;
  2157. };
  2158. let sources = match inst.name() {
  2159. "v_mov_b32" => 1,
  2160. "v_cndmask_b32" => 2,
  2161. _ => continue,
  2162. };
  2163. if f.abs != 0 || f.neg != 0 || f.sdwa.is_some() || f.dpp.is_some() {
  2164. continue;
  2165. }
  2166. for op in f.src.iter().take(sources) {
  2167. match *op {
  2168. Operand::Vector { reg, .. } => work.extend(inst.read(Reg::V(reg))),
  2169. Operand::Scalar { code, .. } if code != NULL => {
  2170. out.extend(inst.read(Reg::S(code)).map(|s| self.origin(s)));
  2171. }
  2172. _ => {}
  2173. }
  2174. }
  2175. // Lanes outside EXEC keep the old value.
  2176. if let Some(Operand::Vector { reg, .. }) = f.dst {
  2177. work.extend(inst.read(Reg::V(reg)));
  2178. }
  2179. }
  2180. true
  2181. }
  2182. /// The load at `site` has a constant offset and takes its base from a
  2183. /// root parameter's SGPR through moves alone: a value that exists
  2184. /// wherever the descriptor is used.
  2185. fn base_from_entry(&self, site: Site) -> bool {
  2186. let inst = self.inst(site);
  2187. let Fields::Smem {
  2188. base: Operand::Scalar { code, .. },
  2189. soffset: Operand::Scalar { code: NULL, .. },
  2190. ..
  2191. } = &inst.fields
  2192. else {
  2193. return false;
  2194. };
  2195. let Some(mut v) = inst.read(Reg::S(*code)) else {
  2196. return false;
  2197. };
  2198. loop {
  2199. if self.inputs[v.0 as usize].is_some() {
  2200. return true;
  2201. }
  2202. let Some(def) = self.def(v) else { return false };
  2203. let Some(k) = def.writes.iter().position(|w| w.1 == v) else {
  2204. return false;
  2205. };
  2206. match copy_source(def, k) {
  2207. Some(Moved::Value(s)) => v = s,
  2208. _ => return false,
  2209. }
  2210. }
  2211. }
  2212. }
  2213. #[derive(Clone, Copy, PartialEq, Eq)]
  2214. enum Moved {
  2215. Const(u32),
  2216. Value(Value),
  2217. }
  2218. impl Tracer<'_> {
  2219. /// For `v_readlane_b32` of a constant lane: the SGPR spilled to that
  2220. /// lane, found by following the VGPR's `v_writelane_b32` writes.
  2221. fn restored(&self, inst: &Inst) -> Option<Moved> {
  2222. let Fields::Valu(v) = &inst.fields else {
  2223. return None;
  2224. };
  2225. if inst.name() != "v_readlane_b32" {
  2226. return None;
  2227. }
  2228. let [Operand::Vector { reg, .. }, lane] = v.src[..] else {
  2229. return None;
  2230. };
  2231. self.spilled(inst.read(Reg::V(reg))?, lane_of(lane)?, &mut Vec::new())
  2232. .ok()
  2233. .flatten()
  2234. }
  2235. /// What lane `lane` of VGPR value `v` holds: `Ok(None)` for a phi in
  2236. /// `seen` (already being resolved), `Err` if not a spilled SGPR.
  2237. fn spilled(&self, v: Value, lane: u32, seen: &mut Vec<Value>) -> Result<Option<Moved>, ()> {
  2238. if let Some((b, i)) = self.phis[v.0 as usize] {
  2239. if seen.contains(&v) {
  2240. return Ok(None);
  2241. }
  2242. seen.push(v);
  2243. let mut found = None;
  2244. for &a in &self.p.blocks[b].phis[i].args {
  2245. if let Some(m) = self.spilled(a, lane, seen)? {
  2246. if found.is_some_and(|f| f != m) {
  2247. return Err(());
  2248. }
  2249. found = Some(m);
  2250. }
  2251. }
  2252. return Ok(found);
  2253. }
  2254. let inst = self.def(v).ok_or(())?;
  2255. let Fields::Valu(w) = &inst.fields else {
  2256. return Err(());
  2257. };
  2258. let (Some(Operand::Vector { reg, .. }), [value, at]) = (w.dst, &w.src[..]) else {
  2259. return Err(());
  2260. };
  2261. if inst.name() != "v_writelane_b32" {
  2262. return Err(());
  2263. }
  2264. if lane_of(*at).ok_or(())? != lane {
  2265. return self.spilled(inst.read(Reg::V(reg)).ok_or(())?, lane, seen);
  2266. }
  2267. match *value {
  2268. Operand::Scalar { code, .. } if code != NULL => {
  2269. inst.read(Reg::S(code)).map(Moved::Value)
  2270. }
  2271. Operand::Literal(x) => Some(Moved::Const(x)),
  2272. Operand::Const(c) => inline(c).map(Moved::Const),
  2273. _ => None,
  2274. }
  2275. .map(Some)
  2276. .ok_or(())
  2277. }
  2278. }
  2279. /// A lane select given as a constant.
  2280. fn lane_of(op: Operand) -> Option<u32> {
  2281. match op {
  2282. Operand::Const(c) => inline(c),
  2283. Operand::Literal(x) => Some(x),
  2284. _ => None,
  2285. }
  2286. }
  2287. /// What dword `k` of a move's result copies.
  2288. fn copy_source(inst: &Inst, k: usize) -> Option<Moved> {
  2289. let Fields::Sop { src, imm, .. } = &inst.fields else {
  2290. return None;
  2291. };
  2292. if inst.name() == "s_movk_i32" {
  2293. return Some(Moved::Const(i32::from((*imm)? as i16) as u32));
  2294. }
  2295. // A mask of S0 bits from bit S1, as the upscaler's compiler makes an
  2296. // immediate sampler's word.
  2297. if let ("s_bfm_b32", 0, [Operand::Const(w), Operand::Const(at)]) = (inst.name(), k, &src[..]) {
  2298. let (w, at) = (inline(*w)? & 31, inline(*at)? & 31);
  2299. return Some(Moved::Const(((1u32 << w) - 1) << at));
  2300. }
  2301. let src = src.first()?;
  2302. match (inst.name(), *src) {
  2303. ("s_mov_b32" | "s_mov_b64", Operand::Scalar { code, .. }) if code != NULL => {
  2304. inst.read(Reg::S(code + k as u8)).map(Moved::Value)
  2305. }
  2306. ("s_mov_b32" | "s_mov_b64", Operand::Scalar { .. }) => Some(Moved::Const(0)),
  2307. ("s_mov_b32", Operand::Literal(x)) => Some(Moved::Const(x)),
  2308. ("s_mov_b32", Operand::Const(c)) => inline(c).map(Moved::Const),
  2309. // shortcut: only the one-operand ways the compiler makes a constant
  2310. // that has no inline form; fold more if descriptors need it.
  2311. ("s_brev_b32", Operand::Const(c)) => inline(c).map(|x| Moved::Const(x.reverse_bits())),
  2312. ("s_not_b32", Operand::Const(c)) => inline(c).map(|x| Moved::Const(!x)),
  2313. // shortcut: a literal below 2^31, whose high dword is 0 whether the
  2314. // hardware extends it with zeros or with its sign.
  2315. ("s_mov_b64", Operand::Literal(x)) if x >> 31 == 0 => {
  2316. Some(Moved::Const(if k == 0 { x } else { 0 }))
  2317. }
  2318. // 64-bit inline integers are sign-extended.
  2319. ("s_mov_b64", Operand::Const(c @ 128..=208)) => {
  2320. let low = inline(c)?;
  2321. Some(Moved::Const(if k == 0 {
  2322. low
  2323. } else {
  2324. ((low as i32) >> 31) as u32
  2325. }))
  2326. }
  2327. _ => None,
  2328. }
  2329. }
  2330. /// The 32-bit value of an inline constant operand.
  2331. pub(crate) fn inline(code: u8) -> Option<u32> {
  2332. let float = |f: f32| Some(f.to_bits());
  2333. match code {
  2334. 128..=192 => Some(u32::from(code) - 128),
  2335. 193..=208 => Some((192 - i32::from(code)) as u32),
  2336. 240 => float(0.5),
  2337. 241 => float(-0.5),
  2338. 242 => float(1.0),
  2339. 243 => float(-1.0),
  2340. 244 => float(2.0),
  2341. 245 => float(-2.0),
  2342. 246 => float(4.0),
  2343. 247 => float(-4.0),
  2344. 248 => Some(0x3E22_F983),
  2345. _ => None,
  2346. }
  2347. }
  2348. #[cfg(test)]
  2349. pub(crate) mod tests {
  2350. use super::*;
  2351. use crate::native::RootType::*;
  2352. const S_ENDPGM: u32 = 0xBF81_0000;
  2353. fn track_words(words: &[u32], layout: &[RootParam], stage: HwStage) -> Resources {
  2354. let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
  2355. let p = crate::ir::build(&code, false, 256).unwrap();
  2356. track(&p, layout, stage, lanes(&p).as_ref()).unwrap()
  2357. }
  2358. /// `p` as one lane runs it, if it structures.
  2359. fn lanes(p: &Program) -> Option<Structured> {
  2360. crate::structure::structure(p).ok()
  2361. }
  2362. fn param(root: RootType, user_data: u8, sgprs: u32) -> RootParam {
  2363. RootParam {
  2364. root,
  2365. table_offset_dwords: 0,
  2366. sgprs,
  2367. base_register: 0,
  2368. user_data,
  2369. slot: 0,
  2370. }
  2371. }
  2372. fn at(param: usize, offset: u32) -> Address {
  2373. Address {
  2374. param,
  2375. offset,
  2376. dynamic: None,
  2377. }
  2378. }
  2379. #[test]
  2380. fn table_descriptors_are_loaded_from_their_range() {
  2381. let r = track_words(
  2382. &[
  2383. 0xBE82_0309, // s_mov_b32 s2, s9
  2384. 0xBE89_0380, // s_mov_b32 s9, 0
  2385. 0xBE83_0380, // s_mov_b32 s3, 0
  2386. 0xF408_0204,
  2387. 0xFA00_0000, // s_load_dwordx4 s[8:11], s[8:9], null
  2388. 0xF40C_0001,
  2389. 0xFA00_0000, // s_load_dwordx8 s[0:7], s[2:3], null
  2390. 0xF080_0F08,
  2391. 0x0040_0002, // image_sample v[0:3], v[2:3], s[0:7], s[8:11]
  2392. S_ENDPGM,
  2393. ],
  2394. &[param(Table, 8, 1), param(Table, 9, 1)],
  2395. HwStage::Ps,
  2396. );
  2397. assert_eq!(r.scalar, [((0, 3), at(0, 0)), ((0, 4), at(1, 0))]);
  2398. let roles: Vec<_> = r.descriptors.iter().map(|d| (d.role, &d.source)).collect();
  2399. assert_eq!(
  2400. roles,
  2401. [
  2402. (
  2403. Role::Resource,
  2404. &Source::Loaded {
  2405. load: (0, 4),
  2406. first: 0
  2407. }
  2408. ),
  2409. (
  2410. Role::Sampler,
  2411. &Source::Loaded {
  2412. load: (0, 3),
  2413. first: 0
  2414. }
  2415. ),
  2416. ]
  2417. );
  2418. }
  2419. #[test]
  2420. fn root_descriptors_are_built_in_code() {
  2421. let r = track_words(
  2422. &[
  2423. 0x8801_FF0B,
  2424. 0x0010_0000, // s_or_b32 s1, s11, 0x100000
  2425. 0xBE80_030A, // s_mov_b32 s0, s10
  2426. 0xBE82_03C1, // s_mov_b32 s2, -1
  2427. 0xBE83_03FF,
  2428. 0x1101_4FAC, // s_mov_b32 s3, 0x11014fac
  2429. 0xF430_0000,
  2430. 0xFA00_0000, // s_buffer_load_dwordx16 s[0:15], s[0:3], null
  2431. S_ENDPGM,
  2432. ],
  2433. &[param(Descriptor, 10, 2)],
  2434. HwStage::Vs,
  2435. );
  2436. assert_eq!(
  2437. r.descriptors[0].source,
  2438. Source::Built {
  2439. address: at(0, 0),
  2440. bits: 0x10_0000,
  2441. words: [u32::MAX, 0x1101_4FAC]
  2442. }
  2443. );
  2444. assert_eq!(
  2445. r.params.iter().map(|p| (p.1, p.2)).collect::<Vec<_>>(),
  2446. [(0, 0), (0, 1)]
  2447. );
  2448. }
  2449. #[test]
  2450. fn heap_indices_from_root_constants_in_a_merged_stage() {
  2451. // User data starts at s8: the constant (index 6) is s14, the heap
  2452. // (index 10) s18.
  2453. let code = [
  2454. 0x8F08_850E, // s_lshl_b32 s8, s14, 5
  2455. 0xBE93_0380, // s_mov_b32 s19, 0
  2456. 0xF408_0209,
  2457. 0x1000_0000, // s_load_dwordx4 s[8:11], s[18:19], s8
  2458. 0xE000_2000,
  2459. 0x8002_0400, // buffer_load_format_x v4, v0, s[8:11], 0 idxen
  2460. S_ENDPGM,
  2461. ];
  2462. let r = track_words(
  2463. &code,
  2464. &[param(Constants, 6, 1), param(ResourceHeap, 10, 1)],
  2465. HwStage::Ms,
  2466. );
  2467. let index = r.params.iter().find(|p| p.1 == 0).unwrap().0;
  2468. let shift = r.scalar[0].1.dynamic.unwrap();
  2469. assert_eq!(r.scalar[0].1.param, 1);
  2470. // The computed term is the shifted constant, not the constant itself.
  2471. assert_ne!(shift, index);
  2472. assert_eq!(
  2473. r.descriptors[0].source,
  2474. Source::Loaded {
  2475. load: (0, 2),
  2476. first: 0
  2477. }
  2478. );
  2479. assert!(r.root_indexed_views.is_empty());
  2480. let table = RootParam {
  2481. slot: 7,
  2482. ..param(Table, 10, 1)
  2483. };
  2484. let indexed = track_words(&code, &[param(Constants, 6, 1), table], HwStage::Ms);
  2485. assert_eq!(
  2486. indexed.root_indexed_views,
  2487. [RootIndexedView {
  2488. table_slot: 7,
  2489. constant_slot: 0,
  2490. constant_dword: 0,
  2491. byte_offset: 0,
  2492. shift: 5,
  2493. }]
  2494. );
  2495. let nonconstant = track_words(&code, &[param(Table, 6, 1), table], HwStage::Ms);
  2496. assert!(nonconstant.root_indexed_views.is_empty());
  2497. }
  2498. #[test]
  2499. fn spilled_sgprs_are_followed_through_vgpr_lanes() {
  2500. let r = track_words(
  2501. &[
  2502. 0xD761_0000,
  2503. 0x0001_0609, // v_writelane_b32 v0, s9, 3
  2504. 0xD760_0002,
  2505. 0x0001_0700, // v_readlane_b32 s2, v0, 3
  2506. 0xBE83_0380, // s_mov_b32 s3, 0
  2507. 0xF40C_0001,
  2508. 0xFA00_0020, // s_load_dwordx8 s[0:7], s[2:3], 0x20
  2509. S_ENDPGM,
  2510. ],
  2511. &[param(Table, 9, 1)],
  2512. HwStage::Ps,
  2513. );
  2514. assert_eq!(r.scalar, [((0, 3), at(0, 0x20))]);
  2515. }
  2516. /// A VGPR a wave reduction used is free again after it: from the first
  2517. /// save on it holds parked scalars alone (an upscaler program parks a
  2518. /// constant buffer's descriptor that way).
  2519. #[test]
  2520. fn a_vgpr_used_before_holds_spilled_sgprs_from_its_first_save() {
  2521. let before = [
  2522. 0x7E00_0281, // v_mov_b32 v0, 1
  2523. 0x7E02_0300, // v_mov_b32 v1, v0
  2524. ];
  2525. let park = [
  2526. 0xD761_0000,
  2527. 0x0001_0609, // v_writelane_b32 v0, s9, 3
  2528. 0xD760_0002,
  2529. 0x0001_0700, // v_readlane_b32 s2, v0, 3
  2530. 0xBE83_0380, // s_mov_b32 s3, 0
  2531. ];
  2532. let load = [
  2533. 0xF40C_0001,
  2534. 0xFA00_0020, // s_load_dwordx8 s[0:7], s[2:3], 0x20
  2535. S_ENDPGM,
  2536. ];
  2537. let words = [&before[..], &park, &load].concat();
  2538. let r = track_words(&words, &[param(Table, 9, 1)], HwStage::Ps);
  2539. assert_eq!(r.scalar, [((0, 5), at(0, 0x20))]);
  2540. // Still lane reads: a lane restored before it is saved, and a
  2541. // register with an ordinary use after the first save.
  2542. let restored_first = [&before[..], &park[2..4], &park[..2], &load].concat();
  2543. let used_after = [&before[..], &park, &before[1..], &load].concat();
  2544. for words in [restored_first, used_after] {
  2545. let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
  2546. let p = crate::ir::build(&code, true, 8).unwrap();
  2547. let insts = p.blocks.iter().flat_map(|b| &b.insts);
  2548. assert_eq!(insts.filter(|i| i.name() == "v_readlane_b32").count(), 1);
  2549. }
  2550. }
  2551. #[test]
  2552. fn descriptors_joined_by_control_flow_are_traced_per_edge() {
  2553. let r = track_words(
  2554. &[
  2555. 0xBE82_0309, // s_mov_b32 s2, s9
  2556. 0xBE83_0380, // s_mov_b32 s3, 0
  2557. 0xBF06_8001, // s_cmp_eq_u32 s1, 0
  2558. 0xBF85_0003, // s_cbranch_scc1 -> 0x1c
  2559. 0xF408_0001,
  2560. 0xFA00_0000, // s_load_dwordx4 s[0:3], s[2:3], null
  2561. 0xBF82_0002, // s_branch -> 0x24
  2562. 0xF408_0001,
  2563. 0xFA00_0010, // 0x1c: s_load_dwordx4 s[0:3], s[2:3], 0x10
  2564. 0xF420_0100,
  2565. 0xFA00_0000, // 0x24: s_buffer_load_dword s4, s[0:3], null
  2566. S_ENDPGM,
  2567. ],
  2568. &[param(Table, 9, 1)],
  2569. HwStage::Ps,
  2570. );
  2571. let Source::Phi { args, .. } = &r.descriptors[0].source else {
  2572. panic!("{:?}", r.descriptors)
  2573. };
  2574. let offsets: Vec<_> = args
  2575. .iter()
  2576. .map(|a| match a {
  2577. Source::Loaded { load, .. } => {
  2578. r.scalar.iter().find(|s| s.0 == *load).unwrap().1.offset
  2579. }
  2580. a => panic!("{a:?}"),
  2581. })
  2582. .collect();
  2583. assert_eq!(offsets.len(), 2);
  2584. assert!(
  2585. offsets.contains(&0) && offsets.contains(&0x10),
  2586. "{offsets:?}"
  2587. );
  2588. }
  2589. /// Two paths add an index to one table in the code and meet before one load
  2590. /// (hair `CS_InterpolateStrands`): the join is the computed term, counted
  2591. /// from the `s_getpc_b64`.
  2592. #[test]
  2593. fn two_paths_into_one_code_table_load() {
  2594. let r = track_words(
  2595. &[
  2596. 0xBE82_1F00, // 0x00: s_getpc_b64 s[2:3]
  2597. 0x8002_FF02,
  2598. 0x0000_0040, // s_add_u32 s2, s2, 0x40
  2599. 0x8203_8003, // s_addc_u32 s3, s3, 0
  2600. 0xBF06_8001, // 0x10: s_cmp_eq_u32 s1, 0
  2601. 0xBF85_0005, // 0x14: s_cbranch_scc1 -> 0x2c
  2602. 0xD70F_0457,
  2603. 0x0000_054A, // 0x18: v_add_co_u32 v87, s4, v74, s2
  2604. 0xD528_0458,
  2605. 0x0010_0680, // v_add_co_ci_u32 v88, s4, 0, s3, s4
  2606. 0xBF82_0004, // 0x28: s_branch -> 0x3c
  2607. 0xD70F_0457,
  2608. 0x0000_054B, // 0x2c: v_add_co_u32 v87, s4, v75, s2
  2609. 0xD528_0458,
  2610. 0x0010_0680, // v_add_co_ci_u32 v88, s4, 0, s3, s4
  2611. 0xDC34_8000,
  2612. 0x577D_0057, // 0x3c: global_load_dwordx2 v[87:88], v[87:88], null
  2613. S_ENDPGM,
  2614. ],
  2615. &[],
  2616. HwStage::Cs,
  2617. );
  2618. assert_eq!(r.scalar.len(), 1);
  2619. let a = r.scalar[0].1;
  2620. assert_eq!((a.param, a.offset), (CODE, 0));
  2621. assert!(a.dynamic.is_some(), "the join is the computed term, the byte in the code");
  2622. }
  2623. /// An address into a table in the code computed per lane and taken from
  2624. /// the first lane (`avgLuminanceCompute` `ColorDownsample`): the per-lane
  2625. /// sum carries the `s_getpc_b64` base, so the first-lane read is looked
  2626. /// through and the lane's index is the computed term. (A first-lane read
  2627. /// of an index alone stays the computed term itself; see
  2628. /// `the_console_waterfall_over_a_first_lane_offset_is_one`.)
  2629. #[test]
  2630. fn a_code_table_address_taken_from_the_first_lane() {
  2631. let r = track_words(
  2632. &[
  2633. 0xBE82_1F00, // 0x00: s_getpc_b64 s[2:3]
  2634. 0xD70F_0457,
  2635. 0x0000_054A, // v_add_co_u32 v87, s4, v74, s2
  2636. 0xD528_0458,
  2637. 0x0010_0680, // v_add_co_ci_u32 v88, s4, 0, s3, s4
  2638. 0x7E0C_0557, // v_readfirstlane_b32 s6, v87
  2639. 0x7E0E_0558, // v_readfirstlane_b32 s7, v88
  2640. 0xF400_0203,
  2641. 0xFA00_0000, // s_load_dword s8, s[6:7], 0x0
  2642. S_ENDPGM,
  2643. ],
  2644. &[],
  2645. HwStage::Cs,
  2646. );
  2647. assert_eq!(r.scalar.len(), 1);
  2648. let a = r.scalar[0].1;
  2649. assert_eq!((a.param, a.offset), (CODE, 4));
  2650. assert!(a.dynamic.is_some(), "the lane's index is the computed term");
  2651. }
  2652. #[test]
  2653. fn a_descriptor_kept_per_lane_is_its_load_and_needs_no_waterfall() {
  2654. // The console compiler's way with a descriptor it joins per lane:
  2655. // the dwords go to VGPRs and come back from the first lane. Every
  2656. // lane holds the one load's dwords, so the descriptor is that load
  2657. // (`lane_copied`), and no waterfall is asked for.
  2658. let mut words = vec![
  2659. 0xBE82_0309, // s_mov_b32 s2, s9
  2660. 0xBE83_0380, // s_mov_b32 s3, 0
  2661. 0xF40C_0001,
  2662. 0xFA00_0000, // s_load_dwordx8 s[0:7], s[2:3], null
  2663. ];
  2664. // v_mov_b32 v10.., s0..; v_readfirstlane_b32 s16.., v10..
  2665. words.extend((0..8).map(|k| 0x7E00_0200 | (10 + k) << 17 | k));
  2666. words.extend((0..8).map(|k| 0x7E00_0400 | (16 + k) << 17 | (0x100 + 10 + k)));
  2667. words.extend([
  2668. 0xF000_1700,
  2669. 0x0004_0D06, // image_load v[13:15], v6, s[16:23]
  2670. S_ENDPGM,
  2671. ]);
  2672. let r = track_words(&words, &[param(Table, 9, 1)], HwStage::Ps);
  2673. let load = (0, 2);
  2674. assert_eq!(r.scalar, [(load, at(0, 0))]);
  2675. let sources: Vec<_> = r.descriptors.iter().map(|d| &d.source).collect();
  2676. assert_eq!(sources, [&Source::Loaded { load, first: 0 }]);
  2677. assert_eq!(r.lane_copied, [load]);
  2678. assert_eq!(r.waterfall, Waterfall::default());
  2679. }
  2680. #[test]
  2681. fn loads_at_one_first_lane_offset_have_one_address() {
  2682. // Two loads of the table entry at the offset v4 holds, each with
  2683. // its own first-lane read, as the console compiler loads a
  2684. // descriptor again wherever it needs it: one address, by which
  2685. // lowering knows them for the same descriptor.
  2686. let r = track_words(
  2687. &[
  2688. 0xBE82_0309, // s_mov_b32 s2, s9
  2689. 0xBE83_0380, // s_mov_b32 s3, 0
  2690. 0x7E08_0504, // v_readfirstlane_b32 s4, v4
  2691. 0xF40C_0201,
  2692. 0x0800_0000, // s_load_dwordx8 s[8:15], s[2:3], s4
  2693. 0x7E0A_0504, // v_readfirstlane_b32 s5, v4
  2694. 0xF40C_0401,
  2695. 0x0A00_0000, // s_load_dwordx8 s[16:23], s[2:3], s5
  2696. 0xF000_1700,
  2697. 0x0004_0D06, // image_load v[13:15], v6, s[16:23]
  2698. S_ENDPGM,
  2699. ],
  2700. &[param(Table, 9, 1)],
  2701. HwStage::Ps,
  2702. );
  2703. let [(_, a), (_, b)] = r.scalar[..] else {
  2704. panic!("{:?}", r.scalar)
  2705. };
  2706. assert_eq!(a, b);
  2707. assert_eq!((a.param, a.offset), (0, 0));
  2708. assert!(
  2709. a.dynamic.is_some(),
  2710. "the lane's offset is the computed term"
  2711. );
  2712. }
  2713. #[test]
  2714. fn descriptors_selected_by_scc_are_traced_per_outcome() {
  2715. // Two buffer descriptors loaded from the table at s9 and one
  2716. // picked with s_cselect_b64 per half, as the compiler makes a
  2717. // conditional choice of resources without a branch.
  2718. let r = track_words(
  2719. &[
  2720. 0xBE8C_0309, // s_mov_b32 s12, s9
  2721. 0xBE8D_0380, // s_mov_b32 s13, 0
  2722. 0xF408_0006,
  2723. 0xFA00_0000, // s_load_dwordx4 s[0:3], s[12:13], null
  2724. 0xF408_0106,
  2725. 0xFA00_0010, // s_load_dwordx4 s[4:7], s[12:13], 0x10
  2726. 0xBF06_800E, // s_cmp_eq_u32 s14, 0
  2727. 0x8588_0400, // s_cselect_b64 s[8:9], s[0:1], s[4:5]
  2728. 0x858A_0602, // s_cselect_b64 s[10:11], s[2:3], s[6:7]
  2729. 0xF420_0404,
  2730. 0xFA00_0000, // s_buffer_load_dword s16, s[8:11], null
  2731. S_ENDPGM,
  2732. ],
  2733. &[param(Table, 9, 1)],
  2734. HwStage::Ps,
  2735. );
  2736. let Source::Select { args, .. } = &r.descriptors[0].source else {
  2737. panic!("{:?}", r.descriptors)
  2738. };
  2739. // SCC set picks the first operand.
  2740. assert_eq!(
  2741. args[..],
  2742. [
  2743. Source::Loaded {
  2744. load: (0, 2),
  2745. first: 0
  2746. },
  2747. Source::Loaded {
  2748. load: (0, 3),
  2749. first: 0
  2750. },
  2751. ]
  2752. );
  2753. assert_eq!(r.scalar, [((0, 2), at(0, 0)), ((0, 3), at(0, 0x10))]);
  2754. }
  2755. /// The FidelityFX upscaler's byte accesses make a loaded buffer
  2756. /// descriptor raw first (stride cleared, records times stride, bounds
  2757. /// in bytes): the access reads the loaded descriptor. Any other change
  2758. /// still fails.
  2759. #[test]
  2760. fn a_descriptor_made_raw_is_the_loaded_one() {
  2761. let words = |mask: u32| -> Vec<u8> {
  2762. [
  2763. 0xBE88_0304, // s_mov_b32 s8, s4
  2764. 0xBE89_0380, // s_mov_b32 s9, 0
  2765. 0xF408_0204,
  2766. 0xFA00_0160, // s_load_dwordx4 s[8:11], s[8:9], 0x160
  2767. 0xBF8C_C07F, // s_waitcnt lgkmcnt(0)
  2768. 0x938C_FF09,
  2769. 0x000E_0010, // s_bfe_u32 s12, s9, 0x000e0010
  2770. 0x848C_810C, // s_max_u32 s12, s12, 1
  2771. 0x8709_FF09,
  2772. mask, // s_and_b32 s9, s9, mask
  2773. 0x870B_FF0B,
  2774. 0xCFFF_FFFF, // s_and_b32 s11, s11, 0xcfffffff
  2775. 0x930A_0C0A, // s_mul_i32 s10, s10, s12
  2776. 0x880B_FF0B,
  2777. 0x3000_0000, // s_or_b32 s11, s11, 0x30000000
  2778. 0xE078_1000,
  2779. 0x8002_0007, // buffer_store_dwordx4 v[0:3], v7, s[8:11], 0 offen
  2780. S_ENDPGM,
  2781. ]
  2782. .iter()
  2783. .flat_map(|w: &u32| w.to_le_bytes())
  2784. .collect()
  2785. };
  2786. let run = |mask| {
  2787. let p = crate::ir::build(&words(mask), false, 256).unwrap();
  2788. track(&p, &[param(Table, 4, 1)], HwStage::Cs, lanes(&p).as_ref())
  2789. };
  2790. assert!(run(0xC000_FFFF).is_ok());
  2791. assert_eq!(
  2792. run(0xC000_FFFE).unwrap_err(),
  2793. ShaderError::Unsupported {
  2794. offset: 0x3c,
  2795. what: "a descriptor changed after loading"
  2796. }
  2797. );
  2798. }
  2799. /// Immediate sampler words the upscaler's compiler makes with a bit
  2800. /// mask and a 64-bit move of a literal.
  2801. #[test]
  2802. fn sampler_words_from_bit_masks_and_wide_literals_are_constants() {
  2803. let code: Vec<u8> = [
  2804. 0xB010_3092, // s_movk_i32 s16, 0x3092
  2805. 0x9211_8C8C, // s_bfm_b32 s17, 12, 12
  2806. 0xBE92_04FF,
  2807. 0x1850_0000, // s_mov_b64 s[18:19], 0x18500000
  2808. S_ENDPGM,
  2809. ]
  2810. .iter()
  2811. .flat_map(|w: &u32| w.to_le_bytes())
  2812. .collect();
  2813. let p = crate::ir::build(&code, false, 256).unwrap();
  2814. let layout = [param(Table, 4, 1)];
  2815. let t = Tracer::new(&p, &layout, HwStage::Cs, None).unwrap();
  2816. let block = &p.blocks[0];
  2817. let value = |n: usize, k: usize| t.origin(block.insts[n].writes[k].1);
  2818. assert_eq!(value(1, 0), Term::Const(0x00FF_F000));
  2819. assert_eq!(value(2, 0), Term::Const(0x1850_0000));
  2820. assert_eq!(value(2, 1), Term::Const(0));
  2821. }
  2822. #[test]
  2823. fn a_selection_that_mixes_two_descriptors_fails() {
  2824. // The high half picked from the first load whatever SCC is: when
  2825. // clear, the descriptor is half of one load and half of the other.
  2826. let code: Vec<u8> = [
  2827. 0xBE8C_0309, // s_mov_b32 s12, s9
  2828. 0xBE8D_0380, // s_mov_b32 s13, 0
  2829. 0xF408_0006,
  2830. 0xFA00_0000, // s_load_dwordx4 s[0:3], s[12:13], null
  2831. 0xF408_0106,
  2832. 0xFA00_0010, // s_load_dwordx4 s[4:7], s[12:13], 0x10
  2833. 0xBF06_800E, // s_cmp_eq_u32 s14, 0
  2834. 0x8588_0400, // s_cselect_b64 s[8:9], s[0:1], s[4:5]
  2835. 0x858A_0202, // s_cselect_b64 s[10:11], s[2:3], s[2:3]
  2836. 0xF420_0404,
  2837. 0xFA00_0000, // s_buffer_load_dword s16, s[8:11], null
  2838. S_ENDPGM,
  2839. ]
  2840. .iter()
  2841. .flat_map(|w: &u32| w.to_le_bytes())
  2842. .collect();
  2843. let p = crate::ir::build(&code, false, 256).unwrap();
  2844. let err = track(&p, &[param(Table, 9, 1)], HwStage::Ps, lanes(&p).as_ref()).unwrap_err();
  2845. assert_eq!(
  2846. err,
  2847. ShaderError::Unsupported {
  2848. offset: 36,
  2849. what: "a descriptor changed after loading"
  2850. }
  2851. );
  2852. }
  2853. #[test]
  2854. fn untraceable_addresses_fail_with_a_reason() {
  2855. let code: Vec<u8> = [0xF408_0001, 0xFA00_0000, S_ENDPGM] // s_load_dwordx4 s[0:3], s[2:3]
  2856. .iter()
  2857. .flat_map(|w: &u32| w.to_le_bytes())
  2858. .collect();
  2859. let p = crate::ir::build(&code, false, 256).unwrap();
  2860. let err = track(&p, &[param(Table, 9, 1)], HwStage::Ps, lanes(&p).as_ref()).unwrap_err();
  2861. assert_eq!(
  2862. err,
  2863. ShaderError::Unsupported {
  2864. offset: 0,
  2865. what: "an address in an SGPR that is no root parameter"
  2866. }
  2867. );
  2868. }
  2869. /// A waterfall loop over an image descriptor each lane loads from the
  2870. /// table at s0 (wave32, assembled with llvm-mc for gfx1030): lane i
  2871. /// reads entry i with two `global_load_dwordx4`, the loop reads the
  2872. /// first active lane's descriptor into s[12:19], samples with the lanes
  2873. /// whose descriptor it is, and repeats for the others. The sampler comes
  2874. /// from the table at s1; the result goes to LDS so the sample is needed.
  2875. pub(crate) const WATERFALL_FETCHED_WAVE32: &[u32] = &[
  2876. 0xBE84_0300, // s_mov_b32 s4, s0
  2877. 0xBE85_0380, // s_mov_b32 s5, 0
  2878. 0xBE86_0301, // s_mov_b32 s6, s1
  2879. 0xBE87_0380, // s_mov_b32 s7, 0
  2880. 0x3402_0085, // v_lshlrev_b32 v1, 5, v0
  2881. 0xDC38_8000,
  2882. 0x0404_0001, // global_load_dwordx4 v[4:7], v1, s[4:5]
  2883. 0xDC38_8010,
  2884. 0x0804_0001, // global_load_dwordx4 v[8:11], v1, s[4:5] offset:16
  2885. 0xF408_0203,
  2886. 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0
  2887. 0x7E04_0D00, // v_cvt_f32_u32 v2, v0
  2888. 0x7E06_0302, // v_mov_b32 v3, v2
  2889. 0xBF8C_0070, // s_waitcnt vmcnt(0) lgkmcnt(0)
  2890. 0xBE94_037E, // s_mov_b32 s20, exec_lo
  2891. 0x7E18_0504, // 0x3c: v_readfirstlane_b32 s12, v4
  2892. 0x7E1A_0505, // v_readfirstlane_b32 s13, v5
  2893. 0x7E1C_0506, // v_readfirstlane_b32 s14, v6
  2894. 0x7E1E_0507, // v_readfirstlane_b32 s15, v7
  2895. 0x7E20_0508, // v_readfirstlane_b32 s16, v8
  2896. 0x7E22_0509, // v_readfirstlane_b32 s17, v9
  2897. 0x7E24_050A, // v_readfirstlane_b32 s18, v10
  2898. 0x7E26_050B, // v_readfirstlane_b32 s19, v11
  2899. 0xD4E2_0015,
  2900. 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5]
  2901. 0xD4E2_0016,
  2902. 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7]
  2903. 0x8715_1615, // s_and_b32 s21, s21, s22
  2904. 0xD4E2_0016,
  2905. 0x0002_1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9]
  2906. 0x8715_1615, // s_and_b32 s21, s21, s22
  2907. 0xD4E2_0016,
  2908. 0x0002_1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11]
  2909. 0x8715_1615, // s_and_b32 s21, s21, s22
  2910. 0xBE95_3C15, // s_and_saveexec_b32 s21, s21
  2911. 0xBF80_0000, // s_nop 0
  2912. 0xF09C_0F08,
  2913. 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D
  2914. 0xBF8C_3F70, // s_waitcnt vmcnt(0)
  2915. 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21
  2916. 0xBF89_FFE6, // s_cbranch_execnz -> 0x3c
  2917. 0xBEFE_0314, // s_mov_b32 exec_lo, s20
  2918. 0xD834_0000,
  2919. 0x0000_0C00, // ds_write_b32 v0, v12
  2920. 0xBF81_0000, // s_endpgm
  2921. ];
  2922. /// [`WATERFALL_FETCHED_WAVE32`] in wave64: 64-bit lane masks.
  2923. pub(crate) const WATERFALL_FETCHED_WAVE64: &[u32] = &[
  2924. 0xBE84_0300, // s_mov_b32 s4, s0
  2925. 0xBE85_0380, // s_mov_b32 s5, 0
  2926. 0xBE86_0301, // s_mov_b32 s6, s1
  2927. 0xBE87_0380, // s_mov_b32 s7, 0
  2928. 0x3402_0085, // v_lshlrev_b32 v1, 5, v0
  2929. 0xDC38_8000,
  2930. 0x0404_0001, // global_load_dwordx4 v[4:7], v1, s[4:5]
  2931. 0xDC38_8010,
  2932. 0x0804_0001, // global_load_dwordx4 v[8:11], v1, s[4:5] offset:16
  2933. 0xF408_0203,
  2934. 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0
  2935. 0x7E04_0D00, // v_cvt_f32_u32 v2, v0
  2936. 0x7E06_0302, // v_mov_b32 v3, v2
  2937. 0xBF8C_0070, // s_waitcnt vmcnt(0) lgkmcnt(0)
  2938. 0xBE94_047E, // s_mov_b64 s[20:21], exec
  2939. 0x7E18_0504, // 0x3c: v_readfirstlane_b32 s12, v4
  2940. 0x7E1A_0505, // v_readfirstlane_b32 s13, v5
  2941. 0x7E1C_0506, // v_readfirstlane_b32 s14, v6
  2942. 0x7E1E_0507, // v_readfirstlane_b32 s15, v7
  2943. 0x7E20_0508, // v_readfirstlane_b32 s16, v8
  2944. 0x7E22_0509, // v_readfirstlane_b32 s17, v9
  2945. 0x7E24_050A, // v_readfirstlane_b32 s18, v10
  2946. 0x7E26_050B, // v_readfirstlane_b32 s19, v11
  2947. 0xD4E2_0016,
  2948. 0x0002_080C, // v_cmp_eq_u64_e64 s[22:23], s[12:13], v[4:5]
  2949. 0xD4E2_0018,
  2950. 0x0002_0C0E, // v_cmp_eq_u64_e64 s[24:25], s[14:15], v[6:7]
  2951. 0x8796_1816, // s_and_b64 s[22:23], s[22:23], s[24:25]
  2952. 0xD4E2_0018,
  2953. 0x0002_1010, // v_cmp_eq_u64_e64 s[24:25], s[16:17], v[8:9]
  2954. 0x8796_1816, // s_and_b64 s[22:23], s[22:23], s[24:25]
  2955. 0xD4E2_0018,
  2956. 0x0002_1412, // v_cmp_eq_u64_e64 s[24:25], s[18:19], v[10:11]
  2957. 0x8796_1816, // s_and_b64 s[22:23], s[22:23], s[24:25]
  2958. 0xBE96_2416, // s_and_saveexec_b64 s[22:23], s[22:23]
  2959. 0xBF80_0000, // s_nop 0
  2960. 0xF09C_0F08,
  2961. 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D
  2962. 0xBF8C_3F70, // s_waitcnt vmcnt(0)
  2963. 0x89FE_167E, // s_xor_b64 exec, exec, s[22:23]
  2964. 0xBF89_FFE6, // s_cbranch_execnz -> 0x3c
  2965. 0xBEFE_0414, // s_mov_b64 exec, s[20:21]
  2966. 0xD834_0000,
  2967. 0x0000_0C00, // ds_write_b32 v0, v12
  2968. 0xBF81_0000, // s_endpgm
  2969. ];
  2970. /// The same waterfall over one of two image descriptors loaded from the
  2971. /// table at s0, picked per lane by `v_cndmask_b32` (lanes below 16 take
  2972. /// the first).
  2973. pub(crate) const WATERFALL_PICKED_WAVE32: &[u32] = &[
  2974. 0xBE84_0300, // s_mov_b32 s4, s0
  2975. 0xBE85_0380, // s_mov_b32 s5, 0
  2976. 0xBE86_0301, // s_mov_b32 s6, s1
  2977. 0xBE87_0380, // s_mov_b32 s7, 0
  2978. 0xF40C_0602,
  2979. 0xFA00_0000, // s_load_dwordx8 s[24:31], s[4:5], 0x0
  2980. 0xF40C_0802,
  2981. 0xFA00_0020, // s_load_dwordx8 s[32:39], s[4:5], 0x20
  2982. 0xF408_0203,
  2983. 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0
  2984. 0x7E04_0D00, // v_cvt_f32_u32 v2, v0
  2985. 0x7E06_0302, // v_mov_b32 v3, v2
  2986. 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0
  2987. 0xBF8C_C07F, // s_waitcnt lgkmcnt(0)
  2988. 0x7E08_0218, // v_mov_b32 v4, s24
  2989. 0x0208_0820, // v_cndmask_b32 v4, s32, v4, vcc_lo
  2990. 0x7E0A_0219, // v_mov_b32 v5, s25
  2991. 0x020A_0A21, // v_cndmask_b32 v5, s33, v5, vcc_lo
  2992. 0x7E0C_021A, // v_mov_b32 v6, s26
  2993. 0x020C_0C22, // v_cndmask_b32 v6, s34, v6, vcc_lo
  2994. 0x7E0E_021B, // v_mov_b32 v7, s27
  2995. 0x020E_0E23, // v_cndmask_b32 v7, s35, v7, vcc_lo
  2996. 0x7E10_021C, // v_mov_b32 v8, s28
  2997. 0x0210_1024, // v_cndmask_b32 v8, s36, v8, vcc_lo
  2998. 0x7E12_021D, // v_mov_b32 v9, s29
  2999. 0x0212_1225, // v_cndmask_b32 v9, s37, v9, vcc_lo
  3000. 0x7E14_021E, // v_mov_b32 v10, s30
  3001. 0x0214_1426, // v_cndmask_b32 v10, s38, v10, vcc_lo
  3002. 0x7E16_021F, // v_mov_b32 v11, s31
  3003. 0x0216_1627, // v_cndmask_b32 v11, s39, v11, vcc_lo
  3004. 0xBE94_037E, // s_mov_b32 s20, exec_lo
  3005. 0x7E18_0504, // 0x7c: v_readfirstlane_b32 s12, v4
  3006. 0x7E1A_0505, // v_readfirstlane_b32 s13, v5
  3007. 0x7E1C_0506, // v_readfirstlane_b32 s14, v6
  3008. 0x7E1E_0507, // v_readfirstlane_b32 s15, v7
  3009. 0x7E20_0508, // v_readfirstlane_b32 s16, v8
  3010. 0x7E22_0509, // v_readfirstlane_b32 s17, v9
  3011. 0x7E24_050A, // v_readfirstlane_b32 s18, v10
  3012. 0x7E26_050B, // v_readfirstlane_b32 s19, v11
  3013. 0xD4E2_0015,
  3014. 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5]
  3015. 0xD4E2_0016,
  3016. 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7]
  3017. 0x8715_1615, // s_and_b32 s21, s21, s22
  3018. 0xD4E2_0016,
  3019. 0x0002_1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9]
  3020. 0x8715_1615, // s_and_b32 s21, s21, s22
  3021. 0xD4E2_0016,
  3022. 0x0002_1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11]
  3023. 0x8715_1615, // s_and_b32 s21, s21, s22
  3024. 0xBE95_3C15, // s_and_saveexec_b32 s21, s21
  3025. 0xBF80_0000, // s_nop 0
  3026. 0xF09C_0F08,
  3027. 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D
  3028. 0xBF8C_3F70, // s_waitcnt vmcnt(0)
  3029. 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21
  3030. 0xBF89_FFE6, // s_cbranch_execnz -> 0x7c
  3031. 0xBEFE_0314, // s_mov_b32 exec_lo, s20
  3032. 0xD834_0000,
  3033. 0x0000_0C00, // ds_write_b32 v0, v12
  3034. 0xBF81_0000, // s_endpgm
  3035. ];
  3036. /// The waterfall loop of [`WATERFALL_PICKED_WAVE32`] over one of two
  3037. /// image descriptors loaded from the table at s0, chosen by control flow
  3038. /// as the compiler lowers an if/else on a per-lane condition: lanes below
  3039. /// 16 move the first into v[4:11], the others the second, each arm
  3040. /// skipped when no lane takes it. The sample goes to the buffer at dword
  3041. /// 16 of the table, at lane * 4.
  3042. pub(crate) const WATERFALL_JOINED_WAVE32: &[u32] = &[
  3043. 0xBE84_0300, // s_mov_b32 s4, s0
  3044. 0xBE85_0380, // s_mov_b32 s5, 0
  3045. 0xBE86_0301, // s_mov_b32 s6, s1
  3046. 0xBE87_0380, // s_mov_b32 s7, 0
  3047. 0xF40C_0602,
  3048. 0xFA00_0000, // s_load_dwordx8 s[24:31], s[4:5], 0x0
  3049. 0xF40C_0802,
  3050. 0xFA00_0020, // s_load_dwordx8 s[32:39], s[4:5], 0x20
  3051. 0xF408_0203,
  3052. 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0
  3053. 0xF408_0A02,
  3054. 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40
  3055. 0x7E04_0D00, // v_cvt_f32_u32 v2, v0
  3056. 0x7E06_0302, // v_mov_b32 v3, v2
  3057. 0x3420_0082, // v_lshlrev_b32 v16, 2, v0
  3058. 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0
  3059. 0xBF8C_C07F, // s_waitcnt lgkmcnt(0)
  3060. 0xBE94_3C6A, // s_and_saveexec_b32 s20, vcc_lo
  3061. 0x8914_147E, // s_xor_b32 s20, exec_lo, s20
  3062. 0xBF88_0008, // s_cbranch_execz -> 0x70
  3063. 0x7E08_0218, // v_mov_b32 v4, s24
  3064. 0x7E0A_0219, // v_mov_b32 v5, s25
  3065. 0x7E0C_021A, // v_mov_b32 v6, s26
  3066. 0x7E0E_021B, // v_mov_b32 v7, s27
  3067. 0x7E10_021C, // v_mov_b32 v8, s28
  3068. 0x7E12_021D, // v_mov_b32 v9, s29
  3069. 0x7E14_021E, // v_mov_b32 v10, s30
  3070. 0x7E16_021F, // v_mov_b32 v11, s31
  3071. 0xBE94_3D14, // 0x70: s_or_saveexec_b32 s20, s20
  3072. 0x897E_147E, // s_xor_b32 exec_lo, exec_lo, s20
  3073. 0xBF88_0008, // s_cbranch_execz -> 0x9c
  3074. 0x7E08_0220, // v_mov_b32 v4, s32
  3075. 0x7E0A_0221, // v_mov_b32 v5, s33
  3076. 0x7E0C_0222, // v_mov_b32 v6, s34
  3077. 0x7E0E_0223, // v_mov_b32 v7, s35
  3078. 0x7E10_0224, // v_mov_b32 v8, s36
  3079. 0x7E12_0225, // v_mov_b32 v9, s37
  3080. 0x7E14_0226, // v_mov_b32 v10, s38
  3081. 0x7E16_0227, // v_mov_b32 v11, s39
  3082. 0x887E_147E, // 0x9c: s_or_b32 exec_lo, exec_lo, s20
  3083. 0xBE97_037E, // s_mov_b32 s23, exec_lo
  3084. 0x7E18_0504, // 0xa4: v_readfirstlane_b32 s12, v4
  3085. 0x7E1A_0505, // v_readfirstlane_b32 s13, v5
  3086. 0x7E1C_0506, // v_readfirstlane_b32 s14, v6
  3087. 0x7E1E_0507, // v_readfirstlane_b32 s15, v7
  3088. 0x7E20_0508, // v_readfirstlane_b32 s16, v8
  3089. 0x7E22_0509, // v_readfirstlane_b32 s17, v9
  3090. 0x7E24_050A, // v_readfirstlane_b32 s18, v10
  3091. 0x7E26_050B, // v_readfirstlane_b32 s19, v11
  3092. 0xD4E2_0015,
  3093. 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5]
  3094. 0xD4E2_0016,
  3095. 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7]
  3096. 0x8715_1615, // s_and_b32 s21, s21, s22
  3097. 0xD4E2_0016,
  3098. 0x0002_1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9]
  3099. 0x8715_1615, // s_and_b32 s21, s21, s22
  3100. 0xD4E2_0016,
  3101. 0x0002_1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11]
  3102. 0x8715_1615, // s_and_b32 s21, s21, s22
  3103. 0xBE95_3C15, // s_and_saveexec_b32 s21, s21
  3104. 0xBF80_0000, // s_nop 0
  3105. 0xF09C_0F08,
  3106. 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D
  3107. 0xBF8C_3F70, // s_waitcnt vmcnt(0)
  3108. 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21
  3109. 0xBF89_FFE6, // s_cbranch_execnz -> 0xa4
  3110. 0xBEFE_0317, // s_mov_b32 exec_lo, s23
  3111. 0xE070_1000,
  3112. 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen
  3113. 0xBF81_0000, // s_endpgm
  3114. ];
  3115. /// The console compiler's waterfall (the title's ray-tracing
  3116. /// resolve and others): each lane holds its entry's byte offset in the
  3117. /// table at s0 (v7 = (lane & 1) * 32); the loop reads the first active
  3118. /// lane's offset, narrows EXEC to the lanes with the same one
  3119. /// (`v_cmpx_eq_u32`), loads that entry with `s_load_dwordx8` and samples,
  3120. /// then drops those lanes (`s_andn2_wrexec_b32`). The sample goes to the
  3121. /// buffer at dword 16 of the table, at lane * 4.
  3122. pub(crate) const WATERFALL_INDEXED_WAVE32: &[u32] = &[
  3123. 0xBE84_0300, // s_mov_b32 s4, s0
  3124. 0xBE85_0380, // s_mov_b32 s5, 0
  3125. 0xBE86_0301, // s_mov_b32 s6, s1
  3126. 0xBE87_0380, // s_mov_b32 s7, 0
  3127. 0xF408_0203,
  3128. 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0
  3129. 0xF408_0A02,
  3130. 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40
  3131. 0x7E04_0D00, // v_cvt_f32_u32 v2, v0
  3132. 0x7E06_0302, // v_mov_b32 v3, v2
  3133. 0x3420_0082, // v_lshlrev_b32 v16, 2, v0
  3134. 0x360E_0081, // v_and_b32 v7, 1, v0
  3135. 0x340E_0E85, // v_lshlrev_b32 v7, 5, v7
  3136. 0xBF8C_C07F, // s_waitcnt lgkmcnt(0)
  3137. 0xBE97_037E, // s_mov_b32 s23, exec_lo
  3138. 0xBE95_037E, // s_mov_b32 s21, exec_lo
  3139. 0x7E28_0507, // 0x40: v_readfirstlane_b32 s20, v7
  3140. 0x7DA4_0E14, // v_cmpx_eq_u32 exec_lo, s20, v7
  3141. 0xF40C_0302,
  3142. 0x2800_0000, // s_load_dwordx8 s[12:19], s[4:5], s20
  3143. 0xBF8C_C07F, // s_waitcnt lgkmcnt(0)
  3144. 0xF09C_0F08,
  3145. 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D
  3146. 0xBF8C_3F70, // s_waitcnt vmcnt(0)
  3147. 0xBE95_4715, // s_andn2_wrexec_b32 s21, s21
  3148. 0xBF89_FFF6, // s_cbranch_execnz -> 0x40
  3149. 0xBEFE_0317, // s_mov_b32 exec_lo, s23
  3150. 0xE070_1000,
  3151. 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen
  3152. 0xBF81_0000, // s_endpgm
  3153. ];
  3154. #[test]
  3155. fn the_console_waterfall_over_a_first_lane_offset_is_one() {
  3156. let r = waterfall(WATERFALL_INDEXED_WAVE32, false).unwrap();
  3157. let image = r
  3158. .descriptors
  3159. .iter()
  3160. .find(|d| d.role == Role::Resource)
  3161. .unwrap();
  3162. let Source::Loaded { load, first: 0 } = image.source else {
  3163. panic!("{:?}", image.source)
  3164. };
  3165. let (_, address) = r.scalar.iter().find(|s| s.0 == load).unwrap();
  3166. assert!(address.dynamic.is_some(), "{address:?}");
  3167. assert_eq!(r.waterfall.compares.len(), 1);
  3168. assert_eq!(r.waterfall.reads.len(), 1);
  3169. assert_eq!(r.waterfall.loads, [load]);
  3170. }
  3171. /// [`WATERFALL_JOINED_WAVE32`] with other sources on each path: lanes
  3172. /// below 16 load table entry (lane & 1) with two `global_load_dwordx4`,
  3173. /// the others pick per lane with `v_cndmask_b32` (lanes below 24 the
  3174. /// first entry, the rest the second).
  3175. pub(crate) const WATERFALL_JOINED_MIXED_WAVE32: &[u32] = &[
  3176. 0xBE84_0300, // s_mov_b32 s4, s0
  3177. 0xBE85_0380, // s_mov_b32 s5, 0
  3178. 0xBE86_0301, // s_mov_b32 s6, s1
  3179. 0xBE87_0380, // s_mov_b32 s7, 0
  3180. 0xF40C_0602,
  3181. 0xFA00_0000, // s_load_dwordx8 s[24:31], s[4:5], 0x0
  3182. 0xF40C_0802,
  3183. 0xFA00_0020, // s_load_dwordx8 s[32:39], s[4:5], 0x20
  3184. 0xF408_0203,
  3185. 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0
  3186. 0xF408_0A02,
  3187. 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40
  3188. 0x7E04_0D00, // v_cvt_f32_u32 v2, v0
  3189. 0x7E06_0302, // v_mov_b32 v3, v2
  3190. 0x3420_0082, // v_lshlrev_b32 v16, 2, v0
  3191. 0x3602_0081, // v_and_b32 v1, 1, v0
  3192. 0x3402_0285, // v_lshlrev_b32 v1, 5, v1
  3193. 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0
  3194. 0xBF8C_C07F, // s_waitcnt lgkmcnt(0)
  3195. 0xBE94_3C6A, // s_and_saveexec_b32 s20, vcc_lo
  3196. 0x8914_147E, // s_xor_b32 s20, exec_lo, s20
  3197. 0xBF88_0004, // s_cbranch_execz -> 0x68
  3198. 0xDC38_8000,
  3199. 0x0404_0001, // global_load_dwordx4 v[4:7], v1, s[4:5]
  3200. 0xDC38_8010,
  3201. 0x0804_0001, // global_load_dwordx4 v[8:11], v1, s[4:5] offset:16
  3202. 0xBE94_3D14, // 0x68: s_or_saveexec_b32 s20, s20
  3203. 0x897E_147E, // s_xor_b32 exec_lo, exec_lo, s20
  3204. 0xBF88_0011, // s_cbranch_execz -> 0xb8
  3205. 0x7D88_0098, // v_cmp_gt_u32 vcc_lo, 24, v0
  3206. 0x7E08_0218, // v_mov_b32 v4, s24
  3207. 0x0208_0820, // v_cndmask_b32 v4, s32, v4, vcc_lo
  3208. 0x7E0A_0219, // v_mov_b32 v5, s25
  3209. 0x020A_0A21, // v_cndmask_b32 v5, s33, v5, vcc_lo
  3210. 0x7E0C_021A, // v_mov_b32 v6, s26
  3211. 0x020C_0C22, // v_cndmask_b32 v6, s34, v6, vcc_lo
  3212. 0x7E0E_021B, // v_mov_b32 v7, s27
  3213. 0x020E_0E23, // v_cndmask_b32 v7, s35, v7, vcc_lo
  3214. 0x7E10_021C, // v_mov_b32 v8, s28
  3215. 0x0210_1024, // v_cndmask_b32 v8, s36, v8, vcc_lo
  3216. 0x7E12_021D, // v_mov_b32 v9, s29
  3217. 0x0212_1225, // v_cndmask_b32 v9, s37, v9, vcc_lo
  3218. 0x7E14_021E, // v_mov_b32 v10, s30
  3219. 0x0214_1426, // v_cndmask_b32 v10, s38, v10, vcc_lo
  3220. 0x7E16_021F, // v_mov_b32 v11, s31
  3221. 0x0216_1627, // v_cndmask_b32 v11, s39, v11, vcc_lo
  3222. 0x887E_147E, // 0xb8: s_or_b32 exec_lo, exec_lo, s20
  3223. 0xBE97_037E, // s_mov_b32 s23, exec_lo
  3224. 0xBF8C_3F70, // s_waitcnt vmcnt(0)
  3225. 0x7E18_0504, // 0xc4: v_readfirstlane_b32 s12, v4
  3226. 0x7E1A_0505, // v_readfirstlane_b32 s13, v5
  3227. 0x7E1C_0506, // v_readfirstlane_b32 s14, v6
  3228. 0x7E1E_0507, // v_readfirstlane_b32 s15, v7
  3229. 0x7E20_0508, // v_readfirstlane_b32 s16, v8
  3230. 0x7E22_0509, // v_readfirstlane_b32 s17, v9
  3231. 0x7E24_050A, // v_readfirstlane_b32 s18, v10
  3232. 0x7E26_050B, // v_readfirstlane_b32 s19, v11
  3233. 0xD4E2_0015,
  3234. 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5]
  3235. 0xD4E2_0016,
  3236. 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7]
  3237. 0x8715_1615, // s_and_b32 s21, s21, s22
  3238. 0xD4E2_0016,
  3239. 0x0002_1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9]
  3240. 0x8715_1615, // s_and_b32 s21, s21, s22
  3241. 0xD4E2_0016,
  3242. 0x0002_1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11]
  3243. 0x8715_1615, // s_and_b32 s21, s21, s22
  3244. 0xBE95_3C15, // s_and_saveexec_b32 s21, s21
  3245. 0xBF80_0000, // s_nop 0
  3246. 0xF09C_0F08,
  3247. 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D
  3248. 0xBF8C_3F70, // s_waitcnt vmcnt(0)
  3249. 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21
  3250. 0xBF89_FFE6, // s_cbranch_execnz -> 0xc4
  3251. 0xBEFE_0317, // s_mov_b32 exec_lo, s23
  3252. 0xE070_1000,
  3253. 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen
  3254. 0xBF81_0000, // s_endpgm
  3255. ];
  3256. /// A waterfall loop whose descriptor changes on each pass: v[4:11] holds
  3257. /// the first table entry on entry and the second after every pass, so
  3258. /// the first lane's dwords are phis of the loop header.
  3259. pub(crate) const WATERFALL_LOOPED_WAVE32: &[u32] = &[
  3260. 0xBE84_0300, // s_mov_b32 s4, s0
  3261. 0xBE85_0380, // s_mov_b32 s5, 0
  3262. 0xBE86_0301, // s_mov_b32 s6, s1
  3263. 0xBE87_0380, // s_mov_b32 s7, 0
  3264. 0xF40C_0602,
  3265. 0xFA00_0000, // s_load_dwordx8 s[24:31], s[4:5], 0x0
  3266. 0xF40C_0802,
  3267. 0xFA00_0020, // s_load_dwordx8 s[32:39], s[4:5], 0x20
  3268. 0xF408_0203,
  3269. 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0
  3270. 0xF408_0A02,
  3271. 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40
  3272. 0x7E04_0D00, // v_cvt_f32_u32 v2, v0
  3273. 0x7E06_0302, // v_mov_b32 v3, v2
  3274. 0x3420_0082, // v_lshlrev_b32 v16, 2, v0
  3275. 0x7E08_0218, // v_mov_b32 v4, s24
  3276. 0x7E0A_0219, // v_mov_b32 v5, s25
  3277. 0x7E0C_021A, // v_mov_b32 v6, s26
  3278. 0x7E0E_021B, // v_mov_b32 v7, s27
  3279. 0x7E10_021C, // v_mov_b32 v8, s28
  3280. 0x7E12_021D, // v_mov_b32 v9, s29
  3281. 0x7E14_021E, // v_mov_b32 v10, s30
  3282. 0x7E16_021F, // v_mov_b32 v11, s31
  3283. 0xBF8C_C07F, // s_waitcnt lgkmcnt(0)
  3284. 0xBE97_037E, // s_mov_b32 s23, exec_lo
  3285. 0x7E18_0504, // 0x64: v_readfirstlane_b32 s12, v4
  3286. 0x7E1A_0505, // v_readfirstlane_b32 s13, v5
  3287. 0x7E1C_0506, // v_readfirstlane_b32 s14, v6
  3288. 0x7E1E_0507, // v_readfirstlane_b32 s15, v7
  3289. 0x7E20_0508, // v_readfirstlane_b32 s16, v8
  3290. 0x7E22_0509, // v_readfirstlane_b32 s17, v9
  3291. 0x7E24_050A, // v_readfirstlane_b32 s18, v10
  3292. 0x7E26_050B, // v_readfirstlane_b32 s19, v11
  3293. 0xD4E2_0015,
  3294. 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5]
  3295. 0xD4E2_0016,
  3296. 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7]
  3297. 0x8715_1615, // s_and_b32 s21, s21, s22
  3298. 0xD4E2_0016,
  3299. 0x0002_1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9]
  3300. 0x8715_1615, // s_and_b32 s21, s21, s22
  3301. 0xD4E2_0016,
  3302. 0x0002_1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11]
  3303. 0x8715_1615, // s_and_b32 s21, s21, s22
  3304. 0xBE95_3C15, // s_and_saveexec_b32 s21, s21
  3305. 0xBF80_0000, // s_nop 0
  3306. 0xF09C_0F08,
  3307. 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D
  3308. 0xBF8C_3F70, // s_waitcnt vmcnt(0)
  3309. 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21
  3310. 0x7E08_0220, // v_mov_b32 v4, s32
  3311. 0x7E0A_0221, // v_mov_b32 v5, s33
  3312. 0x7E0C_0222, // v_mov_b32 v6, s34
  3313. 0x7E0E_0223, // v_mov_b32 v7, s35
  3314. 0x7E10_0224, // v_mov_b32 v8, s36
  3315. 0x7E12_0225, // v_mov_b32 v9, s37
  3316. 0x7E14_0226, // v_mov_b32 v10, s38
  3317. 0x7E16_0227, // v_mov_b32 v11, s39
  3318. 0xBF89_FFDE, // s_cbranch_execnz -> 0x64
  3319. 0xBEFE_0317, // s_mov_b32 exec_lo, s23
  3320. 0xE070_1000,
  3321. 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen
  3322. 0xBF81_0000, // s_endpgm
  3323. ];
  3324. /// A waterfall loop over one of two buffer descriptors (four dwords)
  3325. /// loaded from the table at s0, chosen by nested if/else: lanes below 16
  3326. /// move the first into v[4:7], lanes from 16 to 23 the second, and the
  3327. /// others keep what v[4:7] held. Only lanes below 24 (the same mask)
  3328. /// run the loop, which loads dword `lane` of the chosen buffer, and
  3329. /// store it to the buffer at dword 16 of the table.
  3330. pub(crate) const WATERFALL_JOINED_BUFFER_WAVE32: &[u32] = &[
  3331. 0xBE84_0300, // s_mov_b32 s4, s0
  3332. 0xBE85_0380, // s_mov_b32 s5, 0
  3333. 0xF408_0602,
  3334. 0xFA00_0000, // s_load_dwordx4 s[24:27], s[4:5], 0x0
  3335. 0xF408_0802,
  3336. 0xFA00_0020, // s_load_dwordx4 s[32:35], s[4:5], 0x20
  3337. 0xF408_0A02,
  3338. 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40
  3339. 0x3420_0082, // v_lshlrev_b32 v16, 2, v0
  3340. 0xD4C4_001E,
  3341. 0x0002_0098, // v_cmp_gt_u32_e64 s30, 24, v0
  3342. 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0
  3343. 0xBF8C_C07F, // s_waitcnt lgkmcnt(0)
  3344. 0xBE94_3C6A, // s_and_saveexec_b32 s20, vcc_lo
  3345. 0x8914_147E, // s_xor_b32 s20, exec_lo, s20
  3346. 0xBF88_0004, // s_cbranch_execz -> 0x50
  3347. 0x7E08_0218, // 0x40: v_mov_b32 v4, s24
  3348. 0x7E0A_0219, // v_mov_b32 v5, s25
  3349. 0x7E0C_021A, // v_mov_b32 v6, s26
  3350. 0x7E0E_021B, // v_mov_b32 v7, s27
  3351. 0xBE94_3D14, // 0x50: s_or_saveexec_b32 s20, s20
  3352. 0x897E_147E, // s_xor_b32 exec_lo, exec_lo, s20
  3353. 0xBF88_0007, // s_cbranch_execz -> 0x78
  3354. 0xBE9F_3C1E, // s_and_saveexec_b32 s31, s30
  3355. 0xBF88_0004, // s_cbranch_execz -> 0x74
  3356. 0x7E08_0220, // 0x64: v_mov_b32 v4, s32
  3357. 0x7E0A_0221, // v_mov_b32 v5, s33
  3358. 0x7E0C_0222, // v_mov_b32 v6, s34
  3359. 0x7E0E_0223, // v_mov_b32 v7, s35
  3360. 0x887E_1F7E, // 0x74: s_or_b32 exec_lo, exec_lo, s31
  3361. 0x887E_147E, // 0x78: s_or_b32 exec_lo, exec_lo, s20
  3362. 0xBE97_3C1E, // s_and_saveexec_b32 s23, s30
  3363. 0xBF88_0013, // s_cbranch_execz -> 0xd0
  3364. 0xBE9D_037E, // s_mov_b32 s29, exec_lo
  3365. 0x7E18_0504, // 0x88: v_readfirstlane_b32 s12, v4
  3366. 0x7E1A_0505, // v_readfirstlane_b32 s13, v5
  3367. 0x7E1C_0506, // v_readfirstlane_b32 s14, v6
  3368. 0x7E1E_0507, // v_readfirstlane_b32 s15, v7
  3369. 0xD4E2_0015,
  3370. 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5]
  3371. 0xD4E2_0016,
  3372. 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7]
  3373. 0x8715_1615, // s_and_b32 s21, s21, s22
  3374. 0xBE95_3C15, // s_and_saveexec_b32 s21, s21
  3375. 0xE030_1000,
  3376. 0x8003_0C10, // buffer_load_dword v12, v16, s[12:15], 0 offen
  3377. 0xBF8C_3F70, // s_waitcnt vmcnt(0)
  3378. 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21
  3379. 0xBF89_FFF1, // s_cbranch_execnz -> 0x88
  3380. 0xBEFE_031D, // s_mov_b32 exec_lo, s29
  3381. 0xE070_1000,
  3382. 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen
  3383. 0x887E_177E, // 0xd0: s_or_b32 exec_lo, exec_lo, s23
  3384. 0xBF81_0000, // s_endpgm
  3385. ];
  3386. fn waterfall(words: &[u32], wave64: bool) -> Result<Resources, ShaderError> {
  3387. let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
  3388. let p = crate::ir::build(&code, wave64, 256).unwrap();
  3389. let layout = [param(Table, 0, 1), param(Table, 1, 1)];
  3390. track(&p, &layout, HwStage::Cs, lanes(&p).as_ref())
  3391. }
  3392. #[test]
  3393. fn descriptors_read_from_the_first_lane_of_per_lane_loads_are_traced_to_them() {
  3394. for (words, wave64) in [
  3395. (WATERFALL_FETCHED_WAVE32, false),
  3396. (WATERFALL_FETCHED_WAVE64, true),
  3397. ] {
  3398. let r = waterfall(words, wave64).unwrap();
  3399. let image = r
  3400. .descriptors
  3401. .iter()
  3402. .find(|d| d.role == Role::Resource)
  3403. .unwrap();
  3404. let Source::Fetched { load, first: 0 } = image.source else {
  3405. panic!("{:?}", image.source)
  3406. };
  3407. // The first of the two loads: entry v0 * 32 of the table at s0.
  3408. let a = r.scalar.iter().find(|s| s.0 == load).unwrap().1;
  3409. assert_eq!((a.param, a.offset), (0, 0));
  3410. assert!(a.dynamic.is_some());
  3411. // The sampler is the same for every lane.
  3412. let sampler = r.descriptors.iter().find(|d| d.role == Role::Sampler);
  3413. assert!(matches!(
  3414. sampler.unwrap().source,
  3415. Source::Loaded { first: 0, .. }
  3416. ));
  3417. // Four 64-bit compares of the first lane's dwords with the lane's
  3418. // own; the eight reads become the lane's own dwords.
  3419. assert_eq!(r.waterfall.compares.len(), 4);
  3420. assert_eq!(r.waterfall.reads.len(), 8);
  3421. }
  3422. }
  3423. #[test]
  3424. fn descriptors_read_from_the_first_lane_of_a_per_lane_choice_are_traced_per_lane() {
  3425. let r = waterfall(WATERFALL_PICKED_WAVE32, false).unwrap();
  3426. let image = &r.descriptors[0];
  3427. let Source::Lanes { args, .. } = &image.source else {
  3428. panic!("{:?}", image.source)
  3429. };
  3430. // Lanes with their bit set take the first load (offset 0), the
  3431. // others the second (0x20).
  3432. let offsets: Vec<u32> = args
  3433. .iter()
  3434. .map(|a| match *a {
  3435. Source::Loaded { load, first: 0 } => {
  3436. r.scalar.iter().find(|s| s.0 == load).unwrap().1.offset
  3437. }
  3438. ref a => panic!("{a:?}"),
  3439. })
  3440. .collect();
  3441. assert_eq!(offsets, [0, 0x20]);
  3442. assert_eq!(r.waterfall.compares.len(), 4);
  3443. }
  3444. #[test]
  3445. fn a_first_lane_read_outside_a_loop_is_no_waterfall() {
  3446. // The waterfall without its back edge: the s_cbranch_execnz is an
  3447. // s_nop, so lanes the first one does not match never get a pass.
  3448. let mut words = WATERFALL_FETCHED_WAVE32.to_vec();
  3449. let back = words.iter().position(|&w| w == 0xBF89_FFE6).unwrap();
  3450. words[back] = 0xBF80_0000;
  3451. let err = waterfall(&words, false).unwrap_err();
  3452. assert!(
  3453. matches!(
  3454. err,
  3455. ShaderError::Unsupported {
  3456. what: "a descriptor read from the first lane outside a waterfall loop",
  3457. ..
  3458. }
  3459. ),
  3460. "{err:?}"
  3461. );
  3462. }
  3463. /// Why resource tracking refuses `words`.
  3464. fn refusal(words: &[u32], wave64: bool) -> &'static str {
  3465. match waterfall(words, wave64) {
  3466. Err(ShaderError::Unsupported { what, .. }) => what,
  3467. other => panic!("not refused: {other:?}"),
  3468. }
  3469. }
  3470. const NO_LOOP: &str = "a descriptor read from the first lane outside a waterfall loop";
  3471. const NOT_SELECTED: &str = "a waterfall loop whose compares do not select the access's lanes";
  3472. const BAD_RETRY: &str = "a waterfall loop whose retry does not keep the lanes still waiting";
  3473. const SPLIT: &str = "a waterfall loop nested in another or split over blocks";
  3474. /// The index of `word` in `words`.
  3475. fn word_at(words: &[u32], word: u32) -> usize {
  3476. words.iter().position(|&w| w == word).unwrap()
  3477. }
  3478. #[test]
  3479. fn a_first_lane_read_without_its_compare_is_no_waterfall() {
  3480. // The loop without the compare of dwords 0 and 1: nothing makes
  3481. // the first lane's dwords the lane's own there.
  3482. let mut words = WATERFALL_FETCHED_WAVE32.to_vec();
  3483. let cmp = word_at(&words, 0x0002_080C);
  3484. words[cmp - 1..=cmp].copy_from_slice(&[0xBF80_0000, 0xBF80_0000]);
  3485. assert_eq!(refusal(&words, false), NOT_SELECTED);
  3486. }
  3487. #[test]
  3488. fn a_compare_that_does_not_mask_the_access_is_no_waterfall() {
  3489. // The compares are all there, but their result never narrows EXEC:
  3490. // every lane samples with the first lane's descriptor (reported by
  3491. // ifBars on upstream PR #566).
  3492. let mut words = WATERFALL_JOINED_WAVE32.to_vec();
  3493. let save = word_at(&words, 0xBE95_3C15);
  3494. words[save] = 0xBE95_037E; // s_mov_b32 s21, exec_lo
  3495. assert_eq!(refusal(&words, false), NOT_SELECTED);
  3496. }
  3497. #[test]
  3498. fn an_access_under_a_further_mask_is_no_waterfall() {
  3499. // The access runs for the matching lanes that VCC also holds, yet
  3500. // the retry removes every matching lane.
  3501. let mut words = WATERFALL_JOINED_WAVE32.to_vec();
  3502. let nop = word_at(&words, 0xBE95_3C15) + 1;
  3503. assert_eq!(words[nop], 0xBF80_0000);
  3504. words[nop] = 0x877E_6A7E; // s_and_b32 exec_lo, exec_lo, vcc_lo
  3505. assert_eq!(refusal(&words, false), NOT_SELECTED);
  3506. }
  3507. #[test]
  3508. fn a_loop_that_drops_unmatched_lanes_is_no_waterfall() {
  3509. let mut words = WATERFALL_JOINED_WAVE32.to_vec();
  3510. let retry = word_at(&words, 0x897E_157E);
  3511. words[retry] = 0xBEFE_0380; // s_mov_b32 exec_lo, 0
  3512. assert_eq!(refusal(&words, false), BAD_RETRY);
  3513. }
  3514. #[test]
  3515. fn a_retry_that_keeps_other_lanes_than_those_waiting_is_no_waterfall() {
  3516. // The retry keeps the lanes of VCC that did not just sample, not
  3517. // the waiting ones: lanes 16 and up never sample on the console.
  3518. let mut words = WATERFALL_JOINED_WAVE32.to_vec();
  3519. let retry = word_at(&words, 0x897E_157E);
  3520. words[retry] = 0x8A7E_7E6A; // s_andn2_b32 exec_lo, vcc_lo, exec_lo
  3521. assert_eq!(refusal(&words, false), BAD_RETRY);
  3522. }
  3523. #[test]
  3524. fn a_wave64_retry_of_one_half_is_no_waterfall() {
  3525. // Only the low half of EXEC loses the lanes just served.
  3526. let mut words = WATERFALL_FETCHED_WAVE64.to_vec();
  3527. let retry = word_at(&words, 0x89FE_167E);
  3528. words[retry] = 0x897E_167E; // s_xor_b32 exec_lo, exec_lo, s22
  3529. assert_eq!(refusal(&words, true), BAD_RETRY);
  3530. }
  3531. #[test]
  3532. fn a_descriptor_used_after_exec_is_restored_is_no_waterfall() {
  3533. let mut words = WATERFALL_JOINED_WAVE32.to_vec();
  3534. let sample = word_at(&words, 0xF09C_0F08);
  3535. let restore = word_at(&words, 0xBEFE_0317);
  3536. let image = [words[sample], words[sample + 1]];
  3537. words[sample..sample + 2].fill(0xBF80_0000); // Keep the branch offsets.
  3538. words.splice(restore + 1..restore + 1, image);
  3539. assert_eq!(refusal(&words, false), NO_LOOP);
  3540. }
  3541. #[test]
  3542. fn a_wave64_access_with_exec_hi_overwritten_is_no_waterfall() {
  3543. let mut words = WATERFALL_FETCHED_WAVE64.to_vec();
  3544. let save = word_at(&words, 0xBE96_2416);
  3545. words[save + 1] = 0xBEFF_03C1; // s_mov_b32 exec_hi, -1
  3546. assert_eq!(refusal(&words, true), NOT_SELECTED);
  3547. }
  3548. /// The waterfall with `v_cmpx_eq` narrowing EXEC itself, and the retry
  3549. /// as `todo & !EXEC` (`folded`: in one `s_andn2_wrexec`), as LLVM's
  3550. /// AMDGPU backend writes it for GFX10 and later.
  3551. pub(crate) fn cmpx_waterfall(wave64: bool, folded: bool) -> Vec<u32> {
  3552. let (base, todo, restore): (&[u32], u32, u32) = if wave64 {
  3553. (WATERFALL_FETCHED_WAVE64, 0xBE94_047E, 0xBEFE_0414)
  3554. } else {
  3555. (WATERFALL_JOINED_WAVE32, 0xBE97_037E, 0xBEFE_0317)
  3556. };
  3557. let reads = word_at(base, 0x7E18_0504);
  3558. let sample = word_at(base, 0xF09C_0F08);
  3559. let mut w = base[..=word_at(base, todo)].to_vec();
  3560. // s_mov_b32 s21, exec_lo / s_mov_b64 s[22:23], exec
  3561. w.push(if wave64 { 0xBE96_047E } else { 0xBE95_037E });
  3562. w.extend(&base[reads..reads + 8]); // v_readfirstlane_b32 s12..s19
  3563. w.extend([
  3564. 0x7DE4_080C, // v_cmpx_eq_u64 s[12:13], v[4:5]
  3565. 0x7DE4_0C0E, // v_cmpx_eq_u64 s[14:15], v[6:7]
  3566. 0x7DE4_1010, // v_cmpx_eq_u64 s[16:17], v[8:9]
  3567. 0x7DE4_1412, // v_cmpx_eq_u64 s[18:19], v[10:11]
  3568. ]);
  3569. w.extend(&base[sample..sample + 2]); // image_sample_lz
  3570. match (wave64, folded) {
  3571. // s_andn2_wrexec_b32 s21, s21; s_cbranch_execnz
  3572. (false, true) => w.extend([0xBE95_4715, 0xBF89_FFF0]),
  3573. // s_andn2_b32 s21, s21, exec_lo; s_mov_b32 exec_lo, s21
  3574. (false, false) => w.extend([0x8A15_7E15, 0xBEFE_0315, 0xBF89_FFEF]),
  3575. // s_andn2_wrexec_b64 s[22:23], s[22:23]
  3576. (true, true) => w.extend([0xBE96_3A16, 0xBF89_FFF0]),
  3577. // s_andn2_b64 s[22:23], s[22:23], exec; s_mov_b64 exec, s[22:23]
  3578. (true, false) => w.extend([0x8A96_7E16, 0xBEFE_0416, 0xBF89_FFEF]),
  3579. }
  3580. w.extend(&base[word_at(base, restore)..]);
  3581. w
  3582. }
  3583. #[test]
  3584. fn a_waterfall_narrowed_by_v_cmpx_is_one() {
  3585. for wave64 in [false, true] {
  3586. for folded in [false, true] {
  3587. let r = waterfall(&cmpx_waterfall(wave64, folded), wave64)
  3588. .unwrap_or_else(|e| panic!("wave64 {wave64} folded {folded}: {e:?}"));
  3589. assert_eq!(r.waterfall.compares.len(), 4, "{wave64} {folded}");
  3590. assert_eq!(r.waterfall.reads.len(), 8, "{wave64} {folded}");
  3591. }
  3592. }
  3593. }
  3594. #[test]
  3595. fn a_v_cmpx_waterfall_whose_retry_drops_lanes_is_none() {
  3596. let mut words = cmpx_waterfall(false, false);
  3597. let retry = word_at(&words, 0x8A15_7E15);
  3598. words[retry] = 0x8A15_7E6A; // s_andn2_b32 s21, vcc_lo, exec_lo
  3599. assert_eq!(refusal(&words, false), BAD_RETRY);
  3600. }
  3601. #[test]
  3602. fn a_waterfall_nested_in_another_is_refused_by_name() {
  3603. // An image whose resource and sampler are both per lane, with one
  3604. // loop per operand, the one for the sampler inside the one for the
  3605. // resource (what the SelectionDAG legalisation in LLVM would give).
  3606. // The console gives each lane its own pair. Refused for now: the
  3607. // access of the inner loop reads the first-lane dwords of the outer
  3608. // loop, which another block holds.
  3609. let words = [
  3610. 0xBE84_0300, // s_mov_b32 s4, s0
  3611. 0xBE85_0380, // s_mov_b32 s5, 0
  3612. 0xBE86_0301, // s_mov_b32 s6, s1
  3613. 0xBE87_0380, // s_mov_b32 s7, 0
  3614. 0xF408_0A02,
  3615. 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40
  3616. 0x7E04_0D00, // v_cvt_f32_u32 v2, v0
  3617. 0x7E06_0302, // v_mov_b32 v3, v2
  3618. 0x3420_0082, // v_lshlrev_b32 v16, 2, v0
  3619. 0x3602_0081, // v_and_b32 v1, 1, v0
  3620. 0x3402_0285, // v_lshlrev_b32 v1, 5, v1
  3621. 0x3622_0080, // v_and_b32 v17, 0, v0
  3622. 0x3422_2284, // v_lshlrev_b32 v17, 4, v17
  3623. 0xDC38_8000,
  3624. 0x0404_0001, // global_load_dwordx4 v[4:7], v1, s[4:5]
  3625. 0xDC38_8010,
  3626. 0x0804_0001, // global_load_dwordx4 v[8:11], v1, s[4:5] offset:16
  3627. 0xDC38_8000,
  3628. 0x1406_0011, // global_load_dwordx4 v[20:23], v17, s[6:7]
  3629. 0xBF8C_0070, // s_waitcnt vmcnt(0) lgkmcnt(0)
  3630. 0xBE94_037E, // s_mov_b32 s20, exec_lo
  3631. // L1, the loop over the resource:
  3632. 0x7E18_0504, // v_readfirstlane_b32 s12, v4
  3633. 0x7E1A_0505,
  3634. 0x7E1C_0506,
  3635. 0x7E1E_0507,
  3636. 0x7E20_0508,
  3637. 0x7E22_0509,
  3638. 0x7E24_050A,
  3639. 0x7E26_050B, // v_readfirstlane_b32 s19, v11
  3640. 0xD4E2_0015,
  3641. 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5]
  3642. 0xD4E2_0016,
  3643. 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7]
  3644. 0x8715_1615, // s_and_b32 s21, s21, s22
  3645. 0xD4E2_0016,
  3646. 0x0002_1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9]
  3647. 0x8715_1615, // s_and_b32 s21, s21, s22
  3648. 0xD4E2_0016,
  3649. 0x0002_1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11]
  3650. 0x8715_1615, // s_and_b32 s21, s21, s22
  3651. 0xBE95_3C15, // s_and_saveexec_b32 s21, s21
  3652. 0xBE9A_037E, // s_mov_b32 s26, exec_lo
  3653. // L2, the loop over the sampler:
  3654. 0x7E10_0514, // v_readfirstlane_b32 s8, v20
  3655. 0x7E12_0515, // v_readfirstlane_b32 s9, v21
  3656. 0x7E14_0516, // v_readfirstlane_b32 s10, v22
  3657. 0x7E16_0517, // v_readfirstlane_b32 s11, v23
  3658. 0xD4E2_0018,
  3659. 0x0002_2808, // v_cmp_eq_u64_e64 s24, s[8:9], v[20:21]
  3660. 0xD4E2_0019,
  3661. 0x0002_2C0A, // v_cmp_eq_u64_e64 s25, s[10:11], v[22:23]
  3662. 0x8718_1918, // s_and_b32 s24, s24, s25
  3663. 0xBE98_3C18, // s_and_saveexec_b32 s24, s24
  3664. 0xF09C_0F08,
  3665. 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11]
  3666. 0x897E_187E, // s_xor_b32 exec_lo, exec_lo, s24
  3667. 0xBF89_FFF2, // s_cbranch_execnz L2
  3668. 0xBEFE_031A, // s_mov_b32 exec_lo, s26
  3669. 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21
  3670. 0xBF89_FFDA, // s_cbranch_execnz L1
  3671. 0xBEFE_0314, // s_mov_b32 exec_lo, s20
  3672. 0xE070_1000,
  3673. 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen
  3674. 0xBF81_0000, // s_endpgm
  3675. ];
  3676. assert_eq!(refusal(&words, false), SPLIT);
  3677. }
  3678. #[test]
  3679. fn descriptors_read_from_the_first_lane_of_lds_fail_naming_it() {
  3680. // The waterfall over descriptors each lane read from LDS:
  3681. // ds_read_b128 v[4:7], v1 and ds_read_b128 v[8:11], v1 offset:16
  3682. // in place of the global loads.
  3683. let mut words = WATERFALL_FETCHED_WAVE32.to_vec();
  3684. words[5..9].copy_from_slice(&[0xDBFC_0000, 0x0400_0001, 0xDBFC_0010, 0x0800_0001]);
  3685. let err = waterfall(&words, false).unwrap_err();
  3686. assert!(
  3687. matches!(
  3688. err,
  3689. ShaderError::Unsupported {
  3690. what: "a descriptor read from the first lane of an LDS read",
  3691. ..
  3692. }
  3693. ),
  3694. "{err:?}"
  3695. );
  3696. }
  3697. /// The block of `p` at byte `offset`.
  3698. fn block_at(words: &[u32], offset: usize) -> usize {
  3699. let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
  3700. let p = crate::ir::build(&code, false, 256).unwrap();
  3701. p.blocks.iter().position(|b| b.offset == offset).unwrap()
  3702. }
  3703. /// The table offset of what the scalar load of `s` reads.
  3704. fn table_offset(r: &Resources, s: &Source) -> u32 {
  3705. match *s {
  3706. Source::Loaded { load, first: 0 } => {
  3707. r.scalar.iter().find(|x| x.0 == load).unwrap().1.offset
  3708. }
  3709. ref s => panic!("{s:?}"),
  3710. }
  3711. }
  3712. #[test]
  3713. fn descriptors_read_from_the_first_lane_of_an_if_else_join_are_traced_per_path() {
  3714. let words = WATERFALL_JOINED_WAVE32;
  3715. let r = waterfall(words, false).unwrap();
  3716. let image = r
  3717. .descriptors
  3718. .iter()
  3719. .find(|d| matches!(d.source, Source::LanePhi { .. }))
  3720. .unwrap();
  3721. // The join after the else arm: lanes that ran it (lanes from 16 on)
  3722. // take the second entry (0x20); the others come through the flow
  3723. // block, whose join gives lanes that ran the then arm the first one
  3724. // (0). No lane that skipped the then arm comes that way, so the
  3725. // dwords they held before (the inputs) are not traced.
  3726. let Source::LanePhi { block, args } = &image.source else {
  3727. unreachable!()
  3728. };
  3729. assert_eq!(*block, block_at(words, 0x9c));
  3730. let [Some(flow), Some(other)] = &args[..] else {
  3731. panic!("{args:?}")
  3732. };
  3733. assert_eq!(table_offset(&r, other), 0x20);
  3734. let Source::LanePhi { block, args } = flow else {
  3735. panic!("{flow:?}")
  3736. };
  3737. assert_eq!(*block, block_at(words, 0x70));
  3738. let [None, Some(then)] = &args[..] else {
  3739. panic!("{args:?}")
  3740. };
  3741. assert_eq!(table_offset(&r, then), 0);
  3742. // The loop's compares are of the joined dwords; still recognised.
  3743. assert_eq!(r.waterfall.compares.len(), 4);
  3744. assert_eq!(r.waterfall.reads.len(), 8);
  3745. // Without the lanes' paths the join is refused.
  3746. let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
  3747. let p = crate::ir::build(&code, false, 256).unwrap();
  3748. let layout = [param(Table, 0, 1), param(Table, 1, 1)];
  3749. let err = track(&p, &layout, HwStage::Cs, None).unwrap_err();
  3750. assert!(
  3751. matches!(
  3752. err,
  3753. ShaderError::Unsupported {
  3754. what: "a descriptor read from the first lane of a phi, without the lanes' paths",
  3755. ..
  3756. }
  3757. ),
  3758. "{err:?}"
  3759. );
  3760. }
  3761. #[test]
  3762. fn descriptors_joined_from_a_per_lane_load_and_a_per_lane_choice_are_traced_per_path() {
  3763. let words = WATERFALL_JOINED_MIXED_WAVE32;
  3764. let r = waterfall(words, false).unwrap();
  3765. let image = r
  3766. .descriptors
  3767. .iter()
  3768. .find(|d| matches!(d.source, Source::LanePhi { .. }))
  3769. .unwrap();
  3770. let Source::LanePhi { block, args } = &image.source else {
  3771. unreachable!()
  3772. };
  3773. assert_eq!(*block, block_at(words, 0xb8));
  3774. let [
  3775. Some(Source::LanePhi { args: flow, .. }),
  3776. Some(Source::Lanes { args: picked, .. }),
  3777. ] = &args[..]
  3778. else {
  3779. panic!("{args:?}")
  3780. };
  3781. // The then arm loads each lane's entry from the table at s0.
  3782. let [None, Some(Source::Fetched { load, first: 0 })] = flow[..] else {
  3783. panic!("{flow:?}")
  3784. };
  3785. let a = r.scalar.iter().find(|s| s.0 == load).unwrap().1;
  3786. assert_eq!((a.param, a.offset), (0, 0));
  3787. assert!(a.dynamic.is_some());
  3788. // The else arm picks the first entry where vcc is set.
  3789. let offsets: Vec<u32> = picked.iter().map(|s| table_offset(&r, s)).collect();
  3790. assert_eq!(offsets, [0, 0x20]);
  3791. assert_eq!(r.waterfall.compares.len(), 4);
  3792. }
  3793. #[test]
  3794. fn a_descriptor_read_from_the_first_lane_of_a_loop_phi_fails_naming_it() {
  3795. let err = waterfall(WATERFALL_LOOPED_WAVE32, false).unwrap_err();
  3796. assert!(
  3797. matches!(
  3798. err,
  3799. ShaderError::Unsupported {
  3800. what: "a descriptor read from the first lane of a phi at a loop header",
  3801. ..
  3802. }
  3803. ),
  3804. "{err:?}"
  3805. );
  3806. }
  3807. #[test]
  3808. fn a_per_lane_descriptor_some_lanes_do_not_write_fails() {
  3809. // The else arm of WATERFALL_JOINED_WAVE32 not skipped (its
  3810. // s_cbranch_execz an s_nop): it runs with EXEC clear in the lanes
  3811. // of the then arm, which keep the first entry; the second is not
  3812. // every lane's.
  3813. let mut words = WATERFALL_JOINED_WAVE32.to_vec();
  3814. let skip = words.iter().rposition(|&w| w == 0xBF88_0008).unwrap();
  3815. words[skip] = 0xBF80_0000;
  3816. let err = waterfall(&words, false).unwrap_err();
  3817. assert!(
  3818. matches!(
  3819. err,
  3820. ShaderError::Unsupported {
  3821. what: "a per-lane descriptor written where some lanes may keep the old one",
  3822. ..
  3823. }
  3824. ),
  3825. "{err:?}"
  3826. );
  3827. }
  3828. #[test]
  3829. fn a_buffer_descriptor_joined_per_lane_is_traced_on_the_paths_of_lanes_that_load() {
  3830. let words = WATERFALL_JOINED_BUFFER_WAVE32;
  3831. let r = waterfall(words, false).unwrap();
  3832. let buffer = r
  3833. .descriptors
  3834. .iter()
  3835. .find(|d| matches!(d.source, Source::LanePhi { .. }))
  3836. .unwrap();
  3837. // The outer join: lanes from the else arm's inner join, or (below
  3838. // 16) through the flow block.
  3839. let Source::LanePhi { block, args } = &buffer.source else {
  3840. unreachable!()
  3841. };
  3842. assert_eq!(*block, block_at(words, 0x78));
  3843. let [
  3844. Some(Source::LanePhi { args: flow, .. }),
  3845. Some(Source::LanePhi {
  3846. block: inner,
  3847. args: nested,
  3848. }),
  3849. ] = &args[..]
  3850. else {
  3851. panic!("{args:?}")
  3852. };
  3853. let [None, Some(then)] = &flow[..] else {
  3854. panic!("{flow:?}")
  3855. };
  3856. assert_eq!(table_offset(&r, then), 0);
  3857. // Lanes from 24 on skip the inner arm and keep the inputs, but do
  3858. // not load: that edge is not traced.
  3859. assert_eq!(*inner, block_at(words, 0x74));
  3860. let [None, Some(other)] = &nested[..] else {
  3861. panic!("{nested:?}")
  3862. };
  3863. assert_eq!(table_offset(&r, other), 0x20);
  3864. assert_eq!(r.waterfall.compares.len(), 2);
  3865. assert_eq!(r.waterfall.reads.len(), 4);
  3866. }
  3867. }