lower.rs 484 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498
  1. //! IR to DXIL, one machine instruction at a time (decision 0003).
  2. //!
  3. //! Every register dword is an `i32` (SCC an `i1`); float operations bitcast
  4. //! their operands. Lane masks exist only as the per-lane booleans of
  5. //! structurisation; branches and guards are built from them. A value the
  6. //! emitter cannot express is `Missing` with a reason, and only fails the
  7. //! program when something with an effect (an export, a branch) needs it.
  8. use std::collections::{BTreeMap, HashMap, HashSet};
  9. use super::UserData;
  10. use super::bitcode::{Attr, Bin, Cast, Rmw, Term, V, pred};
  11. use super::container::SigElement;
  12. use super::shader::{Shader, flags};
  13. use crate::ShaderError;
  14. use crate::gfx10::{Dpp, Fields, NULL, Operand};
  15. use crate::io::{Barycentric, Export, Input, Interp, Io, Target};
  16. use crate::ir::{EXEC, Exit, Inst, Program, Reg, Value};
  17. use crate::native::{HwStage, NativeProgram, ResourceType, RootType, StageIo, Usage, UsedResource};
  18. use crate::resource::{Address, CODE, MEMORY, Resources, Role, Site, Source};
  19. use crate::structure::{Atom, Bool, LaneExit, Structured};
  20. /// The ray-tracing node test (`image_bvh_intersect_ray`), a child module so
  21. /// it shares the emitter's state.
  22. #[path = "intersect.rs"]
  23. pub(super) mod intersect;
  24. type Why = &'static str;
  25. /// How an interpolation evaluates an input channel.
  26. #[derive(Debug, Clone, Copy)]
  27. enum Eval {
  28. /// Loaded with this DXIL interpolation mode (1: constant, P0).
  29. Mode(u8),
  30. /// From the vertex values of a constant element: P0 when `p0`, plus
  31. /// i (P1 - P0), plus j (P2 - P0), weights as floats.
  32. Weights {
  33. p0: bool,
  34. i: Option<V>,
  35. j: Option<V>,
  36. },
  37. }
  38. #[derive(Debug, Clone, Copy)]
  39. enum Val {
  40. I32(V),
  41. Bit(V),
  42. Missing(Why),
  43. }
  44. pub(crate) struct Lowered {
  45. pub dxil: Vec<u8>,
  46. /// Bit n: immediate sampler n is used for comparisons.
  47. pub cmp_samplers: u64,
  48. pub root_cbvs: Vec<u8>,
  49. pub root_srvs: Vec<u8>,
  50. pub root_uavs: Vec<u8>,
  51. pub user_data: Vec<UserData>,
  52. pub samplers: Vec<[u32; 4]>,
  53. /// The wave size the shader requires of the host, if any.
  54. pub wave_size: Option<u32>,
  55. /// Heap handles made with a non-uniform index.
  56. #[cfg(test)]
  57. pub nonuniform_handles: u32,
  58. /// Whether the program uses wave operations.
  59. #[cfg(test)]
  60. pub wave_ops: bool,
  61. }
  62. pub(crate) struct Parts<'a> {
  63. pub native: &'a NativeProgram,
  64. pub p: &'a Program,
  65. pub st: &'a Structured,
  66. pub io: &'a Io,
  67. pub res: &'a Resources,
  68. pub inputs: Vec<SigElement>,
  69. pub outputs: Vec<SigElement>,
  70. pub prims: Vec<SigElement>,
  71. /// Mesh: what the group id arrives multiplied by.
  72. pub mesh_stride: u32,
  73. }
  74. enum Stop {
  75. /// A phi whose incoming value has no DXIL form was read: redo with it missing.
  76. Retry(Value, Why),
  77. Fail(ShaderError),
  78. }
  79. pub(crate) fn lower(parts: &Parts) -> Result<Lowered, ShaderError> {
  80. let mut bad = HashMap::new();
  81. loop {
  82. match Lower::new(parts, &bad).run() {
  83. Ok(l) => return Ok(l),
  84. Err(Stop::Retry(v, why)) => {
  85. if bad.insert(v, why).is_some() {
  86. return Err(ShaderError::Unsupported {
  87. offset: 0,
  88. what: "a phi that does not settle",
  89. });
  90. }
  91. }
  92. Err(Stop::Fail(e)) => return Err(e),
  93. }
  94. }
  95. }
  96. const TWO_PI: f32 = std::f32::consts::TAU;
  97. /// `s_sendmsg` id of a mesh or NGG stage's output allocation request.
  98. const GS_ALLOC_REQ: u16 = 9;
  99. /// The f16 bits of inline float constant `c` (240..=248: 0.5, -0.5, 1.0,
  100. /// -1.0, 2.0, -2.0, 4.0, -4.0, 1/(2 pi)).
  101. fn inline_f16(c: u8) -> u32 {
  102. [
  103. 0x3800, 0xB800, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x4400, 0xC400, 0x3118,
  104. ][usize::from(c - 240)]
  105. }
  106. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  107. enum Numeric {
  108. Unorm,
  109. Snorm,
  110. Uscaled,
  111. Sscaled,
  112. Uint,
  113. Sint,
  114. Float,
  115. }
  116. /// A GFX10 buffer format (the unified format of typed buffer loads): the
  117. /// channel widths from the lowest bits up, and how the channels convert.
  118. /// Formats are numbered in families (`8`, `16`, `8_8`, ...: AMD names
  119. /// list channels from the highest bits), each with its numeric formats in
  120. /// the order unorm, snorm, uscaled, sscaled, uint, sint, float.
  121. fn buffer_format(format: u8) -> Option<(&'static [u32], Numeric)> {
  122. use Numeric::*;
  123. const NORM: &[Numeric] = &[Unorm, Snorm, Uscaled, Sscaled, Uint, Sint];
  124. const ALL: &[Numeric] = &[Unorm, Snorm, Uscaled, Sscaled, Uint, Sint, Float];
  125. const WIDE: &[Numeric] = &[Uint, Sint, Float];
  126. // Numbers and order from LLVM's `UfmtGFX10` (`SIDefines.h`); the GFX10
  127. // buffer formats have no 5_9_9_9. Channel order from Mesa
  128. // (`ac_formats.c`): R11G11B10_FLOAT is 10_11_11, and 10_10_10_2 has
  129. // its 2-bit channel in the lowest bits.
  130. const FAMILIES: [(&[u32], &[Numeric]); 14] = [
  131. (&[8], NORM),
  132. (&[16], ALL),
  133. (&[8, 8], NORM),
  134. (&[32], WIDE),
  135. (&[16, 16], ALL),
  136. (&[11, 11, 10], ALL), // 10_11_11
  137. (&[10, 11, 11], ALL), // 11_11_10
  138. (&[2, 10, 10, 10], NORM), // 10_10_10_2
  139. (&[10, 10, 10, 2], NORM), // 2_10_10_10
  140. (&[8, 8, 8, 8], NORM),
  141. (&[32, 32], WIDE),
  142. (&[16, 16, 16, 16], ALL),
  143. (&[32, 32, 32], WIDE),
  144. (&[32, 32, 32, 32], WIDE),
  145. ];
  146. let mut n = usize::from(format.checked_sub(1)?);
  147. for (bits, numerics) in FAMILIES {
  148. if n < numerics.len() {
  149. return Some((bits, numerics[n]));
  150. }
  151. n -= numerics.len();
  152. }
  153. None
  154. }
  155. /// How far a float channel of `width` bits (16, or the unsigned 11- and
  156. /// 10-bit floats of the packed formats) shifts up to be a half:
  157. /// the small floats are a half's exponent (5 bits, biased 15) and the top
  158. /// of its mantissa, without the sign, so `legacyF16ToF32` widens them
  159. /// exactly, denormals, infinities and NaNs included.
  160. fn half_shift(width: u32) -> u32 {
  161. debug_assert!(matches!(width, 10 | 11 | 16), "{width}-bit float");
  162. if width == 16 { 0 } else { 15 - width }
  163. }
  164. struct Lower<'a> {
  165. s: Shader,
  166. x: &'a Parts<'a>,
  167. bad: &'a HashMap<Value, Why>,
  168. lane_fail: HashMap<Value, Why>,
  169. vals: HashMap<Value, Val>,
  170. floats: HashMap<Value, V>,
  171. /// DXIL block per IR block (unreachable: none).
  172. block: Vec<Option<usize>>,
  173. cur: usize,
  174. bools: HashMap<(usize, Bool), V>,
  175. lane_bits: HashMap<Value, V>,
  176. /// IR phi location by value.
  177. phi_at: HashMap<Value, (usize, usize)>,
  178. /// Descriptor dwords with no host value (addresses, formats, all of a constant
  179. /// buffer's): no program reads them as numbers ([`Self::dead`]).
  180. stale: HashSet<Value>,
  181. mask_phis: HashMap<Value, V>,
  182. pending_masks: Vec<(V, usize, usize)>,
  183. data_phis: Vec<(V, usize, usize)>,
  184. read_phis: HashSet<Value>,
  185. params: HashMap<Value, (usize, u32)>,
  186. user_data: Option<V>,
  187. user_reads: BTreeMap<u32, UserData>,
  188. samplers: Vec<[u32; 4]>,
  189. descriptors: HashMap<(Site, bool), &'a Source>,
  190. scalar: HashMap<Site, Address>,
  191. exports: HashMap<Site, &'a Export>,
  192. interps: HashMap<Site, &'a Interp>,
  193. handles: HashMap<(usize, Site, u8, bool, (u32, u32)), V>,
  194. /// Element strides read from the host's table by heap slot
  195. /// ([`super::shader::SLOT_STRIDES`]), by block and descriptor load.
  196. strides: HashMap<(usize, Site, u8), V>,
  197. /// Blocks splitting the edge from one IR block to another.
  198. edges: HashMap<(usize, usize), usize>,
  199. /// Per IR block: a `done` export is behind every lane entering it.
  200. exported: Vec<bool>,
  201. /// Reverse-postorder index per IR block.
  202. rpo: Vec<usize>,
  203. /// DXIL block each IR block ends in (guarded stores split blocks).
  204. tail: Vec<Option<usize>>,
  205. /// The program writes UAVs: barriers fence them too.
  206. writes_uavs: bool,
  207. /// src0 of the current instruction as DPP fetched it.
  208. src0: Option<V>,
  209. /// Compute code that reads other lanes: thread ids follow the host
  210. /// lanes, so lane n is console lane n.
  211. console_lanes: bool,
  212. /// Mesh: the thread index in the group (made in the entry block).
  213. flat: Option<V>,
  214. /// Mesh: IR blocks whose `s_barrier` is left out.
  215. no_barrier: HashSet<usize>,
  216. /// IR blocks whose `s_barrier` not every lane is sure to reach (a lane
  217. /// branch lies between the entry and the block, or the program has a
  218. /// loop a lane can be cut out of): the barrier there keeps its fences
  219. /// and does not wait for the group ([`super::group_sync`]).
  220. fence_only: HashSet<usize>,
  221. /// A group barrier before every LDS access (a console wave run as two host waves).
  222. split_lds: bool,
  223. /// With `split_lds`, LDS accesses in lane branches: per IR block whether every lane runs
  224. /// it, and whether the host waves meet at its start and before its exit ([`lds_meetings`]).
  225. lds_meet: Option<(Vec<bool>, Vec<(bool, bool)>)>,
  226. /// A console wave64 program run as two host waves of 32 that exchange through LDS: the first
  227. /// of two exchange dwords, whether the group has no upper half (32 threads or fewer), and per
  228. /// IR block whether every lane runs it (exchanges need both halves there).
  229. exchange: Option<(u32, bool, Vec<bool>)>,
  230. /// With `exchange`: nothing is exchanged, each host wave acts as a wave
  231. /// of its own ([`with_local_waves`]).
  232. local: bool,
  233. /// The instruction being lowered may read a lane mask as a number under
  234. /// `local` (a bit count, a first set bit, `v_mbcnt`).
  235. local_ok: bool,
  236. /// With `local`: every mask read and lane read is taken per host wave
  237. /// ([`with_local_waves_any`]).
  238. local_any: bool,
  239. /// With `exchange`: VGPR values every lane holds alike ([`lane_uniform`]); a first-lane
  240. /// read of one needs nothing from the other host wave.
  241. uniform: HashSet<Value>,
  242. /// With `exchange`: the wave ORs that only steer a loop over each lane's own bits, which
  243. /// a host wave takes over its own lanes wherever they stand ([`super::own_bits`]).
  244. own_bits: super::own_bits::OwnBits,
  245. /// The console lane (0..63) of this thread, made in the entry block.
  246. clane: Option<V>,
  247. /// The first exchange dword of this thread's console wave ([`Self::exchange_pair`]).
  248. pair: Option<V>,
  249. /// A console wave64 program in host waves of 32: the LDS dword counting the console threads
  250. /// handed to host waves (`wave_base`), and the base made in the entry block.
  251. halves: Option<u32>,
  252. wave_base: Option<V>,
  253. /// Vertex and mesh outputs holding 16-bit values: row, whether two per
  254. /// dword, and the row packed after it.
  255. half_outputs: HashMap<u8, (bool, Option<u8>)>,
  256. /// How lane masks become data.
  257. mask_data: MaskData,
  258. /// The instruction being lowered may read lane masks as data.
  259. mask_ok: bool,
  260. /// Ballots of masks read as data, by low dword: (low, high).
  261. ballots: HashMap<Value, (V, V)>,
  262. /// Masks whose ballot is being built: a mask whose lane bit needs its
  263. /// own value as a number (an opaque mask keyed by a dword it shares
  264. /// with another) would otherwise recurse until the stack overflows.
  265. balloting: HashSet<Value>,
  266. /// Block writing each value.
  267. def_block: HashMap<Value, usize>,
  268. /// IR block being lowered.
  269. cur_ir: usize,
  270. /// Whole-wave sections by block and start index.
  271. sections: HashMap<usize, HashMap<usize, super::wave::Section>>,
  272. /// Values written in a section that code outside it reads.
  273. section_out: HashSet<Value>,
  274. /// The program's constant table (the code from the first byte read
  275. /// through `s_getpc_b64` on): global, first byte, dwords.
  276. code_table: Option<(V, u32, u32)>,
  277. /// Loop headers' iteration counters (see [`LOOP_LIMIT`]): the phi by
  278. /// IR block, and its incoming (value, DXIL block) pairs.
  279. counters: HashMap<usize, (V, Vec<(V, usize)>)>,
  280. /// The block a loop stopped by [`LOOP_LIMIT`] leaves the program from.
  281. abort: Option<usize>,
  282. }
  283. /// Iterations after which a loop is left (per entry into it), unless
  284. /// [`super::loop_limit`] says otherwise. The console runs a loop as long as
  285. /// its data says; data the host has not mirrored yet (a null view reads
  286. /// zeros) can make that four billion iterations, which hangs the host GPU
  287. /// until the driver resets it. A lane that reaches the limit leaves the
  288. /// program as killed (a pixel discards).
  289. // shortcut: a genuine loop of more iterations than this is cut short too.
  290. pub(super) const LOOP_LIMIT: u32 = 1 << 20;
  291. /// Lane masks read as numbers (`s_bcnt1`, `s_ff1`, `v_mbcnt`, scalar
  292. /// compares, bit tests) are ballots of the lanes' booleans, taken where the
  293. /// mask is written: structurisation's `active` masks hold only lanes that
  294. /// reach that block, so the ballot misses none.
  295. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  296. enum MaskData {
  297. /// Compute: host lane n is console lane n (the program declares the
  298. /// console's wave size), so ballots are the console's masks bit for bit
  299. /// and any use is exact.
  300. Console,
  301. /// Pixel and vertex programs: ballots over the host's wave, whatever its
  302. /// size. Only uses that mean the same on any wave are allowed: counts,
  303. /// the first lane, the count below a lane, equality (the HLSL wave
  304. /// operations the console compiler expands). Lane numbers stay host
  305. /// lanes throughout (`v_mbcnt`, `v_readlane` at a computed lane).
  306. Host,
  307. /// Mesh programs: their lanes and waves (LDS per console wave) are the
  308. /// console's but no host wave size can be declared.
  309. None,
  310. }
  311. /// What a value holding a lane mask read as a number stops with.
  312. pub(super) const LANE_MASK: Why = "a lane mask read as data";
  313. /// A mask with lanes outside EXEC where it is written, read as a number where the lanes that
  314. /// run that block are not all of the wave.
  315. pub(super) const MASK_ELSEWHERE: Why = "a lane mask holding lanes elsewhere read as data";
  316. /// Instructions that read a lane mask (not EXEC implicitly, not a lane's
  317. /// bit) as a number.
  318. /// Per IR block: every lane of the wave that started the program runs it – no per-lane branch
  319. /// separates it from the entry (it lies in no lane branch's region: the blocks reachable from
  320. /// the branch that do not post-dominate it). None with an indirect exit (not followed).
  321. fn all_lane_blocks(st: &Structured) -> Option<Vec<bool>> {
  322. let n = st.exits.len();
  323. let mut all = vec![true; n];
  324. for (_, region) in lane_regions(st)? {
  325. for b in (0..n).filter(|&b| region[b]) {
  326. all[b] = false;
  327. }
  328. }
  329. Some(all)
  330. }
  331. /// Every per-lane branch (by its block) with its region: the blocks reachable from it that do
  332. /// not post-dominate it, which only some lanes run. Not the branches the wave takes together
  333. /// ([`Structured::wide`]), nor those on scalar conditions. None with an indirect exit.
  334. fn lane_regions(st: &Structured) -> Option<Vec<(usize, Vec<bool>)>> {
  335. let n = st.exits.len();
  336. let mut succ: Vec<Vec<usize>> = vec![Vec::new(); n];
  337. for (b, e) in st.exits.iter().enumerate() {
  338. match *e {
  339. LaneExit::Jump(t) => succ[b].push(t),
  340. LaneExit::Branch { taken, not_taken, .. } => {
  341. succ[b].push(taken);
  342. succ[b].push(not_taken);
  343. }
  344. LaneExit::End => {}
  345. LaneExit::Indirect => return None,
  346. }
  347. }
  348. // post-dominators (bitsets; a virtual exit after every End)
  349. let words = n.div_ceil(64);
  350. let full = vec![u64::MAX; words];
  351. let mut pdom: Vec<Vec<u64>> = (0..n).map(|b| if succ[b].is_empty() { let mut v = vec![0; words]; v[b / 64] |= 1 << (b % 64); v } else { full.clone() }).collect();
  352. let mut changed = true;
  353. while changed {
  354. changed = false;
  355. for b in (0..n).rev() {
  356. if succ[b].is_empty() {
  357. continue;
  358. }
  359. let mut v = full.clone();
  360. for &t in &succ[b] {
  361. for w in 0..words {
  362. v[w] &= pdom[t][w];
  363. }
  364. }
  365. v[b / 64] |= 1 << (b % 64);
  366. if v != pdom[b] {
  367. pdom[b] = v;
  368. changed = true;
  369. }
  370. }
  371. }
  372. let mut regions = Vec::new();
  373. for (d, e) in st.exits.iter().enumerate() {
  374. let LaneExit::Branch { when, .. } = *e else { continue };
  375. if st.wide.contains(&d) || st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_))) {
  376. continue; // a wave-wide or uniform branch: all lanes go the same way
  377. }
  378. // blocks reachable from the lane branch that do not post-dominate it
  379. let mut seen = vec![false; n];
  380. let mut stack: Vec<usize> = succ[d].clone();
  381. while let Some(b) = stack.pop() {
  382. if seen[b] || pdom[d][b / 64] >> (b % 64) & 1 == 1 {
  383. continue;
  384. }
  385. seen[b] = true;
  386. stack.extend(succ[b].iter().copied());
  387. }
  388. regions.push((d, seen));
  389. }
  390. Some(regions)
  391. }
  392. /// The per-lane branches (by block) whose regions hold a block of `needs` (blocks where two
  393. /// host waves must meet, [`take_needs`]): the ones to take wave-wide
  394. /// ([`crate::structure::structure_wide`]) so that every lane runs those blocks. None if one
  395. /// of them is a branch whose wave-wide meaning is not known ([`Structured::wave_any`]).
  396. pub(super) fn branches_around(st: &Structured, needs: &[usize]) -> Option<Vec<usize>> {
  397. let mut out = Vec::new();
  398. for (d, region) in lane_regions(st)? {
  399. if needs.iter().any(|&b| region.get(b).copied().unwrap_or(false)) {
  400. st.wave_any.get(d).copied().flatten()?;
  401. out.push(d);
  402. }
  403. }
  404. Some(out)
  405. }
  406. /// Whether a refusal is of code that needs every lane of the wave where it stands (two host
  407. /// waves meeting there), which the other forms of the program may give it.
  408. pub(super) fn needs_every_lane(what: &str) -> bool {
  409. what.ends_with("where not every lane runs") || what == MASK_ELSEWHERE
  410. }
  411. /// The blocks where the last lowering on this thread wanted every lane and did not have it
  412. /// (its "... where not every lane runs" refusals), which it forgets.
  413. pub(super) fn take_needs() -> Vec<usize> {
  414. NEEDS.take()
  415. }
  416. fn need(block: usize) {
  417. NEEDS.with_borrow_mut(|n| {
  418. if !n.contains(&block) {
  419. n.push(block);
  420. }
  421. });
  422. }
  423. /// VGPR values that are the same in every lane holding them (`all` is [`all_lane_blocks`]):
  424. /// written by an instruction every arriving lane runs (no guard), lane by lane, from scalars,
  425. /// constants and such values; or loaded from an address made of them. The compiler keeps
  426. /// wave-uniform data in VGPRs and fetches it with `v_readfirstlane`.
  427. /// shortcut: a value joined by a phi counts only where every predecessor is a block all lanes
  428. /// run (no lane branch can have split the arriving lanes); loop-carried values never do.
  429. fn lane_uniform(p: &Program, st: &Structured, all: &[bool]) -> HashSet<Value> {
  430. let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v);
  431. let mut same: HashSet<Value> = HashSet::new();
  432. for b in crate::ir::reverse_postorder(&p.blocks) {
  433. let block = &p.blocks[b];
  434. let whole = block.preds.iter().all(|&q| all.get(q).copied().unwrap_or(false));
  435. for phi in &block.phis {
  436. if matches!(phi.reg, Reg::V(_)) && whole && phi.args.iter().all(|a| same.contains(a)) {
  437. same.insert(phi.value);
  438. }
  439. }
  440. for (i, inst) in block.insts.iter().enumerate() {
  441. let name = inst.name();
  442. let ops: Vec<Operand> = match &inst.fields {
  443. Fields::Valu(v)
  444. if v.dpp.is_none()
  445. && v.sdwa.is_none()
  446. && !name.starts_with("v_mbcnt")
  447. && !name.starts_with("v_cmpx")
  448. && !name.contains("lane") =>
  449. {
  450. v.src.clone()
  451. }
  452. _ => continue,
  453. };
  454. if st.guards[b][i].is_some() {
  455. continue; // lanes outside EXEC keep another value
  456. }
  457. let alike = ops.iter().all(|op| match *op {
  458. Operand::Vector { reg, .. } => {
  459. // every dword of the operand the instruction reads from that register on
  460. let read: Vec<Value> =
  461. inst.reads.iter().filter(|r| matches!(r.0, Reg::V(x) if x >= reg)).map(|r| r.1).collect();
  462. !read.is_empty() && read.iter().all(|x| same.contains(x))
  463. }
  464. // a scalar is one value; a lane mask is not, unless a compare of such values made it
  465. Operand::Scalar { code, .. } if code != NULL => {
  466. inst.read(Reg::S(code)).is_none_or(|x| !is_mask(x) || same.contains(&x))
  467. }
  468. _ => true,
  469. });
  470. if alike {
  471. same.extend(inst.writes.iter().filter(|w| w.0 != Reg::Scc).map(|w| w.1));
  472. }
  473. }
  474. }
  475. same
  476. }
  477. /// What a register value holds, for [`wave_local`].
  478. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  479. enum Wave {
  480. /// Nothing that depends on how the threads are divided into waves.
  481. Plain,
  482. /// The number of the wave's first lane in a mask (`s_ff1`).
  483. First,
  484. /// A reduction over the wave's lanes: a count, a sum, a minimum...
  485. Total(super::wave::Op),
  486. /// A count or sum over the lanes below this one.
  487. Prefix,
  488. /// Derived from what a first-lane atomic returned: the slots the wave reserved.
  489. Base,
  490. /// A mix the idiom does not make.
  491. Mixed,
  492. }
  493. /// Whether a console wave64 program may run with each host wave as a wave of its own
  494. /// ([`with_local_waves`]): its wave-wide values are used only as the allocation idiom uses
  495. /// them, which does not care how the threads are divided into waves. A first-lane number only
  496. /// picks the first lane; a count or sum only goes into that lane's atomic on a shared counter;
  497. /// a prefix only goes onto the base that atomic returned; the first lane does nothing else.
  498. /// Anything else done with them takes one wave to be the whole thread group (a tile's result,
  499. /// say) and is refused, with the offset and what was found.
  500. /// Lane masks read as numbers by other instructions and lane reads outside whole-wave sections
  501. /// are stopped by the lowering itself.
  502. // shortcut: `v_readfirstlane` of a value that differs between lanes is taken as it is (this
  503. // host wave's first lane), and a guarded write of a plain value over a wave-dependent one is
  504. // the only mix of old and new lanes that is looked at.
  505. pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'static str)> {
  506. use super::wave::{Op, Shape};
  507. const FIRST: Why = "a wave's first-lane number used as data";
  508. const TOTAL: Why = "a count or sum over the wave used as data";
  509. const PREFIX: Why = "a count or sum over the lanes below used without a reserved base";
  510. const MIXED: Why = "a value that depends on the wave on some paths only";
  511. const EFFECT: Why = "a write by the wave's first lane other than its reservation";
  512. fn of(kind: &HashMap<Value, Wave>, v: Option<Value>) -> Wave {
  513. v.and_then(|v| kind.get(&v).copied()).unwrap_or(Wave::Plain)
  514. }
  515. fn put(kind: &mut HashMap<Value, Wave>, v: Value, k: Wave) {
  516. if k == Wave::Plain {
  517. kind.remove(&v);
  518. } else {
  519. kind.insert(v, k);
  520. }
  521. }
  522. let wild = |k: Wave| !matches!(k, Wave::Plain | Wave::Base);
  523. let why = |k: Wave| match k {
  524. Wave::First => FIRST,
  525. Wave::Total(_) => TOTAL,
  526. Wave::Prefix => PREFIX,
  527. _ => MIXED,
  528. };
  529. // a mask (by its low dword) under which only a wave's first lane runs
  530. let first_mask = |firsts: &HashSet<Value>, m: Option<Value>| {
  531. m.and_then(|m| st.masks.get(&m)).is_some_and(|&b| {
  532. st.bools
  533. .support(b)
  534. .iter()
  535. .any(|a| matches!(a, Atom::Lane(v) if firsts.contains(v)))
  536. })
  537. };
  538. // One instruction outside a section: the kind of what it writes, and whether it is a
  539. // first lane's reservation.
  540. let step = |inst: &Inst, kind: &HashMap<Value, Wave>, firsts: &mut HashSet<Value>| -> Result<(Wave, bool), Why> {
  541. let name = inst.name();
  542. let val = |op: &Operand| match *op {
  543. Operand::Vector { reg, .. } => inst.read(Reg::V(reg)),
  544. Operand::Scalar { code, .. } if code != NULL => inst.read(Reg::S(code)),
  545. _ => None,
  546. };
  547. let ops: Vec<Operand> = match &inst.fields {
  548. Fields::Valu(v) => v.src.clone(),
  549. Fields::Sop { dst, src, .. } => {
  550. let mut o = src.clone();
  551. if matches!(name, "s_addk_i32" | "s_mulk_i32") {
  552. o.extend(dst.iter().copied());
  553. }
  554. o
  555. }
  556. Fields::Buffer { data, .. } if name.contains("_atomic_") || name.contains("_store_") => {
  557. data.iter().copied().collect()
  558. }
  559. _ => Vec::new(),
  560. };
  561. let kinds: Vec<Wave> = ops.iter().map(|o| of(kind, val(o))).collect();
  562. // Everything else it reads (addresses, descriptors, SCC, the high dwords of wide
  563. // operands) must not depend on the wave. Not EXEC, and not the old value of a VGPR it
  564. // writes, which only the lanes outside EXEC keep.
  565. let named: Vec<Value> = ops.iter().filter_map(&val).collect();
  566. for &(r, v) in &inst.reads {
  567. let kept = matches!(r, Reg::V(_)) && inst.writes.iter().any(|w| w.0 == r);
  568. if matches!(r, Reg::S(c) if c == EXEC || c == EXEC + 1) || kept || named.contains(&v) {
  569. continue;
  570. }
  571. let k = of(kind, Some(v));
  572. if wild(k) {
  573. return Err(why(k));
  574. }
  575. }
  576. let w = kinds.iter().copied().find(|&k| wild(k)).unwrap_or(Wave::Mixed);
  577. let sum = |k: Wave| k == Wave::Total(Op::AddU);
  578. let is_mask = |o: &Operand| {
  579. val(o).is_some_and(|v| st.masks.contains_key(&v) || st.highs.contains_key(&v))
  580. };
  581. let mut reserved = false;
  582. let out = match (name, &kinds[..]) {
  583. ("s_ff1_i32_b64" | "s_ff1_i32_b32", _) if ops.first().is_some_and(is_mask) => Wave::First,
  584. ("s_bcnt1_i32_b64" | "s_bcnt1_i32_b32", _) if ops.first().is_some_and(is_mask) => {
  585. Wave::Total(Op::AddU)
  586. }
  587. // bits of a mask below the lane; with -1 for the mask, the lane's number
  588. ("v_mbcnt_lo_u32_b32" | "v_mbcnt_hi_u32_b32", [_, b]) => {
  589. match (matches!(ops[0], Operand::Scalar { .. }), *b) {
  590. (_, Wave::Prefix) | (true, Wave::Plain | Wave::Base) => Wave::Prefix,
  591. (false, Wave::Plain | Wave::Base) => Wave::Plain,
  592. (_, k) => return Err(why(k)),
  593. }
  594. }
  595. // nothing wave-dependent goes in; what derives from a reserved base stays marked
  596. _ if !kinds.iter().any(|&k| wild(k)) => {
  597. let derives = matches!(inst.fields, Fields::Valu(_) | Fields::Sop { .. });
  598. if derives && kinds.contains(&Wave::Base) { Wave::Base } else { Wave::Plain }
  599. }
  600. ("v_mov_b32" | "s_mov_b32", [k]) => *k,
  601. ("v_cmp_eq_i32" | "v_cmp_eq_u32" | "v_cmpx_eq_i32" | "v_cmpx_eq_u32", [a, b]) => {
  602. // the lane whose own number is the first lane's
  603. let lane = match (*a, *b) {
  604. (Wave::First, k) if !wild(k) => &ops[1],
  605. (k, Wave::First) if !wild(k) => &ops[0],
  606. _ => return Err(why(w)),
  607. };
  608. if !matches!(lane, Operand::Vector { .. }) {
  609. return Err(FIRST);
  610. }
  611. let mask = match &inst.fields {
  612. _ if name.starts_with("v_cmpx") => inst.write(Reg::S(EXEC)),
  613. Fields::Valu(v) => match v.dst {
  614. Some(Operand::Scalar { code, .. }) => inst.write(Reg::S(code)),
  615. _ => None,
  616. },
  617. _ => None,
  618. };
  619. firsts.extend(mask);
  620. Wave::Plain
  621. }
  622. ("v_add_nc_u32" | "s_add_i32", [a, b]) => match (*a, *b) {
  623. (Wave::Prefix, Wave::Base) | (Wave::Base, Wave::Prefix) => Wave::Base,
  624. (Wave::Prefix, Wave::Plain | Wave::Prefix) | (Wave::Plain, Wave::Prefix) => Wave::Prefix,
  625. (x, y) if sum(x) && sum(y) => x,
  626. _ => return Err(why(w)),
  627. },
  628. ("v_sub_nc_u32" | "s_sub_i32", [a, b]) => match (*a, *b) {
  629. (Wave::Base, Wave::Prefix) => Wave::Base,
  630. (Wave::Prefix, Wave::Plain) => Wave::Prefix,
  631. (Wave::Plain, y) if sum(y) && matches!(ops[0], Operand::Const(128)) => y,
  632. _ => return Err(why(w)),
  633. },
  634. ("s_mul_i32" | "v_mul_lo_u32" | "v_mul_u32_u24", [a, b]) => match (*a, *b) {
  635. (x, Wave::Plain) | (Wave::Plain, x) if sum(x) || x == Wave::Prefix => x,
  636. _ => return Err(why(w)),
  637. },
  638. ("s_lshl_b32", [x, Wave::Plain]) | ("v_lshlrev_b32", [Wave::Plain, x])
  639. if sum(*x) || *x == Wave::Prefix =>
  640. {
  641. *x
  642. }
  643. ("v_lshl_add_u32", [Wave::Prefix, Wave::Plain, c]) if !wild(*c) => {
  644. if *c == Wave::Base { Wave::Base } else { Wave::Prefix }
  645. }
  646. // the reservation: the first lane adds its wave's total to a shared counter
  647. (_, [Wave::Total(op)]) if name.contains("_atomic_") => {
  648. let want = match op {
  649. Op::AddU => "buffer_atomic_add",
  650. Op::MinU => "buffer_atomic_umin",
  651. Op::MaxU => "buffer_atomic_umax",
  652. Op::MinI => "buffer_atomic_smin",
  653. Op::MaxI => "buffer_atomic_smax",
  654. Op::Or => "buffer_atomic_or",
  655. Op::And => "buffer_atomic_and",
  656. Op::Xor => "buffer_atomic_xor",
  657. _ => "",
  658. };
  659. if name != want || !first_mask(firsts, inst.read(Reg::S(EXEC))) {
  660. return Err(TOTAL);
  661. }
  662. reserved = true;
  663. Wave::Base
  664. }
  665. _ => return Err(why(w)),
  666. };
  667. Ok((out, reserved))
  668. };
  669. let sections: Vec<_> = (0..p.blocks.len()).map(|b| super::wave::sections(p, b)).collect();
  670. let order = crate::ir::reverse_postorder(&p.blocks);
  671. let pass = |kind: &mut HashMap<Value, Wave>, firsts: &mut HashSet<Value>, check: bool| -> Result<(), (usize, Why)> {
  672. for &b in &order {
  673. let block = &p.blocks[b];
  674. for phi in &block.phis {
  675. let mut k = Wave::Plain;
  676. for (n, &a) in phi.args.iter().enumerate() {
  677. let x = of(kind, Some(a));
  678. k = match (k, x) {
  679. _ if n == 0 => x,
  680. (k, x) if k == x => k,
  681. (Wave::Plain, m @ (Wave::Base | Wave::Prefix))
  682. | (m @ (Wave::Base | Wave::Prefix), Wave::Plain) => m,
  683. _ => Wave::Mixed,
  684. };
  685. }
  686. put(kind, phi.value, k);
  687. }
  688. for (i, inst) in block.insts.iter().enumerate() {
  689. // inside a whole-wave section: what the simulation found each value to be
  690. if let Some((_, sec)) = sections[b].iter().find(|(s, sec)| i > **s && i < sec.end) {
  691. for &(_, w) in &inst.writes {
  692. let k = match sec.shapes.get(&w) {
  693. None => Wave::Mixed,
  694. Some(&Shape::K(_)) => Wave::Plain,
  695. Some(&Shape::Value(v)) => of(kind, Some(v)),
  696. Some(&Shape::Masked(src, _, _)) => of(kind, Some(src)),
  697. Some(&Shape::Active(op, src, mask, _)) => match of(kind, Some(src)) {
  698. Wave::Plain | Wave::Base => Wave::Total(op),
  699. // the first lane's own sum of a total is that total
  700. Wave::Total(o) if o == op && first_mask(firsts, Some(mask)) => Wave::Total(op),
  701. _ => Wave::Mixed,
  702. },
  703. Some(&Shape::Prefix(Op::AddU, src, mask, _, _)) => match of(kind, Some(src)) {
  704. Wave::Plain | Wave::Base => Wave::Prefix,
  705. Wave::Total(Op::AddU) if first_mask(firsts, Some(mask)) => Wave::Prefix,
  706. _ => Wave::Mixed,
  707. },
  708. Some(_) => Wave::Mixed,
  709. };
  710. put(kind, w, k);
  711. }
  712. continue;
  713. }
  714. let name = inst.name();
  715. if name.starts_with("s_cbranch") {
  716. continue; // with the block's exit, below
  717. }
  718. let (k, reserved) = match step(inst, kind, firsts) {
  719. Ok(r) => r,
  720. Err(why) if check => return Err((inst.machine.offset, why)),
  721. Err(_) => (Wave::Mixed, false),
  722. };
  723. // the same test as `Lower::inst`'s `effect`
  724. let effect = matches!(inst.fields, Fields::Exp { .. })
  725. || matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_")
  726. || name.contains("store")
  727. || name.contains("atomic")
  728. || matches!(inst.fields, Fields::Ds { .. })
  729. && !(name.starts_with("ds_read")
  730. || name.starts_with("ds_swizzle")
  731. || name.contains("permute"));
  732. if check && effect && !reserved && first_mask(firsts, inst.read(Reg::S(EXEC))) {
  733. return Err((inst.machine.offset, EFFECT));
  734. }
  735. let guarded = st.guards[b][i].is_some();
  736. for &(r, w) in &inst.writes {
  737. let mut kw = match r {
  738. // "some lane is counted" keeps the count's kind; any other SCC is one bit of data
  739. Reg::Scc if !name.starts_with("s_bcnt1") => {
  740. if wild(k) { Wave::Mixed } else { Wave::Plain }
  741. }
  742. _ => k,
  743. };
  744. // a guarded write leaves the old value in the lanes outside EXEC
  745. if guarded
  746. && matches!(r, Reg::V(_))
  747. && kw == Wave::Plain
  748. && matches!(of(kind, inst.read(r)), Wave::First | Wave::Total(_) | Wave::Prefix)
  749. {
  750. kw = Wave::Mixed;
  751. }
  752. put(kind, w, kw);
  753. }
  754. }
  755. // a branch on "some lane is counted": fine where the structure made it the lane's
  756. // own bit (the mask is EXEC under a scalar condition)
  757. if check
  758. && let Some(last) = block.insts.last()
  759. && last.name().starts_with("s_cbranch_scc")
  760. && let Some(scc) = last.read(Reg::Scc)
  761. && wild(of(kind, Some(scc)))
  762. {
  763. let own = matches!(st.exits[b], LaneExit::Branch { when, .. }
  764. if !st.bools.support(when).iter().any(|a| matches!(a, Atom::Uniform(v) if *v == scc)));
  765. if !own {
  766. return Err((last.machine.offset, TOTAL));
  767. }
  768. }
  769. }
  770. Ok(())
  771. };
  772. let mut kind: HashMap<Value, Wave> = HashMap::new();
  773. let mut firsts: HashSet<Value> = HashSet::new();
  774. // to a fixpoint (values carried around loops), then once more to say what is wrong
  775. let mut settled = false;
  776. for _ in 0..16 {
  777. let before = (kind.clone(), firsts.len());
  778. pass(&mut kind, &mut firsts, false)?;
  779. if (&before.0, before.1) == (&kind, firsts.len()) {
  780. settled = true;
  781. break;
  782. }
  783. }
  784. if !settled {
  785. return Err((0, MIXED));
  786. }
  787. pass(&mut kind, &mut firsts, true)
  788. }
  789. /// The mode of a group barrier the translation adds (host waves meeting):
  790. /// a wait for the group with a shared-memory fence; the fence alone with
  791. /// `VICTORY_GROUP_SYNC=0` ([`super::group_sync`]).
  792. fn meeting_mode() -> u32 {
  793. if super::group_sync() == 0 { 8 } else { 1 | 8 }
  794. }
  795. /// LDS accesses of a console wave run as two host waves, where some sit in blocks that only
  796. /// some lanes run (`all` is [`all_lane_blocks`]): per IR block, whether the host waves meet (a
  797. /// group barrier) at its start and before its exit. `None` if barriers cannot keep the
  798. /// console's order.
  799. ///
  800. /// The console runs the wave's lanes in step, so an LDS write is seen by every later read. Two
  801. /// host waves keep that order if they meet between any two accesses of which one writes. A
  802. /// barrier must be run by every thread, so it cannot stand in a lane branch's region; but
  803. /// every way into and out of such a region passes a block all lanes run, and the waves meet
  804. /// there: before the exit of an all-lane block into a region with LDS accesses, and at the
  805. /// start of an all-lane block entered from one. Accesses in all-lane blocks get their own
  806. /// barrier as before. What that cannot order is a write and a read inside one region (blocks
  807. /// joined without an all-lane block between them): refused.
  808. /// shortcut: two writes in one region are taken not to hit the same dword from both halves.
  809. fn lds_meetings(p: &crate::ir::Program, st: &Structured, all: &[bool]) -> Option<Vec<(bool, bool)>> {
  810. let n = st.exits.len();
  811. let succ = |b: usize| -> Vec<usize> {
  812. match st.exits[b] {
  813. LaneExit::Jump(t) => vec![t],
  814. LaneExit::Branch { taken, not_taken, .. } => vec![taken, not_taken],
  815. LaneExit::End | LaneExit::Indirect => Vec::new(),
  816. }
  817. };
  818. // regions: blocks not every lane runs, joined by the edges between them
  819. let mut region: Vec<usize> = (0..n).collect();
  820. fn find(region: &mut [usize], mut b: usize) -> usize {
  821. while region[b] != b {
  822. region[b] = region[region[b]];
  823. b = region[b];
  824. }
  825. b
  826. }
  827. for b in 0..n {
  828. for t in succ(b) {
  829. if !all[b] && !all[t] {
  830. let (x, y) = (find(&mut region, b), find(&mut region, t));
  831. region[x] = y;
  832. }
  833. }
  834. }
  835. // per region: LDS reads, LDS writes
  836. let mut reads = vec![false; n];
  837. let mut writes = vec![false; n];
  838. for (b, block) in p.blocks.iter().enumerate().take(n) {
  839. if all[b] {
  840. continue;
  841. }
  842. let r = find(&mut region, b);
  843. for i in &block.insts {
  844. let name = i.name();
  845. if !matches!(i.fields, Fields::Ds { .. }) || name.starts_with("ds_swizzle") || name.contains("permute") {
  846. continue;
  847. }
  848. if name.starts_with("ds_read") {
  849. reads[r] = true;
  850. } else {
  851. writes[r] = true;
  852. }
  853. }
  854. }
  855. if (0..n).any(|r| reads[r] && writes[r]) {
  856. return None;
  857. }
  858. let mut meet = vec![(false, false); n];
  859. for b in 0..n {
  860. for t in succ(b) {
  861. if all[b] && !all[t] {
  862. let r = find(&mut region, t);
  863. meet[b].1 |= reads[r] || writes[r];
  864. } else if !all[b] && all[t] {
  865. let r = find(&mut region, b);
  866. meet[t].0 |= reads[r] || writes[r];
  867. }
  868. }
  869. }
  870. Some(meet)
  871. }
  872. /// Masks held as numbers or constant lane sets in guards or lane branches: the lane tests its
  873. /// own bit by its console lane.
  874. fn lane_constant_masks(st: &Structured) -> bool {
  875. let whens = st.exits.iter().filter_map(|e| match *e {
  876. LaneExit::Branch { when, .. } => Some(when),
  877. _ => None,
  878. });
  879. let mut work: Vec<Bool> = st.guards.iter().flatten().flatten().copied().chain(whens).collect();
  880. // Through lane-mask joins too: an edge that brings a number or a constant lane set needs
  881. // the lane's own bit of it.
  882. // shortcut: masks only selects read (`v_cndmask_b32`, carries in) are not followed; such
  883. // a program still stops with "a constant lane mask" or "an opaque lane mask".
  884. let (mut seen, mut joins) = (HashSet::new(), HashSet::new());
  885. while let Some(g) = work.pop() {
  886. if !seen.insert(g) {
  887. continue;
  888. }
  889. for a in st.bools.support(g) {
  890. match a {
  891. Atom::Opaque(_) | Atom::Constant(_) => return true,
  892. Atom::Phi(id) if joins.insert(id) => {
  893. if let Some(edges) = st.phi_masks.get(&id) {
  894. work.extend(edges.iter().copied());
  895. }
  896. }
  897. _ => {}
  898. }
  899. }
  900. }
  901. false
  902. }
  903. /// The widest wave the host GPU runs (0: not known – no host-specific forms); see
  904. /// [`set_host_max_wave`].
  905. static HOST_MAX_WAVE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
  906. /// The host GPU's `WaveLaneCountMax`: 32 lets console wave64 compute programs whose cross-lane
  907. /// code stays inside 32-lane halves run in waves of 32 instead of being refused.
  908. pub fn set_host_max_wave(lanes: u32) {
  909. HOST_MAX_WAVE.store(lanes, std::sync::atomic::Ordering::Relaxed);
  910. }
  911. thread_local! {
  912. /// See [`take_needs`].
  913. static NEEDS: std::cell::RefCell<Vec<usize>> = const { std::cell::RefCell::new(Vec::new()) };
  914. /// See [`with_local_waves`].
  915. static LOCAL_WAVES: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
  916. /// See [`with_local_waves_any`].
  917. static LOCAL_ANY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
  918. }
  919. /// As [`with_local_waves`], with every other use of a lane mask as a number
  920. /// and every lane read and write taken per host wave too: the program runs
  921. /// as it would on a console of 32-lane waves, lanes numbered 0..31 or
  922. /// 32..63 by half. Right for code that only relies on what HLSL's wave
  923. /// operations promise; a program that takes one wave to be its whole
  924. /// thread group gets per-half results. The last resort for programs that
  925. /// do not translate otherwise.
  926. pub(super) fn with_local_waves_any<R>(f: impl FnOnce() -> R) -> R {
  927. let was = LOCAL_ANY.replace(true);
  928. let r = with_local_waves(f);
  929. LOCAL_ANY.set(was);
  930. r
  931. }
  932. /// Runs `f` with console wave64 programs on 32-lane hosts lowered with each
  933. /// host wave as a wave of its own ("local"): no exchange between the two
  934. /// halves of a console wave, so no barriers and no need for every lane to
  935. /// reach the code. What HLSL's wave operations promise holds for any
  936. /// division of the threads into waves, and the idiom the title's compute
  937. /// programs use them for does not care which wave a thread is in: count or
  938. /// sum over the wave, the first lane reserves that many slots with an atomic
  939. /// add, every lane takes the base (`WaveReadLaneFirst`) plus its prefix.
  940. /// Each lane still gets a slot of its own; only the order differs.
  941. /// Only that idiom's operations are lowered this way: a lane mask read as
  942. /// a number by anything but a bit count, a first-set-bit or `v_mbcnt`, and
  943. /// lane reads and writes outside whole-wave sections, stop the translation.
  944. /// shortcut: where a count or sum goes is not checked. A program that uses
  945. /// a wave-wide result as data for the whole console wave (a tile's maximum,
  946. /// say, with one wave per thread group) gets its half's result. It is used
  947. /// only for programs that do not translate otherwise.
  948. pub(super) fn with_local_waves<R>(f: impl FnOnce() -> R) -> R {
  949. let was = LOCAL_WAVES.replace(true);
  950. let r = f();
  951. LOCAL_WAVES.set(was);
  952. r
  953. }
  954. /// `VICTORY_F16_NEAREST=1`: the results of 16-bit float operations (`v_add_f16`,
  955. /// `v_mul_f16`, `v_cvt_f16_f32` ...) are rounded to nearest as the console rounds them
  956. /// ([`Lower::f16_nearest`]) instead of as the host's `f32tof16` does (toward zero on NVIDIA:
  957. /// the last place of a result that is not exact is then one lower than the console's).
  958. /// Off by default: it is exact but untried in a game run, and adds instructions to every
  959. /// such operation. The wave sum of 16-bit floats ([`Lower::half_sum`]) is always exact.
  960. fn f16_nearest_on() -> bool {
  961. #[cfg(test)]
  962. if let Some(on) = TEST_F16_NEAREST.get() {
  963. return on;
  964. }
  965. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  966. *ON.get_or_init(|| std::env::var_os("VICTORY_F16_NEAREST").is_some_and(|v| v == "1"))
  967. }
  968. #[cfg(test)]
  969. thread_local! {
  970. /// A test's choice for [`f16_nearest_on`], for its thread only.
  971. pub(super) static TEST_F16_NEAREST: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
  972. }
  973. /// `VICTORY_WAVE_OWN_BITS=0`: a wave OR where not every lane runs is refused as before
  974. /// ([`super::own_bits`]).
  975. fn own_bits_on() -> bool {
  976. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  977. *ON.get_or_init(|| std::env::var_os("VICTORY_WAVE_OWN_BITS").is_none_or(|v| v != "0"))
  978. }
  979. pub(super) fn host_max_wave() -> u32 {
  980. #[cfg(test)]
  981. if let Some(lanes) = TEST_HOST_WAVE.get() {
  982. return lanes;
  983. }
  984. HOST_MAX_WAVE.load(std::sync::atomic::Ordering::Relaxed)
  985. }
  986. #[cfg(test)]
  987. thread_local! {
  988. /// A test's host wave size, for its thread only ([`set_host_max_wave`] is the process's).
  989. pub(super) static TEST_HOST_WAVE: std::cell::Cell<Option<u32>> = const { std::cell::Cell::new(None) };
  990. }
  991. pub(super) fn reads_mask_as_data(st: &Structured, i: &Inst) -> bool {
  992. let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v);
  993. let ops: Vec<&Operand> = match &i.fields {
  994. // A mask operation (its result a mask) is no data use.
  995. Fields::Sop { .. }
  996. if i.writes
  997. .iter()
  998. .any(|&(r, w)| matches!(r, Reg::S(_)) && is_mask(w)) =>
  999. {
  1000. return false;
  1001. }
  1002. Fields::Sop { src, .. } => src.iter().collect(),
  1003. Fields::Valu(v)
  1004. if !matches!(i.name(), "v_cndmask_b32") && !i.name().contains("_co_ci_") =>
  1005. {
  1006. v.src.iter().collect()
  1007. }
  1008. _ => return false,
  1009. };
  1010. ops.into_iter().any(|op| match *op {
  1011. Operand::Scalar { code, .. } if code != NULL => i.read(Reg::S(code)).is_some_and(is_mask),
  1012. _ => false,
  1013. })
  1014. }
  1015. /// The parameters packing 16-bit rows two per dword and where each lays
  1016. /// its elements out: (first row, [(dword, register, column, columns)]).
  1017. ///
  1018. /// The console gives every 16-bit element whole dwords. A parameter leads
  1019. /// with the first element of its first row, then the first element of its
  1020. /// second row. An element that shares a register behind another one (the
  1021. /// signature packs a short element into the free columns of an earlier
  1022. /// register) is NOT in that row's halves: it follows in the first
  1023. /// parameter, in row order, that has whole dwords left. Grand Theft Auto
  1024. /// VI's packed pedestrian shaders show both cases: TEXCOORD7 (register 1,
  1025. /// columns 2-3, behind the two columns of TEXCOORD0) is exported in dword 3
  1026. /// of parameter 0, after TEXCOORD1's two dwords; TEXCOORD6 (register 4,
  1027. /// column 3, behind the three columns of TEXCOORD4) in dword 3 of
  1028. /// parameter 3, after TEXCOORD5 and TEXCOORD7, while the high half of
  1029. /// TEXCOORD4's second dword stays zero.
  1030. type PackedLayout = Vec<(u8, Vec<(u8, u8, u8, u8)>)>;
  1031. fn packed_layout(elements: &[SigElement], packs: &[(u8, Option<u8>)]) -> PackedLayout {
  1032. let of_row = |r: u8| {
  1033. let mut of: Vec<&SigElement> = elements
  1034. .iter()
  1035. .filter(|e| e.row == Some(u32::from(r)))
  1036. .collect();
  1037. of.sort_by_key(|e| e.col);
  1038. of
  1039. };
  1040. let mut packs = packs.to_vec();
  1041. packs.sort_unstable();
  1042. packs.dedup_by_key(|p| p.0);
  1043. // Per parameter: its first row, the dwords used, the elements.
  1044. let mut layout: Vec<(u8, u8, Vec<(u8, u8, u8, u8)>)> = Vec::new();
  1045. let mut behind = Vec::new();
  1046. for &(a, b) in &packs {
  1047. let mut placed = Vec::new();
  1048. let mut at = 0u8;
  1049. if !of_row(a).is_empty() {
  1050. for r in [Some(a), b].into_iter().flatten() {
  1051. let of = of_row(r);
  1052. let Some((lead, more)) = of.split_first() else {
  1053. continue;
  1054. };
  1055. placed.push((at, r, lead.col, lead.cols));
  1056. at += lead.cols.div_ceil(2);
  1057. behind.extend(more.iter().map(|e| (r, e.col, e.cols)));
  1058. }
  1059. }
  1060. layout.push((a, at, placed));
  1061. }
  1062. behind.sort_unstable();
  1063. for (r, col, cols) in behind {
  1064. let need = cols.div_ceil(2);
  1065. if let Some(p) = layout.iter_mut().find(|p| p.1 + need <= 4) {
  1066. p.2.push((p.1, r, col, cols));
  1067. p.1 += need;
  1068. }
  1069. }
  1070. layout.into_iter().map(|(a, _, of)| (a, of)).collect()
  1071. }
  1072. /// Where half `h` (dword h / 2, the high half when odd) of the parameter
  1073. /// whose first 16-bit row is `a` comes from: a register and column of
  1074. /// `elements`, none for padding ([`packed_layout`]; `packs` lists every
  1075. /// parameter packing two 16-bit rows per dword).
  1076. fn packed_half(
  1077. elements: &[SigElement],
  1078. packs: &[(u8, Option<u8>)],
  1079. a: u8,
  1080. h: u8,
  1081. ) -> Option<(u8, u8)> {
  1082. let layout = packed_layout(elements, packs);
  1083. let (_, of) = layout.iter().find(|p| p.0 == a)?;
  1084. of.iter().find_map(|&(dword, row, col, cols)| {
  1085. let k = h.checked_sub(2 * dword)?;
  1086. (k < cols).then_some((row, col + k))
  1087. })
  1088. }
  1089. /// The pixel inputs packing two 16-bit rows per dword, as (first row,
  1090. /// second row) ([`packed_layout`]).
  1091. fn input_packs(io: &StageIo, inputs: &[SigElement]) -> Vec<(u8, Option<u8>)> {
  1092. let StageIo::Ps {
  1093. inputs: entries, ..
  1094. } = io
  1095. else {
  1096. return Vec::new();
  1097. };
  1098. let partners = half_input_partners(io, inputs);
  1099. entries
  1100. .iter()
  1101. .filter(|i| i.fp16 && i.pack2)
  1102. .map(|i| {
  1103. let b = if i.row2 != i.row {
  1104. Some(i.row2)
  1105. } else {
  1106. partners.get(&i.row).copied()
  1107. };
  1108. (i.row, b)
  1109. })
  1110. .collect()
  1111. }
  1112. /// Vertex or mesh outputs of 16-bit values (see [`Lower::half_outputs`]):
  1113. /// a packed row's partner is the next 16-bit row of the signature that no
  1114. /// output entry names, taken in row order.
  1115. fn half_outputs(io: &StageIo, outputs: &[SigElement]) -> HashMap<u8, (bool, Option<u8>)> {
  1116. let entries = match io {
  1117. StageIo::Vs { outputs, .. } => outputs,
  1118. StageIo::Ms(ms) => &ms.outputs,
  1119. _ => return HashMap::new(),
  1120. };
  1121. let per_vertex = || entries.iter().filter(|o| o.param & 0x80 == 0);
  1122. let mut free: Vec<u8> = outputs
  1123. .iter()
  1124. .filter(|e| e.half && e.kind == 0)
  1125. .filter_map(|e| u8::try_from(e.row?).ok())
  1126. .filter(|&r| !per_vertex().any(|o| o.row == r))
  1127. .collect();
  1128. free.sort_unstable();
  1129. free.dedup();
  1130. let mut halves: Vec<_> = per_vertex().filter(|o| o.fp16).collect();
  1131. halves.sort_by_key(|o| o.row);
  1132. halves
  1133. .into_iter()
  1134. .map(|o| {
  1135. let b = o
  1136. .pack2
  1137. .then(|| free.iter().position(|&r| r > o.row))
  1138. .flatten();
  1139. (o.row, (o.pack2, b.map(|i| free.remove(i))))
  1140. })
  1141. .collect()
  1142. }
  1143. /// Pixel inputs packing two 16-bit rows per dword whose second row the
  1144. /// metadata leaves out (`row2` = `row`): as for outputs
  1145. /// ([`half_outputs`]), the next 16-bit row of the signature that no input
  1146. /// entry names, taken in row order (rows the metadata does give are taken
  1147. /// first).
  1148. fn half_input_partners(io: &StageIo, inputs: &[SigElement]) -> HashMap<u8, u8> {
  1149. let StageIo::Ps {
  1150. inputs: entries, ..
  1151. } = io
  1152. else {
  1153. return HashMap::new();
  1154. };
  1155. let packed = || entries.iter().filter(|i| i.fp16 && i.pack2);
  1156. let mut free: Vec<u8> = inputs
  1157. .iter()
  1158. .filter(|e| e.half && e.kind == 0)
  1159. .filter_map(|e| u8::try_from(e.row?).ok())
  1160. .filter(|&r| !entries.iter().any(|i| i.row == r))
  1161. .filter(|&r| !packed().any(|i| i.row2 != i.row && i.row2 == r))
  1162. .collect();
  1163. free.sort_unstable();
  1164. free.dedup();
  1165. let mut missing: Vec<_> = packed().filter(|i| i.row2 == i.row).collect();
  1166. missing.sort_by_key(|i| i.row);
  1167. let mut partners = HashMap::new();
  1168. for i in missing {
  1169. if let Some(k) = free.iter().position(|&r| r > i.row) {
  1170. partners.insert(i.row, free.remove(k));
  1171. }
  1172. }
  1173. partners
  1174. }
  1175. fn unsupported(offset: usize, what: Why) -> Stop {
  1176. Stop::Fail(ShaderError::Unsupported { offset, what })
  1177. }
  1178. impl<'a> Lower<'a> {
  1179. fn new(x: &'a Parts<'a>, bad: &'a HashMap<Value, Why>) -> Self {
  1180. let p = x.p;
  1181. let mut phi_at = HashMap::new();
  1182. for (b, block) in p.blocks.iter().enumerate() {
  1183. for (i, phi) in block.phis.iter().enumerate() {
  1184. phi_at.insert(phi.value, (b, i));
  1185. }
  1186. }
  1187. let mut s = Shader::new(x.native.stage == HwStage::Ps);
  1188. s.inputs = x.inputs.clone();
  1189. s.outputs = x.outputs.clone();
  1190. let insts = || p.blocks.iter().flat_map(|b| &b.insts);
  1191. let writes_uavs = insts().any(|i| {
  1192. matches!(i.fields, Fields::Image { .. } | Fields::Buffer { .. })
  1193. && (i.name().contains("store") || i.name().contains("atomic"))
  1194. });
  1195. let mut console_lanes = false;
  1196. // LDS accesses get a group barrier each (a console wave split in two host waves)
  1197. let mut split_lds = false;
  1198. // with `split_lds`, LDS accesses in lane branches: the blocks every lane runs, and
  1199. // where the host waves meet around those branches (`lds_meetings`)
  1200. let mut lds_meet: Option<(Vec<bool>, Vec<(bool, bool)>)> = None;
  1201. // a console wave64 program in two host waves of 32 (`exchange`)
  1202. let mut exchange: Option<(u32, bool, Vec<bool>)> = None;
  1203. // a console wave64 program in host waves of 32: the LDS dword of `wave_base`'s counter
  1204. let mut halves: Option<u32> = None;
  1205. if let StageIo::Cs(cs) = x.native.io {
  1206. s.threads = Some(cs.threads);
  1207. s.lds_dwords = cs.lds_bytes() / 4;
  1208. // Code reading other lanes needs the console's wave size and
  1209. // lane order; so do lane masks read as numbers, and LDS shared
  1210. // within one wave, where the console compiler leaves out barriers.
  1211. console_lanes = insts().any(|i| {
  1212. let n = i.name();
  1213. n.starts_with("ds_swizzle")
  1214. || n.contains("permute")
  1215. || n.starts_with("v_mbcnt")
  1216. || matches!(n, "v_readlane_b32" | "v_writelane_b32")
  1217. || matches!(&i.fields, Fields::Valu(v) if v.dpp.is_some())
  1218. || reads_mask_as_data(x.st, i)
  1219. }) || lane_constant_masks(x.st)
  1220. // (a branch the wave takes together asks the wave)
  1221. || !x.st.wide.is_empty();
  1222. let mut wave = if x.native.wave64 { 64 } else { 32 };
  1223. let group = cs.threads.iter().product::<u32>();
  1224. let one_wave = group <= wave;
  1225. // A host whose waves are at most 32 lanes (NVIDIA) refuses `WaveSize(64)`. A console
  1226. // wave64 program whose cross-lane code stays inside 32-lane halves – DPP rows,
  1227. // `ds_swizzle`, `v_permlane16` / `v_permlanex16`, which the ISA confines there – runs
  1228. // exactly in waves of 32: the thread relabelling makes each host wave one half of a
  1229. // console wave (lanes 32k..32k+31). Not when it crosses halves (`v_mbcnt`,
  1230. // `v_readlane`, `v_writelane`, `ds_(b)permute`, masks as numbers or lane-constant
  1231. // masks), nor when LDS may be shared within the console wave without barriers (a
  1232. // group over 32 threads with LDS): those still need 64-lane waves.
  1233. if wave == 64 && host_max_wave() == 32 && (console_lanes || one_wave && s.lds_dwords > 0) {
  1234. let crosses = insts().any(|i| {
  1235. let n = i.name();
  1236. n.starts_with("v_mbcnt")
  1237. || matches!(n, "v_readlane_b32" | "v_writelane_b32")
  1238. || n.starts_with("ds_permute")
  1239. || n.starts_with("ds_bpermute")
  1240. || reads_mask_as_data(x.st, i)
  1241. }) || lane_constant_masks(x.st)
  1242. || !x.st.wide.is_empty();
  1243. if !crosses && (s.lds_dwords == 0 || group <= 32) {
  1244. wave = 32;
  1245. } else {
  1246. // (Groups of several console waves too: each console wave is two host
  1247. // waves, which exchange through their own pair of dwords.)
  1248. // LDS the console shares within its one wave without barriers: split into
  1249. // two waves of 32, a group barrier before every LDS access keeps their order
  1250. // – where every thread of the group gets there (no lane branch around it,
  1251. // no guard), else a barrier would hang the group
  1252. let lds = |i: &Inst| {
  1253. matches!(i.fields, Fields::Ds { .. })
  1254. && !(i.name().starts_with("ds_swizzle") || i.name().contains("permute"))
  1255. };
  1256. if let Some(all) = all_lane_blocks(x.st) {
  1257. let ok = p.blocks.iter().enumerate().all(|(b, blk)| {
  1258. blk.insts.iter().all(|inst| {
  1259. !lds(inst) || all.get(b).copied().unwrap_or(false)
  1260. })
  1261. });
  1262. let mut lds_ok = !(s.lds_dwords > 0 && group > 32) || ok;
  1263. if !lds_ok && let Some(meet) = lds_meetings(p, x.st, &all) {
  1264. lds_meet = Some((all.clone(), meet));
  1265. lds_ok = true;
  1266. }
  1267. if !lds_ok {
  1268. // (the blocks whose LDS accesses not every lane runs: with the
  1269. // branches around them taken wave-wide they get their barriers)
  1270. for (b, blk) in p.blocks.iter().enumerate() {
  1271. if !all.get(b).copied().unwrap_or(false) && blk.insts.iter().any(lds) {
  1272. need(b);
  1273. }
  1274. }
  1275. }
  1276. if lds_ok {
  1277. wave = 32;
  1278. split_lds = s.lds_dwords > 0 && group > 32;
  1279. if crosses {
  1280. // lanes 32..63 are the other host wave: masks, lane reads and lane
  1281. // numbers go through two exchange dwords past the program's LDS
  1282. exchange = Some((s.lds_dwords, group <= 32, all));
  1283. s.lds_dwords += 2 * group.div_ceil(64);
  1284. }
  1285. }
  1286. }
  1287. }
  1288. // `VICTORY_WAVE_WHY=1`: why a program keeps 64-lane waves (one line per reason)
  1289. if wave == 64 && std::env::var_os("VICTORY_WAVE_WHY").is_some() {
  1290. let mut why: Vec<&str> = Vec::new();
  1291. for i in insts() {
  1292. let n = i.name();
  1293. let r = if n.starts_with("v_mbcnt") {
  1294. "v_mbcnt"
  1295. } else if n == "v_readlane_b32" {
  1296. "v_readlane"
  1297. } else if n == "v_writelane_b32" {
  1298. "v_writelane"
  1299. } else if n.starts_with("ds_permute") || n.starts_with("ds_bpermute") {
  1300. "ds_(b)permute"
  1301. } else if reads_mask_as_data(x.st, i) {
  1302. "mask as data"
  1303. } else {
  1304. continue;
  1305. };
  1306. if !why.contains(&r) {
  1307. why.push(r);
  1308. }
  1309. }
  1310. if lane_constant_masks(x.st) {
  1311. why.push("lane-constant mask");
  1312. }
  1313. if s.lds_dwords > 0 && group > 32 {
  1314. why.push("LDS in a group over 32");
  1315. match all_lane_blocks(x.st) {
  1316. None => why.push("an indirect exit"),
  1317. Some(all) if lds_meetings(p, x.st, &all).is_none() => {
  1318. why.push("an LDS read and write in one lane-branch region")
  1319. }
  1320. Some(_) => {}
  1321. }
  1322. }
  1323. why.sort_unstable();
  1324. eprintln!("WAVE64-WHY group={group} lds={} [{}]", s.lds_dwords > 0, why.join(", "));
  1325. }
  1326. }
  1327. if wave == 32 && x.native.wave64 {
  1328. // console threads go to host waves in the order the waves take them (`wave_base`)
  1329. halves = Some(s.lds_dwords);
  1330. s.lds_dwords += 1;
  1331. }
  1332. if console_lanes || one_wave && s.lds_dwords > 0 {
  1333. s.wave_size = Some(wave);
  1334. }
  1335. }
  1336. // The title's barriers a thread of the group may never reach, which
  1337. // leaves the others waiting on the host: those in blocks some lanes
  1338. // do not run, and all of them in a program with a loop closed by a
  1339. // plain jump (a lane still in it at the iteration limit leaves the
  1340. // program there, `abort_block`).
  1341. let fence_only: HashSet<usize> = if insts().any(|i| i.name() == "s_barrier") {
  1342. let order = crate::ir::reverse_postorder(&p.blocks);
  1343. let mut place = vec![usize::MAX; p.blocks.len()];
  1344. for (n, &b) in order.iter().enumerate() {
  1345. place[b] = n;
  1346. }
  1347. let back = |from: usize, to: usize| {
  1348. let at = |b: usize| place.get(b).copied().unwrap_or(usize::MAX);
  1349. at(from) != usize::MAX && at(to) <= at(from)
  1350. };
  1351. let cut_short = x
  1352. .st
  1353. .exits
  1354. .iter()
  1355. .enumerate()
  1356. .any(|(b, e)| matches!(*e, LaneExit::Jump(t) if back(b, t)));
  1357. let all = all_lane_blocks(x.st);
  1358. (0..p.blocks.len())
  1359. .filter(|&b| p.blocks[b].insts.iter().any(|i| i.name() == "s_barrier"))
  1360. .filter(|&b| {
  1361. cut_short
  1362. || all
  1363. .as_ref()
  1364. .is_none_or(|all| !all.get(b).copied().unwrap_or(false))
  1365. })
  1366. .collect()
  1367. } else {
  1368. HashSet::new()
  1369. };
  1370. let mut no_barrier = HashSet::new();
  1371. if let StageIo::Ms(ms) = &x.native.io {
  1372. s.prims = x.prims.clone();
  1373. s.threads = Some([ms.threads, 1, 1]);
  1374. s.lds_dwords = ms.lds_bytes.div_ceil(4);
  1375. s.mesh = Some(super::shader::Mesh {
  1376. max_vertices: ms.max_vertices,
  1377. max_primitives: ms.max_primitives,
  1378. topology: ms.topology,
  1379. });
  1380. // Barriers order the lanes' LDS accesses; the console's
  1381. // allocation request needs them too, but the host does not. One
  1382. // lane sends that request, and what it dominates (the path for
  1383. // counts out of range) runs in that lane alone, so its barrier
  1384. // would hang the host.
  1385. let order = crate::ir::reverse_postorder(&p.blocks);
  1386. let mut index = vec![usize::MAX; p.blocks.len()];
  1387. for (n, &b) in order.iter().enumerate() {
  1388. index[b] = n;
  1389. }
  1390. let idom = crate::ir::idoms(&p.blocks, &order, &index);
  1391. let alloc: Vec<usize> = (0..p.blocks.len())
  1392. .filter(|&b| {
  1393. p.blocks[b].insts.iter().any(|i| {
  1394. i.name() == "s_sendmsg"
  1395. && matches!(i.fields, Fields::Sopp { imm } if imm & 0xF == GS_ALLOC_REQ)
  1396. })
  1397. })
  1398. .collect();
  1399. for &b in &order {
  1400. let mut d = b;
  1401. let dominated = loop {
  1402. if alloc.contains(&d) {
  1403. break true;
  1404. }
  1405. if idom[d] == d || idom[d] == usize::MAX {
  1406. break false;
  1407. }
  1408. d = idom[d];
  1409. };
  1410. if ms.lds_bytes == 0 || dominated {
  1411. no_barrier.insert(b);
  1412. }
  1413. }
  1414. }
  1415. Lower {
  1416. s,
  1417. x,
  1418. bad,
  1419. lane_fail: HashMap::new(),
  1420. vals: HashMap::new(),
  1421. floats: HashMap::new(),
  1422. block: vec![None; p.blocks.len()],
  1423. cur: 0,
  1424. bools: HashMap::new(),
  1425. lane_bits: HashMap::new(),
  1426. phi_at,
  1427. mask_phis: HashMap::new(),
  1428. pending_masks: Vec::new(),
  1429. data_phis: Vec::new(),
  1430. read_phis: HashSet::new(),
  1431. stale: HashSet::new(),
  1432. params: x.res.params.iter().map(|&(v, p, d)| (v, (p, d))).collect(),
  1433. user_data: None,
  1434. user_reads: BTreeMap::new(),
  1435. samplers: Vec::new(),
  1436. descriptors: x
  1437. .res
  1438. .descriptors
  1439. .iter()
  1440. .map(|d| ((d.site, d.role == Role::Sampler), &d.source))
  1441. .collect(),
  1442. scalar: x.res.scalar.iter().copied().collect(),
  1443. exports: x.io.exports.iter().map(|e| (e.site, e)).collect(),
  1444. interps: x.io.interps.iter().map(|(s, i)| (*s, i)).collect(),
  1445. handles: HashMap::new(),
  1446. strides: HashMap::new(),
  1447. edges: HashMap::new(),
  1448. exported: vec![false; p.blocks.len()],
  1449. rpo: vec![usize::MAX; p.blocks.len()],
  1450. tail: vec![None; p.blocks.len()],
  1451. writes_uavs,
  1452. src0: None,
  1453. console_lanes,
  1454. split_lds,
  1455. lds_meet,
  1456. local: exchange.is_some() && LOCAL_WAVES.get(),
  1457. local_ok: false,
  1458. local_any: LOCAL_ANY.get(),
  1459. uniform: match &exchange {
  1460. Some((_, false, all)) if !LOCAL_WAVES.get() => lane_uniform(p, x.st, all),
  1461. _ => HashSet::new(),
  1462. },
  1463. own_bits: match &exchange {
  1464. Some((_, false, _)) if !LOCAL_WAVES.get() && own_bits_on() => {
  1465. super::own_bits::find(p, x.st, std::env::var_os("VICTORY_WAVE_WHY").is_some())
  1466. }
  1467. _ => Default::default(),
  1468. },
  1469. exchange,
  1470. clane: None,
  1471. pair: None,
  1472. halves,
  1473. wave_base: None,
  1474. flat: None,
  1475. no_barrier,
  1476. fence_only,
  1477. half_outputs: half_outputs(&x.native.io, &x.outputs),
  1478. mask_data: match x.native.stage {
  1479. HwStage::Cs => MaskData::Console,
  1480. HwStage::Ps | HwStage::Vs => MaskData::Host,
  1481. _ => MaskData::None,
  1482. },
  1483. mask_ok: false,
  1484. ballots: HashMap::new(),
  1485. balloting: HashSet::new(),
  1486. def_block: p
  1487. .blocks
  1488. .iter()
  1489. .enumerate()
  1490. .flat_map(|(b, block)| {
  1491. block
  1492. .insts
  1493. .iter()
  1494. .flat_map(move |i| i.writes.iter().map(move |w| (w.1, b)))
  1495. .chain(block.phis.iter().map(move |phi| (phi.value, b)))
  1496. })
  1497. .collect(),
  1498. cur_ir: 0,
  1499. sections: HashMap::new(),
  1500. section_out: HashSet::new(),
  1501. code_table: None,
  1502. counters: HashMap::new(),
  1503. abort: None,
  1504. }
  1505. }
  1506. /// The dword of the program's code at byte `byte` (a constant table
  1507. /// the compiler appends to the code), as an internal constant array.
  1508. // shortcut: an index outside the table reads its last dword (the
  1509. // console would read whatever memory follows the code).
  1510. fn code_dword(&mut self, byte: V) -> Result<V, Why> {
  1511. let (g, base, len) = match self.code_table {
  1512. Some(t) => t,
  1513. None => {
  1514. let first = self
  1515. .x
  1516. .res
  1517. .scalar
  1518. .iter()
  1519. .map(|s| s.1)
  1520. .chain(self.x.res.descriptors.iter().flat_map(|d| {
  1521. d.source.leaves().into_iter().filter_map(|l| match l {
  1522. Source::Built { address, .. } => Some(*address),
  1523. _ => None,
  1524. })
  1525. }))
  1526. .filter(|a| a.param == CODE)
  1527. .map(|a| a.offset & !3)
  1528. .min()
  1529. .ok_or("a code table")?;
  1530. let code = &self.x.native.code;
  1531. let words: Vec<u32> = code
  1532. .get(first as usize..)
  1533. .ok_or("a code table past the code")?
  1534. .chunks(4)
  1535. .map(|c| {
  1536. let mut w = [0u8; 4];
  1537. w[..c.len()].copy_from_slice(c);
  1538. u32::from_le_bytes(w)
  1539. })
  1540. .collect();
  1541. if words.is_empty() {
  1542. return Err("a code table past the code");
  1543. }
  1544. let elems: Vec<V> = words.iter().map(|&w| self.s.m.i32(w)).collect();
  1545. let arr = self.s.m.array(words.len() as u32, self.s.t.i32);
  1546. let init = self.s.m.aggregate(arr, &elems);
  1547. let g = self.s.m.constant_global("code", init);
  1548. let t = (g, first, words.len() as u32);
  1549. self.code_table = Some(t);
  1550. t
  1551. }
  1552. };
  1553. let c = self.cur;
  1554. let k = self.s.m.i32(base);
  1555. let rel = self.s.m.bin(c, Bin::Sub, byte, k);
  1556. let two = self.s.m.i32(2);
  1557. let index = self.s.m.bin(c, Bin::LShr, rel, two);
  1558. let last = self.s.m.i32(len - 1);
  1559. let over = self.s.m.cmp(c, pred::IUGT, index, last);
  1560. let index = self.s.m.select(c, over, last, index);
  1561. let at = self.s.m.element(c, g, index);
  1562. Ok(self.s.m.load(c, at))
  1563. }
  1564. /// A global memory load (`global_load_*`): from the program's constant
  1565. /// table, or from a root SRV at the address the title sets.
  1566. fn flat(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  1567. let Fields::Flat { dst, .. } = &inst.fields else {
  1568. unreachable!()
  1569. };
  1570. let name = inst.name();
  1571. if self.scalar.get(&(b, i)).is_some_and(|a| a.param == MEMORY) {
  1572. return self.memory_flat(inst, b, i);
  1573. }
  1574. let rest = name
  1575. .strip_prefix("global_load_")
  1576. .ok_or("a global memory write")?;
  1577. let (n, sub) = match rest {
  1578. "dword" => (1, None),
  1579. "dwordx2" => (2, None),
  1580. "dwordx3" => (3, None),
  1581. "dwordx4" => (4, None),
  1582. "ubyte" => (1, Some((8, false))),
  1583. "sbyte" => (1, Some((8, true))),
  1584. "ushort" => (1, Some((16, false))),
  1585. "sshort" => (1, Some((16, true))),
  1586. _ => return Err(name),
  1587. };
  1588. let a = *self
  1589. .scalar
  1590. .get(&(b, i))
  1591. .ok_or("an untracked global address")?;
  1592. let guard = self.guard(b, i)?;
  1593. let Some(Operand::Vector { reg, .. }) = *dst else {
  1594. return Err("a global load result");
  1595. };
  1596. let c = self.cur;
  1597. let mut off = self.s.m.i32(a.offset);
  1598. if let Some(d) = a.dynamic {
  1599. let d = self.i32_of(d)?;
  1600. off = self.s.m.bin(c, Bin::Add, off, d);
  1601. }
  1602. let h = if a.param == CODE {
  1603. None
  1604. } else {
  1605. let src = Source::Built {
  1606. address: a,
  1607. bits: 0,
  1608. words: [0, 0],
  1609. };
  1610. if let Some(bias) = self.root_bias(a.param) {
  1611. off = self.s.m.bin(c, Bin::Add, off, bias);
  1612. }
  1613. Some(self.handle((b, i), &src, false, (11, 0))?)
  1614. };
  1615. let dword = |l: &mut Self, byte: V| -> Result<V, Why> {
  1616. match h {
  1617. None => l.code_dword(byte),
  1618. Some(h) => {
  1619. let c = l.cur;
  1620. let (u, mask, al) = (l.s.m.undef(l.s.t.i32), l.s.m.i8(1), l.s.m.i32(4));
  1621. let r = l.s.op(
  1622. c,
  1623. "rawBufferLoad.f32",
  1624. Attr::ReadOnly,
  1625. l.s.t.res_ret,
  1626. 139,
  1627. &[h, byte, u, mask, al],
  1628. );
  1629. let x = l.s.m.extract(c, r, 0);
  1630. Ok(l.as_int(x))
  1631. }
  1632. }
  1633. };
  1634. for k in 0..n {
  1635. let x = match sub {
  1636. None => {
  1637. let four = self.s.m.i32(4 * k);
  1638. let at = self.s.m.bin(c, Bin::Add, off, four);
  1639. dword(self, at)?
  1640. }
  1641. Some((width, signed)) => {
  1642. // shortcut: the field is taken not to cross a dword.
  1643. let (not3, three) = (self.s.m.i32(!3), self.s.m.i32(3));
  1644. let at = self.s.m.bin(c, Bin::And, off, not3);
  1645. let w = dword(self, at)?;
  1646. let byte = self.s.m.bin(c, Bin::And, off, three);
  1647. let sh = self.s.m.bin(c, Bin::Shl, byte, three);
  1648. let x = self.s.m.bin(c, Bin::LShr, w, sh);
  1649. let left = self.s.m.i32(32 - width);
  1650. let x = self.s.m.bin(c, Bin::Shl, x, left);
  1651. self.s
  1652. .m
  1653. .bin(c, if signed { Bin::AShr } else { Bin::LShr }, x, left)
  1654. }
  1655. };
  1656. self.write(inst, Reg::V(reg + k as u8), x, guard);
  1657. }
  1658. Ok(())
  1659. }
  1660. /// Finds the whole-wave sections and the values they leave.
  1661. fn find_sections(&mut self) {
  1662. let p = self.x.p;
  1663. let mut inside: HashMap<Value, (usize, usize, usize)> = HashMap::new();
  1664. for b in 0..p.blocks.len() {
  1665. let found = super::wave::sections(p, b);
  1666. for (&start, sec) in &found {
  1667. for i in start + 1..sec.end {
  1668. for &(_, w) in &p.blocks[b].insts[i].writes {
  1669. inside.insert(w, (b, start, sec.end));
  1670. }
  1671. }
  1672. }
  1673. if !found.is_empty() {
  1674. self.sections.insert(b, found);
  1675. }
  1676. }
  1677. if inside.is_empty() {
  1678. return;
  1679. }
  1680. for (b, block) in p.blocks.iter().enumerate() {
  1681. for phi in &block.phis {
  1682. self.section_out
  1683. .extend(phi.args.iter().filter(|a| inside.contains_key(a)));
  1684. }
  1685. for (i, inst) in block.insts.iter().enumerate() {
  1686. for &(_, r) in &inst.reads {
  1687. if let Some(&(sb, start, end)) = inside.get(&r)
  1688. && !(sb == b && i > start && i < end)
  1689. {
  1690. self.section_out.insert(r);
  1691. }
  1692. }
  1693. }
  1694. }
  1695. }
  1696. /// An instruction inside a whole-wave section: the values that leave
  1697. /// the section are made from what the simulation found them to be.
  1698. fn section_inst(&mut self, b: usize, i: usize, start: usize) {
  1699. const UNKNOWN: Why = "a whole-wave section step the simulation does not follow";
  1700. let inst = &self.x.p.blocks[b].insts[i];
  1701. for &(_, w) in &inst.writes {
  1702. let val = if self.section_out.contains(&w) {
  1703. let shape = self.sections[&b][&start].shapes.get(&w).copied();
  1704. let own = self.own_bits.totals.contains(&w);
  1705. match shape.ok_or(UNKNOWN).and_then(|sh| self.shape(sh, own)) {
  1706. Ok(x) => Val::I32(x),
  1707. Err(why) => Val::Missing(why),
  1708. }
  1709. } else {
  1710. Val::Missing(UNKNOWN)
  1711. };
  1712. self.vals.insert(w, val);
  1713. }
  1714. }
  1715. /// A value a whole-wave section leaves, as DXIL wave operations over the
  1716. /// host's active lanes: the console's result with console lanes; on
  1717. /// another wave size, what the HLSL wave operation the console compiler
  1718. /// expanded gives on that wave.
  1719. ///
  1720. /// `own`: a wave OR that only steers a loop over each lane's own bits
  1721. /// ([`super::own_bits`]); where two host waves cannot exchange their halves' ORs it is
  1722. /// this host wave's.
  1723. fn shape(&mut self, shape: super::wave::Shape, own: bool) -> Result<V, Why> {
  1724. use super::wave::{Op, Shape};
  1725. let (op, src, mask, ident, prefix) = match shape {
  1726. Shape::K(k) => return Ok(self.s.m.i32(k)),
  1727. Shape::Value(v) => return self.i32_of(v),
  1728. Shape::Active(op, src, mask, ident) => (op, src, mask, ident, None),
  1729. Shape::Masked(src, mask, ident) => {
  1730. let c = self.cur;
  1731. let &m = self
  1732. .x
  1733. .st
  1734. .masks
  1735. .get(&mask)
  1736. .ok_or("a wave reduction's untracked mask")?;
  1737. let on = self.boolean(m, c)?;
  1738. let x = self.i32_of(src)?;
  1739. let id = self.s.m.i32(ident);
  1740. return Ok(self.s.m.select(c, on, x, id));
  1741. }
  1742. Shape::Prefix(op, src, mask, ident, inclusive) => {
  1743. (op, src, mask, ident, Some(inclusive))
  1744. }
  1745. };
  1746. // Mesh: no host wave size can be declared, so a reduction is over this host wave
  1747. // only. A minimum or maximum is taken that way: the compiler's "next distinct
  1748. // value" loop (the wave's minimum, then the lanes that hold it) serves every
  1749. // lane however the lanes are divided into waves. A sum, a bit reduction or a
  1750. // prefix would be of part of a console wave: still refused.
  1751. if self.mask_data == MaskData::None
  1752. && (prefix.is_some()
  1753. || !matches!(
  1754. op,
  1755. Op::MinU | Op::MaxU | Op::MinI | Op::MaxI | Op::MinF | Op::MaxF
  1756. ))
  1757. {
  1758. return Err("a wave reduction in a mesh shader");
  1759. }
  1760. let c = self.cur;
  1761. let &m = self
  1762. .x
  1763. .st
  1764. .masks
  1765. .get(&mask)
  1766. .ok_or("a wave reduction's untracked mask")?;
  1767. let on = self.boolean(m, c)?;
  1768. let x = self.i32_of(src)?;
  1769. let id = self.s.m.i32(ident);
  1770. let x = self.s.m.select(c, on, x, id);
  1771. self.s.flags |= flags::WAVE_OPS;
  1772. if op == Op::AddH {
  1773. return match prefix {
  1774. Some(_) => Err("a wave prefix of an operation other than a sum"),
  1775. None => self.half_sum(x),
  1776. };
  1777. }
  1778. let float = matches!(op, Op::AddF | Op::MinF | Op::MaxF);
  1779. let (i32t, f32t) = (self.s.t.i32, self.s.t.f32);
  1780. let arg = if float { self.as_float(x) } else { x };
  1781. let ty = if float { f32t } else { i32t };
  1782. let sfx = if float { "f32" } else { "i32" };
  1783. let r = match (op, prefix) {
  1784. (Op::AddU | Op::AddF, Some(inclusive)) => {
  1785. let (k0, k1) = (self.s.m.i8(0), self.s.m.i8(1));
  1786. let r = self.s.op(
  1787. c,
  1788. &format!("wavePrefixOp.{sfx}"),
  1789. Attr::NoUnwind,
  1790. ty,
  1791. 121,
  1792. &[arg, k0, k1],
  1793. );
  1794. if inclusive {
  1795. self.s.m.bin(c, Bin::Add, r, arg)
  1796. } else {
  1797. r
  1798. }
  1799. }
  1800. (_, Some(_)) => return Err("a wave prefix of an operation other than a sum"),
  1801. (Op::Or | Op::And | Op::Xor, None) => {
  1802. let k = self.s.m.i8(match op {
  1803. Op::And => 0,
  1804. Op::Or => 1,
  1805. _ => 2,
  1806. });
  1807. self.s
  1808. .op(c, "waveActiveBit.i32", Attr::NoUnwind, i32t, 120, &[arg, k])
  1809. }
  1810. (_, None) => {
  1811. let (code, unsigned) = match op {
  1812. Op::AddU => (0, 1),
  1813. Op::AddF => (0, 0),
  1814. Op::MinU => (2, 1),
  1815. Op::MaxU => (3, 1),
  1816. Op::MinI | Op::MinF => (2, 0),
  1817. _ => (3, 0),
  1818. };
  1819. let (k, u) = (self.s.m.i8(code), self.s.m.i8(unsigned));
  1820. self.s.op(
  1821. c,
  1822. &format!("waveActiveOp.{sfx}"),
  1823. Attr::NoUnwind,
  1824. ty,
  1825. 119,
  1826. &[arg, k, u],
  1827. )
  1828. }
  1829. };
  1830. // two host waves of 32 hold the console's 64 lanes: their results combine
  1831. let r = if self.local || self.exchange.as_ref().is_some_and(|e| e.1) {
  1832. // this host wave's own result (and prefix): each wave on its own, or a group of
  1833. // 32 threads or fewer, which one host wave holds whole (combining with the 0 a
  1834. // missing half "gives" broke AND, MIN and signed MAX)
  1835. r
  1836. } else if own && prefix.is_none() && op == Op::Or && !self.all_lanes(self.cur_ir) {
  1837. // each thread walks the bits of this value and works only at its own, which the
  1838. // host wave's OR holds: the same run as with the console wave's OR
  1839. r
  1840. } else if self.exchange.is_some() {
  1841. if !self.all_lanes(self.cur_ir) {
  1842. need(self.cur_ir);
  1843. return Err("a wave reduction where not every lane runs");
  1844. }
  1845. let bits = |l: &mut Self, v: V| if float { l.as_int(v) } else { v };
  1846. let back = |l: &mut Self, v: V| if float { l.as_float(v) } else { v };
  1847. match prefix {
  1848. Some(_) => {
  1849. // the upper half adds the lower half's total to its prefix
  1850. let (k0, ku) = (self.s.m.i8(0), self.s.m.i8(u8::from(!float)));
  1851. let total = self.s.op(c, &format!("waveActiveOp.{sfx}"), Attr::NoUnwind, ty, 119, &[arg, k0, ku]);
  1852. let tb = bits(self, total);
  1853. let c = self.cur;
  1854. let (lo, _) = self.exchange_halves(c, tb);
  1855. let lo = back(self, lo);
  1856. let cl = self.console_lane();
  1857. let k32 = self.s.m.i32(32);
  1858. let upper = self.s.m.cmp(c, pred::IUGE, cl, k32);
  1859. let zero = if float { self.s.m.f32(0) } else { self.s.m.i32(0) };
  1860. let add = self.s.m.select(c, upper, lo, zero);
  1861. self.s.m.bin(c, Bin::Add, r, add)
  1862. }
  1863. None => {
  1864. let rb = bits(self, r);
  1865. let c = self.cur;
  1866. let (lo, hi) = self.exchange_halves(c, rb);
  1867. let (lo, hi) = (back(self, lo), back(self, hi));
  1868. match op {
  1869. Op::AddU | Op::AddF => self.s.m.bin(c, Bin::Add, lo, hi),
  1870. Op::Or => self.s.m.bin(c, Bin::Or, lo, hi),
  1871. Op::And => self.s.m.bin(c, Bin::And, lo, hi),
  1872. Op::Xor => self.s.m.bin(c, Bin::Xor, lo, hi),
  1873. _ => {
  1874. // FMax 35, FMin 36, IMax 37, IMin 38, UMax 39, UMin 40
  1875. let code = match op {
  1876. Op::MaxF => 35,
  1877. Op::MinF => 36,
  1878. Op::MinU => 40,
  1879. Op::MaxU => 39,
  1880. Op::MinI => 38,
  1881. _ => 37,
  1882. };
  1883. self.s.op(c, &format!("binary.{sfx}"), Attr::ReadNone, ty, code, &[lo, hi])
  1884. }
  1885. }
  1886. }
  1887. }
  1888. } else {
  1889. r
  1890. };
  1891. Ok(if float { self.as_int(r) } else { r })
  1892. }
  1893. /// The sum of two 16-bit floats (the low halves of `a` and `b`) as the console's
  1894. /// `v_add_f16` gives it: added in f32 and rounded to 16 bits, to nearest
  1895. /// ([`Self::f16_nearest`]).
  1896. fn add_halves(&mut self, a: V, b: V) -> V {
  1897. let c = self.cur;
  1898. let f32t = self.s.t.f32;
  1899. let low = self.s.m.i32(0xFFFF);
  1900. let wide = |l: &mut Self, x: V| {
  1901. let h = l.s.m.bin(c, Bin::And, x, low);
  1902. l.s.op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h])
  1903. };
  1904. let (fa, fb) = (wide(self, a), wide(self, b));
  1905. let f = self.s.m.bin(c, Bin::Add, fa, fb);
  1906. self.f16_nearest(f)
  1907. }
  1908. /// `WaveActiveSum` of 16-bit floats (`x`: each lane's term in its low half, +0 in the
  1909. /// lanes outside the mask), bit for bit as the console adds it: every addition rounds to
  1910. /// 16 bits, so the order counts, and the compiler's is the balanced tree over the lanes
  1911. /// in their order (lanes 2k and 2k+1, then pairs, ... then the wave's two halves;
  1912. /// [`super::wave::buddies`]). Each lane adds its partner's partial sum, read from the
  1913. /// lane whose number differs in one bit, step by step; two host waves of 32 then exchange
  1914. /// their halves' sums for the last addition. The high half of the result is lane 0's,
  1915. /// which no `v_add_f16` writes.
  1916. /// That needs every lane of a full wave there to be read: refused where not every lane
  1917. /// runs, in a thread group that does not fill its waves, and for each half-wave on its
  1918. /// own (half a sum is no sum).
  1919. fn half_sum(&mut self, x: V) -> Result<V, Why> {
  1920. const WHERE: Why = "a wave sum of 16-bit floats where not every lane runs";
  1921. let threads = self.s.threads.ok_or("a wave sum of 16-bit floats outside compute")?;
  1922. if threads.iter().product::<u32>() % 64 != 0 {
  1923. return Err("a wave sum of 16-bit floats in a wave that is not full");
  1924. }
  1925. if self.local {
  1926. return Err("a wave sum of 16-bit floats in a half-wave");
  1927. }
  1928. // two host waves of 32 that exchange, or one host wave of 64 lanes
  1929. let halves = match (&self.exchange, self.s.wave_size) {
  1930. (Some((_, false, _)), _) => true,
  1931. (None, Some(64)) if self.x.p.wave64 => false,
  1932. _ => return Err("a wave sum of 16-bit floats on these waves"),
  1933. };
  1934. let every = if halves {
  1935. self.all_lanes(self.cur_ir)
  1936. } else {
  1937. all_lane_blocks(self.x.st).is_some_and(|all| all.get(self.cur_ir).copied().unwrap_or(false))
  1938. };
  1939. if !every {
  1940. if halves {
  1941. need(self.cur_ir);
  1942. }
  1943. return Err(WHERE);
  1944. }
  1945. let c = self.cur;
  1946. let i32t = self.s.t.i32;
  1947. let lane = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
  1948. let mut sum = x;
  1949. for step in 0..if halves { 5 } else { 6 } {
  1950. let bit = self.s.m.i32(1 << step);
  1951. let partner = self.s.m.bin(c, Bin::Xor, lane, bit);
  1952. let theirs = self.read_lane(sum, partner);
  1953. sum = self.add_halves(sum, theirs);
  1954. }
  1955. let (high, low, zero) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF), self.s.m.i32(0));
  1956. let first = self.read_lane(x, zero);
  1957. let first = self.s.m.bin(c, Bin::And, first, high);
  1958. let sum = self.s.m.bin(c, Bin::And, sum, low);
  1959. let mine = self.s.m.bin(c, Bin::Or, first, sum);
  1960. if !halves {
  1961. return Ok(mine);
  1962. }
  1963. let (lo, hi) = self.exchange_halves(c, mine);
  1964. let c = self.cur;
  1965. let total = self.add_halves(lo, hi);
  1966. let total = self.s.m.bin(c, Bin::And, total, low);
  1967. let first = self.s.m.bin(c, Bin::And, lo, high);
  1968. Ok(self.s.m.bin(c, Bin::Or, first, total))
  1969. }
  1970. fn run(mut self) -> Result<Lowered, Stop> {
  1971. let p = self.x.p;
  1972. let order = crate::ir::reverse_postorder(&p.blocks);
  1973. for (n, &b) in order.iter().enumerate() {
  1974. self.rpo[b] = n;
  1975. }
  1976. for (n, &b) in order.iter().enumerate() {
  1977. self.block[b] = Some(if n == 0 {
  1978. self.s.entry
  1979. } else {
  1980. self.s.m.new_block()
  1981. });
  1982. }
  1983. // Loop headers count iterations (`LOOP_LIMIT`).
  1984. for &b in &order {
  1985. let header = p.blocks[b]
  1986. .preds
  1987. .iter()
  1988. .any(|&q| self.block[q].is_some() && self.rpo[b] <= self.rpo[q]);
  1989. if header {
  1990. let blk = self.block[b].expect("reachable");
  1991. let phi = self.s.m.phi(blk, self.s.t.i32);
  1992. self.counters.insert(b, (phi, Vec::new()));
  1993. }
  1994. }
  1995. self.cur = self.s.entry;
  1996. self.find_sections();
  1997. self.inputs()?;
  1998. if let Some(mesh) = self.s.mesh {
  1999. self.mesh_prologue(mesh).map_err(|w| unsupported(0, w))?;
  2000. self.block[order[0]] = Some(self.cur);
  2001. }
  2002. for &b in &order {
  2003. self.cur = self.block[b].expect("reachable");
  2004. self.cur_ir = b;
  2005. let preds: Vec<usize> = p.blocks[b]
  2006. .preds
  2007. .iter()
  2008. .copied()
  2009. .filter(|&q| self.block[q].is_some())
  2010. .collect();
  2011. self.exported[b] = !preds.is_empty() && preds.iter().all(|&q| self.exported_out(q));
  2012. for (i, phi) in p.blocks[b].phis.iter().enumerate() {
  2013. let val = match phi.reg {
  2014. Reg::S(c) if c == EXEC || c == EXEC + 1 => Val::Missing("a lane mask"),
  2015. _ if self.bad.contains_key(&phi.value) => Val::Missing(self.bad[&phi.value]),
  2016. Reg::Scc => {
  2017. let v = self.s.m.phi(self.cur, self.s.t.i1);
  2018. self.data_phis.push((v, b, i));
  2019. Val::Bit(v)
  2020. }
  2021. _ => {
  2022. let v = self.s.m.phi(self.cur, self.s.t.i32);
  2023. self.data_phis.push((v, b, i));
  2024. Val::I32(v)
  2025. }
  2026. };
  2027. self.vals.insert(phi.value, val);
  2028. }
  2029. if self.lds_meet.as_ref().is_some_and(|(_, meet)| meet[b].0) {
  2030. self.lds_meeting();
  2031. }
  2032. let mut i = 0;
  2033. while i < p.blocks[b].insts.len() {
  2034. self.inst(b, i)?;
  2035. if let Some(end) = self.sections.get(&b).and_then(|s| s.get(&i)).map(|s| s.end) {
  2036. for j in i + 1..end {
  2037. self.section_inst(b, j, i);
  2038. }
  2039. i = end;
  2040. continue;
  2041. }
  2042. i += 1;
  2043. }
  2044. self.mask_ok = self.mask_data == MaskData::Console;
  2045. if self.lds_meet.as_ref().is_some_and(|(_, meet)| meet[b].1) {
  2046. self.lds_meeting();
  2047. }
  2048. self.tail[b] = Some(self.cur);
  2049. self.exit(b)?;
  2050. }
  2051. self.fill_phis()?;
  2052. let user_data = self.user_reads.values().copied().collect();
  2053. self.s.samplers = self.samplers.len() as u32;
  2054. let root_cbvs = self.s.root_cbvs.iter().map(|r| r.0).collect();
  2055. let root_srvs = self.s.root_srvs.iter().map(|r| r.0).collect();
  2056. let root_uavs = self.s.root_uavs.iter().map(|r| r.0).collect();
  2057. let cmp_samplers = self.s.cmp_samplers;
  2058. let wave_size = self.s.wave_size;
  2059. Ok(Lowered {
  2060. wave_size,
  2061. cmp_samplers,
  2062. root_cbvs,
  2063. root_srvs,
  2064. root_uavs,
  2065. #[cfg(test)]
  2066. nonuniform_handles: self.s.nonuniform_handles,
  2067. #[cfg(test)]
  2068. wave_ops: self.s.flags & flags::WAVE_OPS != 0,
  2069. dxil: self.s.finish(),
  2070. user_data,
  2071. samplers: self.samplers,
  2072. })
  2073. }
  2074. fn exported_out(&self, b: usize) -> bool {
  2075. self.exported[b] || self.has_done_export(b)
  2076. }
  2077. fn has_done_export(&self, b: usize) -> bool {
  2078. (0..self.x.p.blocks[b].insts.len())
  2079. .any(|i| self.exports.get(&(b, i)).is_some_and(|e| e.done))
  2080. }
  2081. /// Values of the program's input registers.
  2082. fn inputs(&mut self) -> Result<(), Stop> {
  2083. let io_inputs: HashMap<Value, Input> = self.x.io.inputs.iter().copied().collect();
  2084. for &(reg, v) in &self.x.p.inputs {
  2085. let val = match reg {
  2086. Reg::S(_) if self.params.contains_key(&v) => continue, // loaded on first use
  2087. // Most programs only interpolate with them: loaded on first
  2088. // use as a value (`get`).
  2089. Reg::V(_) if matches!(io_inputs.get(&v), Some(Input::Barycentric { .. })) => {
  2090. continue;
  2091. }
  2092. Reg::S(n) => match io_inputs.get(&v) {
  2093. Some(&input) => self.input(input),
  2094. // Above the SGPRs the hardware initializes, a register
  2095. // holds what the last wave left, so no program depends
  2096. // on it: a read the paths only seem to allow (a branch
  2097. // past the write, taken only with one past the read)
  2098. // reads zero, as VGPRs do.
  2099. None if n <= 105 && self.x.io.initialized_sgprs.is_some_and(|k| n >= k) => {
  2100. Val::I32(self.s.m.i32(0))
  2101. }
  2102. // A scalar parked in a VGPR lane (`ir::unspill`), read where the
  2103. // paths only seem to allow it before any save: the lane of a VGPR
  2104. // nobody wrote, and VGPRs nobody set read as zero.
  2105. None if n >= crate::ir::PARKED => Val::I32(self.s.m.i32(0)),
  2106. None => Val::Missing("a hardware SGPR input"),
  2107. },
  2108. Reg::Scc => Val::Missing("SCC on entry"),
  2109. Reg::V(_) => match io_inputs.get(&v) {
  2110. Some(&input) => self.input(input),
  2111. // Registers no one set read as zero (the validator
  2112. // refuses reads of undef).
  2113. None => Val::I32(self.s.m.i32(0)),
  2114. },
  2115. };
  2116. self.vals.insert(v, val);
  2117. }
  2118. Ok(())
  2119. }
  2120. fn input(&mut self, input: Input) -> Val {
  2121. let (kind, col) = match input {
  2122. Input::VertexId => (1, 0),
  2123. Input::InstanceId => (2, 0),
  2124. Input::Position(c) => (3, c),
  2125. Input::Attribute { row, channel } => {
  2126. return match self.find_input(row, channel) {
  2127. Some((id, col)) => self.load_input(id, col),
  2128. None => Val::Missing("a vertex input the signature lacks"),
  2129. };
  2130. }
  2131. Input::Barycentric { kind, index } => return self.barycentric(kind, index),
  2132. Input::PrimitiveId => return Val::Missing("the primitive id"),
  2133. // The console code tests it against 0 (`v_cmp_ne_u32`), as the
  2134. // host's value can be.
  2135. Input::FrontFace => (13, 0),
  2136. Input::ThreadIdInGroup(c) => return self.thread_id(c),
  2137. Input::GroupId(c) => return self.compute_id("groupId.i32", 94, c),
  2138. Input::GroupInfo => return Val::Missing("the thread-group info SGPR"),
  2139. Input::MeshGroup => {
  2140. let Val::I32(g) = self.compute_id("groupId.i32", 94, 0) else {
  2141. unreachable!()
  2142. };
  2143. let n = self.s.m.i32(self.x.mesh_stride);
  2144. return Val::I32(self.s.m.bin(self.s.entry, Bin::Mul, g, n));
  2145. }
  2146. Input::MergedWaveInfo => {
  2147. // shortcut: only the wave index (bits 24-27) is set; the
  2148. // console's other bits (lane counts) are read by no program.
  2149. let f = self.mesh_thread();
  2150. let shift = self.s.m.i32(self.wave().trailing_zeros());
  2151. let w = self.s.m.bin(self.s.entry, Bin::LShr, f, shift);
  2152. let k24 = self.s.m.i32(24);
  2153. return Val::I32(self.s.m.bin(self.s.entry, Bin::Shl, w, k24));
  2154. }
  2155. _ => return Val::Missing("a pixel system input"),
  2156. };
  2157. let free = self
  2158. .s
  2159. .inputs
  2160. .iter()
  2161. .filter_map(|e| e.row)
  2162. .map(|r| r + 1)
  2163. .max()
  2164. .unwrap_or(0);
  2165. let id = match self.s.inputs.iter().position(|e| e.kind == kind) {
  2166. Some(id) => {
  2167. if kind != 3 {
  2168. self.s.inputs[id].row.get_or_insert(free);
  2169. }
  2170. id
  2171. }
  2172. None if kind >= 3 => return Val::Missing("a pixel system input the signature lacks"),
  2173. None => {
  2174. // The console signature leaves out vertex and instance ids; PC
  2175. // gives them a row after the others.
  2176. let row = self
  2177. .s
  2178. .inputs
  2179. .iter()
  2180. .filter_map(|e| e.row)
  2181. .map(|r| r + 1)
  2182. .max()
  2183. .unwrap_or(0);
  2184. self.s.inputs.push(SigElement {
  2185. name: ["", "SV_VertexID", "SV_InstanceID"][kind as usize].into(),
  2186. index: 0,
  2187. kind,
  2188. comp: 5,
  2189. interp: 0,
  2190. row: Some(row),
  2191. col: 0,
  2192. cols: 1,
  2193. usage: 0,
  2194. half: false,
  2195. });
  2196. self.s.inputs.len() - 1
  2197. }
  2198. };
  2199. self.load_input(id, col)
  2200. }
  2201. /// A component of a compute thread or group id, read in the entry block.
  2202. fn compute_id(&mut self, name: &str, opcode: u32, c: u8) -> Val {
  2203. let (entry, c) = (self.s.entry, self.s.m.i32(u32::from(c)));
  2204. Val::I32(
  2205. self.s
  2206. .op(entry, name, Attr::ReadNone, self.s.t.i32, opcode, &[c]),
  2207. )
  2208. }
  2209. fn find_input(&self, row: u8, channel: u8) -> Option<(usize, u8)> {
  2210. self.s.inputs.iter().enumerate().find_map(|(id, e)| {
  2211. let r = e.row?;
  2212. // `then`, not `then_some`: the channel is only past `col` when
  2213. // the condition holds.
  2214. (r == u32::from(row) && channel >= e.col && channel < e.col + e.cols)
  2215. .then(|| (id, channel - e.col))
  2216. })
  2217. }
  2218. fn load_input(&mut self, id: usize, col: u8) -> Val {
  2219. if self.s.inputs[id].half {
  2220. // shortcut: 16-bit vertex inputs (the fetch routine's) are not
  2221. // unpacked; pixel inputs are (`interp`).
  2222. return Val::Missing("a 16-bit input");
  2223. }
  2224. self.load_any_input(id, col)
  2225. }
  2226. /// An input element's channel as declared (16-bit ones as 32-bit floats).
  2227. fn load_any_input(&mut self, id: usize, col: u8) -> Val {
  2228. let e = &mut self.s.inputs[id];
  2229. e.usage |= 1 << col;
  2230. let (int, bit) = (e.comp != 9, e.comp == 1);
  2231. let ty = if bit {
  2232. self.s.t.i1
  2233. } else if int {
  2234. self.s.t.i32
  2235. } else {
  2236. self.s.t.f32
  2237. };
  2238. let suffix = if bit {
  2239. ".i1"
  2240. } else if int {
  2241. ".i32"
  2242. } else {
  2243. ".f32"
  2244. };
  2245. let entry = self.s.entry;
  2246. let args = [
  2247. self.s.m.i32(id as u32),
  2248. self.s.m.i32(0),
  2249. self.s.m.i8(col),
  2250. self.s.m.undef(self.s.t.i32),
  2251. ];
  2252. let v = self.s.op(
  2253. entry,
  2254. &format!("loadInput{suffix}"),
  2255. Attr::ReadNone,
  2256. ty,
  2257. 4,
  2258. &args,
  2259. );
  2260. if bit {
  2261. let z = self.s.m.cast(entry, Cast::ZExt, v, self.s.t.i32);
  2262. Val::I32(z)
  2263. } else if int {
  2264. Val::I32(v)
  2265. } else {
  2266. Val::I32(self.s.m.cast(entry, Cast::Bitcast, v, self.s.t.i32))
  2267. }
  2268. }
  2269. /// The DXIL form of an IR value.
  2270. fn get(&mut self, v: Value) -> Result<Val, Why> {
  2271. if self.phi_at.contains_key(&v) {
  2272. self.read_phis.insert(v);
  2273. }
  2274. let is_mask = self.x.st.masks.contains_key(&v) || self.x.st.highs.contains_key(&v);
  2275. match self.vals.get(&v) {
  2276. Some(&Val::Missing(_)) | None if self.mask_ok && is_mask => {
  2277. return self.mask_dword(v).map(Val::I32);
  2278. }
  2279. Some(&Val::Missing(w)) => return Err(w),
  2280. Some(&val) => return Ok(val),
  2281. None => {}
  2282. }
  2283. if let Some(&(param, dword)) = self.params.get(&v) {
  2284. let val = self.user(param, dword);
  2285. self.vals.insert(v, val);
  2286. return Ok(val);
  2287. }
  2288. if let Some(loaded) = self.lazy_barycentric(v) {
  2289. loaded?;
  2290. return Ok(self.vals[&v]);
  2291. }
  2292. Err("a value defined after its use")
  2293. }
  2294. /// Loads `v` if it is a barycentric input VGPR not loaded yet (see
  2295. /// `inputs`): `None` if it is not one.
  2296. fn lazy_barycentric(&mut self, v: Value) -> Option<Result<(), Why>> {
  2297. let (kind, index) = self.x.io.inputs.iter().find_map(|&(w, i)| match i {
  2298. Input::Barycentric { kind, index } if w == v => Some((kind, index)),
  2299. _ => None,
  2300. })?;
  2301. let val = self.barycentric(kind, index);
  2302. self.vals.insert(v, val);
  2303. Some(match val {
  2304. Val::Missing(w) => Err(w),
  2305. _ => Ok(()),
  2306. })
  2307. }
  2308. /// Barycentric `index` (0 i, 1 j) of `kind` as a value: a channel of
  2309. /// `SV_Barycentrics` declared with the same interpolation mode.
  2310. ///
  2311. /// GFX10 interpolates P0 + i (P1 - P0) + j (P2 - P0), so i and j are
  2312. /// the weights of vertices 1 and 2. The host's weights (x, y, z) are
  2313. /// those of vertices 0, 1 and 2, vertex 0 being the provoking vertex,
  2314. /// which is the console's P0 (`v_interp_mov` P0 is lowered to a flat
  2315. /// input): i is y and j is z.
  2316. /// shortcut: triangles only; on lines and points the console's i and j
  2317. /// are not checked against the host's weights.
  2318. fn barycentric(&mut self, kind: Barycentric, index: u8) -> Val {
  2319. let Some(mode) = interp_mode(kind) else {
  2320. return Val::Missing("pull-model barycentrics");
  2321. };
  2322. if index > 1 {
  2323. return Val::Missing("pull-model barycentrics");
  2324. }
  2325. // One element per interpolation mode (the console's own, if its
  2326. // signature declares one): DXIL allows two.
  2327. let bary = |e: &SigElement| e.kind == 28;
  2328. let id = match self
  2329. .s
  2330. .inputs
  2331. .iter()
  2332. .position(|e| bary(e) && (e.interp == mode || e.usage == 0))
  2333. {
  2334. Some(id) => id,
  2335. None => {
  2336. let index = self.s.inputs.iter().filter(|e| bary(e)).count() as u32;
  2337. if index >= 2 {
  2338. return Val::Missing("barycentrics of a third interpolation mode");
  2339. }
  2340. // A system value the validator wants unpacked (packing
  2341. // location -1), like other non-packed system values.
  2342. self.s.inputs.push(SigElement {
  2343. name: "SV_Barycentrics".into(),
  2344. index,
  2345. kind: 28,
  2346. comp: 9,
  2347. interp: mode,
  2348. row: None,
  2349. col: 0,
  2350. cols: 3,
  2351. usage: 0,
  2352. half: false,
  2353. });
  2354. self.s.inputs.len() - 1
  2355. }
  2356. };
  2357. let e = &mut self.s.inputs[id];
  2358. if e.col != 0 || e.cols < 3 {
  2359. return Val::Missing("a console barycentrics element without i and j");
  2360. }
  2361. e.row = None;
  2362. e.interp = mode;
  2363. self.s.flags |= flags::BARYCENTRICS;
  2364. self.load_any_input(id, index + 1)
  2365. }
  2366. fn i32_of(&mut self, v: Value) -> Result<V, Why> {
  2367. match self.get(v)? {
  2368. Val::I32(x) => Ok(x),
  2369. Val::Bit(x) => Ok(self.s.m.cast(self.cur, Cast::ZExt, x, self.s.t.i32)),
  2370. Val::Missing(w) => Err(w),
  2371. }
  2372. }
  2373. /// A user-data dword: a root parameter's value.
  2374. fn user(&mut self, param: usize, dword: u32) -> Val {
  2375. let rp = self.x.native.layout[param];
  2376. match rp.root {
  2377. RootType::ResourceHeap | RootType::SamplerHeap => return Val::I32(self.s.m.i32(0)),
  2378. RootType::Constants | RootType::Table => {}
  2379. _ => return Val::Missing("a root descriptor"),
  2380. }
  2381. let index = u32::from(rp.user_data) + dword - self.user_first();
  2382. self.user_reads.insert(
  2383. index,
  2384. UserData {
  2385. index,
  2386. slot: rp.slot,
  2387. root: rp.root,
  2388. dword,
  2389. },
  2390. );
  2391. Val::I32(self.user_at(index))
  2392. }
  2393. /// The user-data index that is dword 0 of the host's user data: 0, or
  2394. /// 16 for a program with a spilled user-data table, whose parameters
  2395. /// all sit at 16 and above. (The host's root signature has 64 dwords:
  2396. /// a builder stage with constants up to index 45, eight root views,
  2397. /// their biases and the memory directory would not fit with 16 dwords
  2398. /// nothing reads in front.)
  2399. fn user_first(&self) -> u32 {
  2400. if crate::spill::is_spilled(self.x.native) {
  2401. 16
  2402. } else {
  2403. 0
  2404. }
  2405. }
  2406. /// A user-data dword no register of the console's holds: one the host
  2407. /// computes when it binds (`root` says what, an `Other` code of
  2408. /// `shader.rs`), placed after the layout's own dwords.
  2409. fn host_word(&mut self, root: RootType, slot: u8, dword: u32) -> V {
  2410. let known = self
  2411. .user_reads
  2412. .values()
  2413. .find(|u| u.root == root && u.slot == slot && u.dword == dword)
  2414. .map(|u| u.index);
  2415. let index = match known {
  2416. Some(index) => index,
  2417. None => {
  2418. let first = self.user_first();
  2419. let layout = &self.x.native.layout;
  2420. let mut index = layout
  2421. .iter()
  2422. .map(|e| u32::from(e.user_data) + e.sgprs)
  2423. .max()
  2424. .unwrap_or(0)
  2425. .saturating_sub(first);
  2426. while self.user_reads.contains_key(&index) {
  2427. index += 1;
  2428. }
  2429. self.user_reads.insert(
  2430. index,
  2431. UserData {
  2432. index,
  2433. slot,
  2434. root,
  2435. dword,
  2436. },
  2437. );
  2438. index
  2439. }
  2440. };
  2441. self.user_at(index)
  2442. }
  2443. /// User-data dword `index`, loaded in the entry block.
  2444. fn user_at(&mut self, index: u32) -> V {
  2445. self.s.user_data = self.s.user_data.max(index + 1);
  2446. let h = match self.user_data {
  2447. Some(h) => h,
  2448. None => {
  2449. let h = self.s.user_data_handle();
  2450. self.user_data = Some(h);
  2451. h
  2452. }
  2453. };
  2454. let entry = self.s.entry;
  2455. let row = self.s.m.i32(index / 4);
  2456. let r = self.s.op(
  2457. entry,
  2458. "cbufferLoadLegacy.i32",
  2459. Attr::ReadOnly,
  2460. self.s.t.cbuf_ret,
  2461. 59,
  2462. &[h, row],
  2463. );
  2464. self.s.m.extract(entry, r, index % 4)
  2465. }
  2466. /// Whether some instruction computes with `v` (scalar or vector
  2467. /// arithmetic), rather than only naming it in a descriptor operand,
  2468. /// moving it (at most `depth` moves are followed) or comparing it: a
  2469. /// waterfall loop keeps a descriptor's dwords per lane, reads the first
  2470. /// lane's back and compares the lanes' with them.
  2471. fn computed_with(&self, v: Value, depth: u32) -> bool {
  2472. self.x.p.blocks.iter().flat_map(|b| &b.insts).any(|i| {
  2473. if !i.reads.iter().any(|r| r.1 == v) {
  2474. return false;
  2475. }
  2476. let name = i.name();
  2477. let moves = matches!(
  2478. name,
  2479. "s_mov_b32"
  2480. | "s_mov_b64"
  2481. | "v_mov_b32"
  2482. | "v_readfirstlane_b32"
  2483. | "v_readlane_b32"
  2484. | "v_writelane_b32"
  2485. | "v_cndmask_b32"
  2486. );
  2487. match &i.fields {
  2488. Fields::Sop { .. } | Fields::Valu(_) if moves => {
  2489. depth > 0 && i.writes.iter().any(|w| self.computed_with(w.1, depth - 1))
  2490. }
  2491. Fields::Sop { .. } | Fields::Valu(_) => {
  2492. !(name.starts_with("v_cmp") || name.starts_with("s_cmp"))
  2493. }
  2494. _ => false,
  2495. }
  2496. })
  2497. }
  2498. /// The title address (low dword, bits from 32 up) of the buffer view
  2499. /// whose descriptor the scalar load at `site` reads from the start of
  2500. /// a table entry, as the host tells it when it binds (`shader.rs`
  2501. /// `USER_VIEW_ADDRESS`); none for anything else. (The console's
  2502. /// descriptor holds more in the second dword, the stride from bit 16
  2503. /// up; code that takes the address masks those away.)
  2504. fn view_address(&mut self, site: Site) -> Option<(V, V)> {
  2505. use super::shader::USER_VIEW_ADDRESS;
  2506. let a = self.scalar.get(&site).copied()?;
  2507. let rp = *self.x.native.layout.get(a.param)?;
  2508. if rp.root != RootType::Table || a.dynamic.is_some() || a.offset % 32 != 0 {
  2509. return None;
  2510. }
  2511. let dword = a.offset / 4;
  2512. let used = self
  2513. .x
  2514. .native
  2515. .used
  2516. .iter()
  2517. .filter(|u| {
  2518. u.root == RootType::Table
  2519. && u.user_data == rp.user_data
  2520. && u.table_offset_dwords <= dword
  2521. })
  2522. .max_by_key(|u| u.table_offset_dwords)?;
  2523. if used.dwords != 4 || !matches!(used.kind, ResourceType::Srv | ResourceType::Uav) {
  2524. return None;
  2525. }
  2526. let lo = self.host_word(RootType::Other(USER_VIEW_ADDRESS), rp.slot, dword);
  2527. let hi = self.host_word(RootType::Other(USER_VIEW_ADDRESS + 1), rp.slot, dword);
  2528. Some((lo, hi))
  2529. }
  2530. /// `lo`, `hi` plus the instruction's byte offset `off`, with the carry.
  2531. fn address_plus(&mut self, lo: V, hi: V, off: i32) -> (V, V) {
  2532. if off == 0 {
  2533. return (lo, hi);
  2534. }
  2535. let c = self.cur;
  2536. let i32t = self.s.t.i32;
  2537. let k = self.s.m.i32(off as u32);
  2538. let sum = self.s.m.bin(c, Bin::Add, lo, k);
  2539. // Up: a carry when the sum wrapped below `lo`. Down: a borrow when
  2540. // it wrapped above.
  2541. let wrapped = self
  2542. .s
  2543. .m
  2544. .cmp(c, if off > 0 { pred::IULT } else { pred::IUGT }, sum, lo);
  2545. let one = self.s.m.cast(c, Cast::ZExt, wrapped, i32t);
  2546. let hi = self.s.m.bin(c, if off > 0 { Bin::Add } else { Bin::Sub }, hi, one);
  2547. (sum, hi)
  2548. }
  2549. /// Title memory at the 40-bit address `lo`, `hi` (`shader.rs`
  2550. /// `SLOT_MEMORY`): the handle of the raw view of the host copy holding
  2551. /// it and the byte in that view. A page without a copy reads zeros
  2552. /// (and drops writes) through the null view at the first slot, and its
  2553. /// number is left for the host, for lanes that run (`guard`).
  2554. fn memory(&mut self, lo: V, hi: V, guard: Option<V>) -> (V, V) {
  2555. use super::shader::{MEMORY_FAULTS, MEMORY_PAGES, SLOT_FAULTS, SLOT_MEMORY, USER_MEMORY_BASE};
  2556. let c = self.cur;
  2557. let (i32t, res) = (self.s.t.i32, self.s.t.res_ret);
  2558. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  2559. let (k16, k8) = (k(self, 16), k(self, 0xFF));
  2560. let low = self.s.m.bin(c, Bin::LShr, lo, k16);
  2561. let high = self.s.m.bin(c, Bin::And, hi, k8);
  2562. let high = self.s.m.bin(c, Bin::Shl, high, k16);
  2563. let page = self.s.m.bin(c, Bin::Or, low, high);
  2564. // Inside the directory whatever the address (lanes that do not run
  2565. // compute one too); its last entry is never filled.
  2566. let last = k(self, MEMORY_PAGES - 1);
  2567. let page = self
  2568. .s
  2569. .op(c, "binary.i32", Attr::ReadNone, i32t, 40, &[page, last]);
  2570. let k3 = k(self, 3);
  2571. let at = self.s.m.bin(c, Bin::Shl, page, k3);
  2572. let directory = self.s.root_srv_handle(SLOT_MEMORY);
  2573. let (iu, both, align) = (self.s.m.undef(i32t), self.s.m.i8(3), k(self, 4));
  2574. let entry = self.s.op(
  2575. c,
  2576. "rawBufferLoad.f32",
  2577. Attr::ReadOnly,
  2578. res,
  2579. 139,
  2580. &[directory, at, iu, both, align],
  2581. );
  2582. let (copy, start) = (self.s.m.extract(c, entry, 0), self.s.m.extract(c, entry, 1));
  2583. let (copy, start) = (self.as_int(copy), self.as_int(start));
  2584. // A page without a copy: its number, at a place by the number, or
  2585. // at the sink for lanes that do not run and pages that have one.
  2586. let zero = k(self, 0);
  2587. let mut missing = self.s.m.cmp(c, pred::EQ, copy, zero);
  2588. if let Some(g) = guard {
  2589. missing = self.s.m.bin(c, Bin::And, missing, g);
  2590. }
  2591. let places = k(self, MEMORY_FAULTS - 1);
  2592. let place = self.s.m.bin(c, Bin::URem, page, places);
  2593. let one = k(self, 1);
  2594. let place = self.s.m.bin(c, Bin::Add, place, one);
  2595. let k2 = k(self, 2);
  2596. let place = self.s.m.bin(c, Bin::Shl, place, k2);
  2597. let place = self.s.m.select(c, missing, place, zero);
  2598. let faults = self.s.root_uav_handle(SLOT_FAULTS);
  2599. let void = self.s.t.void;
  2600. let mask = self.s.m.i8(1);
  2601. self.s.op(
  2602. c,
  2603. "rawBufferStore.i32",
  2604. Attr::NoUnwind,
  2605. void,
  2606. 140,
  2607. &[faults, place, iu, page, iu, iu, iu, mask, align],
  2608. );
  2609. let base = self.host_word(RootType::Other(USER_MEMORY_BASE), 0, 0);
  2610. let slot = self.s.m.bin(c, Bin::Add, base, copy);
  2611. let h = self.s.heap_handle(c, slot, false, true, (11 | 0x1000, 0));
  2612. let k64k = k(self, 0xFFFF);
  2613. let within = self.s.m.bin(c, Bin::And, lo, k64k);
  2614. let byte = self.s.m.bin(c, Bin::Add, start, within);
  2615. (h, byte)
  2616. }
  2617. /// `global_load_*`, `global_store_*` and `global_atomic_*` on title
  2618. /// memory by address (`resource::MEMORY`): the address is the VGPR
  2619. /// pair, each lane its own.
  2620. fn memory_flat(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  2621. let Fields::Flat {
  2622. dst,
  2623. addr,
  2624. data,
  2625. saddr,
  2626. offset,
  2627. lds,
  2628. cache,
  2629. } = &inst.fields
  2630. else {
  2631. unreachable!()
  2632. };
  2633. if *lds || !matches!(saddr, None | Some(Operand::Scalar { code: NULL, .. })) {
  2634. return Err("a global address with a scalar base");
  2635. }
  2636. let Some(Operand::Vector { reg: areg, .. }) = *addr else {
  2637. return Err("a global address not in VGPRs");
  2638. };
  2639. let word = |l: &mut Self, k: u8| -> Result<V, Why> {
  2640. let v = inst.read(Reg::V(areg + k)).ok_or("a global address")?;
  2641. l.i32_of(v)
  2642. };
  2643. let (lo, hi) = (word(self, 0)?, word(self, 1)?);
  2644. let (lo, hi) = self.address_plus(lo, hi, i32::from(*offset));
  2645. let guard = self.guard(b, i)?;
  2646. let c = self.cur;
  2647. let (i32t, res, void) = (self.s.t.i32, self.s.t.res_ret, self.s.t.void);
  2648. let iu = self.s.m.undef(i32t);
  2649. let align = self.s.m.i32(4);
  2650. let name = inst.name();
  2651. let count = |rest: &str| match rest {
  2652. "dword" => Ok(1u8),
  2653. "dwordx2" => Ok(2),
  2654. "dwordx3" => Ok(3),
  2655. "dwordx4" => Ok(4),
  2656. _ => Err(name),
  2657. };
  2658. if let Some(rest) = name.strip_prefix("global_load_") {
  2659. let n = count(rest)?;
  2660. let Some(Operand::Vector { reg, .. }) = *dst else {
  2661. return Err("a global load result");
  2662. };
  2663. let (h, byte) = self.memory(lo, hi, guard);
  2664. let mask = self.s.m.i8((1u8 << n) - 1);
  2665. let r = self.s.op(
  2666. c,
  2667. "rawBufferLoad.f32",
  2668. Attr::ReadOnly,
  2669. res,
  2670. 139,
  2671. &[h, byte, iu, mask, align],
  2672. );
  2673. for k in 0..n {
  2674. let x = self.s.m.extract(c, r, u32::from(k));
  2675. let x = self.as_int(x);
  2676. self.write(inst, Reg::V(reg + k), x, guard);
  2677. }
  2678. return Ok(());
  2679. }
  2680. if let Some(rest) = name.strip_prefix("global_store_") {
  2681. let n = count(rest)?;
  2682. let d = data.as_ref().ok_or("global store data")?;
  2683. let vals = self.vgprs(inst, d, n)?;
  2684. let (h, byte) = self.memory(lo, hi, guard);
  2685. let mut args = vec![h, byte, iu];
  2686. args.extend(&vals);
  2687. args.resize(3 + 4, iu);
  2688. args.push(self.s.m.i8((1u8 << n) - 1));
  2689. args.push(align);
  2690. let at = self.begin_guarded(guard);
  2691. self.s
  2692. .op(self.cur, "rawBufferStore.i32", Attr::NoUnwind, void, 140, &args);
  2693. self.end_guarded(at, &[]);
  2694. return Ok(());
  2695. }
  2696. let Some(op) = name.strip_prefix("global_atomic_") else {
  2697. return Err(name);
  2698. };
  2699. let d = data.as_ref().ok_or("global atomic data")?;
  2700. let v = self.vgprs(inst, d, 1)?[0];
  2701. // With `glc` the value from before comes back, in the result
  2702. // register the instruction names.
  2703. let back = match (*dst, cache.glc) {
  2704. (Some(Operand::Vector { reg, .. }), true) => Some(reg),
  2705. _ => None,
  2706. };
  2707. let old = match back.and_then(|reg| inst.read(Reg::V(reg))) {
  2708. Some(x) => self.i32_of(x)?,
  2709. None => self.s.m.i32(0),
  2710. };
  2711. let (h, byte) = self.memory(lo, hi, guard);
  2712. // DXIL's atomic operations: add 0, and 1, or 2, xor 3, signed
  2713. // minimum 4 and maximum 5, unsigned 6 and 7, exchange 8.
  2714. let simple = match op {
  2715. "add" => Some((0, v)),
  2716. "sub" => {
  2717. let zero = self.s.m.i32(0);
  2718. Some((0, self.s.m.bin(c, Bin::Sub, zero, v)))
  2719. }
  2720. "and" => Some((1, v)),
  2721. "or" => Some((2, v)),
  2722. "xor" => Some((3, v)),
  2723. "smin" => Some((4, v)),
  2724. "smax" => Some((5, v)),
  2725. "umin" => Some((6, v)),
  2726. "umax" => Some((7, v)),
  2727. "swap" => Some((8, v)),
  2728. "fmin" | "fmax" => None,
  2729. _ => return Err(name),
  2730. };
  2731. let at = self.begin_guarded(guard);
  2732. let was = match simple {
  2733. Some((code, x)) => {
  2734. let code = self.s.m.i32(code);
  2735. self.s.op(
  2736. self.cur,
  2737. "atomicBinOp.i32",
  2738. Attr::NoUnwind,
  2739. i32t,
  2740. 78,
  2741. &[h, code, byte, iu, iu, x],
  2742. )
  2743. }
  2744. None => {
  2745. // A float minimum or maximum has no atomic operation on
  2746. // the host: the dword is exchanged for the smaller (larger)
  2747. // of itself and the value until no other thread got in
  2748. // between. Each failed pass means another one's succeeded;
  2749. // the limit only keeps a broken card from hanging.
  2750. let head = self.cur;
  2751. let mask = self.s.m.i8(1);
  2752. let first = self.s.op(
  2753. head,
  2754. "rawBufferLoad.f32",
  2755. Attr::ReadOnly,
  2756. res,
  2757. 139,
  2758. &[h, byte, iu, mask, align],
  2759. );
  2760. let first = self.s.m.extract(head, first, 0);
  2761. let first = self.as_int(first);
  2762. let (pass, done) = (self.s.m.new_block(), self.s.m.new_block());
  2763. self.s.m.terminate(head, Term::Br(pass));
  2764. self.cur = pass;
  2765. let seen = self.s.m.phi(pass, i32t);
  2766. let n = self.s.m.phi(pass, i32t);
  2767. let (f32t, fv) = (self.s.t.f32, self.as_float(v));
  2768. let fseen = self.as_float(seen);
  2769. // `dx.op.binary`: FMax 35, FMin 36.
  2770. let pick = if op == "fmin" { 36 } else { 35 };
  2771. let wanted = self
  2772. .s
  2773. .op(pass, "binary.f32", Attr::ReadNone, f32t, pick, &[fseen, fv]);
  2774. let wanted = self.as_int(wanted);
  2775. let found = self.s.op(
  2776. pass,
  2777. "atomicCompareExchange.i32",
  2778. Attr::NoUnwind,
  2779. i32t,
  2780. 79,
  2781. &[h, byte, iu, iu, seen, wanted],
  2782. );
  2783. let one = self.s.m.i32(1);
  2784. let n1 = self.s.m.bin(pass, Bin::Add, n, one);
  2785. let lost = self.s.m.cmp(pass, pred::NE, found, seen);
  2786. let limit = self.s.m.i32(1 << 16);
  2787. let more = self.s.m.cmp(pass, pred::IULT, n1, limit);
  2788. let again = self.s.m.bin(pass, Bin::And, lost, more);
  2789. self.s.m.terminate(pass, Term::CondBr(again, pass, done));
  2790. let zero = self.s.m.i32(0);
  2791. self.s.m.set_phi(seen, vec![(first, head), (found, pass)]);
  2792. self.s.m.set_phi(n, vec![(zero, head), (n1, pass)]);
  2793. self.cur = done;
  2794. found
  2795. }
  2796. };
  2797. let was = self.end_guarded(at, &[(was, old)])[0];
  2798. if let Some(reg) = back {
  2799. self.write(inst, Reg::V(reg), was, None);
  2800. }
  2801. Ok(())
  2802. }
  2803. /// `s_load_dword*` from title memory by address (`resource::MEMORY`):
  2804. /// the SGPR pair plus the instruction's offsets.
  2805. fn memory_smem(&mut self, inst: &Inst) -> Result<(), Why> {
  2806. let Fields::Smem {
  2807. data: Some(Operand::Scalar { code, .. }),
  2808. base: Operand::Scalar { code: base, .. },
  2809. offset,
  2810. soffset,
  2811. ..
  2812. } = inst.fields
  2813. else {
  2814. return Err("a scalar load from memory");
  2815. };
  2816. let count = match inst.name().strip_prefix("s_load_dword") {
  2817. Some("") => 1u8,
  2818. Some("x2") => 2,
  2819. Some("x4") => 4,
  2820. Some("x8") => 8,
  2821. Some("x16") => 16,
  2822. _ => return Err("a scalar memory access by address"),
  2823. };
  2824. let word = |l: &mut Self, k: u8| -> Result<V, Why> {
  2825. let v = inst.read(Reg::S(base + k)).ok_or("an address not in SGPRs")?;
  2826. l.i32_of(v)
  2827. };
  2828. let (mut lo, mut hi) = (word(self, 0)?, word(self, 1)?);
  2829. let c = self.cur;
  2830. let (i32t, res) = (self.s.t.i32, self.s.t.res_ret);
  2831. if !matches!(soffset, Operand::Scalar { code: NULL, .. }) {
  2832. // An offset register counts up from the address.
  2833. let so = self.operand(inst, &soffset)?;
  2834. let sum = self.s.m.bin(c, Bin::Add, lo, so);
  2835. let carry = self.s.m.cmp(c, pred::IULT, sum, lo);
  2836. let carry = self.s.m.cast(c, Cast::ZExt, carry, i32t);
  2837. hi = self.s.m.bin(c, Bin::Add, hi, carry);
  2838. lo = sum;
  2839. }
  2840. let (iu, align) = (self.s.m.undef(i32t), self.s.m.i32(4));
  2841. for first in (0..count).step_by(4) {
  2842. let n = (count - first).min(4);
  2843. let (lo, hi) = self.address_plus(lo, hi, offset + 4 * i32::from(first));
  2844. let (h, byte) = self.memory(lo, hi, None);
  2845. let mask = self.s.m.i8((1u8 << n) - 1);
  2846. let r = self.s.op(
  2847. c,
  2848. "rawBufferLoad.f32",
  2849. Attr::ReadOnly,
  2850. res,
  2851. 139,
  2852. &[h, byte, iu, mask, align],
  2853. );
  2854. for k in 0..n {
  2855. let x = self.s.m.extract(c, r, u32::from(k));
  2856. let x = self.as_int(x);
  2857. self.write(inst, Reg::S(code + first + k), x, None);
  2858. }
  2859. }
  2860. Ok(())
  2861. }
  2862. /// A dword of a lane mask as a number: the ballot of the lanes' bits,
  2863. /// taken in the block that writes the mask (see [`MaskData`]).
  2864. fn mask_dword(&mut self, v: Value) -> Result<V, Why> {
  2865. let (lo, high) = match self.x.st.highs.get(&v) {
  2866. Some(&lo) => (lo, true),
  2867. None => (v, false),
  2868. };
  2869. let &m = self.x.st.masks.get(&lo).ok_or(LANE_MASK)?;
  2870. // A mask that holds lanes outside EXEC where it is written (the complement of one,
  2871. // say) is the ballot of the lanes that are there: all of them, where two exchanging
  2872. // host waves know every lane runs that block.
  2873. let made = self.def_block.get(&lo).copied();
  2874. let whole = self.exchange.is_some() && !self.local && made.is_none_or(|b| self.all_lanes(b));
  2875. if !self.x.st.active.contains(&lo) && !whole {
  2876. if self.exchange.is_some() && !self.local {
  2877. need(made.unwrap_or(0));
  2878. }
  2879. return Err(MASK_ELSEWHERE);
  2880. }
  2881. let (x, y) = match self.ballots.get(&lo) {
  2882. Some(&xy) => xy,
  2883. None => {
  2884. let at = match self.def_block.get(&lo) {
  2885. // Program inputs (EXEC on entry).
  2886. None => self.s.entry,
  2887. Some(&b) if b == self.cur_ir => self.cur,
  2888. Some(&b) => self.tail[b].ok_or("a lane mask written after its use")?,
  2889. };
  2890. if !self.balloting.insert(lo) {
  2891. return Err("a lane mask whose lanes depend on its own value");
  2892. }
  2893. let bit = self.boolean(m, at);
  2894. self.balloting.remove(&lo);
  2895. let bit = bit?;
  2896. let i32t = self.s.t.i32;
  2897. let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]);
  2898. let r = self
  2899. .s
  2900. .op(at, "waveActiveBallot", Attr::NoUnwind, four, 116, &[bit]);
  2901. self.s.flags |= flags::WAVE_OPS;
  2902. let mut xy = (self.s.m.extract(at, r, 0), self.s.m.extract(at, r, 1));
  2903. if self.exchange.is_some() {
  2904. // a host wave's ballot is its half's 32 bits: the halves exchange them
  2905. let b = self.def_block.get(&lo).copied();
  2906. if self.local {
  2907. if !self.local_ok && !self.local_any {
  2908. return Err("a lane mask read as data in a half-wave");
  2909. }
  2910. } else if !self.exchange.as_ref().is_some_and(|e| e.1) && !b.is_none_or(|b| self.all_lanes(b)) {
  2911. // (a group of 32 or fewer has no other half to exchange with)
  2912. need(b.unwrap_or(0));
  2913. return Err("a lane mask exchanged where not every lane runs");
  2914. }
  2915. xy = self.exchange_halves(at, xy.0);
  2916. }
  2917. self.ballots.insert(lo, xy);
  2918. xy
  2919. }
  2920. };
  2921. Ok(if high { y } else { x })
  2922. }
  2923. // ---- operands ----
  2924. fn operand(&mut self, inst: &Inst, op: &Operand) -> Result<V, Why> {
  2925. match *op {
  2926. Operand::Scalar { code: NULL, .. } => Ok(self.s.m.i32(0)),
  2927. Operand::Scalar { code, .. } => {
  2928. let v = inst.read(Reg::S(code)).ok_or("an unread operand")?;
  2929. self.i32_of(v)
  2930. }
  2931. Operand::Vector { reg, .. } => {
  2932. let v = inst.read(Reg::V(reg)).ok_or("an unread operand")?;
  2933. self.i32_of(v)
  2934. }
  2935. Operand::Const(c) => crate::resource::inline(c)
  2936. .map(|x| self.s.m.i32(x))
  2937. .ok_or("a special operand (vccz, execz, scc, lds_direct)"),
  2938. Operand::Literal(x) => Ok(self.s.m.i32(x)),
  2939. Operand::Attr { .. } => Err("an attribute operand"),
  2940. }
  2941. }
  2942. /// An operand read as f16 data: GFX10 puts an inline f16 constant in
  2943. /// the low half of the operand (upstream PR #637, checked there against
  2944. /// the instruction encodings; the half-and-half reading taken from PR
  2945. /// #458 gave the high half the constant too).
  2946. fn f16_operand(&mut self, inst: &Inst, op: &Operand) -> Result<V, Why> {
  2947. match *op {
  2948. Operand::Const(c @ 240..=248) => Ok(self.s.m.i32(inline_f16(c))),
  2949. _ => self.operand(inst, op),
  2950. }
  2951. }
  2952. fn as_float(&mut self, x: V) -> V {
  2953. self.s.m.cast(self.cur, Cast::Bitcast, x, self.s.t.f32)
  2954. }
  2955. fn as_int(&mut self, f: V) -> V {
  2956. self.s.m.cast(self.cur, Cast::Bitcast, f, self.s.t.i32)
  2957. }
  2958. /// The SDWA operand selection of source `k`: a byte or word of the
  2959. /// dword, zero- or sign-extended (none: the whole dword).
  2960. fn sdwa_src(inst: &Inst, k: usize) -> Option<(u8, bool)> {
  2961. let Fields::Valu(v) = &inst.fields else {
  2962. return None;
  2963. };
  2964. let s = v.sdwa?;
  2965. let sel = *s.src_sel.get(k)?;
  2966. let sext = s.sext >> k & 1 != 0;
  2967. (sel < 6).then_some((sel, sext))
  2968. }
  2969. /// Bits `sel` (0-3 a byte, 4-5 a word) of `x`, extended.
  2970. fn select_bits(&mut self, x: V, sel: u8, sext: bool) -> V {
  2971. let c = self.cur;
  2972. let (width, at) = if sel < 4 {
  2973. (8, 8 * sel)
  2974. } else {
  2975. (16, 16 * (sel - 4))
  2976. };
  2977. let left = self.s.m.i32(u32::from(32 - width - at));
  2978. let t = self.s.m.bin(c, Bin::Shl, x, left);
  2979. let right = self.s.m.i32(32 - u32::from(width));
  2980. let op = if sext { Bin::AShr } else { Bin::LShr };
  2981. self.s.m.bin(c, op, t, right)
  2982. }
  2983. /// A float source with its abs/neg modifiers.
  2984. fn fsrc(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  2985. let Fields::Valu(v) = &inst.fields else {
  2986. unreachable!()
  2987. };
  2988. let op = *v.src.get(k).ok_or("a missing operand")?;
  2989. let selected = Self::sdwa_src(inst, k);
  2990. let mut f = match op {
  2991. _ if selected.is_some() => {
  2992. let (sel, sext) = selected.expect("checked");
  2993. let x = self.operand(inst, &op)?;
  2994. let x = self.select_bits(x, sel, sext);
  2995. self.as_float(x)
  2996. }
  2997. _ if k == 0 && self.src0.is_some() => {
  2998. let x = self.src0.expect("checked");
  2999. self.as_float(x)
  3000. }
  3001. Operand::Vector { reg, .. } | Operand::Scalar { code: reg, .. }
  3002. if !matches!(op, Operand::Scalar { code: NULL, .. }) =>
  3003. {
  3004. let r = if matches!(op, Operand::Vector { .. }) {
  3005. Reg::V(reg)
  3006. } else {
  3007. Reg::S(reg)
  3008. };
  3009. let val = inst.read(r).ok_or("an unread operand")?;
  3010. match self.floats.get(&val) {
  3011. Some(&f) => f,
  3012. None => {
  3013. let x = self.i32_of(val)?;
  3014. self.as_float(x)
  3015. }
  3016. }
  3017. }
  3018. _ => {
  3019. let x = self.operand(inst, &op)?;
  3020. self.as_float(x)
  3021. }
  3022. };
  3023. if v.abs >> k & 1 != 0 {
  3024. f = self.unary(6, f);
  3025. }
  3026. if v.neg >> k & 1 != 0 {
  3027. let z = self.s.m.f32(0x8000_0000);
  3028. f = self.s.m.bin(self.cur, Bin::Sub, z, f);
  3029. }
  3030. Ok(f)
  3031. }
  3032. fn src(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  3033. let Fields::Valu(v) = &inst.fields else {
  3034. unreachable!()
  3035. };
  3036. let op = *v.src.get(k).ok_or("a missing operand")?;
  3037. if v.abs >> k & 1 != 0 || v.neg >> k & 1 != 0 {
  3038. return Err("integer operand modifiers");
  3039. }
  3040. match self.src0 {
  3041. Some(x) if k == 0 => Ok(x),
  3042. _ => {
  3043. let x = self.operand(inst, &op)?;
  3044. Ok(match Self::sdwa_src(inst, k) {
  3045. Some((sel, sext)) => self.select_bits(x, sel, sext),
  3046. None => x,
  3047. })
  3048. }
  3049. }
  3050. }
  3051. fn unary(&mut self, op: u32, f: V) -> V {
  3052. self.s.op(
  3053. self.cur,
  3054. "unary.f32",
  3055. Attr::ReadNone,
  3056. self.s.t.f32,
  3057. op,
  3058. &[f],
  3059. )
  3060. }
  3061. fn binary(&mut self, op: u32, a: V, b: V) -> V {
  3062. self.s.op(
  3063. self.cur,
  3064. "binary.f32",
  3065. Attr::ReadNone,
  3066. self.s.t.f32,
  3067. op,
  3068. &[a, b],
  3069. )
  3070. }
  3071. /// The hardware's maximum (`max`) or minimum of two floats: as DXIL's
  3072. /// FMax/FMin, but -0 orders below +0 (RDNA2 ISA, `v_max_f32`), where
  3073. /// the compare and select DXIL specifies gives either zero.
  3074. fn max_min(&mut self, max: bool, a: V, b: V) -> V {
  3075. let c = self.cur;
  3076. let r = self.binary(if max { 35 } else { 36 }, a, b);
  3077. let (ia, ib) = (self.as_int(a), self.as_int(b));
  3078. let either = self.s.m.bin(c, Bin::Or, ia, ib);
  3079. let magnitude = self.s.m.i32(0x7FFF_FFFF);
  3080. let either = self.s.m.bin(c, Bin::And, either, magnitude);
  3081. let zero = self.s.m.i32(0);
  3082. let zeros = self.s.m.cmp(c, pred::EQ, either, zero);
  3083. // Of two zeros, +0 unless both are -0 (max), -0 unless neither (min).
  3084. let op = if max { Bin::And } else { Bin::Or };
  3085. let sign = self.s.m.bin(c, op, ia, ib);
  3086. let signed = self.as_float(sign);
  3087. self.s.m.select(c, zeros, signed, r)
  3088. }
  3089. fn fmad(&mut self, a: V, b: V, c: V) -> V {
  3090. self.s.op(
  3091. self.cur,
  3092. "tertiary.f32",
  3093. Attr::ReadNone,
  3094. self.s.t.f32,
  3095. 46,
  3096. &[a, b, c],
  3097. )
  3098. }
  3099. /// `f` as an f16 in the low bits, rounded toward zero: the nearest-even
  3100. /// conversion, one step back toward zero where it rounded away (which
  3101. /// also turns an overflow to infinity into the largest finite half).
  3102. fn f16_toward_zero(&mut self, f: V) -> V {
  3103. let c = self.cur;
  3104. let i32t = self.s.t.i32;
  3105. let h = self
  3106. .s
  3107. .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]);
  3108. let back = self
  3109. .s
  3110. .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[h]);
  3111. let (fa, ba) = (self.unary(6, f), self.unary(6, back));
  3112. // Ordered: never for NaN.
  3113. let away = self.s.m.cmp(c, pred::OGT, ba, fa);
  3114. let one = self.s.m.i32(1);
  3115. let stepped = self.s.m.bin(c, Bin::Sub, h, one);
  3116. self.s.m.select(c, away, stepped, h)
  3117. }
  3118. /// `f` as an f16 in the low bits, rounded to nearest, ties to even, as the console's
  3119. /// 16-bit float operations round, whatever the host's own conversion does: D3D lets
  3120. /// `f32tof16` round toward zero, and the NVIDIA driver's does (measured on an RTX 4070:
  3121. /// `wave64_tests`). The conversion toward zero, or the next half away from zero where
  3122. /// that one is nearer, or as near and the first one odd. Past the largest half the next
  3123. /// one counts as 2^16, the bound IEEE rounds by, so 65520 and up become infinity.
  3124. /// (`f` is an f32 result of two halves here; rounding it again to 16 bits gives the
  3125. /// rounding of the exact result, 24 bits being more than twice 11 and two.)
  3126. fn f16_nearest(&mut self, f: V) -> V {
  3127. let c = self.cur;
  3128. let f32t = self.s.t.f32;
  3129. let lo = self.f16_toward_zero(f);
  3130. let (one, zero) = (self.s.m.i32(1), self.s.m.i32(0));
  3131. let hi = self.s.m.bin(c, Bin::Add, lo, one);
  3132. let size = |l: &mut Self, h: V| {
  3133. let w = l.s.op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]);
  3134. l.unary(6, w)
  3135. };
  3136. let (below, above) = (size(self, lo), size(self, hi));
  3137. let (magnitude, infinity) = (self.s.m.i32(0x7FFF), self.s.m.i32(0x7C00));
  3138. let m = self.s.m.bin(c, Bin::And, hi, magnitude);
  3139. let top = self.s.m.cmp(c, pred::EQ, m, infinity);
  3140. let bound = self.s.m.f32(65536.0f32.to_bits());
  3141. let above = self.s.m.select(c, top, bound, above);
  3142. let fa = self.unary(6, f);
  3143. // (both differences are exact: the three values lie within one half's step)
  3144. let under = self.s.m.bin(c, Bin::Sub, fa, below);
  3145. let over = self.s.m.bin(c, Bin::Sub, above, fa);
  3146. // Ordered: never for NaN, which stays what the conversion made of it.
  3147. let nearer = self.s.m.cmp(c, pred::OLT, over, under);
  3148. let tie = self.s.m.cmp(c, pred::OEQ, over, under);
  3149. let odd = self.s.m.bin(c, Bin::And, lo, one);
  3150. let odd = self.s.m.cmp(c, pred::NE, odd, zero);
  3151. let tie = self.s.m.bin(c, Bin::And, tie, odd);
  3152. let up = self.s.m.bin(c, Bin::Or, nearer, tie);
  3153. self.s.m.select(c, up, hi, lo)
  3154. }
  3155. /// `(a >> off[4:0]) & ((1 << width) - 1)`, sign-extended from the field's
  3156. /// top bit when `signed`; widths from 32 on take every bit. A signed
  3157. /// field that runs past bit 31 extends from bit 31, as the hardware
  3158. /// does: the shift is arithmetic then.
  3159. fn bfe(&mut self, a: V, off: V, width: V, signed: bool) -> V {
  3160. let c = self.cur;
  3161. let (k31, k32, zero, one, ones) = (
  3162. self.s.m.i32(31),
  3163. self.s.m.i32(32),
  3164. self.s.m.i32(0),
  3165. self.s.m.i32(1),
  3166. self.s.m.i32(u32::MAX),
  3167. );
  3168. let off = self.s.m.bin(c, Bin::And, off, k31);
  3169. let shift = if signed { Bin::AShr } else { Bin::LShr };
  3170. let shifted = self.s.m.bin(c, shift, a, off);
  3171. let full = self.s.m.cmp(c, pred::IUGE, width, k32);
  3172. let w = self.s.m.bin(c, Bin::And, width, k31);
  3173. let mask = self.s.m.bin(c, Bin::Shl, one, w);
  3174. let mask = self.s.m.bin(c, Bin::Sub, mask, one);
  3175. let mask = self.s.m.select(c, full, ones, mask);
  3176. let r = self.s.m.bin(c, Bin::And, shifted, mask);
  3177. if !signed {
  3178. return r;
  3179. }
  3180. // Sign-extend a field narrower than 32 bits (none for width 0).
  3181. let left = self.s.m.bin(c, Bin::Sub, k32, w);
  3182. let left = self.s.m.bin(c, Bin::And, left, k31);
  3183. let t = self.s.m.bin(c, Bin::Shl, r, left);
  3184. let t = self.s.m.bin(c, Bin::AShr, t, left);
  3185. let is0 = self.s.m.cmp(c, pred::EQ, w, zero);
  3186. let keep = self.s.m.bin(c, Bin::Or, full, is0);
  3187. self.s.m.select(c, keep, r, t)
  3188. }
  3189. /// Whether an f32 value is NaN, tested in integer arithmetic so host
  3190. /// drivers (such as NVIDIA) do not fold `fcmp uno` away under fast-math.
  3191. fn is_nan_f32(&mut self, f: V) -> V {
  3192. let c = self.cur;
  3193. let bits = self.as_int(f);
  3194. let mask = self.s.m.i32(0x7FFF_FFFF);
  3195. let abs = self.s.m.bin(c, Bin::And, bits, mask);
  3196. let inf = self.s.m.i32(0x7F80_0000);
  3197. self.s.m.cmp(c, pred::IUGT, abs, inf)
  3198. }
  3199. /// The median of three. With a NaN among them the hardware gives the
  3200. /// minimum of the three instead (the host's minimum skips NaNs, so that
  3201. /// is the smallest number among them).
  3202. fn med3(&mut self, a: V, b: V, third: V) -> V {
  3203. let c = self.cur;
  3204. let lo = self.binary(36, a, b);
  3205. let hi = self.binary(35, a, b);
  3206. let t = self.binary(36, hi, third);
  3207. let median = self.binary(35, lo, t);
  3208. let least = self.binary(36, lo, third);
  3209. let nan_a = self.is_nan_f32(a);
  3210. let nan_b = self.is_nan_f32(b);
  3211. let nan_3 = self.is_nan_f32(third);
  3212. let nan_ab = self.s.m.bin(c, Bin::Or, nan_a, nan_b);
  3213. let nan = self.s.m.bin(c, Bin::Or, nan_ab, nan_3);
  3214. self.s.m.select(c, nan, least, median)
  3215. }
  3216. /// `a - floor(a)`, which on the hardware never reaches 1.0: where it
  3217. /// would round to it (a tiny negative `a`), the result is `below_one`,
  3218. /// the largest value under 1.0 in the operation's width. Hosts differ
  3219. /// here (some give 1.0). Comparing against a `threshold` distinct from
  3220. /// `below_one` prevents drivers (observed on NVIDIA) from folding
  3221. /// `r > k ? k : r` into `minNum` (`FMNMX`) and swallowing NaN.
  3222. fn fract(&mut self, a: V, threshold: f32, below_one: f32) -> V {
  3223. let c = self.cur;
  3224. let r = self.unary(22, a);
  3225. let limit = self.s.m.f32(threshold.to_bits());
  3226. let k = self.s.m.f32(below_one.to_bits());
  3227. let over = self.s.m.cmp(c, pred::OGE, r, limit);
  3228. self.s.m.select(c, over, k, r)
  3229. }
  3230. /// Sine, or cosine, of an angle in turns, as the hardware takes it. The
  3231. /// whole turns are taken off first (`x - round_even(x)`, exact, within
  3232. /// half a turn), so a large angle keeps its fraction; scaling to radians
  3233. /// first rounds it away. A zero passes unreduced (the sine of -0 is -0).
  3234. /// The sine of a half turn and the cosine of a quarter turn are exactly
  3235. /// +0 on the hardware, where the host's function of the rounded angle
  3236. /// gives about 1e-7. Infinities and NaN give NaN.
  3237. /// shortcut: below 2^-12 turns the hardware scales by a slightly
  3238. /// different constant than 2π (a last-place difference).
  3239. fn trig_turns(&mut self, x: V, cosine: bool) -> V {
  3240. let c = self.cur;
  3241. let zero = self.s.m.f32(0);
  3242. let whole = self.unary(26, x);
  3243. let part = self.s.m.bin(c, Bin::Sub, x, whole);
  3244. let is_zero = self.s.m.cmp(c, pred::OEQ, x, zero);
  3245. let part = self.s.m.select(c, is_zero, x, part);
  3246. let k = self.s.m.f32(TWO_PI.to_bits());
  3247. let angle = self.s.m.bin(c, Bin::Mul, part, k);
  3248. let r = self.unary(if cosine { 12 } else { 13 }, angle);
  3249. let at = if cosine { 0.25f32 } else { 0.5 };
  3250. let at = self.s.m.f32(at.to_bits());
  3251. let size = self.unary(6, part);
  3252. let exact = self.s.m.cmp(c, pred::OEQ, size, at);
  3253. self.s.m.select(c, exact, zero, r)
  3254. }
  3255. /// The high dword of a 32 × 32-bit product.
  3256. fn mul_hi(&mut self, a: V, b: V, signed: bool) -> V {
  3257. let c = self.cur;
  3258. let i64t = self.s.m.int(64);
  3259. let ext = if signed { Cast::SExt } else { Cast::ZExt };
  3260. let a = self.s.m.cast(c, ext, a, i64t);
  3261. let b = self.s.m.cast(c, ext, b, i64t);
  3262. let m = self.s.m.bin(c, Bin::Mul, a, b);
  3263. let k32 = self.s.m.int_const(i64t, 32);
  3264. let hi = self.s.m.bin(c, Bin::LShr, m, k32);
  3265. self.s.flags |= flags::INT64;
  3266. self.s.m.cast(c, Cast::Trunc, hi, self.s.t.i32)
  3267. }
  3268. /// `0 × anything = 0`, as in D3D9.
  3269. fn legacy_mul(&mut self, a: V, b: V) -> V {
  3270. let c = self.cur;
  3271. let m = self.s.m.bin(c, Bin::Mul, a, b);
  3272. let zero = self.s.m.f32(0);
  3273. let az = self.s.m.cmp(c, pred::OEQ, a, zero);
  3274. let bz = self.s.m.cmp(c, pred::OEQ, b, zero);
  3275. let z = self.s.m.bin(c, Bin::Or, az, bz);
  3276. self.s.m.select(c, z, zero, m)
  3277. }
  3278. // ---- lane booleans ----
  3279. fn boolean(&mut self, b: Bool, at: usize) -> Result<V, Why> {
  3280. if b == Bool::TRUE || b == Bool::FALSE {
  3281. return Ok(self.s.m.bool(b == Bool::TRUE));
  3282. }
  3283. if let Some(&v) = self.bools.get(&(at, b)) {
  3284. return Ok(v);
  3285. }
  3286. let (atom, lo, hi) = self.x.st.bools.node(b).expect("not a constant");
  3287. let a = self.atom(atom, at)?;
  3288. let m = &mut self.s.m;
  3289. let v = match (lo, hi) {
  3290. (Bool::FALSE, Bool::TRUE) => a,
  3291. (Bool::TRUE, Bool::FALSE) => {
  3292. let t = m.bool(true);
  3293. m.bin(at, Bin::Xor, a, t)
  3294. }
  3295. (Bool::FALSE, h) => {
  3296. let h = self.boolean(h, at)?;
  3297. self.s.m.bin(at, Bin::And, a, h)
  3298. }
  3299. (l, Bool::TRUE) => {
  3300. let l = self.boolean(l, at)?;
  3301. self.s.m.bin(at, Bin::Or, a, l)
  3302. }
  3303. (l, h) => {
  3304. let l = self.boolean(l, at)?;
  3305. let h = self.boolean(h, at)?;
  3306. self.s.m.select(at, a, h, l)
  3307. }
  3308. };
  3309. self.bools.insert((at, b), v);
  3310. Ok(v)
  3311. }
  3312. fn atom(&mut self, atom: Atom, at: usize) -> Result<V, Why> {
  3313. match atom {
  3314. Atom::Lane(v) => self.lane_bits.get(&v).copied().ok_or_else(|| {
  3315. self.lane_fail
  3316. .get(&v)
  3317. .copied()
  3318. .unwrap_or("a lane mask from a carry")
  3319. }),
  3320. Atom::Uniform(v) => match self.get(v)? {
  3321. Val::Bit(x) => Ok(x),
  3322. Val::I32(x) => {
  3323. let z = self.s.m.i32(0);
  3324. Ok(self.s.m.cmp(at, pred::NE, x, z))
  3325. }
  3326. Val::Missing(w) => Err(w),
  3327. },
  3328. Atom::Phi(id) => {
  3329. if let Some(&v) = self.mask_phis.get(&id) {
  3330. return Ok(v);
  3331. }
  3332. let &(b, i) = self
  3333. .phi_at
  3334. .get(&id)
  3335. .ok_or("a lane-mask join without a phi")?;
  3336. let blk = self.block[b].ok_or("an unreachable join")?;
  3337. let v = self.s.m.phi(blk, self.s.t.i1);
  3338. self.mask_phis.insert(id, v);
  3339. self.pending_masks.push((v, b, i));
  3340. Ok(v)
  3341. }
  3342. // shortcut: "some lane of the quad is set" is taken as true: the
  3343. // lanes it adds only feed derivatives, and exports keep their own
  3344. // masks. Wrong if such a section had a side effect.
  3345. Atom::Quad(_) => Ok(self.s.m.bool(true)),
  3346. // With console lanes, a mask held as a number is the console's:
  3347. // the lane tests its own bit.
  3348. Atom::Opaque(v) if self.console_lanes => {
  3349. let hi = match self.pair_high(v) {
  3350. Some(h) => Some(self.get(h)?),
  3351. None => None,
  3352. };
  3353. let lo = self.get(v)?;
  3354. let word = |w: Val| match w {
  3355. Val::I32(x) => Ok(x),
  3356. _ => Err("an opaque lane mask"),
  3357. };
  3358. let lo = word(lo)?;
  3359. let hi = hi.map(word).transpose()?;
  3360. Ok(self.lane_bit(at, lo, hi))
  3361. }
  3362. Atom::Constant(k) if self.console_lanes => {
  3363. let lo = self.s.m.i32(k as u32);
  3364. let hi = self.s.m.i32((k >> 32) as u32);
  3365. Ok(self.lane_bit(at, lo, Some(hi)))
  3366. }
  3367. Atom::Opaque(_) => Err("an opaque lane mask"),
  3368. Atom::Constant(_) => Err("a constant lane mask"),
  3369. }
  3370. }
  3371. /// A console wave64 program in host waves of 32: the first console thread of this host wave
  3372. /// (0, 32, 64, ...). A GPU need not give a host wave consecutive thread indices (NVIDIA's
  3373. /// 8 x 8 groups), so each wave takes the next 32 from an LDS counter instead: every thread
  3374. /// zeroes it, the group meets, each wave's first lane adds 32 and the wave takes what it
  3375. /// found. Branch-free, in the entry block, which every thread runs.
  3376. fn wave_base(&mut self) -> Option<V> {
  3377. let slot = self.halves?;
  3378. if let Some(v) = self.wave_base {
  3379. return Some(v);
  3380. }
  3381. let (e, i32t) = (self.s.entry, self.s.t.i32);
  3382. let lds = self.s.lds();
  3383. let k = self.s.m.i32(slot);
  3384. let ptr = self.s.m.element(e, lds, k);
  3385. let zero = self.s.m.i32(0);
  3386. self.s.m.store(e, ptr, zero);
  3387. self.group_sync(e);
  3388. let lane = self.s.op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
  3389. let first = self.s.m.cmp(e, pred::EQ, lane, zero);
  3390. let k32 = self.s.m.i32(32);
  3391. let add = self.s.m.select(e, first, k32, zero);
  3392. let ptr = self.s.m.element(e, lds, k);
  3393. let old = self.s.m.atomic(e, Rmw::Add, ptr, add);
  3394. let base = self.s.op(e, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[old]);
  3395. self.s.flags |= flags::WAVE_OPS;
  3396. self.wave_base = Some(base);
  3397. Some(base)
  3398. }
  3399. /// The console thread index of this thread in the group: `wave_base` plus the host lane
  3400. /// (host waves of 32), else the wave's first thread index rounded down plus the lane.
  3401. fn console_thread(&mut self) -> V {
  3402. let (e, i32t) = (self.s.entry, self.s.t.i32);
  3403. let lane = self.s.op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
  3404. if let Some(base) = self.wave_base() {
  3405. return self.s.m.bin(e, Bin::Add, base, lane);
  3406. }
  3407. let flat = self.s.op(e, "flattenedThreadIdInGroup.i32", Attr::ReadNone, i32t, 96, &[]);
  3408. let first = self.s.op(e, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[flat]);
  3409. let wave = self.s.wave_size.unwrap_or(32);
  3410. let mask = self.s.m.i32(!(wave - 1));
  3411. let base = self.s.m.bin(e, Bin::And, first, mask);
  3412. self.s.m.bin(e, Bin::Add, base, lane)
  3413. }
  3414. /// This thread's console lane (0..63): its relabelled thread index (`thread_id`), whose host
  3415. /// wave holds a 32-aligned run of console lanes. Without `exchange`: the host lane.
  3416. fn console_lane(&mut self) -> V {
  3417. if self.exchange.is_none() {
  3418. return self.lane_index();
  3419. }
  3420. if let Some(v) = self.clane {
  3421. return v;
  3422. }
  3423. let (e, i32t) = (self.s.entry, self.s.t.i32);
  3424. let f = self.console_thread();
  3425. let _ = i32t;
  3426. let k63 = self.s.m.i32(63);
  3427. let cl = self.s.m.bin(e, Bin::And, f, k63);
  3428. self.s.flags |= flags::WAVE_OPS;
  3429. self.clane = Some(cl);
  3430. cl
  3431. }
  3432. /// A group barrier with an LDS fence in `block`.
  3433. fn group_sync(&mut self, block: usize) {
  3434. let mode = self.s.m.i32(meeting_mode());
  3435. let void = self.s.t.void;
  3436. self.s.op(block, "barrier", Attr::NoDuplicate, void, 80, &[mode]);
  3437. }
  3438. /// `exchange`: each host wave gives `mine` (the same in all its lanes) for its half; both get
  3439. /// (lower half's, upper half's). A group with no upper half gets 0 for it.
  3440. fn exchange_halves(&mut self, at: usize, mine: V) -> (V, V) {
  3441. let Some((slot, small, _)) = self.exchange.as_ref().map(|(a, b, _)| (*a, *b, ())) else {
  3442. let z = self.s.m.i32(0);
  3443. return (mine, z);
  3444. };
  3445. if small {
  3446. let z = self.s.m.i32(0);
  3447. return (mine, z);
  3448. }
  3449. if self.local {
  3450. // each host wave on its own: its half holds `mine`, the other nothing
  3451. let cl = self.console_lane();
  3452. let (k32, z) = (self.s.m.i32(32), self.s.m.i32(0));
  3453. let upper = self.s.m.cmp(at, pred::IUGE, cl, k32);
  3454. let lo = self.s.m.select(at, upper, z, mine);
  3455. let hi = self.s.m.select(at, upper, mine, z);
  3456. return (lo, hi);
  3457. }
  3458. // the pair of dwords of this thread's console wave: its half's, then both
  3459. let pair = self.exchange_pair(slot);
  3460. let cl = self.console_lane();
  3461. let five = self.s.m.i32(5);
  3462. let half = self.s.m.bin(at, Bin::LShr, cl, five);
  3463. let index = self.s.m.bin(at, Bin::Add, pair, half);
  3464. let lds = self.s.lds();
  3465. let ptr = self.s.m.element(at, lds, index);
  3466. self.s.m.store(at, ptr, mine);
  3467. self.group_sync(at);
  3468. let one = self.s.m.i32(1);
  3469. let k1 = self.s.m.bin(at, Bin::Add, pair, one);
  3470. let p0 = self.s.m.element(at, lds, pair);
  3471. let p1 = self.s.m.element(at, lds, k1);
  3472. let lo = self.s.m.load(at, p0);
  3473. let hi = self.s.m.load(at, p1);
  3474. // the slots are written again only after every thread read them
  3475. self.group_sync(at);
  3476. (lo, hi)
  3477. }
  3478. /// The first of the two exchange dwords of this thread's console wave (made in the entry
  3479. /// block): a group of several console waves has a pair for each.
  3480. fn exchange_pair(&mut self, slot: u32) -> V {
  3481. if let Some(v) = self.pair {
  3482. return v;
  3483. }
  3484. let e = self.s.entry;
  3485. let thread = self.console_thread();
  3486. let six = self.s.m.i32(6);
  3487. let wave = self.s.m.bin(e, Bin::LShr, thread, six);
  3488. let one = self.s.m.i32(1);
  3489. let twice = self.s.m.bin(e, Bin::Shl, wave, one);
  3490. let base = self.s.m.i32(slot);
  3491. let v = self.s.m.bin(e, Bin::Add, base, twice);
  3492. self.pair = Some(v);
  3493. v
  3494. }
  3495. /// The console's decision of the branch closing IR block `b`, which the wave takes
  3496. /// together ([`Structured::wide`]): `when` is the lane's own bit, and the branch is taken
  3497. /// when some lane's `when` holds (`execnz`, `vccnz`, SCC of a mask operation set) or
  3498. /// when every lane's does (`execz`, `vccz`, that SCC clear), [`Structured::wave_any`].
  3499. /// Each host wave asks its lanes and the halves exchange the answers, so both go the
  3500. /// same way and can meet again inside the branch.
  3501. /// SCC of a mask operation as data ([`Structured::scc_some`]): whether some lane of the
  3502. /// console wave has its bit of the result, asked where the operation stands. The lanes
  3503. /// that are elsewhere have no bit (the result is ANDed with EXEC or is EXEC), so with
  3504. /// the console's waves the host wave's answer is the console's; two host waves of 32
  3505. /// exchange theirs, which needs every lane there.
  3506. fn scc_some(&mut self, scc: Value) -> Result<V, Why> {
  3507. let &m = self.x.st.scc_some.get(&scc).ok_or(LANE_MASK)?;
  3508. // (not for a console wave cut into host waves that do not exchange)
  3509. if !self.console_lanes || self.local || self.exchange.is_none() && self.halves.is_some() {
  3510. return Err(LANE_MASK);
  3511. }
  3512. let made = self.def_block.get(&scc).copied();
  3513. let at = match made {
  3514. None => self.s.entry,
  3515. Some(b) if b == self.cur_ir => self.cur,
  3516. Some(b) => self.tail[b].ok_or("a lane mask written after its use")?,
  3517. };
  3518. let bit = self.boolean(m, at)?;
  3519. let (i1t, i32t) = (self.s.t.i1, self.s.t.i32);
  3520. let some = self.s.op(at, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[bit]);
  3521. self.s.flags |= flags::WAVE_OPS;
  3522. if !self.exchange.as_ref().is_some_and(|e| !e.1) {
  3523. return Ok(some);
  3524. }
  3525. if !made.is_none_or(|b| self.all_lanes(b)) {
  3526. need(made.unwrap_or(0));
  3527. return Err("a lane mask exchanged where not every lane runs");
  3528. }
  3529. let some = self.s.m.cast(at, Cast::ZExt, some, i32t);
  3530. let (lo, hi) = self.exchange_halves(at, some);
  3531. let both = self.s.m.bin(at, Bin::Or, lo, hi);
  3532. let z = self.s.m.i32(0);
  3533. Ok(self.s.m.cmp(at, pred::NE, both, z))
  3534. }
  3535. fn wave_wide(&mut self, b: usize, when: Bool) -> Result<V, Why> {
  3536. const WHY: Why = "a wave-wide branch where not every lane runs";
  3537. let any = self.x.st.wave_any.get(b).copied().flatten().ok_or("a wave-wide branch on a scalar condition")?;
  3538. if self.exchange.is_none() && self.halves.is_none() && self.console_lanes && self.mask_data == MaskData::Console {
  3539. // The host's waves are the console's: the wave's own answer. The lanes that are
  3540. // elsewhere have no bit set, as on the console, so "some lane" needs no one but
  3541. // the lanes here, and "every lane's bit is clear" is true of the others anyway.
  3542. let c = self.cur;
  3543. let mine = self.boolean(when, c)?;
  3544. let i1t = self.s.t.i1;
  3545. self.s.flags |= flags::WAVE_OPS;
  3546. let (name, code) = if any { ("waveAnyTrue", 113) } else { ("waveAllTrue", 114) };
  3547. return Ok(self.s.op(c, name, Attr::NoUnwind, i1t, code, &[mine]));
  3548. }
  3549. if self.local || !self.exchange.as_ref().is_some_and(|e| !e.1) {
  3550. return Err(WHY);
  3551. }
  3552. if !self.all_lanes(b) {
  3553. need(b);
  3554. return Err(WHY);
  3555. }
  3556. let c = self.cur;
  3557. let mine = self.boolean(when, c)?;
  3558. // what the halves exchange is "some lane speaks against" either way (for `any`:
  3559. // some lane's `when` holds; else: some lane's does not), so a half with no lane says
  3560. // nothing
  3561. let set = if any {
  3562. mine
  3563. } else {
  3564. let t = self.s.m.bool(true);
  3565. self.s.m.bin(c, Bin::Xor, mine, t)
  3566. };
  3567. let (i1t, i32t) = (self.s.t.i1, self.s.t.i32);
  3568. let some = self.s.op(c, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[set]);
  3569. self.s.flags |= flags::WAVE_OPS;
  3570. let some = self.s.m.cast(c, Cast::ZExt, some, i32t);
  3571. let (lo, hi) = self.exchange_halves(c, some);
  3572. let c = self.cur;
  3573. let both = self.s.m.bin(c, Bin::Or, lo, hi);
  3574. let z = self.s.m.i32(0);
  3575. Ok(self.s.m.cmp(c, if any { pred::NE } else { pred::EQ }, both, z))
  3576. }
  3577. /// Whether every lane runs IR block `b` (always true without `exchange`).
  3578. fn all_lanes(&self, b: usize) -> bool {
  3579. self.exchange.as_ref().is_none_or(|(_, _, all)| all.get(b).copied().unwrap_or(false))
  3580. }
  3581. /// This lane's bit of the mask `lo`, `hi` (wave64).
  3582. fn lane_bit(&mut self, at: usize, lo: V, hi: Option<V>) -> V {
  3583. self.s.flags |= flags::WAVE_OPS;
  3584. let lane = if self.exchange.is_some() {
  3585. self.console_lane()
  3586. } else {
  3587. self.s.op(at, "waveGetLaneIndex", Attr::ReadOnly, self.s.t.i32, 111, &[])
  3588. };
  3589. let (k31, k32, one, z) = (
  3590. self.s.m.i32(31),
  3591. self.s.m.i32(32),
  3592. self.s.m.i32(1),
  3593. self.s.m.i32(0),
  3594. );
  3595. let word = match hi {
  3596. Some(hi) => {
  3597. let low = self.s.m.cmp(at, pred::IULT, lane, k32);
  3598. self.s.m.select(at, low, lo, hi)
  3599. }
  3600. None => lo,
  3601. };
  3602. let sh = self.s.m.bin(at, Bin::And, lane, k31);
  3603. let t = self.s.m.bin(at, Bin::LShr, word, sh);
  3604. let t = self.s.m.bin(at, Bin::And, t, one);
  3605. self.s.m.cmp(at, pred::NE, t, z)
  3606. }
  3607. /// The value of the high dword of the wave64 register pair whose low
  3608. /// dword holds `lo` (none in wave32).
  3609. fn pair_high(&self, lo: Value) -> Option<Value> {
  3610. if !self.x.native.wave64 {
  3611. return None;
  3612. }
  3613. let p = self.x.p;
  3614. let pick = |reg: Reg| match reg {
  3615. Reg::S(c) => Some(Reg::S(c + 1)),
  3616. _ => None,
  3617. };
  3618. if let Some(&(reg, _)) = p.inputs.iter().find(|i| i.1 == lo) {
  3619. let h = pick(reg)?;
  3620. return p.inputs.iter().find(|i| i.0 == h).map(|i| i.1);
  3621. }
  3622. if let Some(&(b, i)) = self.phi_at.get(&lo) {
  3623. let h = pick(p.blocks[b].phis[i].reg)?;
  3624. return p.blocks[b]
  3625. .phis
  3626. .iter()
  3627. .find(|q| q.reg == h)
  3628. .map(|q| q.value);
  3629. }
  3630. let b = *self.def_block.get(&lo)?;
  3631. let inst = p.blocks[b]
  3632. .insts
  3633. .iter()
  3634. .find(|i| i.writes.iter().any(|w| w.1 == lo))?;
  3635. let &(reg, _) = inst.writes.iter().find(|w| w.1 == lo)?;
  3636. inst.write(pick(reg)?)
  3637. }
  3638. fn guard(&mut self, b: usize, i: usize) -> Result<Option<V>, Why> {
  3639. match self.x.st.guards[b][i] {
  3640. None => Ok(None),
  3641. Some(g) => Ok(Some(self.boolean(g, self.cur)?)),
  3642. }
  3643. }
  3644. // ---- results ----
  3645. fn set(&mut self, v: Option<Value>, val: Val) {
  3646. if let Some(v) = v {
  3647. self.vals.insert(v, val);
  3648. }
  3649. }
  3650. /// Writes VGPR `reg` (or the SGPR of a lane read), under `guard`.
  3651. fn write(&mut self, inst: &Inst, reg: Reg, x: V, guard: Option<V>) {
  3652. let x = match (Self::sdwa_dst(inst), reg) {
  3653. (Some((sel, unused)), Reg::V(_)) => self.place_bits(inst, reg, x, sel, unused),
  3654. _ => x,
  3655. };
  3656. self.write_placed(inst, reg, x, guard);
  3657. }
  3658. /// [`Self::write`] of a dword already placed (SDWA applied).
  3659. fn write_placed(&mut self, inst: &Inst, reg: Reg, x: V, guard: Option<V>) {
  3660. let Some(new) = inst.write(reg) else { return };
  3661. let x = match (guard, reg) {
  3662. (Some(g), Reg::V(_)) => {
  3663. let old = match inst.read(reg).map(|o| self.i32_of(o)) {
  3664. Some(Ok(o)) => o,
  3665. // The validator refuses reads of undef.
  3666. _ => self.s.m.i32(0),
  3667. };
  3668. self.s.m.select(self.cur, g, x, old)
  3669. }
  3670. _ => x,
  3671. };
  3672. self.vals.insert(new, Val::I32(x));
  3673. }
  3674. /// The SDWA destination selection: a byte or word, and what the other
  3675. /// bits get (0 zeros, 1 the sign above the field, 2 the old bits).
  3676. fn sdwa_dst(inst: &Inst) -> Option<(u8, u8)> {
  3677. let Fields::Valu(v) = &inst.fields else {
  3678. return None;
  3679. };
  3680. let s = v.sdwa?;
  3681. (s.dst_sel < 6).then_some((s.dst_sel, s.dst_unused))
  3682. }
  3683. /// The low byte or word of `x` placed at `sel` in VGPR `reg`.
  3684. fn place_bits(&mut self, inst: &Inst, reg: Reg, x: V, sel: u8, unused: u8) -> V {
  3685. let c = self.cur;
  3686. let (width, at) = if sel < 4 {
  3687. (8u32, 8 * u32::from(sel))
  3688. } else {
  3689. (16, 16 * u32::from(sel - 4))
  3690. };
  3691. let left = self.s.m.i32(32 - width);
  3692. let t = self.s.m.bin(c, Bin::Shl, x, left);
  3693. let right = self.s.m.i32(32 - width - at);
  3694. if unused == 1 {
  3695. // Bits below the field shift in as zeros.
  3696. return self.s.m.bin(c, Bin::AShr, t, right);
  3697. }
  3698. let field = self.s.m.bin(c, Bin::LShr, t, right);
  3699. if unused != 2 {
  3700. return field;
  3701. }
  3702. let old = match inst.read(reg).map(|o| self.i32_of(o)) {
  3703. Some(Ok(o)) => o,
  3704. _ => self.s.m.i32(0),
  3705. };
  3706. let keep = self.s.m.i32(!((((1u64 << width) - 1) as u32) << at));
  3707. let old = self.s.m.bin(c, Bin::And, old, keep);
  3708. self.s.m.bin(c, Bin::Or, old, field)
  3709. }
  3710. fn write_f(&mut self, inst: &Inst, f: V, guard: Option<V>) -> Result<(), Why> {
  3711. let Fields::Valu(v) = &inst.fields else {
  3712. unreachable!()
  3713. };
  3714. let mut f = f;
  3715. match v.omod {
  3716. 0 => {}
  3717. k => {
  3718. let factor = [1.0f32, 2.0, 4.0, 0.5][usize::from(k)];
  3719. let c = self.s.m.f32(factor.to_bits());
  3720. f = self.s.m.bin(self.cur, Bin::Mul, f, c);
  3721. }
  3722. }
  3723. if v.clamp {
  3724. f = self.unary(7, f);
  3725. }
  3726. let Some(Operand::Vector { reg, .. }) = v.dst else {
  3727. return Err("a float result outside a VGPR");
  3728. };
  3729. let x = self.as_int(f);
  3730. self.write(inst, Reg::V(reg), x, guard);
  3731. if guard.is_none()
  3732. && Self::sdwa_dst(inst).is_none()
  3733. && let Some(new) = inst.write(Reg::V(reg))
  3734. {
  3735. self.floats.insert(new, f);
  3736. }
  3737. Ok(())
  3738. }
  3739. fn write_i(&mut self, inst: &Inst, x: V, guard: Option<V>) -> Result<(), Why> {
  3740. let Fields::Valu(v) = &inst.fields else {
  3741. unreachable!()
  3742. };
  3743. if v.clamp || v.omod != 0 {
  3744. return Err("integer output modifiers");
  3745. }
  3746. match v.dst {
  3747. Some(Operand::Vector { reg, .. }) => self.write(inst, Reg::V(reg), x, guard),
  3748. Some(Operand::Scalar { code, .. }) => self.write(inst, Reg::S(code), x, None),
  3749. _ => return Err("a result without a register"),
  3750. }
  3751. Ok(())
  3752. }
  3753. /// Starts code only the lanes where `guard` holds run (a store under a
  3754. /// lane guard): returns where it started and the join block.
  3755. fn begin_guarded(&mut self, guard: Option<V>) -> Option<(usize, usize)> {
  3756. let g = guard?;
  3757. let (then, join) = (self.s.m.new_block(), self.s.m.new_block());
  3758. self.s.m.terminate(self.cur, Term::CondBr(g, then, join));
  3759. let head = self.cur;
  3760. self.cur = then;
  3761. Some((head, join))
  3762. }
  3763. /// Ends guarded code; each (value inside, value outside) becomes a phi.
  3764. fn end_guarded(&mut self, at: Option<(usize, usize)>, values: &[(V, V)]) -> Vec<V> {
  3765. let Some((head, join)) = at else {
  3766. return values.iter().map(|v| v.0).collect();
  3767. };
  3768. let then = self.cur;
  3769. self.s.m.terminate(then, Term::Br(join));
  3770. self.cur = join;
  3771. values
  3772. .iter()
  3773. .map(|&(inside, outside)| {
  3774. let ty = self.s.m.type_of(inside);
  3775. let phi = self.s.m.phi(join, ty);
  3776. self.s.m.set_phi(phi, vec![(inside, then), (outside, head)]);
  3777. phi
  3778. })
  3779. .collect()
  3780. }
  3781. /// Code that depends on the lane layout: wave operations, and in compute
  3782. /// the console's wave size (lanes are thread ids in group order there).
  3783. /// Pixel lanes match only within a quad.
  3784. fn cross_lane(&mut self, quad: bool) -> Result<(), Why> {
  3785. if self.s.mesh.is_some() {
  3786. // shortcut: no wave size for mesh shaders in SM 6.6, so host
  3787. // lanes cannot follow the console's; emulate through group-shared
  3788. // memory if mesh programs turn out to need these.
  3789. return Err("a cross-lane operation in a mesh shader");
  3790. }
  3791. if self.s.threads.is_none() && !(quad && self.s.pixel) {
  3792. return Err("a cross-lane operation outside compute");
  3793. }
  3794. debug_assert!(self.s.threads.is_none() || self.console_lanes);
  3795. self.s.flags |= flags::WAVE_OPS;
  3796. Ok(())
  3797. }
  3798. /// Component `c` of the thread id in the group. With console lanes, the
  3799. /// thread is relabelled so that its host lane is its console lane: the
  3800. /// flat id is the wave's first lane's, rounded down to the wave size,
  3801. /// plus the lane index. (A bijection while each host wave holds a
  3802. /// wave-aligned run of flat ids, as the console's waves do.)
  3803. fn thread_id(&mut self, c: u8) -> Val {
  3804. if !self.console_lanes {
  3805. return self.compute_id("threadIdInGroup.i32", 95, c);
  3806. }
  3807. let [x, y, _] = self.s.threads.expect("compute");
  3808. let e = self.s.entry;
  3809. let i32t = self.s.t.i32;
  3810. if self.halves.is_some() {
  3811. let f = self.console_thread();
  3812. self.s.flags |= flags::WAVE_OPS;
  3813. let (xk, yk, xy) = (self.s.m.i32(x), self.s.m.i32(y), self.s.m.i32(x * y));
  3814. return Val::I32(match c {
  3815. 0 => self.s.m.bin(e, Bin::URem, f, xk),
  3816. 1 => {
  3817. let t = self.s.m.bin(e, Bin::UDiv, f, xk);
  3818. self.s.m.bin(e, Bin::URem, t, yk)
  3819. }
  3820. _ => self.s.m.bin(e, Bin::UDiv, f, xy),
  3821. });
  3822. }
  3823. let flat = self.s.op(
  3824. e,
  3825. "flattenedThreadIdInGroup.i32",
  3826. Attr::ReadNone,
  3827. i32t,
  3828. 96,
  3829. &[],
  3830. );
  3831. let first = self.s.op(
  3832. e,
  3833. "waveReadLaneFirst.i32",
  3834. Attr::NoUnwind,
  3835. i32t,
  3836. 118,
  3837. &[flat],
  3838. );
  3839. let wave = self.s.wave_size.expect("set with console lanes");
  3840. let mask = self.s.m.i32(!(wave - 1));
  3841. let base = self.s.m.bin(e, Bin::And, first, mask);
  3842. let lane = self.lane_index();
  3843. let f = self.s.m.bin(e, Bin::Add, base, lane);
  3844. self.s.flags |= flags::WAVE_OPS;
  3845. let (xk, yk, xy) = (self.s.m.i32(x), self.s.m.i32(y), self.s.m.i32(x * y));
  3846. Val::I32(match c {
  3847. 0 => self.s.m.bin(e, Bin::URem, f, xk),
  3848. 1 => {
  3849. let t = self.s.m.bin(e, Bin::UDiv, f, xk);
  3850. self.s.m.bin(e, Bin::URem, t, yk)
  3851. }
  3852. _ => self.s.m.bin(e, Bin::UDiv, f, xy),
  3853. })
  3854. }
  3855. /// Mesh: the counts and the primitives no lane exports. The console's
  3856. /// counts come from one lane's allocation request, which DXIL cannot
  3857. /// express (one call, dominating every output write).
  3858. // shortcut: the counts are the declared maxima and each lane first culls
  3859. // its primitive (all indices 0, zero area), so primitives past the
  3860. // program's count are culled and vertices past it unused; this costs
  3861. // the host the unused vertex and primitive slots. Pass the program's own
  3862. // counts if that shows in frame time.
  3863. fn mesh_prologue(&mut self, mut mesh: super::shader::Mesh) -> Result<(), Why> {
  3864. let threads = self.s.threads.expect("mesh")[0];
  3865. if mesh.topology != 2 {
  3866. return Err("a mesh shader not drawing triangles");
  3867. }
  3868. if threads > 128 || mesh.max_vertices > 256 || mesh.max_primitives > 256 {
  3869. return Err("a mesh shader beyond the host's limits");
  3870. }
  3871. // D3D12 caps the outputs of the declared maxima at 32 KiB. Lane n
  3872. // writes only vertex n and primitive n, so maxima past the lanes are
  3873. // never reached: they come down to the lane count when the outputs
  3874. // do not fit.
  3875. use super::container::{MESH_OUTPUT_LIMIT, mesh_output_bytes};
  3876. let (outputs, prims) = (&self.s.outputs, &self.s.prims);
  3877. let fits = |m: super::shader::Mesh| {
  3878. mesh_output_bytes(outputs, prims, m.max_vertices, m.max_primitives) <= MESH_OUTPUT_LIMIT
  3879. };
  3880. if !fits(mesh) {
  3881. mesh.max_vertices = mesh.max_vertices.min(threads);
  3882. mesh.max_primitives = mesh.max_primitives.min(threads);
  3883. // shortcut: outputs past the cap even at the lane count are
  3884. // still emitted with the lower maxima (drivers take them);
  3885. // refuse them here if one hangs.
  3886. // Experiment (`VICTORY_MESH_OUTPUT_STRICT=1`): they are refused.
  3887. if !fits(mesh) && std::env::var_os("VICTORY_MESH_OUTPUT_STRICT").is_some() {
  3888. return Err("a mesh shader whose outputs pass the host's 32 KiB");
  3889. }
  3890. self.s.mesh = Some(mesh);
  3891. }
  3892. let e = self.s.entry;
  3893. let void = self.s.t.void;
  3894. let (v, p) = (
  3895. self.s.m.i32(mesh.max_vertices),
  3896. self.s.m.i32(mesh.max_primitives),
  3897. );
  3898. self.s
  3899. .op(e, "setMeshOutputCounts", Attr::NoUnwind, void, 168, &[v, p]);
  3900. let flat = self.mesh_thread();
  3901. let z = self.s.m.i32(0);
  3902. // Every primitive of the declared count starts culled, also those
  3903. // past the lanes (a count of 256 with 128 lanes): lane n culls
  3904. // primitives n, n + lanes, ... The host draws all it was promised,
  3905. // and one never written has whatever indices its memory held: long
  3906. // triangles over the whole target, each pixel of them shaded.
  3907. let passes = mesh.max_primitives.div_ceil(threads.max(1));
  3908. for pass in 0..passes {
  3909. let index = if pass == 0 {
  3910. flat
  3911. } else {
  3912. let past = self.s.m.i32(pass * threads);
  3913. self.s.m.bin(self.cur, Bin::Add, flat, past)
  3914. };
  3915. let guard = ((pass + 1) * threads > mesh.max_primitives)
  3916. .then(|| self.s.m.cmp(self.cur, pred::IULT, index, p));
  3917. let at = self.begin_guarded(guard);
  3918. self.s.op(
  3919. self.cur,
  3920. "emitIndices",
  3921. Attr::NoUnwind,
  3922. void,
  3923. 169,
  3924. &[index, z, z, z],
  3925. );
  3926. self.end_guarded(at, &[]);
  3927. }
  3928. Ok(())
  3929. }
  3930. /// Mesh: the thread's index in the group, which is its vertex and
  3931. /// primitive index.
  3932. fn mesh_thread(&mut self) -> V {
  3933. if let Some(f) = self.flat {
  3934. return f;
  3935. }
  3936. let e = self.s.entry;
  3937. let f = self.s.op(
  3938. e,
  3939. "flattenedThreadIdInGroup.i32",
  3940. Attr::ReadNone,
  3941. self.s.t.i32,
  3942. 96,
  3943. &[],
  3944. );
  3945. self.flat = Some(f);
  3946. f
  3947. }
  3948. /// The console wave size.
  3949. fn wave(&self) -> u32 {
  3950. if self.x.native.wave64 { 64 } else { 32 }
  3951. }
  3952. fn lane_index(&mut self) -> V {
  3953. if self.s.mesh.is_some() {
  3954. // The console's lane: mesh code reads no other lanes, so host
  3955. // waves need not match the console's.
  3956. let f = self.mesh_thread();
  3957. let m = self.s.m.i32(self.wave() - 1);
  3958. return self.s.m.bin(self.s.entry, Bin::And, f, m);
  3959. }
  3960. self.s.op(
  3961. self.cur,
  3962. "waveGetLaneIndex",
  3963. Attr::ReadOnly,
  3964. self.s.t.i32,
  3965. 111,
  3966. &[],
  3967. )
  3968. }
  3969. /// `x` of lane `src` (in this lane's quad) through quad reads, whose
  3970. /// lane must be a constant.
  3971. fn quad_pick(&mut self, x: V, src: V) -> V {
  3972. self.s.flags |= flags::WAVE_OPS;
  3973. let c = self.cur;
  3974. let three = self.s.m.i32(3);
  3975. let q = self.s.m.bin(c, Bin::And, src, three);
  3976. let mut r = x;
  3977. for n in 0..4 {
  3978. let kn = self.s.m.i32(n);
  3979. let read = self.s.op(
  3980. c,
  3981. "quadReadLaneAt.i32",
  3982. Attr::NoUnwind,
  3983. self.s.t.i32,
  3984. 122,
  3985. &[x, kn],
  3986. );
  3987. let is = self.s.m.cmp(c, pred::EQ, q, kn);
  3988. r = self.s.m.select(c, is, read, r);
  3989. }
  3990. r
  3991. }
  3992. /// `x` in the first lane of this host wave where `guard` holds, and whether it has such a
  3993. /// lane: the console reads the first lane of EXEC, and a lane that got here with EXEC clear
  3994. /// (a guard, not a branch) is not one. With none, `x` of the wave's first lane here.
  3995. fn first_lane(&mut self, x: V, guard: Option<V>) -> (V, V) {
  3996. let c = self.cur;
  3997. let i32t = self.s.t.i32;
  3998. self.s.flags |= flags::WAVE_OPS;
  3999. let first = self.s.op(c, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[x]);
  4000. let Some(g) = guard else {
  4001. return (first, self.s.m.bool(true));
  4002. };
  4003. let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]);
  4004. let r = self.s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[g]);
  4005. let (lo, hi) = (self.s.m.extract(c, r, 0), self.s.m.extract(c, r, 1));
  4006. let (z, k32) = (self.s.m.i32(0), self.s.m.i32(32));
  4007. // FirstbitLo (dx.op 32): the lowest set bit
  4008. let flo = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[lo]);
  4009. let fhi = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[hi]);
  4010. let fhi = self.s.m.bin(c, Bin::Add, fhi, k32);
  4011. let in_lo = self.s.m.cmp(c, pred::NE, lo, z);
  4012. let in_hi = self.s.m.cmp(c, pred::NE, hi, z);
  4013. let any = self.s.m.bin(c, Bin::Or, in_lo, in_hi);
  4014. let lane = self.s.m.select(c, in_lo, flo, fhi);
  4015. // no lane in EXEC: read this lane (one that is here); the read is not used
  4016. let me = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
  4017. let lane = self.s.m.select(c, any, lane, me);
  4018. let at = self.read_lane(x, lane);
  4019. (self.s.m.select(c, any, at, first), any)
  4020. }
  4021. fn read_lane(&mut self, x: V, lane: V) -> V {
  4022. self.s.op(
  4023. self.cur,
  4024. "waveReadLaneAt.i32",
  4025. Attr::NoUnwind,
  4026. self.s.t.i32,
  4027. 117,
  4028. &[x, lane],
  4029. )
  4030. }
  4031. /// The float value of a register value.
  4032. fn float_of(&mut self, v: Value) -> Result<V, Why> {
  4033. if let Some(&f) = self.floats.get(&v) {
  4034. return Ok(f);
  4035. }
  4036. let x = self.i32_of(v)?;
  4037. Ok(self.as_float(x))
  4038. }
  4039. /// The values of VGPRs `reg..reg + n` as `inst` reads them.
  4040. fn vgprs(&mut self, inst: &Inst, op: &Operand, n: u8) -> Result<Vec<V>, Why> {
  4041. let Operand::Vector { reg, .. } = *op else {
  4042. return Err("a vector operand");
  4043. };
  4044. (0..n)
  4045. .map(|k| {
  4046. let v = inst.read(Reg::V(reg + k)).ok_or("an unread operand")?;
  4047. self.i32_of(v)
  4048. })
  4049. .collect()
  4050. }
  4051. /// LDS (thread-group shared memory) and `ds_swizzle`.
  4052. fn ds(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  4053. let Fields::Ds {
  4054. dst,
  4055. addr,
  4056. data,
  4057. offset0,
  4058. offset1,
  4059. gds,
  4060. } = &inst.fields
  4061. else {
  4062. unreachable!()
  4063. };
  4064. if *gds {
  4065. return Err("GDS");
  4066. }
  4067. let name = inst.name();
  4068. let guard = self.guard(b, i)?;
  4069. let c = self.cur;
  4070. let offset = u32::from(*offset0) | u32::from(*offset1) << 8;
  4071. let dst_reg = match dst {
  4072. Some(Operand::Vector { reg, .. }) => Some(*reg),
  4073. _ => None,
  4074. };
  4075. if name == "ds_swizzle_b32" {
  4076. // Bit 15 set: each lane of a quad picks a lane of it; else lanes
  4077. // of each group of 32 combine their index with and/or/xor masks.
  4078. let quad = offset & 0x8000 != 0
  4079. || offset & 0x1C == 0x1C && offset & 0x380 == 0 && offset >> 10 & 0x1F < 4;
  4080. // Mesh: host quads are threads 4n..4n+3 of a 1D group, as the
  4081. // console's, so quad-local swizzles read through quad operations.
  4082. let mesh_quad = self.s.mesh.is_some() && quad;
  4083. if !mesh_quad {
  4084. self.cross_lane(quad)?;
  4085. }
  4086. // The source sits in the address field.
  4087. let x = self.vgprs(inst, addr.as_ref().ok_or("a swizzle source")?, 1)?[0];
  4088. let lane = self.lane_index();
  4089. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  4090. let src = if offset & 0x8000 != 0 {
  4091. let (three, one) = (k(self, 3), k(self, 1));
  4092. let sel = self.s.m.bin(c, Bin::And, lane, three);
  4093. let sh = self.s.m.bin(c, Bin::Shl, sel, one);
  4094. let pattern = k(self, offset & 0xFF);
  4095. let pick = self.s.m.bin(c, Bin::LShr, pattern, sh);
  4096. let pick = self.s.m.bin(c, Bin::And, pick, three);
  4097. let not3 = k(self, !3);
  4098. let base = self.s.m.bin(c, Bin::And, lane, not3);
  4099. self.s.m.bin(c, Bin::Or, base, pick)
  4100. } else {
  4101. let and = k(self, offset & 0x1F | !0x1F);
  4102. let or = k(self, offset >> 5 & 0x1F);
  4103. let xor = k(self, offset >> 10 & 0x1F);
  4104. let t = self.s.m.bin(c, Bin::And, lane, and);
  4105. let t = self.s.m.bin(c, Bin::Or, t, or);
  4106. self.s.m.bin(c, Bin::Xor, t, xor)
  4107. };
  4108. let r = if mesh_quad {
  4109. self.quad_pick(x, src)
  4110. } else {
  4111. self.read_lane(x, src)
  4112. };
  4113. let reg = dst_reg.ok_or("a swizzle result")?;
  4114. self.write(inst, Reg::V(reg), r, guard);
  4115. return Ok(());
  4116. }
  4117. if name == "ds_bpermute_b32" {
  4118. // Backward permute: no LDS is touched. Each lane takes the data
  4119. // register of the lane its address names, (address + offset) / 4
  4120. // within the wave; a source lane outside EXEC gives 0. (Grand
  4121. // Theft Auto VI's checkerboard shadow-mask generators read their
  4122. // neighbours' samples with it; without them every shadowed light
  4123. // was multiplied by an empty mask.)
  4124. // shortcut: a source lane that is not at this instruction on the
  4125. // host (it left through a branch, not a guard) is read as the
  4126. // host gives it; the console reads 0.
  4127. self.cross_lane(false)?;
  4128. if self.exchange.as_ref().is_some_and(|e| !e.1) {
  4129. // a console wave of 64 run as two host waves: the lane named
  4130. // may be in the other one
  4131. return Err("a lane permute across two host waves");
  4132. }
  4133. let at = self.vgprs(inst, addr.as_ref().ok_or("a permute address")?, 1)?[0];
  4134. let x = self.vgprs(inst, data.first().ok_or("a permute source")?, 1)?[0];
  4135. let o = self.s.m.i32(offset);
  4136. let at = self.s.m.bin(c, Bin::Add, at, o);
  4137. let two = self.s.m.i32(2);
  4138. let src = self.s.m.bin(c, Bin::LShr, at, two);
  4139. let last = self.s.m.i32(self.wave() - 1);
  4140. let src = self.s.m.bin(c, Bin::And, src, last);
  4141. let x = match guard {
  4142. Some(g) => {
  4143. let z = self.s.m.i32(0);
  4144. self.s.m.select(c, g, x, z)
  4145. }
  4146. None => x,
  4147. };
  4148. let r = self.read_lane(x, src);
  4149. let reg = dst_reg.ok_or("a permute result")?;
  4150. self.write(inst, Reg::V(reg), r, guard);
  4151. return Ok(());
  4152. }
  4153. if self.s.lds_dwords == 0 {
  4154. return Err("LDS the program does not allocate");
  4155. }
  4156. let a = self.vgprs(inst, addr.as_ref().ok_or("an LDS address")?, 1)?[0];
  4157. // shortcut: LDS addresses are taken as dword-aligned and in bounds
  4158. // (out-of-bounds console accesses read 0 and drop writes).
  4159. let dword = |l: &mut Self, bytes: u32| -> V {
  4160. let c = l.cur;
  4161. let o = l.s.m.i32(bytes);
  4162. let at = l.s.m.bin(c, Bin::Add, a, o);
  4163. let two = l.s.m.i32(2);
  4164. let index = l.s.m.bin(c, Bin::LShr, at, two);
  4165. let lds = l.s.lds();
  4166. l.s.m.element(c, lds, index)
  4167. };
  4168. let width = |n: &str| match n.rsplit('_').next() {
  4169. Some("b64") => 2,
  4170. Some("b96") => 3,
  4171. Some("b128") => 4,
  4172. _ => 1,
  4173. };
  4174. // (byte offset, dwords) per element; read2/write2 scale their two
  4175. // offsets by the element size (×64 for st64).
  4176. let pair = |n: &str| -> Vec<(u32, u32)> {
  4177. let w = width(n);
  4178. let scale = 4 * w * if n.contains("st64") { 64 } else { 1 };
  4179. vec![
  4180. (u32::from(*offset0) * scale, w),
  4181. (u32::from(*offset1) * scale, w),
  4182. ]
  4183. };
  4184. // Bytes and halves: the dword holding them, and their bit position
  4185. // in it (naturally aligned, so they never straddle dwords).
  4186. // `_d16` reads fill a register's low half (`_d16_hi` its high half)
  4187. // and keep the other; `_d16_hi` writes take the data's high half.
  4188. let base = name.trim_end_matches("_hi").trim_end_matches("_d16");
  4189. let sub = match base {
  4190. "ds_read_u8" | "ds_read_i8" | "ds_write_b8" => Some(8u32),
  4191. "ds_read_u16" | "ds_read_i16" | "ds_write_b16" => Some(16),
  4192. _ => None,
  4193. };
  4194. let sub = sub.filter(|_| {
  4195. base == name
  4196. || name.ends_with("_d16") && base.starts_with("ds_read")
  4197. || name.ends_with("_d16_hi")
  4198. });
  4199. if let Some(bits) = sub {
  4200. let p = dword(self, offset);
  4201. let o = self.s.m.i32(offset);
  4202. let at = self.s.m.bin(c, Bin::Add, a, o);
  4203. let three = self.s.m.i32(3);
  4204. let byte = self.s.m.bin(c, Bin::And, at, three);
  4205. let sh = self.s.m.bin(c, Bin::Shl, byte, three);
  4206. let mask = self.s.m.i32((1u32 << bits) - 1);
  4207. if name.starts_with("ds_read") {
  4208. let reg = dst_reg.ok_or("an LDS read result")?;
  4209. let w = self.s.m.load(c, p);
  4210. let x = self.s.m.bin(c, Bin::LShr, w, sh);
  4211. let x = if base.contains("_i") {
  4212. let k = self.s.m.i32(32 - bits);
  4213. let x = self.s.m.bin(c, Bin::Shl, x, k);
  4214. self.s.m.bin(c, Bin::AShr, x, k)
  4215. } else {
  4216. self.s.m.bin(c, Bin::And, x, mask)
  4217. };
  4218. let x = if base == name {
  4219. x
  4220. } else {
  4221. let old = match inst.read(Reg::V(reg)) {
  4222. Some(v) => self.i32_of(v)?,
  4223. None => self.s.m.i32(0),
  4224. };
  4225. let half = self.s.m.i32(0xFFFF);
  4226. let x = self.s.m.bin(c, Bin::And, x, half);
  4227. let (x, keep) = if name.ends_with("_hi") {
  4228. let k16 = self.s.m.i32(16);
  4229. (self.s.m.bin(c, Bin::Shl, x, k16), half)
  4230. } else {
  4231. (x, self.s.m.i32(0xFFFF_0000))
  4232. };
  4233. let old = self.s.m.bin(c, Bin::And, old, keep);
  4234. self.s.m.bin(c, Bin::Or, old, x)
  4235. };
  4236. self.write(inst, Reg::V(reg), x, guard);
  4237. } else {
  4238. // Clear, then set: two atomics, so lanes writing other
  4239. // bytes of the dword keep theirs.
  4240. let mut x = self.vgprs(inst, data.first().ok_or("an LDS write")?, 1)?[0];
  4241. if name != base {
  4242. // The data's high half.
  4243. let k16 = self.s.m.i32(16);
  4244. x = self.s.m.bin(c, Bin::LShr, x, k16);
  4245. }
  4246. let x = self.s.m.bin(c, Bin::And, x, mask);
  4247. let x = self.s.m.bin(c, Bin::Shl, x, sh);
  4248. let m = self.s.m.bin(c, Bin::Shl, mask, sh);
  4249. let ones = self.s.m.i32(u32::MAX);
  4250. let keep = self.s.m.bin(c, Bin::Xor, m, ones);
  4251. use super::bitcode::Rmw;
  4252. let at = self.begin_guarded(guard);
  4253. self.s.m.atomic(self.cur, Rmw::And, p, keep);
  4254. self.s.m.atomic(self.cur, Rmw::Or, p, x);
  4255. self.end_guarded(at, &[]);
  4256. }
  4257. return Ok(());
  4258. }
  4259. if let Some(rest) = name.strip_prefix("ds_read") {
  4260. let elements = if rest.starts_with('2') {
  4261. pair(name)
  4262. } else if matches!(rest, "_b32" | "_b64" | "_b96" | "_b128") {
  4263. vec![(offset, width(name))]
  4264. } else {
  4265. return Err("an LDS read of bytes or halves");
  4266. };
  4267. let reg = dst_reg.ok_or("an LDS read result")?;
  4268. let mut n = 0;
  4269. for (off, w) in elements {
  4270. for k in 0..w {
  4271. let p = dword(self, off + 4 * k);
  4272. let x = self.s.m.load(self.cur, p);
  4273. self.write(inst, Reg::V(reg + n), x, guard);
  4274. n += 1;
  4275. }
  4276. }
  4277. return Ok(());
  4278. }
  4279. if let Some(rest) = name.strip_prefix("ds_write") {
  4280. let elements = if rest.starts_with('2') {
  4281. pair(name)
  4282. } else if matches!(rest, "_b32" | "_b64" | "_b96" | "_b128") {
  4283. vec![(offset, width(name))]
  4284. } else {
  4285. return Err("an LDS write of bytes or halves");
  4286. };
  4287. let mut stores = Vec::new();
  4288. for (e, (off, w)) in elements.into_iter().enumerate() {
  4289. let vals = self.vgprs(inst, data.get(e).ok_or("an LDS write")?, w as u8)?;
  4290. for (k, x) in vals.into_iter().enumerate() {
  4291. stores.push((off + 4 * k as u32, x));
  4292. }
  4293. }
  4294. let at = self.begin_guarded(guard);
  4295. for (off, x) in stores {
  4296. let p = dword(self, off);
  4297. self.s.m.store(self.cur, p, x);
  4298. }
  4299. self.end_guarded(at, &[]);
  4300. return Ok(());
  4301. }
  4302. // Atomics: the old value returns with `_rtn`.
  4303. let op = name
  4304. .strip_prefix("ds_")
  4305. .map(|n| n.replace("_rtn", ""))
  4306. .ok_or("an LDS operation")?;
  4307. use super::bitcode::Rmw;
  4308. let rmw = match op.as_str() {
  4309. "add_u32" => Some(Rmw::Add),
  4310. "sub_u32" => Some(Rmw::Sub),
  4311. "and_b32" => Some(Rmw::And),
  4312. "or_b32" => Some(Rmw::Or),
  4313. "xor_b32" => Some(Rmw::Xor),
  4314. "min_i32" => Some(Rmw::Min),
  4315. "max_i32" => Some(Rmw::Max),
  4316. "min_u32" => Some(Rmw::UMin),
  4317. "max_u32" => Some(Rmw::UMax),
  4318. "wrxchg_b32" => Some(Rmw::Xchg),
  4319. "cmpst_b32" | "max_f32" | "min_f32" => None,
  4320. _ => return Err("an LDS operation"),
  4321. };
  4322. let v0 = self.vgprs(inst, data.first().ok_or("an LDS atomic")?, 1)?[0];
  4323. let v1 = match data.get(1) {
  4324. Some(d) => Some(self.vgprs(inst, d, 1)?[0]),
  4325. None => None,
  4326. };
  4327. let old_reg = dst_reg.and_then(|r| inst.read(Reg::V(r)).map(|v| (r, v)));
  4328. let outside = match old_reg {
  4329. Some((_, v)) => self.i32_of(v).unwrap_or(self.s.m.i32(0)),
  4330. None => self.s.m.i32(0),
  4331. };
  4332. let p = dword(self, offset);
  4333. if let Some(max) = match op.as_str() {
  4334. "max_f32" => Some(true),
  4335. "min_f32" => Some(false),
  4336. _ => None,
  4337. } {
  4338. let at = self.begin_guarded(guard);
  4339. let r = self.lds_float_min_max(p, v0, max);
  4340. let r = self.end_guarded(at, &[(r, outside)])[0];
  4341. if let Some(reg) = dst_reg {
  4342. self.write(inst, Reg::V(reg), r, None);
  4343. }
  4344. return Ok(());
  4345. }
  4346. let at = self.begin_guarded(guard);
  4347. let r = match rmw {
  4348. Some(op) => self.s.m.atomic(self.cur, op, p, v0),
  4349. // Compare with data0, store data1.
  4350. None => self
  4351. .s
  4352. .m
  4353. .cmpxchg(self.cur, p, v0, v1.ok_or("an LDS compare")?),
  4354. };
  4355. let r = self.end_guarded(at, &[(r, outside)])[0];
  4356. if let Some(reg) = dst_reg {
  4357. self.write(inst, Reg::V(reg), r, None);
  4358. }
  4359. Ok(())
  4360. }
  4361. /// `ds_max_f32` (`max`) or `ds_min_f32` on the LDS dword at `p` with
  4362. /// the float bits `data`; the old bits return.
  4363. ///
  4364. /// DXIL has no float atomics on group-shared memory, so this is a
  4365. /// compare-exchange loop around [`Lower::lds_float_pick`], which gives
  4366. /// what RDNA2 writes (measured on gfx1036, reported on the pull
  4367. /// request): an sNaN, data first, then memory, is written quieted;
  4368. /// otherwise a NaN loses to a number (two quiet NaNs give the data);
  4369. /// numbers compare as floats with -0 below +0.
  4370. // shortcut: f32 denormals compare as kept; with the console's MODE
  4371. // flushing them they would order as ±0 first (MODE is not modelled).
  4372. fn lds_float_min_max(&mut self, p: V, data: V, max: bool) -> V {
  4373. let pre = self.cur;
  4374. let init = self.s.m.load(pre, p);
  4375. let (lp, exit) = (self.s.m.new_block(), self.s.m.new_block());
  4376. self.s.m.terminate(pre, Term::Br(lp));
  4377. let i32t = self.s.t.i32;
  4378. let old = self.s.m.phi(lp, i32t);
  4379. self.cur = lp;
  4380. let new = self.lds_float_pick(old, data, max);
  4381. let prev = self.s.m.cmpxchg(lp, p, old, new);
  4382. let done = self.s.m.cmp(lp, pred::EQ, prev, old);
  4383. self.s.m.set_phi(old, vec![(init, pre), (prev, lp)]);
  4384. self.s.m.terminate(lp, Term::CondBr(done, exit, lp));
  4385. self.cur = exit;
  4386. old
  4387. }
  4388. /// What `ds_max_f32` (`max`) or `ds_min_f32` writes over the dword
  4389. /// `mem` with `data` (float bits; see [`Lower::lds_float_min_max`]).
  4390. fn lds_float_pick(&mut self, mem: V, data: V, max: bool) -> V {
  4391. let c = self.cur;
  4392. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  4393. let (abs_mask, inf, quiet, zero) = (
  4394. k(self, 0x7FFF_FFFF),
  4395. k(self, 0x7F80_0000),
  4396. k(self, 0x40_0000),
  4397. k(self, 0),
  4398. );
  4399. let nan = |l: &mut Self, x: V| {
  4400. let m = l.s.m.bin(c, Bin::And, x, abs_mask);
  4401. l.s.m.cmp(c, pred::IUGT, m, inf)
  4402. };
  4403. let snan = |l: &mut Self, x: V| {
  4404. let n = nan(l, x);
  4405. let q = l.s.m.bin(c, Bin::And, x, quiet);
  4406. let sig = l.s.m.cmp(c, pred::EQ, q, zero);
  4407. l.s.m.bin(c, Bin::And, n, sig)
  4408. };
  4409. // A total order of the numbers as signed integers, -0 below +0:
  4410. // negative floats' magnitude bits reversed.
  4411. let key = |l: &mut Self, x: V| {
  4412. let k31 = l.s.m.i32(31);
  4413. let sign = l.s.m.bin(c, Bin::AShr, x, k31);
  4414. let flip = l.s.m.bin(c, Bin::And, sign, abs_mask);
  4415. l.s.m.bin(c, Bin::Xor, x, flip)
  4416. };
  4417. let (dk, mk) = (key(self, data), key(self, mem));
  4418. let take = self
  4419. .s
  4420. .m
  4421. .cmp(c, if max { pred::SGT } else { pred::SLT }, dk, mk);
  4422. let r = self.s.m.select(c, take, data, mem);
  4423. let (dn, mn) = (nan(self, data), nan(self, mem));
  4424. // One NaN: the number; two quiet NaNs: the data.
  4425. let r = self.s.m.select(c, mn, data, r);
  4426. let both = self.s.m.bin(c, Bin::And, dn, mn);
  4427. let only_data = {
  4428. let t = self.s.m.bool(true);
  4429. let not_both = self.s.m.bin(c, Bin::Xor, both, t);
  4430. self.s.m.bin(c, Bin::And, dn, not_both)
  4431. };
  4432. let r = self.s.m.select(c, only_data, mem, r);
  4433. // Signalling NaNs win, quieted: the data's first.
  4434. let qm = self.s.m.bin(c, Bin::Or, mem, quiet);
  4435. let sm = snan(self, mem);
  4436. let r = self.s.m.select(c, sm, qm, r);
  4437. let qd = self.s.m.bin(c, Bin::Or, data, quiet);
  4438. let sd = snan(self, data);
  4439. self.s.m.select(c, sd, qd, r)
  4440. }
  4441. // ---- instructions ----
  4442. // ---- instructions ----
  4443. fn inst(&mut self, b: usize, i: usize) -> Result<(), Stop> {
  4444. let inst: &'a Inst = &self.x.p.blocks[b].insts[i];
  4445. let offset = inst.machine.offset;
  4446. let name = inst.name();
  4447. self.local_ok = name.starts_with("s_bcnt1_i32_")
  4448. || name.starts_with("s_ff1_i32_")
  4449. || name.starts_with("v_mbcnt_");
  4450. self.mask_ok = match self.mask_data {
  4451. MaskData::Console => true,
  4452. MaskData::Host => {
  4453. name.starts_with("s_bcnt1_i32_")
  4454. || name.starts_with("s_ff1_i32_")
  4455. || name.starts_with("v_mbcnt_")
  4456. || matches!(
  4457. name,
  4458. "s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_u64" | "s_cmp_lg_u64"
  4459. )
  4460. }
  4461. // Mesh: only "do all lanes hold the first lane's value?" (`uniform_test`), which
  4462. // each host wave answers for itself.
  4463. MaskData::None => self.uniform_test(inst),
  4464. };
  4465. let effect = matches!(inst.fields, Fields::Exp { .. })
  4466. || matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_")
  4467. || name.contains("store")
  4468. || name.contains("atomic")
  4469. || name == "s_barrier"
  4470. || matches!(inst.fields, Fields::Ds { .. })
  4471. && !(name.starts_with("ds_read")
  4472. || name.starts_with("ds_swizzle")
  4473. || name.contains("permute"));
  4474. if self.split_lds
  4475. && matches!(inst.fields, Fields::Ds { .. })
  4476. && !(name.starts_with("ds_swizzle") || name.contains("permute"))
  4477. && self.lds_meet.as_ref().is_none_or(|(all, _)| all[b])
  4478. {
  4479. // the two host waves of a console wave meet before each LDS access: what the other
  4480. // half wrote is visible, and what it still reads is not overwritten
  4481. let mode = self.s.m.i32(meeting_mode());
  4482. let void = self.s.t.void;
  4483. self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]);
  4484. }
  4485. let r = match &inst.fields {
  4486. Fields::Sop { .. } => self.sop(inst),
  4487. Fields::Sopp { .. } if name == "s_barrier" && self.no_barrier.contains(&b) => Ok(()),
  4488. Fields::Sopp { .. } if name == "s_barrier" => {
  4489. // Thread-group sync with a shared-memory fence, and a UAV
  4490. // fence when the program writes UAVs (the waits before an
  4491. // s_barrier make those writes visible on the console).
  4492. let mut mode = if self.writes_uavs { 1 | 2 | 8 } else { 1 | 8 };
  4493. // Without the wait for the group (bit 0) where not every
  4494. // lane arrives, or where the switch says so.
  4495. let waits = match super::group_sync() {
  4496. 0 => false,
  4497. 1 => !self.fence_only.contains(&b),
  4498. _ => true,
  4499. };
  4500. if !waits {
  4501. mode &= !1;
  4502. }
  4503. let mode = self.s.m.i32(mode);
  4504. let void = self.s.t.void;
  4505. self.s
  4506. .op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]);
  4507. Ok(())
  4508. }
  4509. Fields::Sopp { .. } => Ok(()),
  4510. Fields::Smem { .. } => self.smem(inst, (b, i)),
  4511. Fields::Valu(_) if name.starts_with("v_interp_") => self.interp(inst, (b, i)),
  4512. Fields::Valu(_) => self.valu(inst, b, i),
  4513. Fields::Vintrp { .. } => self.interp(inst, (b, i)),
  4514. // The ray and node test. A failure is a refusal at once: an
  4515. // instruction without a side effect otherwise only stops the
  4516. // program where its results are needed, and two trace programs
  4517. // came out without their test that way.
  4518. Fields::Image { .. } if name.starts_with("image_bvh") => {
  4519. return self
  4520. .bvh(inst, b, i)
  4521. .map_err(|why| unsupported(offset, why));
  4522. }
  4523. Fields::Image { .. } => self.image(inst, b, i),
  4524. Fields::Buffer { .. } => self.buffer(inst, b, i),
  4525. Fields::Exp { .. } => self.export(b, i),
  4526. Fields::Ds { .. } => self.ds(inst, b, i),
  4527. Fields::Flat { .. } if name.starts_with("global_") => self.flat(inst, b, i),
  4528. Fields::Flat { .. } => Err("flat memory"),
  4529. };
  4530. match r {
  4531. Ok(()) => Ok(()),
  4532. Err(why) if effect => Err(unsupported(offset, why)),
  4533. Err(why) => {
  4534. for &(_, v) in &inst.writes {
  4535. self.vals.insert(v, Val::Missing(why));
  4536. }
  4537. Ok(())
  4538. }
  4539. }
  4540. }
  4541. /// The two host waves of a console wave meet (a group barrier with a shared-memory
  4542. /// fence): LDS writes before are seen by reads after.
  4543. fn lds_meeting(&mut self) {
  4544. let mode = self.s.m.i32(meeting_mode());
  4545. let void = self.s.t.void;
  4546. self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]);
  4547. }
  4548. /// Whether `v` is a register no program reads as a number: a descriptor dword without
  4549. /// a host value ([`Self::stale`]), a lane mask's dword (outside compute, where a ballot
  4550. /// gives the mask as data), or a join of only such values. Compiled code joins numbers
  4551. /// with numbers: where one of these meets numbers at a join, the register is dead on
  4552. /// that path (a variable set in one arm of a branch, its use behind a flag kept in a
  4553. /// VGPR).
  4554. fn dead(&self, v: Value, seen: &mut Vec<Value>) -> bool {
  4555. if self.stale.contains(&v) {
  4556. return true;
  4557. }
  4558. let st = self.x.st;
  4559. if self.mask_data != MaskData::Console
  4560. && (st.masks.contains_key(&v) || st.highs.contains_key(&v))
  4561. {
  4562. return true;
  4563. }
  4564. let Some(&(b, i)) = self.phi_at.get(&v) else {
  4565. return false;
  4566. };
  4567. if seen.contains(&v) {
  4568. return true;
  4569. }
  4570. seen.push(v);
  4571. self.x.p.blocks[b].phis[i]
  4572. .args
  4573. .iter()
  4574. .all(|&a| self.dead(a, seen))
  4575. }
  4576. /// `s_bcnt1_i32_b*` of the lanes that differ from the first lane's value:
  4577. /// `v_readfirstlane_b32 s, v`, `v_cmp_eq_u32 m, s, v`, `s_xor_b* d, m, exec`. The
  4578. /// compiler tests a value for being the same in the whole wave this way, to take a
  4579. /// scalar path; both paths give each lane the same result, so the lanes of a host
  4580. /// wave may ask it of their own first lane, whatever the wave's size.
  4581. fn uniform_test(&self, inst: &Inst) -> bool {
  4582. let p = self.x.p;
  4583. let writer = |v: Value| -> Option<&'a Inst> {
  4584. let b = *self.def_block.get(&v)?;
  4585. p.blocks[b]
  4586. .insts
  4587. .iter()
  4588. .find(|i| i.writes.iter().any(|w| w.1 == v))
  4589. };
  4590. let scalar = |i: &Inst, op: &Operand| match *op {
  4591. Operand::Scalar { code, .. } if code != NULL && code != EXEC => i.read(Reg::S(code)),
  4592. _ => None,
  4593. };
  4594. if !inst.name().starts_with("s_bcnt1_i32_") {
  4595. return false;
  4596. }
  4597. let Fields::Sop { src, .. } = &inst.fields else {
  4598. return false;
  4599. };
  4600. let Some(xor) = src.first().and_then(|o| scalar(inst, o)).and_then(writer) else {
  4601. return false;
  4602. };
  4603. let Fields::Sop { src, .. } = &xor.fields else {
  4604. return false;
  4605. };
  4606. if !matches!(xor.name(), "s_xor_b64" | "s_xor_b32")
  4607. || !src
  4608. .iter()
  4609. .any(|o| matches!(o, Operand::Scalar { code: EXEC, .. }))
  4610. {
  4611. return false;
  4612. }
  4613. let Some(cmp) = src.iter().find_map(|o| scalar(xor, o)).and_then(writer) else {
  4614. return false;
  4615. };
  4616. let Fields::Valu(f) = &cmp.fields else {
  4617. return false;
  4618. };
  4619. if !matches!(cmp.name(), "v_cmp_eq_u32" | "v_cmp_eq_i32") || f.sdwa.is_some() || f.dpp.is_some() {
  4620. return false;
  4621. }
  4622. let lanes = f.src.iter().find_map(|o| match *o {
  4623. Operand::Vector { reg, .. } => cmp.read(Reg::V(reg)),
  4624. _ => None,
  4625. });
  4626. let first = f.src.iter().find_map(|o| scalar(cmp, o)).and_then(writer);
  4627. lanes.is_some()
  4628. && first.is_some_and(|fl| {
  4629. fl.name() == "v_readfirstlane_b32"
  4630. && matches!(&fl.fields, Fields::Valu(g)
  4631. if matches!(g.src.first(), Some(&Operand::Vector { reg, .. })
  4632. if fl.read(Reg::V(reg)) == lanes))
  4633. })
  4634. }
  4635. fn is_mask(&self, v: Option<Value>) -> bool {
  4636. v.is_some_and(|v| self.x.st.masks.contains_key(&v))
  4637. }
  4638. fn sop(&mut self, inst: &Inst) -> Result<(), Why> {
  4639. let Fields::Sop { dst, src, imm } = &inst.fields else {
  4640. unreachable!()
  4641. };
  4642. let name = inst.name();
  4643. let scc = inst.write(Reg::Scc);
  4644. let dst_code = match dst {
  4645. Some(Operand::Scalar { code, .. }) => Some(*code),
  4646. _ => None,
  4647. };
  4648. let lo = dst_code.and_then(|c| inst.write(Reg::S(c)));
  4649. if inst.write(Reg::S(EXEC)).is_some() || self.is_mask(lo) {
  4650. return Err(LANE_MASK);
  4651. }
  4652. if matches!(
  4653. name,
  4654. "s_setreg_imm32_b32" | "s_setreg_b32" | "s_swappc_b64" | "s_version"
  4655. ) || name.starts_with("s_waitcnt")
  4656. {
  4657. // shortcut: the float MODE register is not modelled; s_swappc_b64 is the
  4658. // vertex fetch call, whose results arrive as inputs.
  4659. return Err("a register the emitter does not model");
  4660. }
  4661. if name == "s_getpc_b64" {
  4662. // The address of the next instruction is no number the host has: tables in
  4663. // the code are read by their tracked address. As a number the counter is
  4664. // that instruction's offset in the code, so an address paths join before
  4665. // one load is the byte in the code, whichever table each path took
  4666. // (resource tracking gives such a join as the computed term, with no base).
  4667. let z = self.s.m.i32(0);
  4668. let at = self.s.m.i32(inst.machine.offset as u32 + 4);
  4669. let hi = dst_code.and_then(|c| inst.write(Reg::S(c + 1)));
  4670. self.set(lo, Val::I32(at));
  4671. self.set(hi, Val::I32(z));
  4672. return Ok(());
  4673. }
  4674. let c = self.cur;
  4675. let src32 = |l: &mut Self, k: usize| -> Result<V, Why> {
  4676. // SOPK arithmetic reads its destination as the first source.
  4677. if k == 0 && matches!(name, "s_addk_i32" | "s_mulk_i32") {
  4678. let d = dst.as_ref().ok_or("a missing operand")?;
  4679. return l.operand(inst, d);
  4680. }
  4681. let op = src.get(k).ok_or("a missing operand")?;
  4682. l.operand(inst, op)
  4683. };
  4684. let sext16 = |l: &mut Self| l.s.m.i32(i32::from(imm.unwrap_or(0) as i16) as u32);
  4685. // Dword `h` of 64-bit source `k` (inline constants sign-extend).
  4686. let half = |l: &mut Self, k: usize, h: u8| -> Result<V, Why> {
  4687. match src.get(k) {
  4688. Some(&Operand::Scalar { code, .. }) if code != NULL => {
  4689. let v = inst.read(Reg::S(code + h)).ok_or("an unread operand")?;
  4690. l.i32_of(v)
  4691. }
  4692. Some(op) if h == 0 => l.operand(inst, op),
  4693. Some(Operand::Const(k)) => {
  4694. let x = crate::resource::inline(*k).ok_or("a special operand")?;
  4695. Ok(l.s.m.i32(if (x as i32) < 0 { u32::MAX } else { 0 }))
  4696. }
  4697. _ => Ok(l.s.m.i32(0)),
  4698. }
  4699. };
  4700. if let Some(op) = name.strip_prefix("s_bitcmp") {
  4701. // SCC is whether bit src1 (mod 32, or mod 64 for the 64-bit form)
  4702. // of src0 is clear (bitcmp0) or set (bitcmp1).
  4703. let (bit, k31) = (src32(self, 1)?, self.s.m.i32(31));
  4704. let idx = self.s.m.bin(c, Bin::And, bit, k31);
  4705. let word = if op.ends_with("_b64") {
  4706. let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
  4707. let k32 = self.s.m.i32(32);
  4708. let upper = self.s.m.bin(c, Bin::And, bit, k32);
  4709. let z = self.s.m.i32(0);
  4710. let upper = self.s.m.cmp(c, pred::NE, upper, z);
  4711. self.s.m.select(c, upper, b, a)
  4712. } else {
  4713. src32(self, 0)?
  4714. };
  4715. let shifted = self.s.m.bin(c, Bin::LShr, word, idx);
  4716. let one = self.s.m.i32(1);
  4717. let tested = self.s.m.bin(c, Bin::And, shifted, one);
  4718. let want = self.s.m.i32(u32::from(op.starts_with('1')));
  4719. let r = self.s.m.cmp(c, pred::EQ, tested, want);
  4720. self.set(scc, Val::Bit(r));
  4721. return Ok(());
  4722. }
  4723. if let Some(op) = name.strip_prefix("s_cmp_").filter(|o| o.ends_with("_u64")) {
  4724. // eq and lg only: both dwords.
  4725. let mut r = None;
  4726. for h in 0..2 {
  4727. let (a, b) = (half(self, 0, h)?, half(self, 1, h)?);
  4728. let e = self.s.m.cmp(c, pred::EQ, a, b);
  4729. r = Some(match r {
  4730. Some(x) => self.s.m.bin(c, Bin::And, x, e),
  4731. None => e,
  4732. });
  4733. }
  4734. let mut r = r.expect("two dwords");
  4735. if op.starts_with("lg") {
  4736. let t = self.s.m.bool(true);
  4737. r = self.s.m.bin(c, Bin::Xor, r, t);
  4738. }
  4739. self.set(scc, Val::Bit(r));
  4740. return Ok(());
  4741. }
  4742. if let Some(op) = name.strip_prefix("s_cmp_").or(name.strip_prefix("s_cmpk_")) {
  4743. let (a, b) = if name.starts_with("s_cmpk_") {
  4744. let b = if op.ends_with("_i32") {
  4745. sext16(self)
  4746. } else {
  4747. self.s.m.i32(u32::from(imm.unwrap_or(0)))
  4748. };
  4749. (src32(self, 0)?, b)
  4750. } else {
  4751. if op.ends_with("64") {
  4752. return Err("a 64-bit scalar compare");
  4753. }
  4754. (src32(self, 0)?, src32(self, 1)?)
  4755. };
  4756. let signed = op.ends_with("_i32");
  4757. let p = match &op[..2] {
  4758. "eq" => pred::EQ,
  4759. "lg" => pred::NE,
  4760. "gt" if signed => pred::SGT,
  4761. "ge" if signed => pred::SGE,
  4762. "lt" if signed => pred::SLT,
  4763. "le" if signed => pred::SLE,
  4764. "gt" => pred::IUGT,
  4765. "ge" => pred::IUGE,
  4766. "lt" => pred::IULT,
  4767. "le" => pred::IULE,
  4768. _ => return Err("a scalar compare"),
  4769. };
  4770. let r = self.s.m.cmp(c, p, a, b);
  4771. self.set(scc, Val::Bit(r));
  4772. return Ok(());
  4773. }
  4774. let wide = name.ends_with("_b64") || name.ends_with("_u64") || name.ends_with("_i64");
  4775. if wide {
  4776. let hi = dst_code.and_then(|c| inst.write(Reg::S(c + 1)));
  4777. let nonzero = |l: &mut Self, a: V, b: V| {
  4778. let o = l.s.m.bin(c, Bin::Or, a, b);
  4779. let z = l.s.m.i32(0);
  4780. l.s.m.cmp(c, pred::NE, o, z)
  4781. };
  4782. return match name {
  4783. "s_bcnt1_i32_b64" => {
  4784. let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
  4785. let i32t = self.s.t.i32;
  4786. let na = self
  4787. .s
  4788. .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 31, &[a]);
  4789. let nb = self
  4790. .s
  4791. .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 31, &[b]);
  4792. let r = self.s.m.bin(c, Bin::Add, na, nb);
  4793. self.set(lo, Val::I32(r));
  4794. let z = self.s.m.i32(0);
  4795. let s = self.s.m.cmp(c, pred::NE, r, z);
  4796. self.set(scc, Val::Bit(s));
  4797. Ok(())
  4798. }
  4799. "s_ff1_i32_b64" => {
  4800. // The lowest set bit; -1 for none (as DXIL's first bit low).
  4801. let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
  4802. let i32t = self.s.t.i32;
  4803. let fa = self
  4804. .s
  4805. .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[a]);
  4806. let fb = self
  4807. .s
  4808. .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[b]);
  4809. let (z, k32) = (self.s.m.i32(0), self.s.m.i32(32));
  4810. let fb32 = self.s.m.bin(c, Bin::Add, fb, k32);
  4811. let none = self.s.m.cmp(c, pred::EQ, b, z);
  4812. let fb = self.s.m.select(c, none, fb, fb32);
  4813. let low = self.s.m.cmp(c, pred::NE, a, z);
  4814. let r = self.s.m.select(c, low, fa, fb);
  4815. self.set(lo, Val::I32(r));
  4816. Ok(())
  4817. }
  4818. "s_and_b64" | "s_or_b64" | "s_xor_b64" | "s_andn2_b64" | "s_orn2_b64"
  4819. | "s_nand_b64" | "s_nor_b64" | "s_xnor_b64" | "s_not_b64" => {
  4820. let ones = self.s.m.i32(u32::MAX);
  4821. let mut r = Vec::new();
  4822. for h in 0..2u8 {
  4823. let a = half(self, 0, h)?;
  4824. let x = if name == "s_not_b64" {
  4825. self.s.m.bin(c, Bin::Xor, a, ones)
  4826. } else {
  4827. let mut b = half(self, 1, h)?;
  4828. if name.contains("n2") {
  4829. b = self.s.m.bin(c, Bin::Xor, b, ones);
  4830. }
  4831. let op = match &name[2..5] {
  4832. "and" | "nan" => Bin::And,
  4833. "or_" | "orn" | "nor" => Bin::Or,
  4834. _ => Bin::Xor,
  4835. };
  4836. let x = self.s.m.bin(c, op, a, b);
  4837. if matches!(name, "s_nand_b64" | "s_nor_b64" | "s_xnor_b64") {
  4838. self.s.m.bin(c, Bin::Xor, x, ones)
  4839. } else {
  4840. x
  4841. }
  4842. };
  4843. r.push(x);
  4844. }
  4845. self.set(lo, Val::I32(r[0]));
  4846. self.set(hi, Val::I32(r[1]));
  4847. let s = nonzero(self, r[0], r[1]);
  4848. self.set(scc, Val::Bit(s));
  4849. Ok(())
  4850. }
  4851. "s_lshl_b64" | "s_lshr_b64" | "s_ashr_i64" => {
  4852. let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
  4853. let n = src32(self, 1)?;
  4854. let i64t = self.s.m.int(64);
  4855. self.s.flags |= flags::INT64;
  4856. let a = self.s.m.cast(c, Cast::ZExt, a, i64t);
  4857. let b = self.s.m.cast(c, Cast::ZExt, b, i64t);
  4858. let k32 = self.s.m.int_const(i64t, 32);
  4859. let b = self.s.m.bin(c, Bin::Shl, b, k32);
  4860. let x = self.s.m.bin(c, Bin::Or, a, b);
  4861. let k63 = self.s.m.i32(63);
  4862. let n = self.s.m.bin(c, Bin::And, n, k63);
  4863. let n = self.s.m.cast(c, Cast::ZExt, n, i64t);
  4864. let op = match name {
  4865. "s_lshl_b64" => Bin::Shl,
  4866. "s_lshr_b64" => Bin::LShr,
  4867. _ => Bin::AShr,
  4868. };
  4869. let r = self.s.m.bin(c, op, x, n);
  4870. let rl = self.s.m.cast(c, Cast::Trunc, r, self.s.t.i32);
  4871. let rh = self.s.m.bin(c, Bin::LShr, r, k32);
  4872. let rh = self.s.m.cast(c, Cast::Trunc, rh, self.s.t.i32);
  4873. self.set(lo, Val::I32(rl));
  4874. self.set(hi, Val::I32(rh));
  4875. let s = nonzero(self, rl, rh);
  4876. self.set(scc, Val::Bit(s));
  4877. Ok(())
  4878. }
  4879. "s_mov_b64" => {
  4880. // Each half by itself: two numbers that travel as a pair (two scalars
  4881. // parked in neighbouring VGPR lanes, say) need not both have a value.
  4882. for (h, v) in [(0, lo), (1, hi)] {
  4883. let val = match half(self, 0, h) {
  4884. Ok(a) => Val::I32(a),
  4885. Err(why) => Val::Missing(why),
  4886. };
  4887. self.set(v, val);
  4888. }
  4889. Ok(())
  4890. }
  4891. "s_cselect_b64" => {
  4892. let cond = self.scc_in(inst)?;
  4893. for (h, v) in [(0, lo), (1, hi)] {
  4894. let (a, b) = (half(self, 0, h)?, half(self, 1, h)?);
  4895. let r = self.s.m.select(c, cond, a, b);
  4896. self.set(v, Val::I32(r));
  4897. }
  4898. Ok(())
  4899. }
  4900. _ => Err(name),
  4901. };
  4902. }
  4903. let m = &mut self.s.m;
  4904. let _ = m;
  4905. let (r, carry): (V, Option<V>) = match name {
  4906. "s_mov_b32" => (src32(self, 0)?, None),
  4907. "s_movk_i32" => (sext16(self), None),
  4908. "s_cselect_b32" => {
  4909. let cond = self.scc_in(inst)?;
  4910. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  4911. (self.s.m.select(c, cond, a, b), None)
  4912. }
  4913. "s_brev_b32" => {
  4914. let a = src32(self, 0)?;
  4915. let r = self
  4916. .s
  4917. .op(c, "unary.i32", Attr::ReadNone, self.s.t.i32, 30, &[a]);
  4918. (r, None)
  4919. }
  4920. "s_not_b32" => {
  4921. let a = src32(self, 0)?;
  4922. let ones = self.s.m.i32(u32::MAX);
  4923. (self.s.m.bin(c, Bin::Xor, a, ones), None)
  4924. }
  4925. "s_add_u32" | "s_add_i32" | "s_addk_i32" => {
  4926. let a = src32(self, 0)?;
  4927. let b = if name == "s_addk_i32" {
  4928. sext16(self)
  4929. } else {
  4930. src32(self, 1)?
  4931. };
  4932. let r = self.s.m.bin(c, Bin::Add, a, b);
  4933. let carry = if name == "s_add_u32" {
  4934. Some(self.s.m.cmp(c, pred::IULT, r, a))
  4935. } else {
  4936. None
  4937. };
  4938. (r, carry)
  4939. }
  4940. "s_sub_u32" | "s_sub_i32" => {
  4941. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  4942. let r = self.s.m.bin(c, Bin::Sub, a, b);
  4943. let carry = (name == "s_sub_u32").then(|| self.s.m.cmp(c, pred::IULT, a, b));
  4944. (r, carry)
  4945. }
  4946. "s_addc_u32" | "s_subb_u32" => {
  4947. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  4948. let cin = self.scc_in(inst)?;
  4949. let (r, carry) = self.add_sub_carry(c, name == "s_addc_u32", a, b, Some(cin));
  4950. (r, Some(carry))
  4951. }
  4952. "s_mul_i32" | "s_mulk_i32" => {
  4953. let a = src32(self, 0)?;
  4954. let b = if name == "s_mulk_i32" {
  4955. sext16(self)
  4956. } else {
  4957. src32(self, 1)?
  4958. };
  4959. (self.s.m.bin(c, Bin::Mul, a, b), None)
  4960. }
  4961. "s_mul_hi_u32" | "s_mul_hi_i32" => {
  4962. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  4963. (self.mul_hi(a, b, name.ends_with("i32")), None)
  4964. }
  4965. "s_flbit_i32_b32" | "s_flbit_i32" => {
  4966. // The first bit from the top (differing from the sign for
  4967. // the signed form), -1 for none: DXIL's first-bit-high.
  4968. let a = src32(self, 0)?;
  4969. let op = if name == "s_flbit_i32_b32" { 33 } else { 34 };
  4970. let r = self
  4971. .s
  4972. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]);
  4973. (r, None)
  4974. }
  4975. "s_ff1_i32_b32" | "s_bcnt1_i32_b32" => {
  4976. // First set bit (-1 for zero, as DXIL's), or the bit count.
  4977. let a = src32(self, 0)?;
  4978. let op = if name == "s_ff1_i32_b32" { 32 } else { 31 };
  4979. let r = self
  4980. .s
  4981. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]);
  4982. (r, None)
  4983. }
  4984. "s_bfe_u32" | "s_bfe_i32" => {
  4985. // src1: offset in bits 0-4, width in bits 16-22.
  4986. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  4987. let (k16, k127) = (self.s.m.i32(16), self.s.m.i32(0x7F));
  4988. let w = self.s.m.bin(c, Bin::LShr, b, k16);
  4989. let w = self.s.m.bin(c, Bin::And, w, k127);
  4990. (self.bfe(a, b, w, name == "s_bfe_i32"), None)
  4991. }
  4992. "s_and_b32" | "s_or_b32" | "s_xor_b32" | "s_andn2_b32" | "s_orn2_b32"
  4993. | "s_nand_b32" | "s_nor_b32" | "s_xnor_b32" => {
  4994. let (a, mut b) = (src32(self, 0)?, src32(self, 1)?);
  4995. let ones = self.s.m.i32(u32::MAX);
  4996. if name.contains("n2") {
  4997. b = self.s.m.bin(c, Bin::Xor, b, ones);
  4998. }
  4999. let op = match &name[2..5] {
  5000. "and" | "nan" => Bin::And,
  5001. "or_" | "orn" | "nor" => Bin::Or,
  5002. _ => Bin::Xor,
  5003. };
  5004. let mut r = self.s.m.bin(c, op, a, b);
  5005. if matches!(name, "s_nand_b32" | "s_nor_b32" | "s_xnor_b32") {
  5006. r = self.s.m.bin(c, Bin::Xor, r, ones);
  5007. }
  5008. (r, None)
  5009. }
  5010. "s_lshl_b32" | "s_lshr_b32" | "s_ashr_i32" => {
  5011. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5012. let k31 = self.s.m.i32(31);
  5013. let b = self.s.m.bin(c, Bin::And, b, k31);
  5014. let op = match name {
  5015. "s_lshl_b32" => Bin::Shl,
  5016. "s_lshr_b32" => Bin::LShr,
  5017. _ => Bin::AShr,
  5018. };
  5019. (self.s.m.bin(c, op, a, b), None)
  5020. }
  5021. "s_lshl1_add_u32" | "s_lshl2_add_u32" | "s_lshl3_add_u32" | "s_lshl4_add_u32" => {
  5022. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5023. let k = self.s.m.i32(u32::from(name.as_bytes()[6] - b'0'));
  5024. let t = self.s.m.bin(c, Bin::Shl, a, k);
  5025. (self.s.m.bin(c, Bin::Add, t, b), None)
  5026. }
  5027. "s_min_u32" | "s_max_u32" | "s_min_i32" | "s_max_i32" => {
  5028. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5029. let p = match name {
  5030. "s_min_u32" => pred::IULT,
  5031. "s_max_u32" => pred::IUGT,
  5032. "s_min_i32" => pred::SLT,
  5033. _ => pred::SGT,
  5034. };
  5035. let t = self.s.m.cmp(c, p, a, b);
  5036. (self.s.m.select(c, t, a, b), None)
  5037. }
  5038. "s_abs_i32" => {
  5039. let a = src32(self, 0)?;
  5040. let z = self.s.m.i32(0);
  5041. let neg = self.s.m.cmp(c, pred::SLT, a, z);
  5042. let n = self.s.m.bin(c, Bin::Sub, z, a);
  5043. (self.s.m.select(c, neg, n, a), None)
  5044. }
  5045. "s_bitset0_b32" | "s_bitset1_b32" => {
  5046. // Sets (clears) bit src[4:0] of the destination it reads.
  5047. let old = self.operand(inst, dst.as_ref().ok_or("a missing operand")?)?;
  5048. let a = src32(self, 0)?;
  5049. let (k31, one) = (self.s.m.i32(31), self.s.m.i32(1));
  5050. let a = self.s.m.bin(c, Bin::And, a, k31);
  5051. let bit = self.s.m.bin(c, Bin::Shl, one, a);
  5052. if name == "s_bitset1_b32" {
  5053. (self.s.m.bin(c, Bin::Or, old, bit), None)
  5054. } else {
  5055. let ones = self.s.m.i32(u32::MAX);
  5056. let nb = self.s.m.bin(c, Bin::Xor, bit, ones);
  5057. (self.s.m.bin(c, Bin::And, old, nb), None)
  5058. }
  5059. }
  5060. "s_bfm_b32" => {
  5061. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5062. let k31 = self.s.m.i32(31);
  5063. let one = self.s.m.i32(1);
  5064. let a = self.s.m.bin(c, Bin::And, a, k31);
  5065. let b = self.s.m.bin(c, Bin::And, b, k31);
  5066. let m = self.s.m.bin(c, Bin::Shl, one, a);
  5067. let m = self.s.m.bin(c, Bin::Sub, m, one);
  5068. (self.s.m.bin(c, Bin::Shl, m, b), None)
  5069. }
  5070. _ => return Err(name),
  5071. };
  5072. self.set(lo, Val::I32(r));
  5073. if let Some(scc) = scc {
  5074. let val = match carry {
  5075. Some(k) => Val::Bit(k),
  5076. None if matches!(
  5077. name,
  5078. "s_mov_b32"
  5079. | "s_movk_i32"
  5080. | "s_cselect_b32"
  5081. | "s_brev_b32"
  5082. | "s_mul_i32"
  5083. | "s_mulk_i32"
  5084. ) =>
  5085. {
  5086. return Ok(());
  5087. }
  5088. None if name.starts_with("s_add") || name.starts_with("s_sub") => {
  5089. Val::Missing("the carry of a scalar operation")
  5090. }
  5091. None => {
  5092. let z = self.s.m.i32(0);
  5093. Val::Bit(self.s.m.cmp(c, pred::NE, r, z))
  5094. }
  5095. };
  5096. self.vals.insert(scc, val);
  5097. }
  5098. Ok(())
  5099. }
  5100. /// `a + b (+ cin)` or `a - b (- cin)` with the carry (borrow) out, as the
  5101. /// scalar and vector add-with-carry instructions set it.
  5102. fn add_sub_carry(&mut self, c: usize, add: bool, a: V, b: V, cin: Option<V>) -> (V, V) {
  5103. let op = if add { Bin::Add } else { Bin::Sub };
  5104. let mut r = self.s.m.bin(c, op, a, b);
  5105. // Without a carry in: a + b wraps below a; a - b borrows when a < b.
  5106. let mut carry = if add {
  5107. self.s.m.cmp(c, pred::IULT, r, a)
  5108. } else {
  5109. self.s.m.cmp(c, pred::IULT, a, b)
  5110. };
  5111. if let Some(cin) = cin {
  5112. let one = self.s.m.cast(c, Cast::ZExt, cin, self.s.t.i32);
  5113. let t = r;
  5114. r = self.s.m.bin(c, op, t, one);
  5115. // The carry in carries on when the partial result is all ones
  5116. // (add) or zero (sub).
  5117. let edge = self.s.m.i32(if add { u32::MAX } else { 0 });
  5118. let at_edge = self.s.m.cmp(c, pred::EQ, t, edge);
  5119. let more = self.s.m.bin(c, Bin::And, cin, at_edge);
  5120. carry = self.s.m.bin(c, Bin::Or, carry, more);
  5121. }
  5122. (r, carry)
  5123. }
  5124. fn scc_in(&mut self, inst: &Inst) -> Result<V, Why> {
  5125. let v = inst.read(Reg::Scc).ok_or("an unread SCC")?;
  5126. match self.get(v)? {
  5127. Val::Bit(x) => Ok(x),
  5128. _ => Err("SCC without a value"),
  5129. }
  5130. }
  5131. fn smem(&mut self, inst: &Inst, site: Site) -> Result<(), Why> {
  5132. let Fields::Smem {
  5133. data,
  5134. offset,
  5135. soffset,
  5136. ..
  5137. } = &inst.fields
  5138. else {
  5139. unreachable!()
  5140. };
  5141. let name = inst.name();
  5142. if let Some(a) = self.scalar.get(&site).copied().filter(|a| a.param == CODE) {
  5143. return self.code_smem(inst, a);
  5144. }
  5145. if self.scalar.get(&site).is_some_and(|a| a.param == MEMORY) {
  5146. return self.memory_smem(inst);
  5147. }
  5148. let Some(rest) = name.strip_prefix("s_buffer_load_dword") else {
  5149. return self.descriptor_data(inst, site);
  5150. };
  5151. let count = match rest {
  5152. "" => 1,
  5153. "x2" => 2,
  5154. "x4" => 4,
  5155. "x8" => 8,
  5156. "x16" => 16,
  5157. _ => return Err("a scalar buffer load"),
  5158. };
  5159. let Some(Operand::Scalar { code, .. }) = *data else {
  5160. return Err("a scalar buffer load");
  5161. };
  5162. let src = self
  5163. .descriptors
  5164. .get(&(site, false))
  5165. .copied()
  5166. .ok_or("an untracked descriptor")?;
  5167. let kind = self.used_kind(src);
  5168. let c = self.cur;
  5169. let (base, extra) = self.built_offset(src)?;
  5170. let offset = &((*offset as u32).wrapping_add(base) as i32);
  5171. let mut addr = self.s.m.i32(*offset as u32);
  5172. if let Some(x) = extra {
  5173. addr = self.s.m.bin(c, Bin::Add, addr, x);
  5174. }
  5175. if !matches!(soffset, Operand::Scalar { code: NULL, .. }) {
  5176. let so = self.operand(inst, soffset)?;
  5177. addr = self.s.m.bin(c, Bin::Add, addr, so);
  5178. }
  5179. if matches!(src, Source::Built { address, .. } if address.param == CODE) {
  5180. // A descriptor built around a table in the code.
  5181. for k in 0..count {
  5182. let off = self.s.m.i32(4 * k);
  5183. let a = self.s.m.bin(c, Bin::Add, addr, off);
  5184. let x = self.code_dword(a)?;
  5185. self.write(inst, Reg::S(code + k as u8), x, None);
  5186. }
  5187. return Ok(());
  5188. }
  5189. // A buffer the program picks from the view heap by an index it
  5190. // computes (`ResourceHeap`) has no used-resource entry, and the
  5191. // heap holds a buffer view there, not a constant buffer: read as
  5192. // raw bytes, as a table's SRV is below. Read as a constant buffer
  5193. // (the host's validation: "Descriptor Type in Heap: SRV, Register
  5194. // Type: CBV", heap index 17) the loads gave nothing: Grand Theft
  5195. // Auto VI's meshlet culling (BatchCullMeshlets,
  5196. // BatchCullPreSkinnedMeshlets, BatchCullBatchCSMeshlets) reads its
  5197. // batch records, mesh headers and instance transforms this way, so
  5198. // it passed no meshlet and every indirect mesh draw ran empty.
  5199. // The host's table of strides by heap slot tells a buffer view
  5200. // (not 0) from anything else, which is still read as a constant
  5201. // buffer; only the load that fits the slot runs.
  5202. let picked = match kind {
  5203. None => self.slot_stride(src)?,
  5204. Some(_) => None,
  5205. };
  5206. if let Some(stride) = picked {
  5207. let zero = self.s.m.i32(0);
  5208. let is_buffer = self.s.m.cmp(self.cur, pred::NE, stride, zero);
  5209. let at = self.begin_guarded(Some(is_buffer));
  5210. let h = self.handle(site, src, false, (11, 0))?;
  5211. let mut raw = Vec::new();
  5212. for k in 0..count {
  5213. let b = self.cur;
  5214. let off = self.s.m.i32(4 * k);
  5215. let a = self.s.m.bin(b, Bin::Add, addr, off);
  5216. let mask = self.s.m.i8(1);
  5217. let (u, al) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
  5218. let r = self.s.op(
  5219. b,
  5220. "rawBufferLoad.f32",
  5221. Attr::ReadOnly,
  5222. self.s.t.res_ret,
  5223. 139,
  5224. &[h, a, u, mask, al],
  5225. );
  5226. let x = self.s.m.extract(b, r, 0);
  5227. let x = self.as_int(x);
  5228. raw.push((x, zero));
  5229. }
  5230. let raw = self.end_guarded(at, &raw);
  5231. let other = self.s.m.cmp(self.cur, pred::EQ, stride, zero);
  5232. let at = self.begin_guarded(Some(other));
  5233. let h = self.handle(site, src, false, (13, 0x1_0000))?;
  5234. let mut both = Vec::new();
  5235. for (k, &r) in raw.iter().enumerate() {
  5236. let b = self.cur;
  5237. let off = self.s.m.i32(4 * k as u32);
  5238. let a = self.s.m.bin(b, Bin::Add, addr, off);
  5239. let x = self.cbuffer_dword(h, a);
  5240. both.push((x, r));
  5241. }
  5242. let both = self.end_guarded(at, &both);
  5243. for (k, x) in both.into_iter().enumerate() {
  5244. self.write(inst, Reg::S(code + k as u8), x, None);
  5245. }
  5246. return Ok(());
  5247. }
  5248. if matches!(kind, Some(u) if u.kind == ResourceType::Srv) {
  5249. let h = self.handle(site, src, false, (11, 0))?;
  5250. for k in 0..count {
  5251. let off = self.s.m.i32(4 * k);
  5252. let a = self.s.m.bin(c, Bin::Add, addr, off);
  5253. let mask = self.s.m.i8(1);
  5254. let (u, al) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
  5255. let r = self.s.op(
  5256. c,
  5257. "rawBufferLoad.f32",
  5258. Attr::ReadOnly,
  5259. self.s.t.res_ret,
  5260. 139,
  5261. &[h, a, u, mask, al],
  5262. );
  5263. let x = self.s.m.extract(c, r, 0);
  5264. let x = self.as_int(x);
  5265. self.write(inst, Reg::S(code + k as u8), x, None);
  5266. }
  5267. return Ok(());
  5268. }
  5269. let h = self.handle(site, src, false, (13, 0x1_0000))?;
  5270. let constant = match addr {
  5271. V::Const(_)
  5272. if matches!(soffset, Operand::Scalar { code: NULL, .. }) && extra.is_none() =>
  5273. {
  5274. Some(*offset as u32)
  5275. }
  5276. _ => None,
  5277. };
  5278. let mut rows: HashMap<u32, V> = HashMap::new();
  5279. for k in 0..count {
  5280. let x = match constant {
  5281. Some(base) => {
  5282. let byte = base + 4 * k;
  5283. let row = match rows.get(&(byte >> 4)) {
  5284. Some(&r) => r,
  5285. None => {
  5286. let ri = self.s.m.i32(byte >> 4);
  5287. let r = self.s.op(
  5288. c,
  5289. "cbufferLoadLegacy.i32",
  5290. Attr::ReadOnly,
  5291. self.s.t.cbuf_ret,
  5292. 59,
  5293. &[h, ri],
  5294. );
  5295. rows.insert(byte >> 4, r);
  5296. r
  5297. }
  5298. };
  5299. self.s.m.extract(c, row, (byte >> 2) & 3)
  5300. }
  5301. None => {
  5302. let off = self.s.m.i32(4 * k);
  5303. let a = self.s.m.bin(c, Bin::Add, addr, off);
  5304. self.cbuffer_dword(h, a)
  5305. }
  5306. };
  5307. self.write(inst, Reg::S(code + k as u8), x, None);
  5308. }
  5309. Ok(())
  5310. }
  5311. /// A descriptor load (`s_load_dword*` from a table or heap) whose dwords
  5312. /// the code also reads as numbers: the console compiler computes sizes
  5313. /// from descriptor bits (an image's width, height, depth, levels; a
  5314. /// buffer's record count) instead of querying them. Those fields are
  5315. /// rebuilt from the host view's dimensions in the GFX10 layout (image
  5316. /// dword 1 bits 30-31 and dword 2 bits 0-13 width - 1, dword 2 bits
  5317. /// 14-29 height - 1, dword 3 identity swizzle, last level at 16, type at
  5318. /// 28, dword 4 depth or layers - 1; buffer dword 2 the record count).
  5319. // shortcut: the base level reads 0 (the host view starts at its own
  5320. // level 0, so sizes the code shifts by it come out right) and the other
  5321. // dwords (addresses, formats, tiling) have no host value: reading them
  5322. // stops the program.
  5323. fn descriptor_data(&mut self, inst: &Inst, site: Site) -> Result<(), Why> {
  5324. const OTHER: Why = "a descriptor's address or format read as data";
  5325. let Fields::Smem {
  5326. data: Some(Operand::Scalar { code, .. }),
  5327. ..
  5328. } = inst.fields
  5329. else {
  5330. return Err("a scalar memory read as data");
  5331. };
  5332. let count = match inst.name().strip_prefix("s_load_dword") {
  5333. Some("") => 1u32,
  5334. Some("x2") => 2,
  5335. Some("x4") => 4,
  5336. Some("x8") => 8,
  5337. Some("x16") => 16,
  5338. _ => return Err("a scalar memory read as data"),
  5339. };
  5340. // How the program uses the descriptor tells the view's kind: an image or buffer
  5341. // instruction before a scalar buffer load, which reads any buffer.
  5342. let x = self.x;
  5343. let uses = |of: Site| {
  5344. x.res
  5345. .descriptors
  5346. .iter()
  5347. .filter(|d| d.role == Role::Resource)
  5348. .filter_map(move |d| {
  5349. d.source.leaves().into_iter().find_map(|l| match *l {
  5350. Source::Loaded { load, first } if load == of => Some((d.site, first)),
  5351. _ => None,
  5352. })
  5353. })
  5354. };
  5355. let by_scalar_load = |u: &(Site, u8)| {
  5356. matches!(x.p.blocks[u.0.0].insts[u.0.1].fields, Fields::Smem { .. })
  5357. };
  5358. let use_of = |of: Site| uses(of).find(|u| !by_scalar_load(u)).or_else(|| uses(of).next());
  5359. // The console compiler loads a descriptor again wherever it needs it, and for a
  5360. // size it reads the dwords of a load that nothing uses as a descriptor (a texture
  5361. // picked from the heap by an index held per lane: one load for its width, one for
  5362. // its base level, one for each read of the image). Another load of as many dwords
  5363. // from the same address reads the same descriptor, so what uses that one tells
  5364. // this one's kind. The handle is still made from this load's own operands, which
  5365. // hold here.
  5366. let address = self.scalar.get(&site).copied();
  5367. let twin = || {
  5368. let a = address?;
  5369. let same = |s: Site| x.p.blocks[s.0].insts[s.1].name() == inst.name();
  5370. x.res
  5371. .scalar
  5372. .iter()
  5373. .filter(|(s, b)| *s != site && *b == a && same(*s))
  5374. .find_map(|(s, _)| use_of(*s))
  5375. };
  5376. let use_at = use_of(site).or_else(twin);
  5377. let Some((at, first)) = use_at else {
  5378. // A descriptor kept per lane in VGPRs (`Resources::lane_copied`): the code only
  5379. // copies its dwords and compares them, lane against first lane, and every load
  5380. // that reaches those lanes reads one address. Each dword stands in as its place
  5381. // in the table, so the lanes compare equal as they do on the console.
  5382. if self.x.res.lane_copied.contains(&site)
  5383. && let Some(a) = self.scalar.get(&site).copied()
  5384. {
  5385. for k in 0..count {
  5386. let x = self.s.m.i32(a.offset / 4 + k);
  5387. self.write(inst, Reg::S(code + k as u8), x, None);
  5388. }
  5389. return Ok(());
  5390. }
  5391. // A sampler's descriptor: no program reads its dwords as numbers, so where one
  5392. // meets numbers at a join the register is dead on that path (`dead`), as a
  5393. // descriptor's address or format is.
  5394. let sampler = x.res.descriptors.iter().any(|d| {
  5395. d.role == Role::Sampler
  5396. && d.source.leaves().into_iter().any(
  5397. |l| matches!(*l, Source::Loaded { load, .. } if load == site),
  5398. )
  5399. });
  5400. if sampler {
  5401. self.stale.extend(inst.writes.iter().map(|w| w.1));
  5402. return Err("a sampler's descriptor read as data");
  5403. }
  5404. // A buffer view the code only takes the address of, to walk
  5405. // the memory behind it (a ray-tracing structure): the address
  5406. // from the host, the other dwords have no value.
  5407. if count <= 4
  5408. && let Some((lo, hi)) = self.view_address(site)
  5409. {
  5410. for k in 0..count {
  5411. let reg = Reg::S(code + k as u8);
  5412. match k {
  5413. 0 => self.write(inst, reg, lo, None),
  5414. 1 => self.write(inst, reg, hi, None),
  5415. _ => {
  5416. if let Some(v) = inst.write(reg) {
  5417. self.vals.insert(v, Val::Missing(OTHER));
  5418. self.stale.insert(v);
  5419. }
  5420. }
  5421. }
  5422. }
  5423. return Ok(());
  5424. }
  5425. return Err("a descriptor read only as data");
  5426. };
  5427. let src = Source::Loaded { load: site, first };
  5428. let used = self.used_kind(&src);
  5429. let ui: &Inst = &self.x.p.blocks[at.0].insts[at.1];
  5430. let un = ui.name();
  5431. let uav = un.contains("store")
  5432. || un.contains("atomic")
  5433. || used.is_some_and(|u| u.kind == ResourceType::Uav);
  5434. let u = if uav { 0x1000 } else { 0 };
  5435. let (props, image) = match &ui.fields {
  5436. // A ray-tracing structure in a buffer of the host: read raw.
  5437. Fields::Image { .. } if un.starts_with("image_bvh") => ((11, 0), None),
  5438. Fields::Image { dim, .. } => {
  5439. let kind = match dim {
  5440. 0 => 1,
  5441. 1 => 2,
  5442. 2 => 4,
  5443. 4 => 6,
  5444. 5 => 7,
  5445. _ => return Err("an image dimension (cube or MSAA)"),
  5446. };
  5447. ((kind | u, 0x409), Some(kind))
  5448. }
  5449. Fields::Buffer { idxen, format, .. } => {
  5450. let stride = used.map_or(0, |u| u.stride);
  5451. let props = if un.starts_with("buffer_load_format")
  5452. || un.starts_with("buffer_store_format")
  5453. {
  5454. (10 | u, 0x409)
  5455. } else if *idxen && format.is_none() && stride >= 4 && stride.is_multiple_of(4) {
  5456. (12 | u, stride)
  5457. } else {
  5458. (11 | u, 0)
  5459. };
  5460. if used.is_some_and(|u| u.kind == ResourceType::Cbv) {
  5461. self.stale.extend(inst.writes.iter().map(|w| w.1));
  5462. return Err("a constant buffer's descriptor read as data");
  5463. }
  5464. (props, None)
  5465. }
  5466. // Read by scalar buffer loads alone: the raw view `smem` reads it through.
  5467. Fields::Smem { .. } if used.is_some_and(|u| u.kind == ResourceType::Srv) => {
  5468. ((11, 0), None)
  5469. }
  5470. // A constant buffer: nothing of its descriptor is a number.
  5471. Fields::Smem { .. } => {
  5472. self.stale.extend(inst.writes.iter().map(|w| w.1));
  5473. return Err("a constant buffer's descriptor read as data");
  5474. }
  5475. _ => return Err("a scalar memory read as data"),
  5476. };
  5477. let h = self.handle(site, &src, false, props)?;
  5478. let c = self.cur;
  5479. let i32t = self.s.t.i32;
  5480. let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
  5481. let mip = if image.is_some() && !uav {
  5482. self.s.m.i32(0)
  5483. } else {
  5484. self.s.m.undef(i32t)
  5485. };
  5486. let d = self
  5487. .s
  5488. .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]);
  5489. let field = |l: &mut Self, k: u32| l.s.m.extract(c, d, k);
  5490. let words: Vec<(u32, V)> = match image {
  5491. Some(kind) => {
  5492. let one = self.s.m.i32(1);
  5493. let w = field(self, 0);
  5494. let (height, depth) = match kind {
  5495. 1 => (one, one),
  5496. 2 => (field(self, 1), one),
  5497. 6 => (one, field(self, 1)),
  5498. _ => (field(self, 1), field(self, 2)),
  5499. };
  5500. let levels = if uav { one } else { field(self, 3) };
  5501. let less = |l: &mut Self, x: V| l.s.m.bin(c, Bin::Sub, x, one);
  5502. let (w, height, depth, levels) = (
  5503. less(self, w),
  5504. less(self, height),
  5505. less(self, depth),
  5506. less(self, levels),
  5507. );
  5508. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  5509. let (k30, k2, k14, k16, mask) = (
  5510. k(self, 30),
  5511. k(self, 2),
  5512. k(self, 14),
  5513. k(self, 16),
  5514. k(self, 0x3FFF),
  5515. );
  5516. let d1 = self.s.m.bin(c, Bin::Shl, w, k30);
  5517. let hi = self.s.m.bin(c, Bin::LShr, w, k2);
  5518. let hi = self.s.m.bin(c, Bin::And, hi, mask);
  5519. let ht = self.s.m.bin(c, Bin::Shl, height, k14);
  5520. let d2 = self.s.m.bin(c, Bin::Or, hi, ht);
  5521. let ty = [0, 8, 9, 0, 10, 0, 12, 13][kind as usize];
  5522. let base = k(self, 0xFAC | ty << 28);
  5523. let last = self.s.m.bin(c, Bin::Shl, levels, k16);
  5524. let d3 = self.s.m.bin(c, Bin::Or, base, last);
  5525. vec![(1, d1), (2, d2), (3, d3), (4, depth)]
  5526. }
  5527. None => {
  5528. // A raw view counts bytes; the descriptor's record count is in elements.
  5529. let n = field(self, 0);
  5530. let stride = used.map_or(0, |u| u.stride);
  5531. let n = if props.0 & 0xFF == 11 && stride > 1 {
  5532. let k = self.s.m.i32(stride);
  5533. self.s.m.bin(c, Bin::UDiv, n, k)
  5534. } else {
  5535. n
  5536. };
  5537. let mut words = vec![(2, n)];
  5538. // Its address too, where the code computes with it and the
  5539. // host can tell it.
  5540. let computed = (0..2u8).any(|k| {
  5541. inst.write(Reg::S(code + first + k))
  5542. .is_some_and(|v| self.computed_with(v, 6))
  5543. });
  5544. if first == 0
  5545. && computed
  5546. && let Some((lo, hi)) = self.view_address(site)
  5547. {
  5548. words.extend([(0, lo), (1, hi)]);
  5549. }
  5550. words
  5551. }
  5552. };
  5553. for k in 0..count {
  5554. let rel = k.wrapping_sub(u32::from(first));
  5555. match words.iter().find(|w| w.0 == rel) {
  5556. Some(&(_, x)) => self.write(inst, Reg::S(code + k as u8), x, None),
  5557. None => {
  5558. if let Some(v) = inst.write(Reg::S(code + k as u8)) {
  5559. self.vals.insert(v, Val::Missing(OTHER));
  5560. self.stale.insert(v);
  5561. }
  5562. }
  5563. }
  5564. }
  5565. Ok(())
  5566. }
  5567. /// `s_load_dword*` from the program's constant table.
  5568. fn code_smem(&mut self, inst: &Inst, a: Address) -> Result<(), Why> {
  5569. let Fields::Smem {
  5570. data: Some(Operand::Scalar { code, .. }),
  5571. ..
  5572. } = inst.fields
  5573. else {
  5574. return Err("a scalar load");
  5575. };
  5576. let count = match inst.name().strip_prefix("s_load_dword") {
  5577. Some("") => 1u32,
  5578. Some("x2") => 2,
  5579. Some("x4") => 4,
  5580. Some("x8") => 8,
  5581. Some("x16") => 16,
  5582. _ => return Err("a scalar load from the code"),
  5583. };
  5584. let c = self.cur;
  5585. let mut addr = self.s.m.i32(a.offset);
  5586. if let Some(value) = a.dynamic {
  5587. let mut d = self.i32_of(value)?;
  5588. // A term held per lane reached the address through
  5589. // `v_readfirstlane_b32`: the first lane's.
  5590. let per_lane = self.def_block.get(&value).is_some_and(|&b| {
  5591. let writes = |i: &Inst| i.writes.iter().any(|w| w.1 == value && matches!(w.0, Reg::V(_)));
  5592. self.x.p.blocks[b].insts.iter().any(writes)
  5593. });
  5594. if per_lane {
  5595. self.s.flags |= flags::WAVE_OPS;
  5596. let i32t = self.s.t.i32;
  5597. d = self.s.op(c, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[d]);
  5598. }
  5599. addr = self.s.m.bin(c, Bin::Add, addr, d);
  5600. }
  5601. for k in 0..count {
  5602. let off = self.s.m.i32(4 * k);
  5603. let at = self.s.m.bin(c, Bin::Add, addr, off);
  5604. let x = self.code_dword(at)?;
  5605. self.write(inst, Reg::S(code + k as u8), x, None);
  5606. }
  5607. Ok(())
  5608. }
  5609. /// The dword at a computed byte address of a constant buffer.
  5610. fn cbuffer_dword(&mut self, h: V, a: V) -> V {
  5611. let c = self.cur;
  5612. let four = self.s.m.i32(4);
  5613. let ri = self.s.m.bin(c, Bin::LShr, a, four);
  5614. let r = self.s.op(
  5615. c,
  5616. "cbufferLoadLegacy.i32",
  5617. Attr::ReadOnly,
  5618. self.s.t.cbuf_ret,
  5619. 59,
  5620. &[h, ri],
  5621. );
  5622. let two = self.s.m.i32(2);
  5623. let three = self.s.m.i32(3);
  5624. let comp = self.s.m.bin(c, Bin::LShr, a, two);
  5625. let comp = self.s.m.bin(c, Bin::And, comp, three);
  5626. let mut x = self.s.m.extract(c, r, 0);
  5627. for j in 1..4 {
  5628. let e = self.s.m.extract(c, r, j);
  5629. let jc = self.s.m.i32(j);
  5630. let is = self.s.m.cmp(c, pred::EQ, comp, jc);
  5631. x = self.s.m.select(c, is, e, x);
  5632. }
  5633. x
  5634. }
  5635. /// `channels` channels of the element at byte `off` of raw buffer `h`,
  5636. /// converted from the GFX10 buffer format `format` as the hardware's
  5637. /// typed loads do (channels past the format's read 0, 0, 0, 1).
  5638. // shortcut: the descriptor's channel swizzle is taken as the identity
  5639. // (it is for raw views and the descriptors code builds), elements of 4
  5640. // bytes or more as dword-aligned. Norm formats divide, which the AMD
  5641. // driver does 1 ULP off the hardware's correctly rounded conversion for
  5642. // some values; correct it with an integer check if a title compares
  5643. // converted values exactly.
  5644. fn format_load(&mut self, h: V, off: V, format: u8, channels: u32) -> Result<Vec<V>, Why> {
  5645. let (bits, numeric) = buffer_format(format).ok_or("a buffer format")?;
  5646. let c = self.cur;
  5647. let total: u32 = bits.iter().sum();
  5648. let (u, align) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
  5649. let load = |l: &mut Self, at: V, n: u32| -> Vec<V> {
  5650. let mask = l.s.m.i8((1u8 << n) - 1);
  5651. let r = l.s.op(
  5652. c,
  5653. "rawBufferLoad.f32",
  5654. Attr::ReadOnly,
  5655. l.s.t.res_ret,
  5656. 139,
  5657. &[h, at, u, mask, align],
  5658. );
  5659. (0..n)
  5660. .map(|k| {
  5661. let x = l.s.m.extract(c, r, k);
  5662. l.as_int(x)
  5663. })
  5664. .collect()
  5665. };
  5666. let words = if total < 32 {
  5667. // A byte or half inside the dword that holds it.
  5668. let (not3, three) = (self.s.m.i32(!3), self.s.m.i32(3));
  5669. let at = self.s.m.bin(c, Bin::And, off, not3);
  5670. let w = load(self, at, 1)[0];
  5671. let byte = self.s.m.bin(c, Bin::And, off, three);
  5672. let sh = self.s.m.bin(c, Bin::Shl, byte, three);
  5673. vec![self.s.m.bin(c, Bin::LShr, w, sh)]
  5674. } else {
  5675. load(self, off, total / 32)
  5676. };
  5677. let float = |l: &mut Self, f: V| l.as_int(f);
  5678. let mut out = Vec::new();
  5679. let mut at = 0;
  5680. for &w in bits {
  5681. let word = words[(at / 32) as usize];
  5682. let field = if w == 32 {
  5683. word
  5684. } else {
  5685. let sh = self.s.m.i32(at % 32);
  5686. let t = self.s.m.bin(c, Bin::LShr, word, sh);
  5687. let m = self.s.m.i32((1 << w) - 1);
  5688. self.s.m.bin(c, Bin::And, t, m)
  5689. };
  5690. at += w;
  5691. // Sign-extended from the field's top bit.
  5692. let signed = |l: &mut Self| {
  5693. if w == 32 {
  5694. return field;
  5695. }
  5696. let k = l.s.m.i32(32 - w);
  5697. let t = l.s.m.bin(c, Bin::Shl, field, k);
  5698. l.s.m.bin(c, Bin::AShr, t, k)
  5699. };
  5700. let f32t = self.s.t.f32;
  5701. let x = match numeric {
  5702. Numeric::Unorm => {
  5703. let f = self.s.m.cast(c, Cast::UiToFp, field, f32t);
  5704. let max = self.s.m.f32((((1u64 << w) - 1) as f32).to_bits());
  5705. let q = self.s.m.bin(c, Bin::SDiv, f, max);
  5706. float(self, q)
  5707. }
  5708. Numeric::Snorm => {
  5709. let s = signed(self);
  5710. let f = self.s.m.cast(c, Cast::SiToFp, s, f32t);
  5711. let max = self.s.m.f32((((1u64 << (w - 1)) - 1) as f32).to_bits());
  5712. let q = self.s.m.bin(c, Bin::SDiv, f, max);
  5713. let lo = self.s.m.f32((-1.0f32).to_bits());
  5714. let q = self.binary(35, q, lo);
  5715. float(self, q)
  5716. }
  5717. Numeric::Uscaled => {
  5718. let f = self.s.m.cast(c, Cast::UiToFp, field, f32t);
  5719. float(self, f)
  5720. }
  5721. Numeric::Sscaled => {
  5722. let s = signed(self);
  5723. let f = self.s.m.cast(c, Cast::SiToFp, s, f32t);
  5724. float(self, f)
  5725. }
  5726. Numeric::Uint => field,
  5727. Numeric::Sint => signed(self),
  5728. Numeric::Float if w == 32 => field,
  5729. Numeric::Float => {
  5730. let h = match half_shift(w) {
  5731. 0 => field,
  5732. k => {
  5733. let sh = self.s.m.i32(k);
  5734. self.s.m.bin(c, Bin::Shl, field, sh)
  5735. }
  5736. };
  5737. let f = self
  5738. .s
  5739. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]);
  5740. float(self, f)
  5741. }
  5742. };
  5743. out.push(x);
  5744. }
  5745. let one = match numeric {
  5746. Numeric::Uint | Numeric::Sint => 1,
  5747. _ => 1.0f32.to_bits(),
  5748. };
  5749. for k in out.len() as u32..channels {
  5750. out.push(self.s.m.i32(if k == 3 { one } else { 0 }));
  5751. }
  5752. out.truncate(channels as usize);
  5753. Ok(out)
  5754. }
  5755. /// The byte offset a buffer descriptor built around a root descriptor adds
  5756. /// (constant and computed parts); none for other descriptors.
  5757. fn built_offset(&mut self, src: &Source) -> Result<(u32, Option<V>), Why> {
  5758. match src {
  5759. Source::Built { address, .. } => {
  5760. let mut x = match address.dynamic {
  5761. Some(v) => Some(self.i32_of(v)?),
  5762. None => None,
  5763. };
  5764. if let Some(bias) = self.root_bias(address.param) {
  5765. x = Some(match x {
  5766. Some(d) => self.s.m.bin(self.cur, Bin::Add, d, bias),
  5767. None => bias,
  5768. });
  5769. }
  5770. Ok((address.offset, x))
  5771. }
  5772. _ => Ok((0, None)),
  5773. }
  5774. }
  5775. /// For a root view the host binds as a raw view that may begin before
  5776. /// the title's address (`shader.rs` `USER_VIEW_BIAS`): the bytes to add
  5777. /// to offsets through it. Every root UAV, and the root SRVs of programs
  5778. /// with a spilled user-data table (the others keep the views they
  5779. /// have).
  5780. fn root_bias(&mut self, param: usize) -> Option<V> {
  5781. use super::shader::USER_VIEW_BIAS;
  5782. let rp = *self.x.native.layout.get(param)?;
  5783. if rp.root != RootType::Descriptor {
  5784. return None;
  5785. }
  5786. let kind = self
  5787. .x
  5788. .native
  5789. .used
  5790. .iter()
  5791. .find(|u| u.user_data == rp.user_data)
  5792. .map(|u| u.kind);
  5793. let biased = match kind {
  5794. Some(ResourceType::Uav) => true,
  5795. Some(ResourceType::Srv) => crate::spill::is_spilled(self.x.native),
  5796. _ => false,
  5797. };
  5798. biased.then(|| self.host_word(RootType::Other(USER_VIEW_BIAS), rp.slot, 0))
  5799. }
  5800. /// The used-resource entry a descriptor loaded from a table falls in.
  5801. fn used_kind(&self, src: &Source) -> Option<&'a UsedResource> {
  5802. if let Source::Phi { args, .. } | Source::Select { args, .. } | Source::Lanes { args, .. } =
  5803. src
  5804. {
  5805. return self.used_kind(args.first()?);
  5806. }
  5807. if let Source::LanePhi { args, .. } = src {
  5808. return args.iter().flatten().find_map(|a| self.used_kind(a));
  5809. }
  5810. if let Source::Built { address, .. } = src {
  5811. let rp = self.x.native.layout.get(address.param)?;
  5812. return self
  5813. .x
  5814. .native
  5815. .used
  5816. .iter()
  5817. .find(|u| u.root == RootType::Descriptor && u.user_data == rp.user_data);
  5818. }
  5819. let (Source::Loaded { load, first } | Source::Fetched { load, first }) = src else {
  5820. return None;
  5821. };
  5822. let a = self.scalar.get(load)?;
  5823. let rp = self.x.native.layout.get(a.param)?;
  5824. if rp.root != RootType::Table {
  5825. return None;
  5826. }
  5827. let dword = (a.offset / 4) + u32::from(*first);
  5828. self.x
  5829. .native
  5830. .used
  5831. .iter()
  5832. .filter(|u| {
  5833. u.root == RootType::Table
  5834. && u.user_data == rp.user_data
  5835. && u.table_offset_dwords <= dword
  5836. })
  5837. .max_by_key(|u| u.table_offset_dwords)
  5838. }
  5839. /// A handle for the descriptor `src` read at `site`.
  5840. fn handle(
  5841. &mut self,
  5842. site: Site,
  5843. src: &Source,
  5844. sampler: bool,
  5845. props: (u32, u32),
  5846. ) -> Result<V, Why> {
  5847. match src {
  5848. Source::Loaded { load, first } => {
  5849. let key = (self.cur, *load, *first, sampler, props);
  5850. if let Some(&h) = self.handles.get(&key) {
  5851. return Ok(h);
  5852. }
  5853. let index = self.heap_index(*load, *first, sampler)?;
  5854. // A waterfall loop's load at the first lane's offset reads
  5855. // each lane's own entry (see `resource::Waterfall`).
  5856. let per_lane = self.x.res.waterfall.loads.contains(load);
  5857. let h = self
  5858. .s
  5859. .heap_handle(self.cur, index, sampler, per_lane, props);
  5860. self.handles.insert(key, h);
  5861. Ok(h)
  5862. }
  5863. Source::Constant(words) if sampler => {
  5864. let words: [u32; 4] = words
  5865. .get(..4)
  5866. .and_then(|w| w.try_into().ok())
  5867. .ok_or("a sampler constant")?;
  5868. let n = match self.samplers.iter().position(|w| *w == words) {
  5869. Some(n) => n,
  5870. None => {
  5871. self.samplers.push(words);
  5872. self.samplers.len() - 1
  5873. }
  5874. };
  5875. if props.0 & 0x8000 != 0 {
  5876. // shortcut: one sampler used with and without comparison
  5877. // would need two static samplers; it becomes a comparison one.
  5878. self.s.cmp_samplers |= 1 << n;
  5879. }
  5880. Ok(self.s.sampler_handle(self.cur, n as u32))
  5881. }
  5882. Source::Constant(_) => Err("a constant resource descriptor"),
  5883. Source::Built { address, .. } => {
  5884. let rp = *self
  5885. .x
  5886. .native
  5887. .layout
  5888. .get(address.param)
  5889. .ok_or("a descriptor built around a table in the code")?;
  5890. let kind = self
  5891. .x
  5892. .native
  5893. .used
  5894. .iter()
  5895. .find(|u| u.user_data == rp.user_data)
  5896. .map(|u| u.kind);
  5897. match (rp.root, kind, props.0) {
  5898. (RootType::Descriptor, Some(ResourceType::Cbv) | None, 13) => {
  5899. Ok(self.s.root_cbv_handle(rp.slot))
  5900. }
  5901. (RootType::Descriptor, Some(ResourceType::Srv), 11) => {
  5902. Ok(self.s.root_srv_handle(rp.slot))
  5903. }
  5904. // A root UAV: a raw buffer whether the access reads
  5905. // (11) or writes (11 with the UAV bit). Indexed
  5906. // accesses reach here as raw ones at index times the
  5907. // entry's stride (`buffer`).
  5908. (RootType::Descriptor, Some(ResourceType::Uav), 11 | 0x100b) => {
  5909. Ok(self.s.root_uav_handle(rp.slot))
  5910. }
  5911. (RootType::Descriptor, Some(ResourceType::Srv), 0x100b) => {
  5912. Err("a write through a root SRV")
  5913. }
  5914. _ => Err("a typed root view"),
  5915. }
  5916. }
  5917. Source::Phi { block, args } => {
  5918. let _ = site;
  5919. let phi = self.descriptor_phi(*block, args, sampler, 8)?;
  5920. Ok(self.s.heap_handle(self.cur, phi, sampler, false, props))
  5921. }
  5922. Source::Select { scc, args } => {
  5923. // The heap index of each choice, picked by SCC (uniform).
  5924. let [
  5925. Source::Loaded { load: a, first: fa },
  5926. Source::Loaded { load: b, first: fb },
  5927. ] = args[..]
  5928. else {
  5929. return Err("a descriptor chosen by a condition");
  5930. };
  5931. let cond = match self.get(*scc)? {
  5932. Val::Bit(x) => x,
  5933. _ => return Err("SCC without a value"),
  5934. };
  5935. let set = self.heap_index(a, fa, sampler)?;
  5936. let clear = self.heap_index(b, fb, sampler)?;
  5937. let index = self.s.m.select(self.cur, cond, set, clear);
  5938. Ok(self.s.heap_handle(self.cur, index, sampler, false, props))
  5939. }
  5940. Source::Fetched { .. } | Source::Lanes { .. } | Source::LanePhi { .. } => {
  5941. // A descriptor each lane has its own of (a waterfall loop
  5942. // reads it from the first active lane): each lane's heap
  5943. // index, non-uniform.
  5944. let index = self.lane_heap_index(src, sampler)?;
  5945. Ok(self.s.heap_handle(self.cur, index, sampler, true, props))
  5946. }
  5947. }
  5948. }
  5949. /// The heap index a descriptor phi picks. Each predecessor computes its
  5950. /// heap index at its end and the join picks one with a phi; a
  5951. /// predecessor whose descriptor is itself chosen by control flow (a
  5952. /// phi of an earlier join, which dominates it) gives that join's phi,
  5953. /// at most `depth` joins deep.
  5954. fn descriptor_phi(
  5955. &mut self,
  5956. block: usize,
  5957. args: &[Source],
  5958. sampler: bool,
  5959. depth: u32,
  5960. ) -> Result<V, Why> {
  5961. const WHY: Why = "a descriptor chosen by control flow";
  5962. let p = self.x.p;
  5963. let mut incoming = Vec::new();
  5964. for (&q, arg) in p.blocks[block].preds.iter().zip(args) {
  5965. if self.block[q].is_none() {
  5966. continue;
  5967. }
  5968. let tail = self.tail[q].ok_or(WHY)?;
  5969. let at = self.edges.get(&(q, block)).copied().unwrap_or(tail);
  5970. let index = match arg {
  5971. Source::Loaded { load, first } => {
  5972. let here = std::mem::replace(&mut self.cur, at);
  5973. let index = self.heap_index(*load, *first, sampler);
  5974. self.cur = here;
  5975. index?
  5976. }
  5977. Source::Phi { block: inner, args: inner_args } if depth > 0 => {
  5978. self.descriptor_phi(*inner, inner_args, sampler, depth - 1)?
  5979. }
  5980. _ => return Err(WHY),
  5981. };
  5982. incoming.push((index, at));
  5983. }
  5984. let join = self.block[block].ok_or(WHY)?;
  5985. let phi = self.s.m.phi(join, self.s.t.i32);
  5986. self.s.m.set_phi(phi, incoming);
  5987. Ok(phi)
  5988. }
  5989. /// The bytes per element of the buffer view `src` names, if the program
  5990. /// picks it from the view heap at an index it computes (root type
  5991. /// `ResourceHeap`): read from the host's table by heap slot in the
  5992. /// current block.
  5993. fn slot_stride(&mut self, src: &Source) -> Result<Option<V>, Why> {
  5994. let Source::Loaded { load, first } = src else {
  5995. return Ok(None);
  5996. };
  5997. let heap = self
  5998. .scalar
  5999. .get(load)
  6000. .and_then(|a| self.x.native.layout.get(a.param))
  6001. .is_some_and(|p| p.root == RootType::ResourceHeap);
  6002. if !heap {
  6003. return Ok(None);
  6004. }
  6005. let key = (self.cur, *load, *first);
  6006. if let Some(&v) = self.strides.get(&key) {
  6007. return Ok(Some(v));
  6008. }
  6009. let c = self.cur;
  6010. let slot = self.heap_index(*load, *first, false)?;
  6011. // Inside the table whatever the index (lanes that do not run
  6012. // compute one too): a root view has no bounds of its own.
  6013. let last = self.s.m.i32(super::shader::SLOT_STRIDES_COUNT - 1);
  6014. let i32t = self.s.t.i32;
  6015. let slot = self.s.op(c, "binary.i32", Attr::ReadNone, i32t, 40, &[slot, last]);
  6016. let two = self.s.m.i32(2);
  6017. let byte = self.s.m.bin(c, Bin::Shl, slot, two);
  6018. let h = self.s.root_srv_handle(super::shader::SLOT_STRIDES);
  6019. let iu = self.s.m.undef(self.s.t.i32);
  6020. let mask = self.s.m.i8(1);
  6021. let align = self.s.m.i32(4);
  6022. let r = self.s.op(
  6023. c,
  6024. "rawBufferLoad.f32",
  6025. Attr::ReadOnly,
  6026. self.s.t.res_ret,
  6027. 139,
  6028. &[h, byte, iu, mask, align],
  6029. );
  6030. let f = self.s.m.extract(c, r, 0);
  6031. let v = self.as_int(f);
  6032. self.strides.insert(key, v);
  6033. Ok(Some(v))
  6034. }
  6035. /// The heap index of a descriptor that may differ between lanes,
  6036. /// computed in the current block (or, chosen by control flow, at the
  6037. /// join).
  6038. fn lane_heap_index(&mut self, src: &Source, sampler: bool) -> Result<V, Why> {
  6039. match src {
  6040. Source::Loaded { load, first } => self.heap_index(*load, *first, sampler),
  6041. Source::Fetched { load, first } => self.fetched_index(*load, *first, sampler),
  6042. Source::Lanes { mask, args } | Source::Select { scc: mask, args } => {
  6043. let [a, b] = &args[..] else {
  6044. return Err("a descriptor chosen per lane");
  6045. };
  6046. let cond = if matches!(src, Source::Lanes { .. }) {
  6047. let &m = self
  6048. .x
  6049. .st
  6050. .masks
  6051. .get(mask)
  6052. .ok_or("a descriptor chosen per lane by an untracked mask")?;
  6053. self.boolean(m, self.cur)?
  6054. } else {
  6055. match self.get(*mask)? {
  6056. Val::Bit(x) => x,
  6057. _ => return Err("SCC without a value"),
  6058. }
  6059. };
  6060. let set = self.lane_heap_index(a, sampler)?;
  6061. let clear = self.lane_heap_index(b, sampler)?;
  6062. Ok(self.s.m.select(self.cur, cond, set, clear))
  6063. }
  6064. Source::LanePhi { block, args } => {
  6065. // Each predecessor computes its heap index at its end (what
  6066. // it reads is there: the dwords are, on that edge); the join
  6067. // picks the one of the edge the lane came by. An edge no
  6068. // lane reading it takes gives index 0.
  6069. let join =
  6070. self.block[*block].ok_or("a per-lane descriptor chosen by control flow")?;
  6071. let mut incoming = Vec::new();
  6072. for (&q, arg) in self.x.p.blocks[*block].preds.iter().zip(args) {
  6073. if self.block[q].is_none() {
  6074. continue;
  6075. }
  6076. let tail =
  6077. self.tail[q].ok_or("a per-lane descriptor joined from a later block")?;
  6078. let at = self.edges.get(&(q, *block)).copied().unwrap_or(tail);
  6079. let index = match arg {
  6080. Some(arg) => {
  6081. let here = std::mem::replace(&mut self.cur, at);
  6082. let index = self.lane_heap_index(arg, sampler);
  6083. self.cur = here;
  6084. index?
  6085. }
  6086. None => self.s.m.i32(0),
  6087. };
  6088. incoming.push((index, at));
  6089. }
  6090. let phi = self.s.m.phi(join, self.s.t.i32);
  6091. self.s.m.set_phi(phi, incoming);
  6092. Ok(phi)
  6093. }
  6094. _ => Err("a per-lane descriptor from neither a heap load nor a choice of them"),
  6095. }
  6096. }
  6097. /// The heap index of the descriptor at dword `first` of what the global
  6098. /// load at `load` reads, in each lane: its address (base plus offsets)
  6099. /// over the descriptor size.
  6100. fn fetched_index(&mut self, load: Site, first: u8, sampler: bool) -> Result<V, Why> {
  6101. const WHY: Why = "a per-lane descriptor load";
  6102. let a = *self
  6103. .scalar
  6104. .get(&load)
  6105. .ok_or("an untracked descriptor load")?;
  6106. match self.x.native.layout.get(a.param).map(|p| p.root) {
  6107. Some(RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap) => {}
  6108. _ => return Err("a descriptor outside the heaps"),
  6109. }
  6110. let li: &Inst = &self.x.p.blocks[load.0].insts[load.1];
  6111. let Fields::Flat {
  6112. addr: Some(Operand::Vector { reg, .. }),
  6113. saddr,
  6114. offset,
  6115. ..
  6116. } = li.fields
  6117. else {
  6118. return Err(WHY);
  6119. };
  6120. let c = self.cur;
  6121. // The low dword of the address: SGPR base plus VGPR offset, or the
  6122. // VGPR pair's low half (heap addresses fit in 32 bits).
  6123. let mut at = self.i32_of(li.read(Reg::V(reg)).ok_or(WHY)?)?;
  6124. if let Some(Operand::Scalar { code, .. }) = saddr
  6125. && code != NULL
  6126. {
  6127. let base = self.i32_of(li.read(Reg::S(code)).ok_or(WHY)?)?;
  6128. at = self.s.m.bin(c, Bin::Add, base, at);
  6129. }
  6130. let k = self
  6131. .s
  6132. .m
  6133. .i32((offset as i32 as u32).wrapping_add(4 * u32::from(first)));
  6134. at = self.s.m.bin(c, Bin::Add, at, k);
  6135. let shift = self.s.m.i32(if sampler { 4 } else { 5 });
  6136. Ok(self.s.m.bin(c, Bin::LShr, at, shift))
  6137. }
  6138. /// The heap index of the descriptor at dword `first` of what the scalar
  6139. /// load at `load` reads, computed in the current block.
  6140. fn heap_index(&mut self, load: Site, first: u8, sampler: bool) -> Result<V, Why> {
  6141. let a = *self
  6142. .scalar
  6143. .get(&load)
  6144. .ok_or("an untracked descriptor load")?;
  6145. match self.x.native.layout.get(a.param).map(|p| p.root) {
  6146. Some(RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap) => {}
  6147. _ => return Err("a descriptor outside the heaps"),
  6148. }
  6149. let li: &Inst = &self.x.p.blocks[load.0].insts[load.1];
  6150. let Fields::Smem {
  6151. base,
  6152. offset,
  6153. soffset,
  6154. ..
  6155. } = &li.fields
  6156. else {
  6157. return Err("a descriptor load");
  6158. };
  6159. let Operand::Scalar { code, .. } = *base else {
  6160. return Err("a descriptor load");
  6161. };
  6162. let c = self.cur;
  6163. let base = li.read(Reg::S(code)).ok_or("a descriptor load")?;
  6164. let mut addr = self.i32_of(base)?;
  6165. let k = self
  6166. .s
  6167. .m
  6168. .i32((*offset as u32).wrapping_add(4 * u32::from(first)));
  6169. addr = self.s.m.bin(c, Bin::Add, addr, k);
  6170. if !matches!(soffset, Operand::Scalar { code: NULL, .. }) {
  6171. let so = self.operand(li, soffset)?;
  6172. addr = self.s.m.bin(c, Bin::Add, addr, so);
  6173. }
  6174. let shift = self.s.m.i32(if sampler { 4 } else { 5 });
  6175. Ok(self.s.m.bin(c, Bin::LShr, addr, shift))
  6176. }
  6177. fn valu(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  6178. let Fields::Valu(v) = &inst.fields else {
  6179. unreachable!()
  6180. };
  6181. let name = inst.name();
  6182. if self.x.res.waterfall.compares.contains(&(b, i)) {
  6183. // The first lane's dwords of a waterfall loop are each lane's
  6184. // own (see `resource::Waterfall`).
  6185. self.lane(inst, Some(true));
  6186. return Ok(());
  6187. }
  6188. if let Some(rest) = name.strip_prefix("v_cmp_").or(name.strip_prefix("v_cmpx_")) {
  6189. let r = if v.dpp.is_some() {
  6190. Err("a compare with DPP")
  6191. } else {
  6192. self.compare(inst, rest)
  6193. };
  6194. if let Err(why) = r {
  6195. for &(_, w) in &inst.writes {
  6196. self.lane_fail.insert(w, why);
  6197. }
  6198. }
  6199. return r;
  6200. }
  6201. let mut guard = self.guard(b, i)?;
  6202. if let Some(d) = v.dpp {
  6203. let (x, enable) = self.dpp(inst, d)?;
  6204. guard = match (guard, enable) {
  6205. (Some(g), Some(e)) => Some(self.s.m.bin(self.cur, Bin::And, g, e)),
  6206. (g, e) => g.or(e),
  6207. };
  6208. self.src0 = Some(x);
  6209. }
  6210. let r = self.valu_op(inst, guard);
  6211. self.src0 = None;
  6212. r
  6213. }
  6214. /// DPP: src0 as read from another lane, and which lanes write their
  6215. /// result (none: all).
  6216. fn dpp(&mut self, inst: &Inst, dpp: Dpp) -> Result<(V, Option<V>), Why> {
  6217. let Fields::Valu(v) = &inst.fields else {
  6218. unreachable!()
  6219. };
  6220. let Some(&Operand::Vector { reg, .. }) = v.src.first() else {
  6221. return Err("a DPP operand");
  6222. };
  6223. let x = self.i32_of(inst.read(Reg::V(reg)).ok_or("a DPP operand")?)?;
  6224. // Quad permutations and DPP8 stay in groups the pixel layout shares.
  6225. let quad = matches!(dpp, Dpp::Row { ctrl: 0..=0xFF, .. });
  6226. let mesh_quad = self.s.mesh.is_some() && quad;
  6227. if !mesh_quad {
  6228. self.cross_lane(quad)?;
  6229. }
  6230. let c = self.cur;
  6231. let lane = self.lane_index();
  6232. let k = |l: &mut Self, n: u32| l.s.m.i32(n);
  6233. let (sixteen_mask, low) = (k(self, !15), k(self, 15));
  6234. let row = self.s.m.bin(c, Bin::And, lane, sixteen_mask);
  6235. let pos = self.s.m.bin(c, Bin::And, lane, low);
  6236. // Source lane, and whether it lies in the row.
  6237. let (src, inside, masks, zero) = match dpp {
  6238. Dpp::Lanes { sel, .. } => {
  6239. let (seven, not7, three) = (k(self, 7), k(self, !7), k(self, 3));
  6240. let p = self.s.m.bin(c, Bin::And, lane, seven);
  6241. let sh = self.s.m.bin(c, Bin::Mul, p, three);
  6242. let sel = k(self, sel);
  6243. let pick = self.s.m.bin(c, Bin::LShr, sel, sh);
  6244. let pick = self.s.m.bin(c, Bin::And, pick, seven);
  6245. let base = self.s.m.bin(c, Bin::And, lane, not7);
  6246. (self.s.m.bin(c, Bin::Or, base, pick), None, None, false)
  6247. }
  6248. Dpp::Row {
  6249. ctrl,
  6250. row_mask,
  6251. bank_mask,
  6252. bound_ctrl,
  6253. ..
  6254. } => {
  6255. let n = u32::from(ctrl & 15);
  6256. let (src, inside) = match ctrl {
  6257. 0..=0xFF => {
  6258. let (three, one, not3) = (k(self, 3), k(self, 1), k(self, !3));
  6259. let p = self.s.m.bin(c, Bin::And, lane, three);
  6260. let sh = self.s.m.bin(c, Bin::Shl, p, one);
  6261. let perm = k(self, u32::from(ctrl));
  6262. let pick = self.s.m.bin(c, Bin::LShr, perm, sh);
  6263. let pick = self.s.m.bin(c, Bin::And, pick, three);
  6264. let base = self.s.m.bin(c, Bin::And, lane, not3);
  6265. (self.s.m.bin(c, Bin::Or, base, pick), None)
  6266. }
  6267. 0x101..=0x10F | 0x111..=0x11F => {
  6268. let nn = k(self, n);
  6269. let left = ctrl < 0x110;
  6270. let (op, p) = if left {
  6271. (Bin::Add, pred::IULT)
  6272. } else {
  6273. (Bin::Sub, pred::IUGE)
  6274. };
  6275. let s = self.s.m.bin(c, op, lane, nn);
  6276. // Left: pos + n < 16; right: pos >= n.
  6277. let bound = if left { k(self, 16 - n) } else { nn };
  6278. (s, Some(self.s.m.cmp(c, p, pos, bound)))
  6279. }
  6280. 0x121..=0x12F => {
  6281. let nn = k(self, n);
  6282. let t = self.s.m.bin(c, Bin::Sub, pos, nn);
  6283. let t = self.s.m.bin(c, Bin::And, t, low);
  6284. (self.s.m.bin(c, Bin::Or, row, t), None)
  6285. }
  6286. 0x140 | 0x141 => {
  6287. let m = k(self, if ctrl == 0x140 { 15 } else { 7 });
  6288. let t = self.s.m.bin(c, Bin::Xor, lane, m);
  6289. (t, None)
  6290. }
  6291. 0x150..=0x15F => {
  6292. let nn = k(self, n);
  6293. (self.s.m.bin(c, Bin::Or, row, nn), None)
  6294. }
  6295. 0x160..=0x16F => {
  6296. let nn = k(self, n);
  6297. (self.s.m.bin(c, Bin::Xor, lane, nn), None)
  6298. }
  6299. _ => return Err("a DPP lane pattern"),
  6300. };
  6301. let masks = (row_mask != 0xF || bank_mask != 0xF).then_some((row_mask, bank_mask));
  6302. (src, inside, masks, bound_ctrl)
  6303. }
  6304. };
  6305. let mut r = if mesh_quad {
  6306. self.quad_pick(x, src)
  6307. } else {
  6308. self.read_lane(x, src)
  6309. };
  6310. let mut enable = None;
  6311. if let Some(inside) = inside {
  6312. if zero {
  6313. let z = k(self, 0);
  6314. r = self.s.m.select(c, inside, r, z);
  6315. } else {
  6316. enable = Some(inside);
  6317. }
  6318. }
  6319. if let Some((rows, banks)) = masks {
  6320. // Row (16 lanes) and bank (4 lanes of a row) write masks.
  6321. let (four, two, three) = (k(self, 4), k(self, 2), k(self, 3));
  6322. let ri = self.s.m.bin(c, Bin::LShr, lane, four);
  6323. let ri = self.s.m.bin(c, Bin::And, ri, three);
  6324. let bi = self.s.m.bin(c, Bin::LShr, lane, two);
  6325. let bi = self.s.m.bin(c, Bin::And, bi, three);
  6326. let (rm, bm) = (k(self, u32::from(rows)), k(self, u32::from(banks)));
  6327. let rb = self.s.m.bin(c, Bin::LShr, rm, ri);
  6328. let bb = self.s.m.bin(c, Bin::LShr, bm, bi);
  6329. let both = self.s.m.bin(c, Bin::And, rb, bb);
  6330. let (one, z) = (k(self, 1), k(self, 0));
  6331. let both = self.s.m.bin(c, Bin::And, both, one);
  6332. let on = self.s.m.cmp(c, pred::NE, both, z);
  6333. enable = Some(match enable {
  6334. Some(e) => self.s.m.bin(c, Bin::And, e, on),
  6335. None => on,
  6336. });
  6337. }
  6338. Ok((r, enable))
  6339. }
  6340. fn valu_op(&mut self, inst: &Inst, guard: Option<V>) -> Result<(), Why> {
  6341. let Fields::Valu(v) = &inst.fields else {
  6342. unreachable!()
  6343. };
  6344. let name = inst.name();
  6345. let c = self.cur;
  6346. let f = |l: &mut Self, k| l.fsrc(inst, k);
  6347. let s = |l: &mut Self, k| l.src(inst, k);
  6348. let float = |l: &mut Self, r: V| l.write_f(inst, r, guard);
  6349. let int = |l: &mut Self, r: V| l.write_i(inst, r, guard);
  6350. if let Some(r) = self.valu16(inst, name, guard) {
  6351. return r;
  6352. }
  6353. if let Some(op) = name.strip_prefix("v_pk_") {
  6354. return self.packed16(inst, op, guard);
  6355. }
  6356. match name {
  6357. "v_mad_u64_u32" => {
  6358. // a * b + c, c and the result 64 bits wide; the carry out
  6359. // of the sum is this lane's bit of the mask it names.
  6360. let (a, b) = (s(self, 0)?, s(self, 1)?);
  6361. let x = self.src64(inst, 2)?;
  6362. let i64t = self.s.m.int(64);
  6363. self.s.flags |= flags::INT64;
  6364. let a = self.s.m.cast(c, Cast::ZExt, a, i64t);
  6365. let b = self.s.m.cast(c, Cast::ZExt, b, i64t);
  6366. let product = self.s.m.bin(c, Bin::Mul, a, b);
  6367. let r = self.s.m.bin(c, Bin::Add, product, x);
  6368. let carry = self.s.m.cmp(c, pred::IULT, r, x);
  6369. let Some(Operand::Vector { reg, .. }) = v.dst else {
  6370. return Err("a 64-bit result");
  6371. };
  6372. let (lo, hi) = self.split64(r);
  6373. self.write(inst, Reg::V(reg), lo, guard);
  6374. self.write(inst, Reg::V(reg + 1), hi, guard);
  6375. if let Some(Operand::Scalar { code, .. }) = v.carry
  6376. && let Some(w) = inst.write(Reg::S(code))
  6377. {
  6378. self.lane_bits.insert(w, carry);
  6379. }
  6380. for &(_, w) in &inst.writes {
  6381. self.vals
  6382. .entry(w)
  6383. .or_insert(Val::Missing("a lane mask read as data"));
  6384. }
  6385. Ok(())
  6386. }
  6387. "v_lshlrev_b64" | "v_lshrrev_b64" | "v_ashrrev_i64" => {
  6388. let n = s(self, 0)?;
  6389. let x = self.src64(inst, 1)?;
  6390. let i64t = self.s.m.int(64);
  6391. let k63 = self.s.m.i32(63);
  6392. let n = self.s.m.bin(c, Bin::And, n, k63);
  6393. let n = self.s.m.cast(c, Cast::ZExt, n, i64t);
  6394. let op = match name {
  6395. "v_lshlrev_b64" => Bin::Shl,
  6396. "v_lshrrev_b64" => Bin::LShr,
  6397. _ => Bin::AShr,
  6398. };
  6399. let r = self.s.m.bin(c, op, x, n);
  6400. let Some(Operand::Vector { reg, .. }) = v.dst else {
  6401. return Err("a 64-bit result");
  6402. };
  6403. let (lo, hi) = self.split64(r);
  6404. self.write(inst, Reg::V(reg), lo, guard);
  6405. self.write(inst, Reg::V(reg + 1), hi, guard);
  6406. Ok(())
  6407. }
  6408. "v_cubeid_f32" | "v_cubesc_f32" | "v_cubetc_f32" | "v_cubema_f32" => {
  6409. // Cube-map face coordinates (AMD's ISA): the major axis is z
  6410. // when |z| >= |x| and |z| >= |y|, else y when |y| >= |x|,
  6411. // else x.
  6412. let (x, y, z) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  6413. let (ax, ay, az) = (self.unary(6, x), self.unary(6, y), self.unary(6, z));
  6414. let zx = self.s.m.cmp(c, pred::OGE, az, ax);
  6415. let zy = self.s.m.cmp(c, pred::OGE, az, ay);
  6416. let zmaj = self.s.m.bin(c, Bin::And, zx, zy);
  6417. let ymaj = self.s.m.cmp(c, pred::OGE, ay, ax);
  6418. let zero = self.s.m.f32(0);
  6419. let neg = |l: &mut Self, v: V| l.s.m.cmp(c, pred::OLT, v, zero);
  6420. let minus = |l: &mut Self, v: V| {
  6421. let z = l.s.m.f32(0x8000_0000);
  6422. l.s.m.bin(c, Bin::Sub, z, v)
  6423. };
  6424. let pick = |l: &mut Self, zv: V, yv: V, xv: V| {
  6425. let t = l.s.m.select(c, ymaj, yv, xv);
  6426. l.s.m.select(c, zmaj, zv, t)
  6427. };
  6428. let r = match name {
  6429. "v_cubeid_f32" => {
  6430. let k = |l: &mut Self, v: f32| l.s.m.f32(v.to_bits());
  6431. let (nz, ny, nx) = (neg(self, z), neg(self, y), neg(self, x));
  6432. let (f5, f4, f3, f2, f1, f0) = (
  6433. k(self, 5.0),
  6434. k(self, 4.0),
  6435. k(self, 3.0),
  6436. k(self, 2.0),
  6437. k(self, 1.0),
  6438. k(self, 0.0),
  6439. );
  6440. let zf = self.s.m.select(c, nz, f5, f4);
  6441. let yf = self.s.m.select(c, ny, f3, f2);
  6442. let xf = self.s.m.select(c, nx, f1, f0);
  6443. pick(self, zf, yf, xf)
  6444. }
  6445. "v_cubesc_f32" => {
  6446. let (nz, nx) = (neg(self, z), neg(self, x));
  6447. let (mx, mz) = (minus(self, x), minus(self, z));
  6448. let zf = self.s.m.select(c, nz, mx, x);
  6449. let xf = self.s.m.select(c, nx, z, mz);
  6450. pick(self, zf, x, xf)
  6451. }
  6452. "v_cubetc_f32" => {
  6453. let ny = neg(self, y);
  6454. let (my, mz) = (minus(self, y), minus(self, z));
  6455. let yf = self.s.m.select(c, ny, mz, z);
  6456. pick(self, my, yf, my)
  6457. }
  6458. _ => {
  6459. let t = pick(self, z, y, x);
  6460. let two = self.s.m.f32(2.0f32.to_bits());
  6461. self.s.m.bin(c, Bin::Mul, t, two)
  6462. }
  6463. };
  6464. float(self, r)
  6465. }
  6466. "v_movrels_b32" | "v_movreld_b32" | "v_movrelsd_b32" => {
  6467. // M0 indexes the source (movrels), the destination (movreld)
  6468. // or both, from the encoded register up to the program's
  6469. // VGPR count (the registers the instruction reads or writes).
  6470. let m0 = self.i32_of(inst.read(Reg::S(crate::ir::M0)).ok_or("M0")?)?;
  6471. let (
  6472. Some(&Operand::Vector { reg: sreg, .. }),
  6473. Some(Operand::Vector { reg: dreg, .. }),
  6474. ) = (v.src.first(), v.dst)
  6475. else {
  6476. return Err("an M0-relative move");
  6477. };
  6478. let indexed_src = name != "v_movreld_b32";
  6479. let value = if indexed_src {
  6480. let mut r = self.s.m.i32(0);
  6481. for k in 0..=255u8.saturating_sub(sreg) {
  6482. let Some(x) = inst.read(Reg::V(sreg + k)) else {
  6483. break;
  6484. };
  6485. let x = self.i32_of(x)?;
  6486. let kk = self.s.m.i32(u32::from(k));
  6487. let is = self.s.m.cmp(c, pred::EQ, m0, kk);
  6488. r = self.s.m.select(c, is, x, r);
  6489. }
  6490. r
  6491. } else {
  6492. s(self, 0)?
  6493. };
  6494. if name == "v_movrels_b32" {
  6495. return int(self, value);
  6496. }
  6497. for k in 0..=255u8.saturating_sub(dreg) {
  6498. let Some(_) = inst.write(Reg::V(dreg + k)) else {
  6499. break;
  6500. };
  6501. let old = match inst.read(Reg::V(dreg + k)) {
  6502. Some(o) => self.i32_of(o)?,
  6503. None => self.s.m.i32(0),
  6504. };
  6505. let kk = self.s.m.i32(u32::from(k));
  6506. let is = self.s.m.cmp(c, pred::EQ, m0, kk);
  6507. let x = self.s.m.select(c, is, value, old);
  6508. self.write_placed(inst, Reg::V(dreg + k), x, guard);
  6509. }
  6510. Ok(())
  6511. }
  6512. "v_swap_b32" => {
  6513. let (
  6514. Some(&Operand::Vector { reg: sreg, .. }),
  6515. Some(Operand::Vector { reg: dreg, .. }),
  6516. ) = (v.src.first(), v.dst)
  6517. else {
  6518. return Err("v_swap_b32");
  6519. };
  6520. let a = self.i32_of(inst.read(Reg::V(dreg)).ok_or("v_swap_b32")?)?;
  6521. let b = self.i32_of(inst.read(Reg::V(sreg)).ok_or("v_swap_b32")?)?;
  6522. self.write_placed(inst, Reg::V(dreg), b, guard);
  6523. if dreg != sreg {
  6524. self.write_placed(inst, Reg::V(sreg), a, guard);
  6525. }
  6526. Ok(())
  6527. }
  6528. "v_ffbh_u32" | "v_ffbh_i32" => {
  6529. // Counted from the top bit, -1 when none (DXIL's too).
  6530. let a = s(self, 0)?;
  6531. let op = if name == "v_ffbh_u32" { 33 } else { 34 };
  6532. let r = self
  6533. .s
  6534. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]);
  6535. int(self, r)
  6536. }
  6537. "v_mov_b32" => {
  6538. if v.abs != 0 || v.neg != 0 || v.clamp || v.omod != 0 {
  6539. let a = f(self, 0)?;
  6540. return float(self, a);
  6541. }
  6542. let a = s(self, 0)?;
  6543. int(self, a)
  6544. }
  6545. "v_add_f32" | "v_sub_f32" | "v_subrev_f32" | "v_mul_f32" | "v_mul_legacy_f32"
  6546. | "v_max_f32" | "v_min_f32" => {
  6547. let (a, bb) = (f(self, 0)?, f(self, 1)?);
  6548. let r = match name {
  6549. "v_add_f32" => self.s.m.bin(c, Bin::Add, a, bb),
  6550. "v_sub_f32" => self.s.m.bin(c, Bin::Sub, a, bb),
  6551. "v_subrev_f32" => self.s.m.bin(c, Bin::Sub, bb, a),
  6552. "v_mul_f32" => self.s.m.bin(c, Bin::Mul, a, bb),
  6553. "v_mul_legacy_f32" => self.legacy_mul(a, bb),
  6554. "v_max_f32" => self.max_min(true, a, bb),
  6555. _ => self.max_min(false, a, bb),
  6556. };
  6557. float(self, r)
  6558. }
  6559. "v_fma_f32" | "v_fmaak_f32" | "v_fmamk_f32" => {
  6560. // shortcut: DXIL has no fused f32 multiply-add; FMad lets the driver fuse.
  6561. let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  6562. let r = self.fmad(a, bb, cc);
  6563. float(self, r)
  6564. }
  6565. "v_div_scale_f32" => {
  6566. // RDNA2 ISA: src0 = value to scale, src1 = denominator, src2 = numerator.
  6567. let (a, den, num) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  6568. let (ai, ni, di) = (self.as_int(a), self.as_int(num), self.as_int(den));
  6569. let (k23, k255, kabs) = (
  6570. self.s.m.i32(23),
  6571. self.s.m.i32(0xFF),
  6572. self.s.m.i32(0x7FFF_FFFF),
  6573. );
  6574. let (zero, k23_exp, k232_exp, k96) = (
  6575. self.s.m.i32(0),
  6576. self.s.m.i32(23),
  6577. self.s.m.i32(232),
  6578. self.s.m.i32(96),
  6579. );
  6580. let exp_of = |l: &mut Self, x: V| {
  6581. let s = l.s.m.bin(c, Bin::LShr, x, k23);
  6582. l.s.m.bin(c, Bin::And, s, k255)
  6583. };
  6584. let (e1, e2) = (exp_of(self, ni), exp_of(self, di));
  6585. let n_abs = self.s.m.bin(c, Bin::And, ni, kabs);
  6586. let d_abs = self.s.m.bin(c, Bin::And, di, kabs);
  6587. let z1 = self.s.m.cmp(c, pred::EQ, n_abs, zero);
  6588. let z2 = self.s.m.cmp(c, pred::EQ, d_abs, zero);
  6589. let any_zero = self.s.m.bin(c, Bin::Or, z1, z2);
  6590. let special = {
  6591. let s1 = self.s.m.cmp(c, pred::EQ, e1, k255);
  6592. let s2 = self.s.m.cmp(c, pred::EQ, e2, k255);
  6593. let a12 = self.s.m.bin(c, Bin::Or, s1, s2);
  6594. self.s.m.bin(c, Bin::Or, a12, any_zero)
  6595. };
  6596. let is_den = self.s.m.cmp(c, pred::EQ, ai, di);
  6597. let diff = self.s.m.bin(c, Bin::Sub, e2, e1);
  6598. let den_tiny = self.s.m.cmp(c, pred::IULE, e2, k23_exp);
  6599. let den_huge = self.s.m.cmp(c, pred::IUGE, e2, k232_exp);
  6600. let num_tiny_exp = self.s.m.cmp(c, pred::IULE, e1, k23_exp);
  6601. let num_huge = self.s.m.cmp(c, pred::IUGE, e1, k232_exp);
  6602. let num_gap = self.s.m.cmp(c, pred::SGE, diff, k96);
  6603. let not_den_huge = {
  6604. let t = self.s.m.bool(true);
  6605. self.s.m.bin(c, Bin::Xor, den_huge, t)
  6606. };
  6607. let num_gap = self.s.m.bin(c, Bin::And, num_gap, not_den_huge);
  6608. let num_tiny = self.s.m.bin(c, Bin::Or, num_tiny_exp, num_gap);
  6609. let up_raw = self.s.m.select(c, is_den, den_tiny, num_tiny);
  6610. let dn_raw = self.s.m.select(c, is_den, den_huge, num_huge);
  6611. let not_special = {
  6612. let t = self.s.m.bool(true);
  6613. self.s.m.bin(c, Bin::Xor, special, t)
  6614. };
  6615. let up = self.s.m.bin(c, Bin::And, up_raw, not_special);
  6616. let dn = self.s.m.bin(c, Bin::And, dn_raw, not_special);
  6617. let uncancelled = {
  6618. let x_tiny = self.s.m.bin(c, Bin::Xor, den_tiny, num_tiny);
  6619. let x_huge = self.s.m.bin(c, Bin::Xor, den_huge, num_huge);
  6620. self.s.m.bin(c, Bin::Or, x_tiny, x_huge)
  6621. };
  6622. let flag_raw = self.s.m.select(c, is_den, uncancelled, up_raw);
  6623. let flag = self.s.m.bin(c, Bin::And, flag_raw, not_special);
  6624. let k_up = self.s.m.f32(0x5F80_0000);
  6625. let k_dn = self.s.m.f32(0x1F80_0000);
  6626. let a_up = self.s.m.bin(c, Bin::Mul, a, k_up);
  6627. let a_dn = self.s.m.bin(c, Bin::Mul, a, k_dn);
  6628. let r = self.s.m.select(c, dn, a_dn, a);
  6629. let r = self.s.m.select(c, up, a_up, r);
  6630. let qnan = self.s.m.f32(0x7FC0_0000);
  6631. let r = self.s.m.select(c, any_zero, qnan, r);
  6632. float(self, r)?;
  6633. if let Some(Operand::Scalar { code, .. }) = v.carry
  6634. && let Some(w) = inst.write(Reg::S(code))
  6635. {
  6636. self.lane_bits.insert(w, flag);
  6637. }
  6638. for &(_, w) in &inst.writes {
  6639. self.vals
  6640. .entry(w)
  6641. .or_insert(Val::Missing("a lane mask read as data"));
  6642. }
  6643. Ok(())
  6644. }
  6645. "v_div_fmas_f32" => {
  6646. let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  6647. let m = inst
  6648. .read(Reg::S(crate::ir::VCC))
  6649. .and_then(|v| self.x.st.masks.get(&v).copied())
  6650. .ok_or("v_div_fmas_f32 without VCC")?;
  6651. let vcc = self.boolean(m, c)?;
  6652. let tmp = self.fmad(a, bb, cc);
  6653. let ci = self.as_int(cc);
  6654. let (k23, k255, k128) = (self.s.m.i32(23), self.s.m.i32(0xFF), self.s.m.i32(128));
  6655. let sh = self.s.m.bin(c, Bin::LShr, ci, k23);
  6656. let exp = self.s.m.bin(c, Bin::And, sh, k255);
  6657. let exp_ge = self.s.m.cmp(c, pred::IUGE, exp, k128);
  6658. let (k_up, k_dn) = (self.s.m.f32(0x5F80_0000), self.s.m.f32(0x1F80_0000));
  6659. let scale = self.s.m.select(c, exp_ge, k_up, k_dn);
  6660. let scaled = self.s.m.bin(c, Bin::Mul, tmp, scale);
  6661. let r = self.s.m.select(c, vcc, scaled, tmp);
  6662. float(self, r)
  6663. }
  6664. "v_div_fixup_f32" => {
  6665. let (q, den, num) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  6666. let (qi, di, ni) = (self.as_int(q), self.as_int(den), self.as_int(num));
  6667. let (ksign, kabs, kinf) = (
  6668. self.s.m.i32(0x8000_0000),
  6669. self.s.m.i32(0x7FFF_FFFF),
  6670. self.s.m.i32(0x7F80_0000),
  6671. );
  6672. let (kqnan_bit, kneg_qnan, zero) = (
  6673. self.s.m.i32(0x0040_0000),
  6674. self.s.m.i32(0xFFC0_0000),
  6675. self.s.m.i32(0),
  6676. );
  6677. let sign = {
  6678. let x = self.s.m.bin(c, Bin::Xor, ni, di);
  6679. self.s.m.bin(c, Bin::And, x, ksign)
  6680. };
  6681. let q_abs = self.s.m.bin(c, Bin::And, qi, kabs);
  6682. let d_abs = self.s.m.bin(c, Bin::And, di, kabs);
  6683. let n_abs = self.s.m.bin(c, Bin::And, ni, kabs);
  6684. let q_nan = self.s.m.cmp(c, pred::IUGT, q_abs, kinf);
  6685. let d_nan = self.s.m.cmp(c, pred::IUGT, d_abs, kinf);
  6686. let n_nan = self.s.m.cmp(c, pred::IUGT, n_abs, kinf);
  6687. let d_inf = self.s.m.cmp(c, pred::EQ, d_abs, kinf);
  6688. let n_inf = self.s.m.cmp(c, pred::EQ, n_abs, kinf);
  6689. let d_zero = self.s.m.cmp(c, pred::EQ, d_abs, zero);
  6690. let n_zero = self.s.m.cmp(c, pred::EQ, n_abs, zero);
  6691. let both_inf = self.s.m.bin(c, Bin::And, n_inf, d_inf);
  6692. let both_zero = self.s.m.bin(c, Bin::And, n_zero, d_zero);
  6693. let invalid = self.s.m.bin(c, Bin::Or, both_inf, both_zero);
  6694. let make_inf = {
  6695. let t = self.s.m.bin(c, Bin::Or, n_inf, d_zero);
  6696. self.s.m.bin(c, Bin::Or, t, q_nan)
  6697. };
  6698. let make_zero = self.s.m.bin(c, Bin::Or, d_inf, n_zero);
  6699. let signed_q = self.s.m.bin(c, Bin::Or, sign, q_abs);
  6700. let signed_inf = self.s.m.bin(c, Bin::Or, sign, kinf);
  6701. let n_qnan = self.s.m.bin(c, Bin::Or, ni, kqnan_bit);
  6702. let d_qnan = self.s.m.bin(c, Bin::Or, di, kqnan_bit);
  6703. let r = self.s.m.select(c, make_zero, sign, signed_q);
  6704. let r = self.s.m.select(c, make_inf, signed_inf, r);
  6705. let r = self.s.m.select(c, invalid, kneg_qnan, r);
  6706. let r = self.s.m.select(c, d_nan, d_qnan, r);
  6707. let r = self.s.m.select(c, n_nan, n_qnan, r);
  6708. let rf = self.as_float(r);
  6709. float(self, rf)
  6710. }
  6711. "v_fmac_f32" | "v_mac_f32" | "v_mac_legacy_f32" => {
  6712. let (a, bb) = (f(self, 0)?, f(self, 1)?);
  6713. let Some(Operand::Vector { reg, .. }) = v.dst else {
  6714. return Err("an accumulator");
  6715. };
  6716. let acc = inst.read(Reg::V(reg)).ok_or("an accumulator")?;
  6717. let acc = match self.floats.get(&acc) {
  6718. Some(&x) => x,
  6719. None => {
  6720. let x = self.i32_of(acc)?;
  6721. self.as_float(x)
  6722. }
  6723. };
  6724. let r = match name {
  6725. "v_fmac_f32" => self.fmad(a, bb, acc),
  6726. "v_mac_f32" => {
  6727. let m = self.s.m.bin(c, Bin::Mul, a, bb);
  6728. self.s.m.bin(c, Bin::Add, m, acc)
  6729. }
  6730. _ => {
  6731. let m = self.legacy_mul(a, bb);
  6732. self.s.m.bin(c, Bin::Add, m, acc)
  6733. }
  6734. };
  6735. float(self, r)
  6736. }
  6737. "v_mad_f32" | "v_madak_f32" | "v_madmk_f32" | "v_mad_legacy_f32" => {
  6738. let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  6739. let m = if name == "v_mad_legacy_f32" {
  6740. self.legacy_mul(a, bb)
  6741. } else {
  6742. self.s.m.bin(c, Bin::Mul, a, bb)
  6743. };
  6744. let r = self.s.m.bin(c, Bin::Add, m, cc);
  6745. float(self, r)
  6746. }
  6747. "v_max3_f32" | "v_min3_f32" | "v_med3_f32" => {
  6748. let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  6749. let r = match name {
  6750. "v_max3_f32" => {
  6751. let t = self.max_min(true, a, bb);
  6752. self.max_min(true, t, cc)
  6753. }
  6754. "v_min3_f32" => {
  6755. let t = self.max_min(false, a, bb);
  6756. self.max_min(false, t, cc)
  6757. }
  6758. _ => self.med3(a, bb, cc),
  6759. };
  6760. float(self, r)
  6761. }
  6762. "v_rcp_f32" | "v_rcp_iflag_f32" => {
  6763. // shortcut: the hardware reciprocal is approximate (1 ULP); this divides.
  6764. let a = f(self, 0)?;
  6765. let one = self.s.m.f32(1.0f32.to_bits());
  6766. let r = self.s.m.bin(c, Bin::SDiv, one, a);
  6767. float(self, r)
  6768. }
  6769. "v_rsq_f32" | "v_sqrt_f32" | "v_log_f32" | "v_exp_f32" | "v_fract_f32"
  6770. | "v_trunc_f32" | "v_floor_f32" | "v_ceil_f32" | "v_rndne_f32" | "v_sin_f32"
  6771. | "v_cos_f32" => {
  6772. let a = f(self, 0)?;
  6773. let op = match name {
  6774. "v_rsq_f32" => 25,
  6775. "v_sqrt_f32" => 24,
  6776. "v_log_f32" => 23,
  6777. "v_exp_f32" => 21,
  6778. "v_fract_f32" => 22,
  6779. "v_trunc_f32" => 29,
  6780. "v_floor_f32" => 27,
  6781. "v_ceil_f32" => 28,
  6782. "v_rndne_f32" => 26,
  6783. "v_sin_f32" => 13,
  6784. _ => 12,
  6785. };
  6786. let r = match op {
  6787. 12 | 13 => self.trig_turns(a, op == 12),
  6788. 22 => self.fract(a, 1.0, f32::from_bits(0x3F7F_FFFF)),
  6789. _ => self.unary(op, a),
  6790. };
  6791. float(self, r)
  6792. }
  6793. "v_cvt_i32_f32" | "v_cvt_u32_f32" | "v_cvt_flr_i32_f32" | "v_cvt_rpi_i32_f32" => {
  6794. let mut a = f(self, 0)?;
  6795. if name == "v_cvt_rpi_i32_f32" {
  6796. let h = self.s.m.f32(0.5f32.to_bits());
  6797. a = self.s.m.bin(c, Bin::Add, a, h);
  6798. }
  6799. if name != "v_cvt_i32_f32" && name != "v_cvt_u32_f32" {
  6800. a = self.unary(27, a);
  6801. }
  6802. // D3D's conversions saturate and give 0 for NaN, as the
  6803. // hardware does (checked on the RX 6700 XT and WARP).
  6804. let op = if name == "v_cvt_u32_f32" {
  6805. Cast::FpToUi
  6806. } else {
  6807. Cast::FpToSi
  6808. };
  6809. let r = self.s.m.cast(c, op, a, self.s.t.i32);
  6810. int(self, r)
  6811. }
  6812. "v_cvt_f32_i32" | "v_cvt_f32_u32" | "v_cvt_f32_ubyte0" | "v_cvt_f32_ubyte1"
  6813. | "v_cvt_f32_ubyte2" | "v_cvt_f32_ubyte3" => {
  6814. let mut a = s(self, 0)?;
  6815. if let Some(n) = name.strip_prefix("v_cvt_f32_ubyte") {
  6816. let sh = self.s.m.i32(8 * u32::from(n.as_bytes()[0] - b'0'));
  6817. let ff = self.s.m.i32(0xff);
  6818. a = self.s.m.bin(c, Bin::LShr, a, sh);
  6819. a = self.s.m.bin(c, Bin::And, a, ff);
  6820. }
  6821. let op = if name == "v_cvt_f32_i32" {
  6822. Cast::SiToFp
  6823. } else {
  6824. Cast::UiToFp
  6825. };
  6826. let r = self.s.m.cast(c, op, a, self.s.t.f32);
  6827. float(self, r)
  6828. }
  6829. "v_cvt_f32_f64" => {
  6830. let (lo, hi) = self.f64_pair(inst, 0)?;
  6831. let bits = self.f64_to_f32_bits(lo, hi);
  6832. let r = self.as_float(bits);
  6833. float(self, r)
  6834. }
  6835. "v_fma_mix_f32" | "v_fma_mixlo_f16" | "v_fma_mixhi_f16" => {
  6836. // Each source is f32, or with op_sel_hi the low (op_sel: high)
  6837. // f16 half; neg_hi is the absolute value here.
  6838. let mut xs = Vec::new();
  6839. for i in 0..3 {
  6840. let op = v.src.get(i).ok_or("a missing operand")?;
  6841. let mut x = if v.opsel_hi >> i & 1 != 0 {
  6842. let x = self.f16_operand(inst, op)?;
  6843. let h = if v.opsel >> i & 1 != 0 {
  6844. let k16 = self.s.m.i32(16);
  6845. self.s.m.bin(c, Bin::LShr, x, k16)
  6846. } else {
  6847. x
  6848. };
  6849. self.s
  6850. .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[h])
  6851. } else {
  6852. let x = self.operand(inst, op)?;
  6853. self.as_float(x)
  6854. };
  6855. if v.neg_hi >> i & 1 != 0 {
  6856. x = self.unary(6, x);
  6857. }
  6858. if v.neg >> i & 1 != 0 {
  6859. let z = self.s.m.f32(0x8000_0000);
  6860. x = self.s.m.bin(c, Bin::Sub, z, x);
  6861. }
  6862. xs.push(x);
  6863. }
  6864. let mut r = self.fmad(xs[0], xs[1], xs[2]);
  6865. if name == "v_fma_mix_f32" {
  6866. return float(self, r);
  6867. }
  6868. if v.clamp {
  6869. r = self.unary(7, r);
  6870. }
  6871. // The f16 result goes to one half; the other half stays.
  6872. let Some(Operand::Vector { reg, .. }) = v.dst else {
  6873. return Err("a mixed-precision result");
  6874. };
  6875. let old = match inst.read(Reg::V(reg)) {
  6876. Some(o) => self.i32_of(o)?,
  6877. None => self.s.m.i32(0),
  6878. };
  6879. let h = self
  6880. .s
  6881. .op(c, "legacyF32ToF16", Attr::ReadNone, self.s.t.i32, 130, &[r]);
  6882. let (keep, h) = if name == "v_fma_mixhi_f16" {
  6883. let k16 = self.s.m.i32(16);
  6884. (0xFFFF, self.s.m.bin(c, Bin::Shl, h, k16))
  6885. } else {
  6886. (0xFFFF_0000, h)
  6887. };
  6888. let keep = self.s.m.i32(keep);
  6889. let old = self.s.m.bin(c, Bin::And, old, keep);
  6890. let x = self.s.m.bin(c, Bin::Or, old, h);
  6891. self.write(inst, Reg::V(reg), x, guard);
  6892. Ok(())
  6893. }
  6894. "v_cvt_pkrtz_f16_f32" => {
  6895. let (a, bb) = (f(self, 0)?, f(self, 1)?);
  6896. let lo = self.f16_toward_zero(a);
  6897. let hi = self.f16_toward_zero(bb);
  6898. let sh = self.s.m.i32(16);
  6899. let hi = self.s.m.bin(c, Bin::Shl, hi, sh);
  6900. let r = self.s.m.bin(c, Bin::Or, lo, hi);
  6901. int(self, r)
  6902. }
  6903. "v_cvt_f16_f32" if v.opsel == 0 => {
  6904. // Rounded to nearest even (the MODE default) into the low half.
  6905. let a = f(self, 0)?;
  6906. let r = self
  6907. .s
  6908. .op(c, "legacyF32ToF16", Attr::ReadNone, self.s.t.i32, 130, &[a]);
  6909. let Some(Operand::Vector { reg, .. }) = v.dst else {
  6910. return Err("a 16-bit result outside a VGPR");
  6911. };
  6912. let r = self.low_half(inst, reg, r);
  6913. int(self, r)
  6914. }
  6915. "v_pack_b32_f16" => {
  6916. // Two f16 sources (op_sel: their high halves; abs and neg on
  6917. // the sign bit) into the low and high half.
  6918. let mut halves = Vec::new();
  6919. for k in 0..2 {
  6920. let op = v.src.get(k).ok_or("a missing operand")?;
  6921. let mut x = self.f16_operand(inst, op)?;
  6922. if v.opsel >> k & 1 != 0 {
  6923. let k16 = self.s.m.i32(16);
  6924. x = self.s.m.bin(c, Bin::LShr, x, k16);
  6925. }
  6926. let mask = if v.abs >> k & 1 != 0 { 0x7FFF } else { 0xFFFF };
  6927. let mask = self.s.m.i32(mask);
  6928. x = self.s.m.bin(c, Bin::And, x, mask);
  6929. if v.neg >> k & 1 != 0 {
  6930. let sign = self.s.m.i32(0x8000);
  6931. x = self.s.m.bin(c, Bin::Xor, x, sign);
  6932. }
  6933. halves.push(x);
  6934. }
  6935. let k16 = self.s.m.i32(16);
  6936. let hi = self.s.m.bin(c, Bin::Shl, halves[1], k16);
  6937. let r = self.s.m.bin(c, Bin::Or, halves[0], hi);
  6938. int(self, r)
  6939. }
  6940. "v_cvt_f32_f16" if v.opsel == 0 => {
  6941. let a = s(self, 0)?;
  6942. let r = self
  6943. .s
  6944. .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[a]);
  6945. float(self, r)
  6946. }
  6947. "v_cndmask_b32" => {
  6948. let mask = match v.src.get(2) {
  6949. Some(&Operand::Scalar { code, .. }) => inst.read(Reg::S(code)),
  6950. _ => None,
  6951. };
  6952. const UNTRACKED: Why = "a select on an untracked mask";
  6953. let cond = match mask.and_then(|m| self.x.st.masks.get(&m).copied()) {
  6954. Some(m) => self.boolean(m, c)?,
  6955. // A mask the code holds as a number (a constant bit
  6956. // pattern: every other lane, every other pair...):
  6957. // this lane's bit of it. Exact where host lanes are
  6958. // the console's.
  6959. None if self.mask_data == MaskData::Console => {
  6960. // Each host wave taken as a wave of its own has no
  6961. // console lane numbers to pick the bits by.
  6962. if self.local {
  6963. return Err("a constant lane mask in a half-wave");
  6964. }
  6965. let m = mask.ok_or(UNTRACKED)?;
  6966. let lo = self.i32_of(m).map_err(|_| UNTRACKED)?;
  6967. // wave64: the register after it holds lanes 32-63.
  6968. let high = match v.src.get(2) {
  6969. Some(&Operand::Scalar { code, .. }) if self.x.native.wave64 => {
  6970. Some(inst.read(Reg::S(code + 1)).ok_or(UNTRACKED)?)
  6971. }
  6972. _ => None,
  6973. };
  6974. let hi = match high {
  6975. Some(h) => Some(self.i32_of(h).map_err(|_| UNTRACKED)?),
  6976. None => None,
  6977. };
  6978. self.cross_lane(false)?;
  6979. self.lane_bit(c, lo, hi)
  6980. }
  6981. None => return Err(UNTRACKED),
  6982. };
  6983. if v.abs != 0 || v.neg != 0 {
  6984. let (a, bb) = (f(self, 0)?, f(self, 1)?);
  6985. let r = self.s.m.select(c, cond, bb, a);
  6986. return float(self, r);
  6987. }
  6988. let (a, bb) = (s(self, 0)?, s(self, 1)?);
  6989. let r = self.s.m.select(c, cond, bb, a);
  6990. int(self, r)
  6991. }
  6992. "v_add_co_u32" | "v_sub_co_u32" | "v_subrev_co_u32" | "v_add_co_ci_u32"
  6993. | "v_sub_co_ci_u32" | "v_subrev_co_ci_u32" => {
  6994. // The carry (borrow) out is a lane mask: this lane's bit.
  6995. let (mut a, mut bb) = (s(self, 0)?, s(self, 1)?);
  6996. if name.contains("subrev") {
  6997. std::mem::swap(&mut a, &mut bb);
  6998. }
  6999. let cin = if name.ends_with("_ci_u32") {
  7000. let m = match v.src.get(2) {
  7001. Some(&Operand::Scalar { code, .. }) => inst.read(Reg::S(code)),
  7002. _ => None,
  7003. };
  7004. let m = m
  7005. .and_then(|m| self.x.st.masks.get(&m).copied())
  7006. .ok_or("a carry-in from an untracked mask")?;
  7007. Some(self.boolean(m, c)?)
  7008. } else {
  7009. None
  7010. };
  7011. let (r, carry) = self.add_sub_carry(c, name.starts_with("v_add"), a, bb, cin);
  7012. int(self, r)?;
  7013. if let Some(Operand::Scalar { code, .. }) = v.carry
  7014. && let Some(w) = inst.write(Reg::S(code))
  7015. {
  7016. self.lane_bits.insert(w, carry);
  7017. }
  7018. for &(_, w) in &inst.writes {
  7019. self.vals
  7020. .entry(w)
  7021. .or_insert(Val::Missing("a lane mask read as data"));
  7022. }
  7023. Ok(())
  7024. }
  7025. "v_readlane_b32" => {
  7026. let (a, lane) = (s(self, 0)?, s(self, 1)?);
  7027. // A computed lane in a pixel or vertex program is a host lane
  7028. // (from a mask or `v_mbcnt`); a constant one is the console's.
  7029. if self.mask_data == MaskData::Host && !matches!(lane, V::Const(_)) {
  7030. self.s.flags |= flags::WAVE_OPS;
  7031. } else {
  7032. self.cross_lane(false)?;
  7033. }
  7034. if let Some(slot) = self.exchange.as_ref().map(|e| e.0) {
  7035. if self.local && self.local_any {
  7036. // this host wave's lane of that number (lanes 32..63 are 0..31 here)
  7037. let k31 = self.s.m.i32(31);
  7038. let here = self.s.m.bin(self.cur, Bin::And, lane, k31);
  7039. let r = self.read_lane(a, here);
  7040. return int(self, r);
  7041. }
  7042. if self.local {
  7043. return Err("a lane read in a half-wave");
  7044. }
  7045. if self.exchange.as_ref().is_some_and(|e| e.1) {
  7046. // a group of 32 or fewer: the lane is in this host wave
  7047. let r = self.read_lane(a, lane);
  7048. return int(self, r);
  7049. }
  7050. // the lane that holds it may be in the other host wave: it gives it through LDS
  7051. if !self.all_lanes(self.cur_ir) {
  7052. need(self.cur_ir);
  7053. return Err("a lane read where not every lane runs");
  7054. }
  7055. let cl = self.console_lane();
  7056. let is = self.s.m.cmp(self.cur, pred::EQ, cl, lane);
  7057. let k = self.exchange_pair(slot);
  7058. let at = self.begin_guarded(Some(is));
  7059. let lds = self.s.lds();
  7060. let ptr = self.s.m.element(self.cur, lds, k);
  7061. self.s.m.store(self.cur, ptr, a);
  7062. self.end_guarded(at, &[]);
  7063. let c2 = self.cur;
  7064. self.group_sync(c2);
  7065. let ptr = self.s.m.element(c2, lds, k);
  7066. let r = self.s.m.load(c2, ptr);
  7067. self.group_sync(c2);
  7068. return int(self, r);
  7069. }
  7070. let r = self.read_lane(a, lane);
  7071. int(self, r)
  7072. }
  7073. "v_writelane_b32" => {
  7074. // The lane given takes the scalar; the others keep their value.
  7075. let (a, lane) = (s(self, 0)?, s(self, 1)?);
  7076. let Some(Operand::Vector { reg, .. }) = v.dst else {
  7077. return Err("a lane write");
  7078. };
  7079. let old = match inst.read(Reg::V(reg)) {
  7080. Some(o) => self.i32_of(o)?,
  7081. None => self.s.m.i32(0),
  7082. };
  7083. self.cross_lane(false)?;
  7084. if self.local && !self.local_any {
  7085. return Err("a lane write in a half-wave");
  7086. }
  7087. let me = self.console_lane();
  7088. let is = self.s.m.cmp(c, pred::EQ, me, lane);
  7089. let r = self.s.m.select(c, is, a, old);
  7090. int(self, r)
  7091. }
  7092. "v_readfirstlane_b32"
  7093. if inst
  7094. .writes
  7095. .first()
  7096. .is_some_and(|w| self.x.res.waterfall.reads.contains(&w.1)) =>
  7097. {
  7098. // A waterfall loop's read of a descriptor dword: the lane's own.
  7099. let a = s(self, 0)?;
  7100. int(self, a)
  7101. }
  7102. "v_readfirstlane_b32"
  7103. if matches!(v.src.first(), Some(&Operand::Vector { reg, .. })
  7104. if inst.read(Reg::V(reg)).is_some_and(|x| self.own_bits.alike.contains(&x))) =>
  7105. {
  7106. // The bits a loop over a wave OR has still to visit (`own_bits`): every lane of
  7107. // the host wave holds the same, so the first lane's is the lane's own.
  7108. let a = s(self, 0)?;
  7109. int(self, a)
  7110. }
  7111. "v_readfirstlane_b32" => {
  7112. let a = s(self, 0)?;
  7113. let (mine, any) = self.first_lane(a, guard);
  7114. // two host waves that exchange: the console's first lane may be in the other
  7115. // one, unless every lane holds the same value
  7116. let alike = match v.src.first() {
  7117. Some(&Operand::Vector { reg, .. }) => {
  7118. inst.read(Reg::V(reg)).is_some_and(|x| self.uniform.contains(&x))
  7119. }
  7120. _ => true,
  7121. };
  7122. let halves = self.exchange.as_ref().is_some_and(|e| !e.1) && !self.local;
  7123. let r = if halves && !alike {
  7124. if !self.all_lanes(self.cur_ir) {
  7125. need(self.cur_ir);
  7126. return Err("a first-lane read where not every lane runs");
  7127. }
  7128. let c = self.cur;
  7129. let i32t = self.s.t.i32;
  7130. let has = self.s.m.cast(c, Cast::ZExt, any, i32t);
  7131. let (lo_has, hi_has) = self.exchange_halves(c, has);
  7132. let (lo, hi) = self.exchange_halves(c, mine);
  7133. let z = self.s.m.i32(0);
  7134. let in_lo = self.s.m.cmp(c, pred::NE, lo_has, z);
  7135. let in_hi = self.s.m.cmp(c, pred::NE, hi_has, z);
  7136. // neither half has a lane in EXEC: the console reads lane 0
  7137. let hi = self.s.m.select(c, in_hi, hi, lo);
  7138. self.s.m.select(c, in_lo, lo, hi)
  7139. } else {
  7140. mine
  7141. };
  7142. int(self, r)
  7143. }
  7144. _ => {
  7145. let r = self.integer(inst, name)?;
  7146. int(self, r)
  7147. }
  7148. }
  7149. }
  7150. /// A 64-bit source (a register pair; inline constants sign-extend).
  7151. fn src64(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  7152. let Fields::Valu(v) = &inst.fields else {
  7153. unreachable!()
  7154. };
  7155. if v.abs >> k & 1 != 0 || v.neg >> k & 1 != 0 || v.sdwa.is_some() || v.dpp.is_some() {
  7156. return Err("64-bit operand modifiers");
  7157. }
  7158. let c = self.cur;
  7159. let i64t = self.s.m.int(64);
  7160. self.s.flags |= flags::INT64;
  7161. let op = *v.src.get(k).ok_or("a missing operand")?;
  7162. let pair = |l: &mut Self, r: Reg, r1: Reg| -> Result<V, Why> {
  7163. let lo = l.i32_of(inst.read(r).ok_or("an unread operand")?)?;
  7164. let hi = l.i32_of(inst.read(r1).ok_or("an unread operand")?)?;
  7165. Ok(l.join64(lo, hi))
  7166. };
  7167. match op {
  7168. Operand::Vector { reg, .. } => pair(self, Reg::V(reg), Reg::V(reg + 1)),
  7169. Operand::Scalar { code, .. } if code != NULL => {
  7170. pair(self, Reg::S(code), Reg::S(code + 1))
  7171. }
  7172. Operand::Const(k @ 128..=208) => {
  7173. let x = crate::resource::inline(k).ok_or("a special operand")?;
  7174. Ok(self.s.m.int_const(i64t, i64::from(x as i32)))
  7175. }
  7176. _ => {
  7177. // Literals and the null register: zero-extended.
  7178. let x = self.operand(inst, &op)?;
  7179. Ok(self.s.m.cast(c, Cast::ZExt, x, i64t))
  7180. }
  7181. }
  7182. }
  7183. /// Reads an IEEE-754 binary64 operand as `(lo, hi)` 32-bit words, applying
  7184. /// `abs` and `neg` input modifiers on operand `k`.
  7185. fn f64_pair(&mut self, inst: &Inst, k: usize) -> Result<(V, V), Why> {
  7186. let Fields::Valu(v) = &inst.fields else {
  7187. unreachable!()
  7188. };
  7189. if v.sdwa.is_some() || v.dpp.is_some() {
  7190. return Err("64-bit operand modifiers");
  7191. }
  7192. let op = *v.src.get(k).ok_or("a missing operand")?;
  7193. let pair = |l: &mut Self, r: Reg, r1: Reg| -> Result<(V, V), Why> {
  7194. let lo = l.i32_of(inst.read(r).ok_or("an unread operand")?)?;
  7195. let hi = l.i32_of(inst.read(r1).ok_or("an unread operand")?)?;
  7196. Ok((lo, hi))
  7197. };
  7198. let (lo, mut hi) = match op {
  7199. Operand::Vector { reg, .. } => pair(self, Reg::V(reg), Reg::V(reg + 1))?,
  7200. Operand::Scalar { code, .. } if code != NULL => {
  7201. pair(self, Reg::S(code), Reg::S(code + 1))?
  7202. }
  7203. Operand::Const(128) => (self.s.m.i32(0), self.s.m.i32(0)),
  7204. Operand::Const(c @ 240..=248) => {
  7205. const INLINE_F64: [f64; 9] = [
  7206. 0.5,
  7207. -0.5,
  7208. 1.0,
  7209. -1.0,
  7210. 2.0,
  7211. -2.0,
  7212. 4.0,
  7213. -4.0,
  7214. 1.0 / std::f64::consts::TAU,
  7215. ];
  7216. let bits = INLINE_F64[(c - 240) as usize].to_bits();
  7217. (self.s.m.i32(bits as u32), self.s.m.i32((bits >> 32) as u32))
  7218. }
  7219. // GFX10 places a 32-bit literal in the high 32 bits of a 64-bit float operand.
  7220. Operand::Literal(x) => (self.s.m.i32(0), self.s.m.i32(x)),
  7221. _ => return Err("a 64-bit float operand"),
  7222. };
  7223. let c = self.cur;
  7224. if v.abs >> k & 1 != 0 {
  7225. let mask = self.s.m.i32(0x7FFF_FFFF);
  7226. hi = self.s.m.bin(c, Bin::And, hi, mask);
  7227. }
  7228. if v.neg >> k & 1 != 0 {
  7229. let sign = self.s.m.i32(0x8000_0000);
  7230. hi = self.s.m.bin(c, Bin::Xor, hi, sign);
  7231. }
  7232. Ok((lo, hi))
  7233. }
  7234. /// Converts IEEE-754 binary64 `(lo, hi)` to binary32 bits with round-to-nearest-even,
  7235. /// without requiring host `DOUBLES` (`f64`) support.
  7236. fn f64_to_f32_bits(&mut self, lo: V, hi: V) -> V {
  7237. let c = self.cur;
  7238. let k0 = self.s.m.i32(0);
  7239. let k1 = self.s.m.i32(1);
  7240. let sign_mask = self.s.m.i32(0x8000_0000);
  7241. let sign = self.s.m.bin(c, Bin::And, hi, sign_mask);
  7242. let k20 = self.s.m.i32(20);
  7243. let k7ff = self.s.m.i32(0x7FF);
  7244. let exp64 = self.s.m.bin(c, Bin::LShr, hi, k20);
  7245. let exp64 = self.s.m.bin(c, Bin::And, exp64, k7ff);
  7246. let frac_mask = self.s.m.i32(0x000F_FFFF);
  7247. let frac_hi = self.s.m.bin(c, Bin::And, hi, frac_mask);
  7248. let frac_any = self.s.m.bin(c, Bin::Or, frac_hi, lo);
  7249. let frac_nz = self.s.m.cmp(c, pred::NE, frac_any, k0);
  7250. let k3 = self.s.m.i32(3);
  7251. let k29 = self.s.m.i32(29);
  7252. let m23_hi = self.s.m.bin(c, Bin::Shl, frac_hi, k3);
  7253. let m23_lo = self.s.m.bin(c, Bin::LShr, lo, k29);
  7254. let m23 = self.s.m.bin(c, Bin::Or, m23_hi, m23_lo);
  7255. let rem_mask = self.s.m.i32(0x1FFF_FFFF);
  7256. let rem = self.s.m.bin(c, Bin::And, lo, rem_mask);
  7257. let half_rem = self.s.m.i32(0x1000_0000);
  7258. let gt_half = self.s.m.cmp(c, pred::IUGT, rem, half_rem);
  7259. let eq_half = self.s.m.cmp(c, pred::EQ, rem, half_rem);
  7260. let m23_odd_bit = self.s.m.bin(c, Bin::And, m23, k1);
  7261. let m23_odd = self.s.m.cmp(c, pred::NE, m23_odd_bit, k0);
  7262. let tie_up = self.s.m.bin(c, Bin::And, eq_half, m23_odd);
  7263. let norm_round = self.s.m.bin(c, Bin::Or, gt_half, tie_up);
  7264. let norm_inc = self.s.m.select(c, norm_round, k1, k0);
  7265. // Normal range: exp64 in [897, 1150] -> exp32 in [1, 254].
  7266. let k896 = self.s.m.i32(896);
  7267. let k23 = self.s.m.i32(23);
  7268. let exp32 = self.s.m.bin(c, Bin::Sub, exp64, k896);
  7269. let exp32_sh = self.s.m.bin(c, Bin::Shl, exp32, k23);
  7270. let norm_body = self.s.m.bin(c, Bin::Add, exp32_sh, m23);
  7271. let norm_body = self.s.m.bin(c, Bin::Add, norm_body, norm_inc);
  7272. let norm_res = self.s.m.bin(c, Bin::Or, sign, norm_body);
  7273. // Subnormal range: exp64 in [874, 896] -> shift in [1, 23].
  7274. let k897 = self.s.m.i32(897);
  7275. let k32 = self.s.m.i32(32);
  7276. let k31 = self.s.m.i32(31);
  7277. let imp = self.s.m.i32(0x0080_0000);
  7278. let sig24 = self.s.m.bin(c, Bin::Or, imp, m23);
  7279. let raw_shift = self.s.m.bin(c, Bin::Sub, k897, exp64);
  7280. // Clamp shift to [1, 23] so shifts never produce poison outside the subnormal branch.
  7281. let lt1 = self.s.m.cmp(c, pred::IULT, raw_shift, k1);
  7282. let shift = self.s.m.select(c, lt1, k1, raw_shift);
  7283. let gt23 = self.s.m.cmp(c, pred::IUGT, shift, k23);
  7284. let shift = self.s.m.select(c, gt23, k23, shift);
  7285. let sub_m = self.s.m.bin(c, Bin::LShr, sig24, shift);
  7286. let inv_shift = self.s.m.bin(c, Bin::Sub, k32, shift);
  7287. let lost = self.s.m.bin(c, Bin::Shl, sig24, inv_shift);
  7288. let round_bit = self.s.m.bin(c, Bin::LShr, lost, k31);
  7289. let round_on = self.s.m.cmp(c, pred::NE, round_bit, k0);
  7290. let low31 = self.s.m.i32(0x7FFF_FFFF);
  7291. let lost_lo = self.s.m.bin(c, Bin::And, lost, low31);
  7292. let sticky = self.s.m.bin(c, Bin::Or, lost_lo, rem);
  7293. let sticky_on = self.s.m.cmp(c, pred::NE, sticky, k0);
  7294. let sub_odd_bit = self.s.m.bin(c, Bin::And, sub_m, k1);
  7295. let sub_odd = self.s.m.cmp(c, pred::NE, sub_odd_bit, k0);
  7296. let sub_tie = self.s.m.bin(c, Bin::Or, sticky_on, sub_odd);
  7297. let sub_round = self.s.m.bin(c, Bin::And, round_on, sub_tie);
  7298. let sub_inc = self.s.m.select(c, sub_round, k1, k0);
  7299. let sub_body = self.s.m.bin(c, Bin::Add, sub_m, sub_inc);
  7300. let sub_res = self.s.m.bin(c, Bin::Or, sign, sub_body);
  7301. // Underflow range: exp64 < 874. Only exp64 == 873 with non-zero fraction rounds up to min subnormal (1).
  7302. let k873 = self.s.m.i32(873);
  7303. let eq873 = self.s.m.cmp(c, pred::EQ, exp64, k873);
  7304. let round_min = self.s.m.bin(c, Bin::And, eq873, frac_nz);
  7305. let min_bit = self.s.m.select(c, round_min, k1, k0);
  7306. let under_res = self.s.m.bin(c, Bin::Or, sign, min_bit);
  7307. // Overflow / Inf / NaN: exp64 >= 1151.
  7308. let is_exp_all = self.s.m.cmp(c, pred::EQ, exp64, k7ff);
  7309. let is_nan = self.s.m.bin(c, Bin::And, is_exp_all, frac_nz);
  7310. let inf_bits = self.s.m.i32(0x7F80_0000);
  7311. let qnan_bits = self.s.m.i32(0x7FC0_0000);
  7312. let nan_body = self.s.m.bin(c, Bin::Or, qnan_bits, m23);
  7313. let over_body = self.s.m.select(c, is_nan, nan_body, inf_bits);
  7314. let over_res = self.s.m.bin(c, Bin::Or, sign, over_body);
  7315. // Select final result by exponent range.
  7316. let k874 = self.s.m.i32(874);
  7317. let k1151 = self.s.m.i32(1151);
  7318. let is_under = self.s.m.cmp(c, pred::IULT, exp64, k874);
  7319. let is_sub = self.s.m.cmp(c, pred::IULT, exp64, k897);
  7320. let is_over = self.s.m.cmp(c, pred::IUGE, exp64, k1151);
  7321. let r = self.s.m.select(c, is_over, over_res, norm_res);
  7322. let r = self.s.m.select(c, is_sub, sub_res, r);
  7323. self.s.m.select(c, is_under, under_res, r)
  7324. }
  7325. fn join64(&mut self, lo: V, hi: V) -> V {
  7326. let c = self.cur;
  7327. let ty = self.s.m.int(64);
  7328. let lo = self.s.m.cast(c, Cast::ZExt, lo, ty);
  7329. let hi = self.s.m.cast(c, Cast::ZExt, hi, ty);
  7330. let shift = self.s.m.int_const(ty, 32);
  7331. let hi = self.s.m.bin(c, Bin::Shl, hi, shift);
  7332. self.s.m.bin(c, Bin::Or, lo, hi)
  7333. }
  7334. /// The low and high dwords of an i64.
  7335. fn split64(&mut self, x: V) -> (V, V) {
  7336. let c = self.cur;
  7337. let i64t = self.s.m.int(64);
  7338. let k32 = self.s.m.int_const(i64t, 32);
  7339. let lo = self.s.m.cast(c, Cast::Trunc, x, self.s.t.i32);
  7340. let hi = self.s.m.bin(c, Bin::LShr, x, k32);
  7341. let hi = self.s.m.cast(c, Cast::Trunc, hi, self.s.t.i32);
  7342. (lo, hi)
  7343. }
  7344. /// Source `k` of a 16-bit operation in the low 16 bits (the rest 0):
  7345. /// op_sel (or an SDWA word select) picks the high half; inline float
  7346. /// constants are f16 values here.
  7347. fn half_src(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  7348. let Fields::Valu(v) = &inst.fields else {
  7349. unreachable!()
  7350. };
  7351. let op = *v.src.get(k).ok_or("a missing operand")?;
  7352. let mut high = v.opsel >> k & 1 != 0;
  7353. if let Some(sd) = v.sdwa {
  7354. match sd.src_sel.get(k).copied().unwrap_or(6) {
  7355. 4 => {}
  7356. 5 => high = true,
  7357. 6 => {}
  7358. _ => return Err("a byte select on a 16-bit operation"),
  7359. }
  7360. }
  7361. let x = match self.src0 {
  7362. Some(x) if k == 0 => x,
  7363. _ => self.f16_operand(inst, &op)?,
  7364. };
  7365. let c = self.cur;
  7366. let x = if high {
  7367. let k16 = self.s.m.i32(16);
  7368. self.s.m.bin(c, Bin::LShr, x, k16)
  7369. } else {
  7370. x
  7371. };
  7372. let m = self.s.m.i32(0xFFFF);
  7373. Ok(self.s.m.bin(c, Bin::And, x, m))
  7374. }
  7375. /// An f16 source as an f32 (exact), with its abs/neg modifiers.
  7376. fn half_fsrc(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  7377. let Fields::Valu(v) = &inst.fields else {
  7378. unreachable!()
  7379. };
  7380. let h = self.half_src(inst, k)?;
  7381. let f32t = self.s.t.f32;
  7382. let mut f = self
  7383. .s
  7384. .op(self.cur, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]);
  7385. if v.abs >> k & 1 != 0 {
  7386. f = self.unary(6, f);
  7387. }
  7388. if v.neg >> k & 1 != 0 {
  7389. let z = self.s.m.f32(0x8000_0000);
  7390. f = self.s.m.bin(self.cur, Bin::Sub, z, f);
  7391. }
  7392. Ok(f)
  7393. }
  7394. /// Writes a 16-bit result (low bits of `x`) into the destination's low
  7395. /// half, or its high half with op_sel bit 3 (or an SDWA WORD_1 select);
  7396. /// the other half is kept (GFX10).
  7397. fn write_half(&mut self, inst: &Inst, x: V, guard: Option<V>) -> Result<(), Why> {
  7398. let Fields::Valu(v) = &inst.fields else {
  7399. unreachable!()
  7400. };
  7401. let Some(Operand::Vector { reg, .. }) = v.dst else {
  7402. return Err("a 16-bit result outside a VGPR");
  7403. };
  7404. let mut high = v.opsel >> 3 & 1 != 0;
  7405. // SDWA: the word written, the other one kept (preserve) or zero
  7406. // (pad; a sign extension above the high word adds nothing).
  7407. let mut keep = true;
  7408. if let Some(sd) = v.sdwa {
  7409. match (sd.dst_sel, sd.dst_unused) {
  7410. (4, 2) => {}
  7411. (5, 2) => high = true,
  7412. (4 | 6, _) => keep = false,
  7413. (5, _) => (high, keep) = (true, false),
  7414. _ => return Err("an SDWA destination of a 16-bit operation"),
  7415. }
  7416. }
  7417. let c = self.cur;
  7418. let old = match inst.read(Reg::V(reg)).map(|o| self.i32_of(o)) {
  7419. Some(Ok(o)) if keep => o,
  7420. _ => self.s.m.i32(0),
  7421. };
  7422. let (k16, low) = (self.s.m.i32(16), self.s.m.i32(0xFFFF));
  7423. let x = self.s.m.bin(c, Bin::And, x, low);
  7424. let r = if high {
  7425. let o = self.s.m.bin(c, Bin::And, old, low);
  7426. let x = self.s.m.bin(c, Bin::Shl, x, k16);
  7427. self.s.m.bin(c, Bin::Or, o, x)
  7428. } else {
  7429. let keep = self.s.m.i32(0xFFFF_0000);
  7430. let o = self.s.m.bin(c, Bin::And, old, keep);
  7431. self.s.m.bin(c, Bin::Or, o, x)
  7432. };
  7433. self.write_placed(inst, Reg::V(reg), r, guard);
  7434. Ok(())
  7435. }
  7436. /// 16-bit operations, computed in f32 or i32: f16 sums, differences and
  7437. /// products are exact there and round once to f16 (f32 has the 2 x 11 +
  7438. /// 2 bits that make double rounding harmless); `None` if `name` is none.
  7439. fn valu16(&mut self, inst: &Inst, name: &str, guard: Option<V>) -> Option<Result<(), Why>> {
  7440. const FLOAT2: &[&str] = &[
  7441. "v_add_f16",
  7442. "v_sub_f16",
  7443. "v_subrev_f16",
  7444. "v_mul_f16",
  7445. "v_max_f16",
  7446. "v_min_f16",
  7447. ];
  7448. const FLOAT3: &[&str] = &[
  7449. "v_fma_f16",
  7450. "v_mad_f16",
  7451. "v_fmac_f16",
  7452. "v_mac_f16",
  7453. "v_max3_f16",
  7454. "v_min3_f16",
  7455. "v_med3_f16",
  7456. ];
  7457. const FLOAT1: &[&str] = &[
  7458. "v_rcp_f16",
  7459. "v_sqrt_f16",
  7460. "v_rsq_f16",
  7461. "v_log_f16",
  7462. "v_exp_f16",
  7463. "v_fract_f16",
  7464. "v_trunc_f16",
  7465. "v_floor_f16",
  7466. "v_ceil_f16",
  7467. "v_rndne_f16",
  7468. "v_sin_f16",
  7469. "v_cos_f16",
  7470. "v_cvt_f16_u16",
  7471. "v_cvt_f16_i16",
  7472. ];
  7473. const INT: &[&str] = &[
  7474. "v_add_nc_u16",
  7475. "v_sub_nc_u16",
  7476. "v_subrev_nc_u16",
  7477. "v_mul_lo_u16",
  7478. "v_lshlrev_b16",
  7479. "v_lshrrev_b16",
  7480. "v_ashrrev_i16",
  7481. "v_max_u16",
  7482. "v_max_i16",
  7483. "v_min_u16",
  7484. "v_min_i16",
  7485. "v_cvt_u16_f16",
  7486. "v_cvt_i16_f16",
  7487. "v_cvt_norm_i16_f16",
  7488. "v_cvt_norm_u16_f16",
  7489. ];
  7490. let all = [FLOAT1, FLOAT2, FLOAT3, INT];
  7491. if !all.iter().any(|l| l.contains(&name))
  7492. && !matches!(name, "v_cvt_f16_f32" | "v_cvt_f32_f16")
  7493. {
  7494. return None;
  7495. }
  7496. Some(self.valu16_op(inst, name, guard, FLOAT1, FLOAT2, FLOAT3))
  7497. }
  7498. #[allow(clippy::too_many_arguments)]
  7499. fn valu16_op(
  7500. &mut self,
  7501. inst: &Inst,
  7502. name: &str,
  7503. guard: Option<V>,
  7504. float1: &[&str],
  7505. float2: &[&str],
  7506. float3: &[&str],
  7507. ) -> Result<(), Why> {
  7508. let Fields::Valu(v) = &inst.fields else {
  7509. unreachable!()
  7510. };
  7511. let c = self.cur;
  7512. let i32t = self.s.t.i32;
  7513. let f32t = self.s.t.f32;
  7514. if name == "v_cvt_f32_f16" {
  7515. let f = self.half_fsrc(inst, 0)?;
  7516. return self.write_f(inst, f, guard);
  7517. }
  7518. let float_result = |l: &mut Self, mut f: V| -> Result<(), Why> {
  7519. match v.omod {
  7520. 0 => {}
  7521. k => {
  7522. let factor = [1.0f32, 2.0, 4.0, 0.5][usize::from(k)];
  7523. let k = l.s.m.f32(factor.to_bits());
  7524. f = l.s.m.bin(l.cur, Bin::Mul, f, k);
  7525. }
  7526. }
  7527. if v.clamp {
  7528. f = l.unary(7, f);
  7529. }
  7530. // The console rounds to nearest; the host's conversion may round toward zero
  7531. // (NVIDIA's does), one step of the last place lower where the two differ.
  7532. // shortcut: the host's conversion unless `VICTORY_F16_NEAREST=1`
  7533. // ([`f16_nearest_on`]), which costs a dozen instructions per result.
  7534. let h = if f16_nearest_on() {
  7535. l.f16_nearest(f)
  7536. } else {
  7537. l.s.op(l.cur, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f])
  7538. };
  7539. l.write_half(inst, h, guard)
  7540. };
  7541. if name == "v_cvt_f16_f32" {
  7542. let f = self.fsrc(inst, 0)?;
  7543. return float_result(self, f);
  7544. }
  7545. if float2.contains(&name) {
  7546. let (a, b) = (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?);
  7547. let r = match name {
  7548. "v_add_f16" => self.s.m.bin(c, Bin::Add, a, b),
  7549. "v_sub_f16" => self.s.m.bin(c, Bin::Sub, a, b),
  7550. "v_subrev_f16" => self.s.m.bin(c, Bin::Sub, b, a),
  7551. "v_mul_f16" => self.s.m.bin(c, Bin::Mul, a, b),
  7552. "v_max_f16" => self.max_min(true, a, b),
  7553. _ => self.max_min(false, a, b),
  7554. };
  7555. return float_result(self, r);
  7556. }
  7557. if float3.contains(&name) {
  7558. let (a, b) = (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?);
  7559. let acc = if matches!(name, "v_fmac_f16" | "v_mac_f16") {
  7560. // The accumulator is the destination's half that is written.
  7561. let Some(Operand::Vector { reg, .. }) = v.dst else {
  7562. return Err("an accumulator");
  7563. };
  7564. let x = self.i32_of(inst.read(Reg::V(reg)).ok_or("an accumulator")?)?;
  7565. let x = if v.opsel >> 3 & 1 != 0 {
  7566. let k16 = self.s.m.i32(16);
  7567. self.s.m.bin(c, Bin::LShr, x, k16)
  7568. } else {
  7569. x
  7570. };
  7571. let m = self.s.m.i32(0xFFFF);
  7572. let x = self.s.m.bin(c, Bin::And, x, m);
  7573. self.s
  7574. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x])
  7575. } else {
  7576. self.half_fsrc(inst, 2)?
  7577. };
  7578. let r = match name {
  7579. // shortcut: fused f16 multiply-adds as FMad in f32 (the
  7580. // product is exact; the sum rounds twice).
  7581. "v_fma_f16" | "v_fmac_f16" | "v_mad_f16" | "v_mac_f16" => self.fmad(a, b, acc),
  7582. "v_max3_f16" => {
  7583. let t = self.max_min(true, a, b);
  7584. self.max_min(true, t, acc)
  7585. }
  7586. "v_min3_f16" => {
  7587. let t = self.max_min(false, a, b);
  7588. self.max_min(false, t, acc)
  7589. }
  7590. _ => self.med3(a, b, acc),
  7591. };
  7592. return float_result(self, r);
  7593. }
  7594. if float1.contains(&name) {
  7595. let r = match name {
  7596. "v_cvt_f16_u16" | "v_cvt_f16_i16" => {
  7597. let mut x = self.half_src(inst, 0)?;
  7598. let op = if name == "v_cvt_f16_i16" {
  7599. let k16 = self.s.m.i32(16);
  7600. let t = self.s.m.bin(c, Bin::Shl, x, k16);
  7601. x = self.s.m.bin(c, Bin::AShr, t, k16);
  7602. Cast::SiToFp
  7603. } else {
  7604. Cast::UiToFp
  7605. };
  7606. self.s.m.cast(c, op, x, f32t)
  7607. }
  7608. "v_rcp_f16" => {
  7609. let a = self.half_fsrc(inst, 0)?;
  7610. let one = self.s.m.f32(1.0f32.to_bits());
  7611. self.s.m.bin(c, Bin::SDiv, one, a)
  7612. }
  7613. _ => {
  7614. let a = self.half_fsrc(inst, 0)?;
  7615. let op = match name {
  7616. "v_sqrt_f16" => 24,
  7617. "v_rsq_f16" => 25,
  7618. "v_log_f16" => 23,
  7619. "v_exp_f16" => 21,
  7620. "v_fract_f16" => 22,
  7621. "v_trunc_f16" => 29,
  7622. "v_floor_f16" => 27,
  7623. "v_ceil_f16" => 28,
  7624. "v_rndne_f16" => 26,
  7625. "v_sin_f16" => 13,
  7626. _ => 12,
  7627. };
  7628. match op {
  7629. 12 | 13 => self.trig_turns(a, op == 12),
  7630. // Any f16 in (-2^-11, 0) has fract >= 1 - 2^-12; clamp to 0x3bff (1 - 2^-11).
  7631. 22 => self.fract(a, 1.0 - 1.0 / 4096.0, 1.0 - 1.0 / 2048.0),
  7632. _ => self.unary(op, a),
  7633. }
  7634. }
  7635. };
  7636. return float_result(self, r);
  7637. }
  7638. if matches!(name, "v_cvt_u16_f16" | "v_cvt_i16_f16") {
  7639. if v.clamp || v.omod != 0 {
  7640. return Err("modifiers on a 16-bit integer operation");
  7641. }
  7642. // Toward zero, saturating at the 16-bit range (infinities
  7643. // included); NaN gives 0. Clamped in f32 first, where every
  7644. // f16 is exact, so the conversion never leaves i32's range
  7645. // (upstream PR #384's arithmetic; the source's abs and neg
  7646. // modifiers are applied by `half_fsrc`, as before).
  7647. let a = self.half_fsrc(inst, 0)?;
  7648. let (lo, hi) = if name == "v_cvt_u16_f16" {
  7649. (0.0f32, 65535.0f32)
  7650. } else {
  7651. (-32768.0, 32767.0)
  7652. };
  7653. let (lo, hi) = (self.s.m.f32(lo.to_bits()), self.s.m.f32(hi.to_bits()));
  7654. let t = self.binary(35, a, lo);
  7655. let t = self.binary(36, t, hi);
  7656. let r = self.s.m.cast(c, Cast::FpToSi, t, i32t);
  7657. let nan = self.s.m.cmp(c, pred::UNO, a, a);
  7658. let z = self.s.m.i32(0);
  7659. let r = self.s.m.select(c, nan, z, r);
  7660. return self.write_half(inst, r, guard);
  7661. }
  7662. if matches!(name, "v_cvt_norm_i16_f16" | "v_cvt_norm_u16_f16") {
  7663. if v.clamp || v.omod != 0 {
  7664. return Err("modifiers on a 16-bit integer operation");
  7665. }
  7666. let r = self.cvt_norm16(inst, name == "v_cvt_norm_i16_f16")?;
  7667. return self.write_half(inst, r, guard);
  7668. }
  7669. // 16-bit integers: computed on the low halves, the low 16 bits kept.
  7670. if v.clamp || v.omod != 0 || v.abs != 0 || v.neg != 0 {
  7671. return Err("modifiers on a 16-bit integer operation");
  7672. }
  7673. let r = {
  7674. let (mut a, mut b) = (self.half_src(inst, 0)?, self.half_src(inst, 1)?);
  7675. let k16 = self.s.m.i32(16);
  7676. let sext = |l: &mut Self, x: V| {
  7677. let t = l.s.m.bin(c, Bin::Shl, x, k16);
  7678. l.s.m.bin(c, Bin::AShr, t, k16)
  7679. };
  7680. if name.ends_with("_i16") {
  7681. a = sext(self, a);
  7682. b = sext(self, b);
  7683. }
  7684. let k15 = self.s.m.i32(15);
  7685. match name {
  7686. "v_add_nc_u16" => self.s.m.bin(c, Bin::Add, a, b),
  7687. "v_sub_nc_u16" => self.s.m.bin(c, Bin::Sub, a, b),
  7688. "v_subrev_nc_u16" => self.s.m.bin(c, Bin::Sub, b, a),
  7689. "v_mul_lo_u16" => self.s.m.bin(c, Bin::Mul, a, b),
  7690. "v_lshlrev_b16" | "v_lshrrev_b16" | "v_ashrrev_i16" => {
  7691. // src0 is the shift (4 bits), src1 the value.
  7692. let sh = self.s.m.bin(c, Bin::And, a, k15);
  7693. let x = if name == "v_ashrrev_i16" {
  7694. sext(self, b)
  7695. } else {
  7696. b
  7697. };
  7698. let op = match name {
  7699. "v_lshlrev_b16" => Bin::Shl,
  7700. "v_lshrrev_b16" => Bin::LShr,
  7701. _ => Bin::AShr,
  7702. };
  7703. self.s.m.bin(c, op, x, sh)
  7704. }
  7705. _ => {
  7706. let p = match name {
  7707. "v_max_u16" => pred::IUGT,
  7708. "v_min_u16" => pred::IULT,
  7709. "v_max_i16" => pred::SGT,
  7710. _ => pred::SLT,
  7711. };
  7712. let t = self.s.m.cmp(c, p, a, b);
  7713. self.s.m.select(c, t, a, b)
  7714. }
  7715. }
  7716. };
  7717. self.write_half(inst, r, guard)
  7718. }
  7719. /// `v_cvt_norm_i16_f16` / `v_cvt_norm_u16_f16`: the f16 source (with its
  7720. /// abs/neg modifiers) clamped to [-1, 1] or [0, 1], times 32767 or 65535,
  7721. /// rounded to nearest even once from the exact product; NaN gives 0.
  7722. /// Worked on the f16's bits in integers, because in f32 the product
  7723. /// (up to 26 significant bits) would round before the rounding to an
  7724. /// integer.
  7725. fn cvt_norm16(&mut self, inst: &Inst, signed: bool) -> Result<V, Why> {
  7726. let Fields::Valu(v) = &inst.fields else {
  7727. unreachable!()
  7728. };
  7729. let c = self.cur;
  7730. let k = |l: &mut Self, x: u32| l.s.m.i32(x);
  7731. let mut h = self.half_src(inst, 0)?;
  7732. if v.abs & 1 != 0 {
  7733. let m = k(self, 0x7FFF);
  7734. h = self.s.m.bin(c, Bin::And, h, m);
  7735. }
  7736. if v.neg & 1 != 0 {
  7737. let m = k(self, 0x8000);
  7738. h = self.s.m.bin(c, Bin::Xor, h, m);
  7739. }
  7740. let scale = if signed { 0x7FFF } else { 0xFFFF };
  7741. let (k0, k1, k10) = (k(self, 0), k(self, 1), k(self, 10));
  7742. let mag_mask = k(self, 0x7FFF);
  7743. let mag = self.s.m.bin(c, Bin::And, h, mag_mask);
  7744. let k15 = k(self, 15);
  7745. let neg = self.s.m.bin(c, Bin::LShr, h, k15);
  7746. let neg = self.s.m.cmp(c, pred::NE, neg, k0);
  7747. // |x| < 1: x = m * 2^-s with m < 2^11 and 11 <= s <= 24.
  7748. let exp = self.s.m.bin(c, Bin::LShr, mag, k10);
  7749. let man_mask = k(self, 0x3FF);
  7750. let man = self.s.m.bin(c, Bin::And, mag, man_mask);
  7751. let implicit = k(self, 0x400);
  7752. let normal = self.s.m.bin(c, Bin::Or, man, implicit);
  7753. let sub = self.s.m.cmp(c, pred::EQ, exp, k0);
  7754. let m = self.s.m.select(c, sub, man, normal);
  7755. let k25 = k(self, 25);
  7756. let s_norm = self.s.m.bin(c, Bin::Sub, k25, exp);
  7757. let k24 = k(self, 24);
  7758. let sh = self.s.m.select(c, sub, k24, s_norm);
  7759. let ks = k(self, scale);
  7760. let p = self.s.m.bin(c, Bin::Mul, m, ks);
  7761. let q = self.s.m.bin(c, Bin::LShr, p, sh);
  7762. let one_s = self.s.m.bin(c, Bin::Shl, k1, sh);
  7763. let low_mask = self.s.m.bin(c, Bin::Sub, one_s, k1);
  7764. let rem = self.s.m.bin(c, Bin::And, p, low_mask);
  7765. let half = self.s.m.bin(c, Bin::LShr, one_s, k1);
  7766. let above = self.s.m.cmp(c, pred::IUGT, rem, half);
  7767. let tie = self.s.m.cmp(c, pred::EQ, rem, half);
  7768. let odd = self.s.m.bin(c, Bin::And, q, k1);
  7769. let odd = self.s.m.cmp(c, pred::NE, odd, k0);
  7770. let tie_up = self.s.m.bin(c, Bin::And, tie, odd);
  7771. let up = self.s.m.bin(c, Bin::Or, above, tie_up);
  7772. let r = self.s.m.select(c, up, k1, k0);
  7773. let r = self.s.m.bin(c, Bin::Add, q, r);
  7774. // |x| >= 1 (and infinity) saturates; NaN gives 0.
  7775. let one_h = k(self, 0x3C00);
  7776. let big = self.s.m.cmp(c, pred::IUGE, mag, one_h);
  7777. let r = self.s.m.select(c, big, ks, r);
  7778. let inf = k(self, 0x7C00);
  7779. let nan = self.s.m.cmp(c, pred::IUGT, mag, inf);
  7780. let r = self.s.m.select(c, nan, k0, r);
  7781. let r = if signed {
  7782. let n = self.s.m.bin(c, Bin::Sub, k0, r);
  7783. self.s.m.select(c, neg, n, r)
  7784. } else {
  7785. self.s.m.select(c, neg, k0, r)
  7786. };
  7787. let m16 = k(self, 0xFFFF);
  7788. Ok(self.s.m.bin(c, Bin::And, r, m16))
  7789. }
  7790. /// Half `high` of source `k` of a packed (VOP3P) operation, in the low
  7791. /// 16 bits: op_sel picks the half the low result reads, op_sel_hi the
  7792. /// half the high result reads. Packed integer instructions see the f32
  7793. /// bits of an inline float constant.
  7794. fn packed_src(&mut self, inst: &Inst, k: usize, high: bool, float: bool) -> Result<V, Why> {
  7795. let Fields::Valu(v) = &inst.fields else {
  7796. unreachable!()
  7797. };
  7798. let op = *v.src.get(k).ok_or("a missing operand")?;
  7799. let sel = if high { v.opsel_hi } else { v.opsel } >> k & 1 != 0;
  7800. let x = if float {
  7801. self.f16_operand(inst, &op)?
  7802. } else {
  7803. self.operand(inst, &op)?
  7804. };
  7805. let c = self.cur;
  7806. let x = if sel {
  7807. let k16 = self.s.m.i32(16);
  7808. self.s.m.bin(c, Bin::LShr, x, k16)
  7809. } else {
  7810. x
  7811. };
  7812. let m = self.s.m.i32(0xFFFF);
  7813. Ok(self.s.m.bin(c, Bin::And, x, m))
  7814. }
  7815. /// Packed 16-bit operations (`v_pk_*`): each half computed as the
  7816. /// 16-bit operation does, f16 through f32 as in [`Self::valu16`].
  7817. fn packed16(&mut self, inst: &Inst, op: &str, guard: Option<V>) -> Result<(), Why> {
  7818. let Fields::Valu(v) = &inst.fields else {
  7819. unreachable!()
  7820. };
  7821. let float = op.ends_with("_f16");
  7822. let n = match op {
  7823. "fma_f16" | "mad_u16" | "mad_i16" => 3,
  7824. "add_f16" | "mul_f16" | "min_f16" | "max_f16" | "add_u16" | "sub_u16" | "add_i16"
  7825. | "sub_i16" | "mul_lo_u16" | "lshlrev_b16" | "lshrrev_b16" | "ashrrev_i16"
  7826. | "max_u16" | "min_u16" | "max_i16" | "min_i16" => 2,
  7827. _ => return Err("a packed 16-bit operation"),
  7828. };
  7829. if v.omod != 0 || !float && (v.clamp || v.neg != 0 || v.neg_hi != 0) {
  7830. return Err("modifiers on a packed integer operation");
  7831. }
  7832. let c = self.cur;
  7833. let (i32t, f32t) = (self.s.t.i32, self.s.t.f32);
  7834. let mut halves = Vec::new();
  7835. for high in [false, true] {
  7836. let mut xs = Vec::new();
  7837. for k in 0..n {
  7838. let h = self.packed_src(inst, k, high, float)?;
  7839. if float {
  7840. let mut f = self
  7841. .s
  7842. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]);
  7843. let neg = if high { v.neg_hi } else { v.neg };
  7844. if neg >> k & 1 != 0 {
  7845. let z = self.s.m.f32(0x8000_0000);
  7846. f = self.s.m.bin(c, Bin::Sub, z, f);
  7847. }
  7848. xs.push(f);
  7849. } else {
  7850. xs.push(h);
  7851. }
  7852. }
  7853. let r = if float {
  7854. let mut f = match op {
  7855. "add_f16" => self.s.m.bin(c, Bin::Add, xs[0], xs[1]),
  7856. "mul_f16" => self.s.m.bin(c, Bin::Mul, xs[0], xs[1]),
  7857. "min_f16" => self.max_min(false, xs[0], xs[1]),
  7858. "max_f16" => self.max_min(true, xs[0], xs[1]),
  7859. // shortcut: FMad in f32, as v_fma_f16.
  7860. _ => self.fmad(xs[0], xs[1], xs[2]),
  7861. };
  7862. if v.clamp {
  7863. f = self.unary(7, f);
  7864. }
  7865. self.s
  7866. .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f])
  7867. } else {
  7868. let k16 = self.s.m.i32(16);
  7869. let sext = |l: &mut Self, x: V| {
  7870. let t = l.s.m.bin(c, Bin::Shl, x, k16);
  7871. l.s.m.bin(c, Bin::AShr, t, k16)
  7872. };
  7873. if op.ends_with("_i16") {
  7874. for x in &mut xs {
  7875. *x = sext(self, *x);
  7876. }
  7877. }
  7878. let k15 = self.s.m.i32(15);
  7879. match op {
  7880. "add_u16" | "add_i16" => self.s.m.bin(c, Bin::Add, xs[0], xs[1]),
  7881. "sub_u16" | "sub_i16" => self.s.m.bin(c, Bin::Sub, xs[0], xs[1]),
  7882. "mul_lo_u16" => self.s.m.bin(c, Bin::Mul, xs[0], xs[1]),
  7883. "mad_u16" | "mad_i16" => {
  7884. let m = self.s.m.bin(c, Bin::Mul, xs[0], xs[1]);
  7885. self.s.m.bin(c, Bin::Add, m, xs[2])
  7886. }
  7887. "lshlrev_b16" | "lshrrev_b16" | "ashrrev_i16" => {
  7888. let sh = self.s.m.bin(c, Bin::And, xs[0], k15);
  7889. let o = match op {
  7890. "lshlrev_b16" => Bin::Shl,
  7891. "lshrrev_b16" => Bin::LShr,
  7892. _ => Bin::AShr,
  7893. };
  7894. let x = if op == "ashrrev_i16" {
  7895. sext(self, xs[1])
  7896. } else {
  7897. xs[1]
  7898. };
  7899. self.s.m.bin(c, o, x, sh)
  7900. }
  7901. _ => {
  7902. let p = match op {
  7903. "max_u16" => pred::IUGT,
  7904. "min_u16" => pred::IULT,
  7905. "max_i16" => pred::SGT,
  7906. _ => pred::SLT,
  7907. };
  7908. let t = self.s.m.cmp(c, p, xs[0], xs[1]);
  7909. self.s.m.select(c, t, xs[0], xs[1])
  7910. }
  7911. }
  7912. };
  7913. let m = self.s.m.i32(0xFFFF);
  7914. halves.push(self.s.m.bin(c, Bin::And, r, m));
  7915. }
  7916. let k16 = self.s.m.i32(16);
  7917. let hi = self.s.m.bin(c, Bin::Shl, halves[1], k16);
  7918. let r = self.s.m.bin(c, Bin::Or, halves[0], hi);
  7919. let Some(Operand::Vector { reg, .. }) = v.dst else {
  7920. return Err("a packed result outside a VGPR");
  7921. };
  7922. self.write(inst, Reg::V(reg), r, guard);
  7923. Ok(())
  7924. }
  7925. fn integer(&mut self, inst: &Inst, name: &'static str) -> Result<V, Why> {
  7926. let c = self.cur;
  7927. let s = |l: &mut Self, k| l.src(inst, k);
  7928. let k = |l: &mut Self, x: u32| l.s.m.i32(x);
  7929. let m31 = |l: &mut Self, x: V| {
  7930. let k31 = l.s.m.i32(31);
  7931. l.s.m.bin(c, Bin::And, x, k31)
  7932. };
  7933. Ok(match name {
  7934. "v_and_b32" | "v_or_b32" | "v_xor_b32" | "v_add_nc_u32" | "v_sub_nc_u32"
  7935. | "v_subrev_nc_u32" | "v_mul_lo_u32" => {
  7936. let (a, b) = (s(self, 0)?, s(self, 1)?);
  7937. let (op, a, b) = match name {
  7938. "v_and_b32" => (Bin::And, a, b),
  7939. "v_or_b32" => (Bin::Or, a, b),
  7940. "v_xor_b32" => (Bin::Xor, a, b),
  7941. "v_add_nc_u32" => (Bin::Add, a, b),
  7942. "v_sub_nc_u32" => (Bin::Sub, a, b),
  7943. "v_subrev_nc_u32" => (Bin::Sub, b, a),
  7944. _ => (Bin::Mul, a, b),
  7945. };
  7946. self.s.m.bin(c, op, a, b)
  7947. }
  7948. "v_xnor_b32" => {
  7949. let (a, b) = (s(self, 0)?, s(self, 1)?);
  7950. let x = self.s.m.bin(c, Bin::Xor, a, b);
  7951. let ones = k(self, u32::MAX);
  7952. self.s.m.bin(c, Bin::Xor, x, ones)
  7953. }
  7954. "v_not_b32" => {
  7955. let a = s(self, 0)?;
  7956. let ones = k(self, u32::MAX);
  7957. self.s.m.bin(c, Bin::Xor, a, ones)
  7958. }
  7959. "v_lshlrev_b32" | "v_lshrrev_b32" | "v_ashrrev_i32" => {
  7960. let (sh, a) = (s(self, 0)?, s(self, 1)?);
  7961. let sh = m31(self, sh);
  7962. let op = match name {
  7963. "v_lshlrev_b32" => Bin::Shl,
  7964. "v_lshrrev_b32" => Bin::LShr,
  7965. _ => Bin::AShr,
  7966. };
  7967. self.s.m.bin(c, op, a, sh)
  7968. }
  7969. "v_lshl_add_u32" | "v_lshl_or_b32" | "v_add_lshl_u32" | "v_and_or_b32"
  7970. | "v_or3_b32" | "v_xad_u32" | "v_add3_u32" | "v_xor3_b32" => {
  7971. let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  7972. match name {
  7973. "v_lshl_add_u32" | "v_lshl_or_b32" => {
  7974. let b = m31(self, b);
  7975. let t = self.s.m.bin(c, Bin::Shl, a, b);
  7976. let op = if name == "v_lshl_add_u32" {
  7977. Bin::Add
  7978. } else {
  7979. Bin::Or
  7980. };
  7981. self.s.m.bin(c, op, t, d)
  7982. }
  7983. "v_add_lshl_u32" => {
  7984. let t = self.s.m.bin(c, Bin::Add, a, b);
  7985. let d = m31(self, d);
  7986. self.s.m.bin(c, Bin::Shl, t, d)
  7987. }
  7988. _ => {
  7989. let (o1, o2) = match name {
  7990. "v_and_or_b32" => (Bin::And, Bin::Or),
  7991. "v_or3_b32" => (Bin::Or, Bin::Or),
  7992. "v_xad_u32" => (Bin::Xor, Bin::Add),
  7993. "v_add3_u32" => (Bin::Add, Bin::Add),
  7994. _ => (Bin::Xor, Bin::Xor),
  7995. };
  7996. let t = self.s.m.bin(c, o1, a, b);
  7997. self.s.m.bin(c, o2, t, d)
  7998. }
  7999. }
  8000. }
  8001. "v_mul_u32_u24" | "v_mul_i32_i24" => {
  8002. let (a, b) = (s(self, 0)?, s(self, 1)?);
  8003. let (sh, op) = (
  8004. k(self, 8),
  8005. if name == "v_mul_i32_i24" {
  8006. Bin::AShr
  8007. } else {
  8008. Bin::LShr
  8009. },
  8010. );
  8011. let a = self.s.m.bin(c, Bin::Shl, a, sh);
  8012. let a = self.s.m.bin(c, op, a, sh);
  8013. let b = self.s.m.bin(c, Bin::Shl, b, sh);
  8014. let b = self.s.m.bin(c, op, b, sh);
  8015. self.s.m.bin(c, Bin::Mul, a, b)
  8016. }
  8017. "v_bfe_u32" | "v_bfe_i32" => {
  8018. let (a, off, w) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  8019. let w = m31(self, w);
  8020. self.bfe(a, off, w, name == "v_bfe_i32")
  8021. }
  8022. "v_bfi_b32" => {
  8023. let (m, a, b) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  8024. let ones = k(self, u32::MAX);
  8025. let nm = self.s.m.bin(c, Bin::Xor, m, ones);
  8026. let x = self.s.m.bin(c, Bin::And, m, a);
  8027. let y = self.s.m.bin(c, Bin::And, nm, b);
  8028. self.s.m.bin(c, Bin::Or, x, y)
  8029. }
  8030. "v_max_i32" | "v_min_i32" | "v_max_u32" | "v_min_u32" => {
  8031. let (a, b) = (s(self, 0)?, s(self, 1)?);
  8032. let p = match name {
  8033. "v_max_i32" => pred::SGT,
  8034. "v_min_i32" => pred::SLT,
  8035. "v_max_u32" => pred::IUGT,
  8036. _ => pred::IULT,
  8037. };
  8038. let t = self.s.m.cmp(c, p, a, b);
  8039. self.s.m.select(c, t, a, b)
  8040. }
  8041. "v_mul_hi_u32" | "v_mul_hi_i32" => {
  8042. let (a, b) = (s(self, 0)?, s(self, 1)?);
  8043. self.mul_hi(a, b, name == "v_mul_hi_i32")
  8044. }
  8045. "v_alignbit_b32" | "v_alignbyte_b32" => {
  8046. // The low dword of {a, b} >> shift.
  8047. let (a, b, sh) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  8048. let sh = if name == "v_alignbyte_b32" {
  8049. let three = k(self, 3);
  8050. let t = self.s.m.bin(c, Bin::And, sh, three);
  8051. let k3 = k(self, 3);
  8052. self.s.m.bin(c, Bin::Shl, t, k3)
  8053. } else {
  8054. m31(self, sh)
  8055. };
  8056. let k32 = k(self, 32);
  8057. let lo = self.s.m.bin(c, Bin::LShr, b, sh);
  8058. let left = self.s.m.bin(c, Bin::Sub, k32, sh);
  8059. let left = m31(self, left);
  8060. let hi = self.s.m.bin(c, Bin::Shl, a, left);
  8061. let zero = k(self, 0);
  8062. let none = self.s.m.cmp(c, pred::EQ, sh, zero);
  8063. let hi = self.s.m.select(c, none, zero, hi);
  8064. self.s.m.bin(c, Bin::Or, lo, hi)
  8065. }
  8066. "v_bfrev_b32" => {
  8067. let a = s(self, 0)?;
  8068. self.s
  8069. .op(c, "unary.i32", Attr::ReadNone, self.s.t.i32, 30, &[a])
  8070. }
  8071. "v_bcnt_u32_b32" => {
  8072. let (a, b) = (s(self, 0)?, s(self, 1)?);
  8073. let n = self
  8074. .s
  8075. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 31, &[a]);
  8076. self.s.m.bin(c, Bin::Add, n, b)
  8077. }
  8078. "v_mad_u32_u24" | "v_mad_i32_i24" => {
  8079. let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  8080. let (sh, op) = (
  8081. k(self, 8),
  8082. if name == "v_mad_i32_i24" {
  8083. Bin::AShr
  8084. } else {
  8085. Bin::LShr
  8086. },
  8087. );
  8088. let a = self.s.m.bin(c, Bin::Shl, a, sh);
  8089. let a = self.s.m.bin(c, op, a, sh);
  8090. let b = self.s.m.bin(c, Bin::Shl, b, sh);
  8091. let b = self.s.m.bin(c, op, b, sh);
  8092. let m = self.s.m.bin(c, Bin::Mul, a, b);
  8093. self.s.m.bin(c, Bin::Add, m, d)
  8094. }
  8095. "v_min3_i32" | "v_max3_i32" | "v_min3_u32" | "v_max3_u32" | "v_med3_i32"
  8096. | "v_med3_u32" => {
  8097. let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  8098. let signed = name.ends_with("i32");
  8099. let (lt, gt) = if signed {
  8100. (pred::SLT, pred::SGT)
  8101. } else {
  8102. (pred::IULT, pred::IUGT)
  8103. };
  8104. let pick = |l: &mut Self, p, x, y| {
  8105. let t = l.s.m.cmp(c, p, x, y);
  8106. l.s.m.select(c, t, x, y)
  8107. };
  8108. match &name[2..6] {
  8109. "min3" => {
  8110. let t = pick(self, lt, a, b);
  8111. pick(self, lt, t, d)
  8112. }
  8113. "max3" => {
  8114. let t = pick(self, gt, a, b);
  8115. pick(self, gt, t, d)
  8116. }
  8117. _ => {
  8118. let lo = pick(self, lt, a, b);
  8119. let hi = pick(self, gt, a, b);
  8120. let t = pick(self, lt, hi, d);
  8121. pick(self, gt, lo, t)
  8122. }
  8123. }
  8124. }
  8125. "v_perm_b32" => {
  8126. // Byte i of the result is byte S of {src0, src1} (src1 the
  8127. // low dword) for selector byte S below 8; 8-11 repeat the
  8128. // sign of bytes 1 and 3 of src1, then of src0; 12 is 0x00,
  8129. // higher 0xFF.
  8130. let Fields::Valu(v) = &inst.fields else {
  8131. unreachable!()
  8132. };
  8133. let sel = match v.src.get(2) {
  8134. Some(&Operand::Literal(x)) => x,
  8135. Some(&Operand::Const(k)) => crate::resource::inline(k).ok_or(name)?,
  8136. _ => {
  8137. // A computed selector: each byte picked at run time.
  8138. let (a, b, sv) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  8139. let mut r = k(self, 0);
  8140. for i in 0..4u32 {
  8141. let (sh, ff) = (k(self, 8 * i), k(self, 0xFF));
  8142. let sel = self.s.m.bin(c, Bin::LShr, sv, sh);
  8143. let sel = self.s.m.bin(c, Bin::And, sel, ff);
  8144. // Select a dword and a byte within it.
  8145. // Later selects handle codes 8 and above.
  8146. let four = k(self, 4);
  8147. let zero = k(self, 0);
  8148. let high = self.s.m.bin(c, Bin::And, sel, four);
  8149. let high = self.s.m.cmp(c, pred::NE, high, zero);
  8150. let word = self.s.m.select(c, high, a, b);
  8151. let three = k(self, 3);
  8152. let index = self.s.m.bin(c, Bin::And, sel, three);
  8153. let bits = self.s.m.bin(c, Bin::Shl, index, three);
  8154. let x = self.s.m.bin(c, Bin::LShr, word, bits);
  8155. let mut byte = self.s.m.bin(c, Bin::And, x, ff);
  8156. // 8-11: the sign of bytes 1, 3 of src1, then of src0.
  8157. for (n, src, bit) in [(8, b, 15), (9, b, 31), (10, a, 15), (11, a, 31)]
  8158. {
  8159. let left = k(self, 31 - bit);
  8160. let t = self.s.m.bin(c, Bin::Shl, src, left);
  8161. let k31 = k(self, 31);
  8162. let t = self.s.m.bin(c, Bin::AShr, t, k31);
  8163. let t = self.s.m.bin(c, Bin::And, t, ff);
  8164. let kn = k(self, n);
  8165. let is = self.s.m.cmp(c, pred::EQ, sel, kn);
  8166. byte = self.s.m.select(c, is, t, byte);
  8167. }
  8168. let (k12, z) = (k(self, 12), k(self, 0));
  8169. let is12 = self.s.m.cmp(c, pred::EQ, sel, k12);
  8170. byte = self.s.m.select(c, is12, z, byte);
  8171. let above = self.s.m.cmp(c, pred::IUGT, sel, k12);
  8172. byte = self.s.m.select(c, above, ff, byte);
  8173. let at = k(self, 8 * i);
  8174. let byte = self.s.m.bin(c, Bin::Shl, byte, at);
  8175. r = self.s.m.bin(c, Bin::Or, r, byte);
  8176. }
  8177. return Ok(r);
  8178. }
  8179. };
  8180. let (a, b) = (s(self, 0)?, s(self, 1)?);
  8181. let mut r = k(self, 0);
  8182. for i in 0..4 {
  8183. let pick = sel >> (8 * i) & 0xFF;
  8184. let byte = match pick {
  8185. 0..=7 => {
  8186. let (src, n) = if pick < 4 { (b, pick) } else { (a, pick - 4) };
  8187. let sh = k(self, 8 * n);
  8188. let t = self.s.m.bin(c, Bin::LShr, src, sh);
  8189. let ff = k(self, 0xFF);
  8190. self.s.m.bin(c, Bin::And, t, ff)
  8191. }
  8192. 8..=11 => {
  8193. let src = if pick < 10 { b } else { a };
  8194. let bit = if pick % 2 == 0 { 15 } else { 31 };
  8195. let left = k(self, 31 - bit);
  8196. let t = self.s.m.bin(c, Bin::Shl, src, left);
  8197. let k31 = k(self, 31);
  8198. let t = self.s.m.bin(c, Bin::AShr, t, k31);
  8199. let ff = k(self, 0xFF);
  8200. self.s.m.bin(c, Bin::And, t, ff)
  8201. }
  8202. 12 => continue,
  8203. _ => k(self, 0xFF),
  8204. };
  8205. let at = k(self, 8 * i);
  8206. let byte = self.s.m.bin(c, Bin::Shl, byte, at);
  8207. r = self.s.m.bin(c, Bin::Or, r, byte);
  8208. }
  8209. r
  8210. }
  8211. "v_bfm_b32" => {
  8212. // ((1 << src0[4:0]) - 1) << src1[4:0]
  8213. let (a, b) = (s(self, 0)?, s(self, 1)?);
  8214. let one = k(self, 1);
  8215. let (a, b) = (m31(self, a), m31(self, b));
  8216. let m = self.s.m.bin(c, Bin::Shl, one, a);
  8217. let m = self.s.m.bin(c, Bin::Sub, m, one);
  8218. self.s.m.bin(c, Bin::Shl, m, b)
  8219. }
  8220. "v_cvt_pk_u8_f32" => {
  8221. // src0 rounded to nearest even and saturated to a byte, into
  8222. // byte src1[1:0] of src2.
  8223. let f = self.fsrc(inst, 0)?;
  8224. let (b, d) = (s(self, 1)?, s(self, 2)?);
  8225. let f = self.unary(26, f);
  8226. let (zero, max) = (self.s.m.f32(0), self.s.m.f32(255.0f32.to_bits()));
  8227. let f = self.binary(35, f, zero);
  8228. let f = self.binary(36, f, max);
  8229. let x = self.s.m.cast(c, Cast::FpToUi, f, self.s.t.i32);
  8230. let (three, k3) = (k(self, 3), k(self, 3));
  8231. let sh = self.s.m.bin(c, Bin::And, b, three);
  8232. let sh = self.s.m.bin(c, Bin::Shl, sh, k3);
  8233. let x = self.s.m.bin(c, Bin::Shl, x, sh);
  8234. let ff = k(self, 0xFF);
  8235. let hole = self.s.m.bin(c, Bin::Shl, ff, sh);
  8236. let ones = k(self, u32::MAX);
  8237. let hole = self.s.m.bin(c, Bin::Xor, hole, ones);
  8238. let d = self.s.m.bin(c, Bin::And, d, hole);
  8239. self.s.m.bin(c, Bin::Or, d, x)
  8240. }
  8241. "v_ffbl_b32" => {
  8242. // -1 for zero, as DXIL's first-bit-low.
  8243. let a = s(self, 0)?;
  8244. self.s
  8245. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 32, &[a])
  8246. }
  8247. "v_mbcnt_lo_u32_b32" | "v_mbcnt_hi_u32_b32" => {
  8248. // Bits of the mask's low (high) half below this lane, plus src1:
  8249. // with an all-ones mask, the lane index.
  8250. let (a, b) = (s(self, 0)?, s(self, 1)?);
  8251. // Mesh lanes are the console's by construction; pixel and
  8252. // vertex lanes are the host's, as their masks are.
  8253. if self.mask_data == MaskData::Host {
  8254. // Host lanes: the mask must be one (a ballot) or all lanes.
  8255. let Fields::Valu(v) = &inst.fields else {
  8256. unreachable!()
  8257. };
  8258. let host = match v.src.first() {
  8259. Some(&Operand::Const(193)) => true,
  8260. Some(&Operand::Scalar { code, .. }) => {
  8261. inst.read(Reg::S(code)).is_some_and(|m| {
  8262. self.x.st.masks.contains_key(&m) || self.x.st.highs.contains_key(&m)
  8263. })
  8264. }
  8265. _ => false,
  8266. };
  8267. if !host {
  8268. return Err("v_mbcnt of a mask that is no ballot (console lane layout)");
  8269. }
  8270. self.s.flags |= flags::WAVE_OPS;
  8271. } else if self.s.mesh.is_none() {
  8272. self.cross_lane(false)?;
  8273. }
  8274. let lane = self.console_lane();
  8275. let below = if name == "v_mbcnt_lo_u32_b32" {
  8276. lane
  8277. } else {
  8278. let (k32, z) = (k(self, 32), k(self, 0));
  8279. let t = self.s.m.bin(c, Bin::Sub, lane, k32);
  8280. let low = self.s.m.cmp(c, pred::IULT, lane, k32);
  8281. self.s.m.select(c, low, z, t)
  8282. };
  8283. // (1 << below) - 1, all ones from 32 on.
  8284. let (one, k32, ones) = (k(self, 1), k(self, 32), k(self, u32::MAX));
  8285. let sh = m31(self, below);
  8286. let m = self.s.m.bin(c, Bin::Shl, one, sh);
  8287. let m = self.s.m.bin(c, Bin::Sub, m, one);
  8288. let full = self.s.m.cmp(c, pred::IUGE, below, k32);
  8289. let m = self.s.m.select(c, full, ones, m);
  8290. let x = self.s.m.bin(c, Bin::And, a, m);
  8291. let n = self
  8292. .s
  8293. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 31, &[x]);
  8294. self.s.m.bin(c, Bin::Add, n, b)
  8295. }
  8296. _ => return Err(name),
  8297. })
  8298. }
  8299. fn compare(&mut self, inst: &Inst, rest: &str) -> Result<(), Why> {
  8300. let (op, ty) = rest.rsplit_once('_').ok_or("a compare")?;
  8301. let c = self.cur;
  8302. let r = match ty {
  8303. "f32" | "f16" if op == "class" => {
  8304. // Bit k of src1 tests class k: signalling NaN, quiet NaN,
  8305. // -inf, -normal, -denormal, -0, +0, +denormal, +normal, +inf.
  8306. let f16 = ty == "f16";
  8307. let x = if f16 {
  8308. let Fields::Valu(v) = &inst.fields else {
  8309. unreachable!()
  8310. };
  8311. let mut h = self.half_src(inst, 0)?;
  8312. if v.abs & 1 != 0 {
  8313. let m = self.s.m.i32(0x7FFF);
  8314. h = self.s.m.bin(c, Bin::And, h, m);
  8315. }
  8316. if v.neg & 1 != 0 {
  8317. let s = self.s.m.i32(0x8000);
  8318. h = self.s.m.bin(c, Bin::Xor, h, s);
  8319. }
  8320. h
  8321. } else {
  8322. let x = self.fsrc(inst, 0)?;
  8323. self.as_int(x)
  8324. };
  8325. let mask = self.src(inst, 1)?;
  8326. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  8327. let (exp_sh, sign_sh, exp_mask, mant_mask, quiet_bit) = if f16 {
  8328. (10, 15, 0x1F, 0x03FF, 0x0200)
  8329. } else {
  8330. (23, 31, 0xFF, 0x7F_FFFF, 0x40_0000)
  8331. };
  8332. let (k_exp, k_sign, k_emax, mant, quiet) = (
  8333. k(self, exp_sh),
  8334. k(self, sign_sh),
  8335. k(self, exp_mask),
  8336. k(self, mant_mask),
  8337. k(self, quiet_bit),
  8338. );
  8339. let e = self.s.m.bin(c, Bin::LShr, x, k_exp);
  8340. let e = self.s.m.bin(c, Bin::And, e, k_emax);
  8341. let m = self.s.m.bin(c, Bin::And, x, mant);
  8342. let neg = self.s.m.bin(c, Bin::LShr, x, k_sign);
  8343. let zero = k(self, 0);
  8344. let (e0, emax) = (
  8345. self.s.m.cmp(c, pred::EQ, e, zero),
  8346. self.s.m.cmp(c, pred::EQ, e, k_emax),
  8347. );
  8348. let m0 = self.s.m.cmp(c, pred::EQ, m, zero);
  8349. let q = self.s.m.bin(c, Bin::And, x, quiet);
  8350. let q = self.s.m.cmp(c, pred::NE, q, zero);
  8351. // Positive classes 6-9; negative ones are 11 minus those.
  8352. let (normal, inf, zero_c, denorm) =
  8353. (k(self, 8), k(self, 9), k(self, 6), k(self, 7));
  8354. let t = self.s.m.select(c, m0, zero_c, denorm);
  8355. let t = self.s.m.select(c, e0, t, normal);
  8356. let t = self.s.m.select(c, emax, inf, t);
  8357. let eleven = k(self, 11);
  8358. let mirrored = self.s.m.bin(c, Bin::Sub, eleven, t);
  8359. let is_neg = self.s.m.cmp(c, pred::NE, neg, zero);
  8360. let t = self.s.m.select(c, is_neg, mirrored, t);
  8361. let (one, snan) = (k(self, 1), k(self, 0));
  8362. let nan_class = self.s.m.select(c, q, one, snan);
  8363. let yes = self.s.m.bool(true);
  8364. let nan = self.s.m.bin(c, Bin::Xor, m0, yes);
  8365. let nan = self.s.m.bin(c, Bin::And, nan, emax);
  8366. let t = self.s.m.select(c, nan, nan_class, t);
  8367. let bit = self.s.m.bin(c, Bin::LShr, mask, t);
  8368. let bit = self.s.m.bin(c, Bin::And, bit, one);
  8369. self.s.m.cmp(c, pred::NE, bit, zero)
  8370. }
  8371. "f32" | "f16" => {
  8372. let (a, b) = if ty == "f16" {
  8373. (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?)
  8374. } else {
  8375. (self.fsrc(inst, 0)?, self.fsrc(inst, 1)?)
  8376. };
  8377. if op == "lg" {
  8378. // Ordered and not equal, false for a NaN, as `olt | ogt`.
  8379. // `fcmp one` means the same, but the AMD D3D12 driver
  8380. // runs it as unordered (true for a NaN) where NVIDIA
  8381. // and WARP do not; olt and ogt agree on all three.
  8382. let lt = self.s.m.cmp(c, pred::OLT, a, b);
  8383. let gt = self.s.m.cmp(c, pred::OGT, a, b);
  8384. self.s.m.bin(c, Bin::Or, lt, gt)
  8385. } else {
  8386. let p = match op {
  8387. "f" => pred::FALSE,
  8388. "lt" => pred::OLT,
  8389. "eq" => pred::OEQ,
  8390. "le" => pred::OLE,
  8391. "gt" => pred::OGT,
  8392. "ge" => pred::OGE,
  8393. "o" => pred::ORD,
  8394. "u" => pred::UNO,
  8395. "nge" => pred::ULT,
  8396. "nlg" => pred::UEQ,
  8397. "ngt" => pred::ULE,
  8398. "nle" => pred::UGT,
  8399. "neq" => pred::UNE,
  8400. "nlt" => pred::UGE,
  8401. "tru" => pred::TRUE,
  8402. _ => return Err(inst.name()),
  8403. };
  8404. self.s.m.cmp(c, p, a, b)
  8405. }
  8406. }
  8407. "u64" | "i64" => {
  8408. let (a, b) = (self.src64(inst, 0)?, self.src64(inst, 1)?);
  8409. let signed = ty == "i64";
  8410. let p = match op {
  8411. "eq" => pred::EQ,
  8412. "ne" | "lg" => pred::NE,
  8413. "lt" if signed => pred::SLT,
  8414. "le" if signed => pred::SLE,
  8415. "gt" if signed => pred::SGT,
  8416. "ge" if signed => pred::SGE,
  8417. "lt" => pred::IULT,
  8418. "le" => pred::IULE,
  8419. "gt" => pred::IUGT,
  8420. "ge" => pred::IUGE,
  8421. _ => return Err("a 64-bit compare"),
  8422. };
  8423. self.s.m.cmp(c, p, a, b)
  8424. }
  8425. "u32" | "i32" | "u16" | "i16" => {
  8426. let (a, b) = if ty.ends_with("16") {
  8427. let (mut a, mut b) = (self.half_src(inst, 0)?, self.half_src(inst, 1)?);
  8428. if ty == "i16" {
  8429. let k16 = self.s.m.i32(16);
  8430. for x in [&mut a, &mut b] {
  8431. let t = self.s.m.bin(c, Bin::Shl, *x, k16);
  8432. *x = self.s.m.bin(c, Bin::AShr, t, k16);
  8433. }
  8434. }
  8435. (a, b)
  8436. } else {
  8437. (self.src(inst, 0)?, self.src(inst, 1)?)
  8438. };
  8439. let signed = ty == "i32" || ty == "i16";
  8440. let p = match op {
  8441. "eq" => pred::EQ,
  8442. "ne" | "lg" => pred::NE,
  8443. "lt" if signed => pred::SLT,
  8444. "le" if signed => pred::SLE,
  8445. "gt" if signed => pred::SGT,
  8446. "ge" if signed => pred::SGE,
  8447. "lt" => pred::IULT,
  8448. "le" => pred::IULE,
  8449. "gt" => pred::IUGT,
  8450. "ge" => pred::IUGE,
  8451. "f" | "t" => {
  8452. self.lane(inst, Some(op == "t"));
  8453. return Ok(());
  8454. }
  8455. _ => return Err("an integer compare"),
  8456. };
  8457. self.s.m.cmp(c, p, a, b)
  8458. }
  8459. _ => return Err(inst.name()),
  8460. };
  8461. self.lane_bits_for(inst, r);
  8462. Ok(())
  8463. }
  8464. fn lane(&mut self, inst: &Inst, value: Option<bool>) {
  8465. let b = self.s.m.bool(value == Some(true));
  8466. self.lane_bits_for(inst, b);
  8467. }
  8468. fn lane_bits_for(&mut self, inst: &Inst, r: V) {
  8469. let Fields::Valu(v) = &inst.fields else {
  8470. return;
  8471. };
  8472. let code = if inst.name().starts_with("v_cmpx") {
  8473. Some(EXEC)
  8474. } else {
  8475. match v.dst {
  8476. Some(Operand::Scalar { code, .. }) => Some(code),
  8477. _ => None,
  8478. }
  8479. };
  8480. if let Some(lo) = code.and_then(|c| inst.write(Reg::S(c))) {
  8481. self.lane_bits.insert(lo, r);
  8482. }
  8483. for &(_, w) in &inst.writes {
  8484. self.vals
  8485. .entry(w)
  8486. .or_insert(Val::Missing("a lane mask read as data"));
  8487. }
  8488. }
  8489. fn interp(&mut self, inst: &Inst, site: Site) -> Result<(), Why> {
  8490. let Some(&interp) = self.interps.get(&site) else {
  8491. return Err("the first half of an interpolation");
  8492. };
  8493. let name = inst.name();
  8494. let (dst, src) = match &inst.fields {
  8495. Fields::Vintrp { dst, src, .. } => (*dst, Some(*src)),
  8496. Fields::Valu(v) => {
  8497. if v.abs != 0 || v.neg != 0 {
  8498. return Err("interpolation operand modifiers");
  8499. }
  8500. (v.dst.ok_or("an interpolation")?, v.src.get(1).copied())
  8501. }
  8502. _ => unreachable!(),
  8503. };
  8504. let Operand::Vector { reg, .. } = dst else {
  8505. return Err("an interpolation");
  8506. };
  8507. // A float operand of the instruction.
  8508. let float = |l: &mut Self, op: Option<Operand>| -> Result<V, Why> {
  8509. let x = l.operand(inst, &op.ok_or("an interpolation operand")?)?;
  8510. Ok(l.as_float(x))
  8511. };
  8512. // What the result adds to the evaluated channel (a second half's
  8513. // first half, when the halves evaluate on their own).
  8514. let mut add = None;
  8515. let (attribute, eval) = match *interp {
  8516. Interp::Interpolated {
  8517. attribute,
  8518. barycentric,
  8519. ..
  8520. } => {
  8521. let mode = interp_mode(barycentric).ok_or("pull-model interpolation")?;
  8522. let eval = if self.per_vertex(attribute.row) {
  8523. // The element is read per vertex elsewhere, so it is
  8524. // constant: weigh its vertices with SV_Barycentrics.
  8525. let mut ij = [None; 2];
  8526. for (index, w) in ij.iter_mut().enumerate() {
  8527. let x = match self.barycentric(barycentric, index as u8) {
  8528. Val::I32(x) => x,
  8529. Val::Missing(w) => return Err(w),
  8530. Val::Bit(_) => unreachable!(),
  8531. };
  8532. *w = Some(self.as_float(x));
  8533. }
  8534. Eval::Weights {
  8535. p0: true,
  8536. i: ij[0],
  8537. j: ij[1],
  8538. }
  8539. } else {
  8540. Eval::Mode(mode)
  8541. };
  8542. (attribute, eval)
  8543. }
  8544. // P0, the provoking vertex: a flat (nointerpolation) input.
  8545. Interp::Vertex {
  8546. attribute,
  8547. vertex: 2,
  8548. } => (attribute, Eval::Mode(1)),
  8549. // P10 and P20: what the first and second halves weigh, P1 - P0
  8550. // and P2 - P0, which is what the hardware holds for an
  8551. // attribute the program also interpolates.
  8552. Interp::Vertex { attribute, vertex } if self.interpolated(attribute.row) => {
  8553. let one = Some(self.s.m.f32(1f32.to_bits()));
  8554. let (i, j) = if vertex == 0 {
  8555. (one, None)
  8556. } else {
  8557. (None, one)
  8558. };
  8559. (attribute, Eval::Weights { p0: false, i, j })
  8560. }
  8561. Interp::Vertex { .. } => return Err("a non-provoking vertex value"),
  8562. // A half of an interpolation with computed i or j: P0 + i P10,
  8563. // or the old dst (f16: the third operand) + j P20.
  8564. Interp::Weighted { attribute } if name.starts_with("v_interp_p1") => {
  8565. let i = Some(float(self, src)?);
  8566. (
  8567. attribute,
  8568. Eval::Weights {
  8569. p0: true,
  8570. i,
  8571. j: None,
  8572. },
  8573. )
  8574. }
  8575. Interp::Weighted { attribute } => {
  8576. let old = match &inst.fields {
  8577. Fields::Valu(v) => v.src.get(2).copied(),
  8578. _ => Some(dst),
  8579. };
  8580. add = Some(float(self, old)?);
  8581. let j = Some(float(self, src)?);
  8582. (
  8583. attribute,
  8584. Eval::Weights {
  8585. p0: false,
  8586. i: None,
  8587. j,
  8588. },
  8589. )
  8590. }
  8591. };
  8592. let packing = match &self.x.native.io {
  8593. StageIo::Ps { inputs, .. } => inputs
  8594. .iter()
  8595. .find(|i| i.row == attribute.row && i.fp16)
  8596. .map(|i| {
  8597. let packs = if i.pack2 {
  8598. input_packs(&self.x.native.io, &self.s.inputs)
  8599. } else {
  8600. Vec::new()
  8601. };
  8602. (i.pack2, packs)
  8603. }),
  8604. _ => None,
  8605. };
  8606. let f16 = name.ends_with("_f16");
  8607. // The evaluated channel plus `add`, as a float.
  8608. let total = |l: &mut Self, row: u8, ch: u8| -> Result<V, Why> {
  8609. let x = l.eval_channel(row, ch, eval)?;
  8610. let x = l.as_float(x);
  8611. Ok(match add {
  8612. Some(a) => l.s.m.bin(l.cur, Bin::Add, a, x),
  8613. None => x,
  8614. })
  8615. };
  8616. let x = match packing {
  8617. None if f16 || attribute.high => return Err("a 16-bit read of a 32-bit input"),
  8618. None => {
  8619. let x = total(self, attribute.row, attribute.channel)?;
  8620. self.as_int(x)
  8621. }
  8622. Some((pack2, packs)) => {
  8623. // 16-bit values: one in the low half of each dword, or two
  8624. // per dword (`packed_half`); the host's are 32-bit floats.
  8625. let half = |l: &mut Self, h: u8| -> Result<Option<V>, Why> {
  8626. let src = if pack2 {
  8627. packed_half(&l.s.inputs, &packs, attribute.row, h)
  8628. } else {
  8629. h.is_multiple_of(2).then_some((attribute.row, h / 2))
  8630. };
  8631. match src {
  8632. Some((row, ch)) => total(l, row, ch).map(Some),
  8633. None => Ok(None),
  8634. }
  8635. };
  8636. let to_f16 = |l: &mut Self, f: V| {
  8637. let i32t = l.s.t.i32;
  8638. l.s.op(l.cur, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f])
  8639. };
  8640. let h = 2 * attribute.channel + u8::from(attribute.high);
  8641. let c = self.cur;
  8642. if name == "v_interp_p1ll_f16" {
  8643. // An f32 result from 16-bit vertex values.
  8644. let f = half(self, h)?.ok_or("a packed input half no element holds")?;
  8645. self.as_int(f)
  8646. } else if f16 {
  8647. let f = half(self, h)?.ok_or("a packed input half no element holds")?;
  8648. let lo = to_f16(self, f);
  8649. self.low_half(inst, reg, lo)
  8650. } else if matches!(eval, Eval::Mode(1)) {
  8651. // The whole dword of a flat input: both halves.
  8652. let h = 2 * attribute.channel;
  8653. let z = self.s.m.i32(0);
  8654. let lo = match half(self, h)? {
  8655. Some(f) => to_f16(self, f),
  8656. None => z,
  8657. };
  8658. let hi = match half(self, h + 1)? {
  8659. Some(f) => to_f16(self, f),
  8660. None => z,
  8661. };
  8662. let k16 = self.s.m.i32(16);
  8663. let hi = self.s.m.bin(c, Bin::Shl, hi, k16);
  8664. self.s.m.bin(c, Bin::Or, lo, hi)
  8665. } else {
  8666. return Err("32-bit interpolation of a 16-bit input");
  8667. }
  8668. }
  8669. };
  8670. // A pixel interpolates in every lane; guards only hide inactive ones.
  8671. self.write(inst, Reg::V(reg), x, None);
  8672. Ok(())
  8673. }
  8674. /// Whether the program reads attribute row `row` per vertex (an
  8675. /// interpolation with computed barycentrics, or P10 or P20): then its
  8676. /// element is declared constant and read with `attributeAtVertex`.
  8677. fn per_vertex(&self, row: u8) -> bool {
  8678. self.x.io.interps.iter().any(|(_, i)| match *i {
  8679. Interp::Weighted { attribute } => attribute.row == row,
  8680. Interp::Vertex { attribute, vertex } => {
  8681. attribute.row == row && vertex != 2 && self.interpolated(row)
  8682. }
  8683. Interp::Interpolated { .. } => false,
  8684. })
  8685. }
  8686. /// Whether the program interpolates attribute row `row` (so the
  8687. /// hardware holds P1 - P0 and P2 - P0 for it).
  8688. fn interpolated(&self, row: u8) -> bool {
  8689. self.x.io.interps.iter().any(|(_, i)| match *i {
  8690. Interp::Interpolated { attribute, .. } | Interp::Weighted { attribute } => {
  8691. attribute.row == row
  8692. }
  8693. Interp::Vertex { .. } => false,
  8694. })
  8695. }
  8696. /// Channel `ch` of input row `row` evaluated as `eval` says, as raw bits.
  8697. fn eval_channel(&mut self, row: u8, ch: u8, eval: Eval) -> Result<V, Why> {
  8698. let (id, col) = self
  8699. .find_input(row, ch)
  8700. .ok_or("an input the signature lacks")?;
  8701. let mode = match eval {
  8702. Eval::Mode(mode) => mode,
  8703. Eval::Weights { .. } => 1,
  8704. };
  8705. let e = &mut self.s.inputs[id];
  8706. if e.interp != mode && e.usage != 0 {
  8707. return Err("one input interpolated two ways");
  8708. }
  8709. e.interp = mode;
  8710. let Eval::Weights { p0, i, j } = eval else {
  8711. return match self.load_any_input(id, col) {
  8712. Val::I32(x) => Ok(x),
  8713. _ => Err("an input"),
  8714. };
  8715. };
  8716. let v0 = self.vertex_input(id, col, 0);
  8717. let c = self.cur;
  8718. let mut acc = p0.then_some(v0);
  8719. for (k, w) in [(1, i), (2, j)] {
  8720. let Some(w) = w else { continue };
  8721. let vk = self.vertex_input(id, col, k);
  8722. let d = self.s.m.bin(c, Bin::Sub, vk, v0);
  8723. acc = Some(match acc {
  8724. Some(a) => self.fmad(w, d, a),
  8725. None => self.s.m.bin(c, Bin::Mul, w, d),
  8726. });
  8727. }
  8728. let acc = acc.ok_or("an interpolation")?;
  8729. Ok(self.as_int(acc))
  8730. }
  8731. /// Vertex `k` (0 the provoking vertex, as `barycentric` orders them)
  8732. /// of a constant input element's channel, as a float.
  8733. fn vertex_input(&mut self, id: usize, col: u8, k: u8) -> V {
  8734. let e = &mut self.s.inputs[id];
  8735. e.usage |= 1 << col;
  8736. let int = e.comp != 9;
  8737. let (ty, suffix) = if int {
  8738. (self.s.t.i32, ".i32")
  8739. } else {
  8740. (self.s.t.f32, ".f32")
  8741. };
  8742. self.s.flags |= flags::BARYCENTRICS;
  8743. let entry = self.s.entry;
  8744. let args = [
  8745. self.s.m.i32(id as u32),
  8746. self.s.m.i32(0),
  8747. self.s.m.i8(col),
  8748. self.s.m.i8(k),
  8749. ];
  8750. let v = self.s.op(
  8751. entry,
  8752. &format!("attributeAtVertex{suffix}"),
  8753. Attr::ReadNone,
  8754. ty,
  8755. 137,
  8756. &args,
  8757. );
  8758. if int {
  8759. self.s.m.cast(entry, Cast::Bitcast, v, self.s.t.f32)
  8760. } else {
  8761. v
  8762. }
  8763. }
  8764. /// `x` (an f16 in the low bits) as the low half of VGPR `reg`: 16-bit
  8765. /// results keep the register's high half (GFX10).
  8766. fn low_half(&mut self, inst: &Inst, reg: u8, x: V) -> V {
  8767. let c = self.cur;
  8768. let old = match inst.read(Reg::V(reg)).map(|o| self.i32_of(o)) {
  8769. Some(Ok(o)) => o,
  8770. _ => self.s.m.i32(0),
  8771. };
  8772. let (high, low) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF));
  8773. let old = self.s.m.bin(c, Bin::And, old, high);
  8774. let x = self.s.m.bin(c, Bin::And, x, low);
  8775. self.s.m.bin(c, Bin::Or, old, x)
  8776. }
  8777. fn image(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  8778. let Fields::Image {
  8779. data,
  8780. addr,
  8781. dmask,
  8782. dim,
  8783. unorm,
  8784. a16,
  8785. d16,
  8786. tfe,
  8787. lwe,
  8788. ..
  8789. } = &inst.fields
  8790. else {
  8791. unreachable!()
  8792. };
  8793. if *tfe || *lwe {
  8794. return Err("an image access with tfe or lwe");
  8795. }
  8796. let name = inst.name();
  8797. // A load or sample with no channel enabled returns the first.
  8798. let dmask = if *dmask == 0 { &1 } else { dmask };
  8799. let site = (b, i);
  8800. let guard = self.guard(b, i)?;
  8801. let c = self.cur;
  8802. let (kind, coords) = match dim {
  8803. 0 => (1, 1),
  8804. 1 => (2, 2),
  8805. 2 => (4, 3),
  8806. // Sampled (face coordinates and face, see `cube_direction`) or
  8807. // sized only.
  8808. 3 if name.starts_with("image_sample")
  8809. || name.starts_with("image_gather")
  8810. || name == "image_get_resinfo" =>
  8811. {
  8812. (5, 3)
  8813. }
  8814. 4 => (6, 2),
  8815. 5 => (7, 3),
  8816. _ => return Err("an image dimension (cube loads or MSAA)"),
  8817. };
  8818. // Address VGPRs in order.
  8819. let mut regs = Vec::new();
  8820. for a in addr {
  8821. if let Operand::Vector { reg, dwords } = *a {
  8822. regs.extend((0..dwords).map(|k| reg + k));
  8823. }
  8824. }
  8825. // Full 32-bit address VGPR at `reg_idx` (offset, bias, z-compare).
  8826. let addr_u32 = |l: &mut Self, reg_idx: usize| -> Result<V, Why> {
  8827. let r = *regs.get(reg_idx).ok_or("an image address")?;
  8828. let v = inst.read(Reg::V(r)).ok_or("an image address")?;
  8829. l.i32_of(v)
  8830. };
  8831. // With a16, two 16-bit components per VGPR starting at `base_reg`, low half first.
  8832. let addr_packed = |l: &mut Self, base_reg: usize, k: usize| -> Result<V, Why> {
  8833. let x = addr_u32(l, base_reg + if *a16 { k / 2 } else { k })?;
  8834. if !*a16 {
  8835. return Ok(x);
  8836. }
  8837. let c = l.cur;
  8838. let (sh, mask) = (l.s.m.i32(16 * (k as u32 % 2)), l.s.m.i32(0xFFFF));
  8839. let x = l.s.m.bin(c, Bin::LShr, x, sh);
  8840. Ok(l.s.m.bin(c, Bin::And, x, mask))
  8841. };
  8842. let addr_val = |l: &mut Self, k: usize| -> Result<V, Why> { addr_packed(l, 0, k) };
  8843. let src = self
  8844. .descriptors
  8845. .get(&(site, false))
  8846. .copied()
  8847. .ok_or("an untracked image")?;
  8848. let store = name.starts_with("image_store");
  8849. let uav = store
  8850. || self
  8851. .used_kind(src)
  8852. .is_some_and(|u| u.kind == ResourceType::Uav);
  8853. let props = (kind | if uav { 0x1000 } else { 0 }, 0x409);
  8854. if let Some(op) = name.strip_prefix("image_atomic_") {
  8855. // GLC returns the old value. DXIL implements subtraction by adding
  8856. // the two's complement of the operand at the same width.
  8857. let code = match op {
  8858. "add" | "sub" => 0,
  8859. "and" => 1,
  8860. "or" => 2,
  8861. "xor" => 3,
  8862. "smin" => 4,
  8863. "smax" => 5,
  8864. "umin" => 6,
  8865. "umax" => 7,
  8866. "swap" => 8,
  8867. "cmpswap" => u32::MAX,
  8868. _ => return Err(name),
  8869. };
  8870. let Fields::Image { cache, .. } = &inst.fields else {
  8871. unreachable!()
  8872. };
  8873. if *d16 || *a16 {
  8874. return Err("a 16-bit image atomic");
  8875. }
  8876. // Compare-exchange consumes a replacement followed by a comparand.
  8877. let compare = code == u32::MAX;
  8878. let wide = match (compare, *dmask) {
  8879. (false, 1) | (true, 3) => false,
  8880. (false, 3) | (true, 15) => true,
  8881. _ => return Err("an image atomic data mask"),
  8882. };
  8883. let iu = self.s.m.undef(self.s.t.i32);
  8884. let mut cs = vec![iu; 3];
  8885. for (k, slot) in cs.iter_mut().enumerate().take(coords) {
  8886. *slot = addr_val(self, k)?;
  8887. }
  8888. let Operand::Vector { reg, .. } = *data else {
  8889. return Err("image atomic data");
  8890. };
  8891. let width = if wide { 2 } else { 1 };
  8892. let vals = self.vgprs(inst, data, if compare { 2 * width } else { width })?;
  8893. let (ty, component) = if wide {
  8894. self.s.flags |= flags::INT64 | flags::ATOMIC_TYPED64 | flags::ATOMIC_HEAP64;
  8895. (self.s.m.int(64), 0x107) // one uint64_t in an R32G32_UINT view
  8896. } else {
  8897. (self.s.t.i32, 0x105)
  8898. };
  8899. let original = if wide {
  8900. self.join64(vals[0], vals[1])
  8901. } else {
  8902. vals[0]
  8903. };
  8904. let value = if op == "sub" {
  8905. let zero = self.s.m.int_const(ty, 0);
  8906. self.s.m.bin(c, Bin::Sub, zero, original)
  8907. } else {
  8908. original
  8909. };
  8910. let h = self.handle(site, src, false, (kind | 0x1000, component))?;
  8911. let mut args = vec![h];
  8912. let (intrinsic, opcode) = if compare {
  8913. let comparand = if wide {
  8914. self.join64(vals[2], vals[3])
  8915. } else {
  8916. vals[1]
  8917. };
  8918. args.extend(cs);
  8919. args.extend([comparand, value]);
  8920. let intrinsic = if wide {
  8921. "atomicCompareExchange.i64"
  8922. } else {
  8923. "atomicCompareExchange.i32"
  8924. };
  8925. (intrinsic, 79)
  8926. } else {
  8927. args.push(self.s.m.i32(code));
  8928. args.extend(cs);
  8929. args.push(value);
  8930. (
  8931. if wide {
  8932. "atomicBinOp.i64"
  8933. } else {
  8934. "atomicBinOp.i32"
  8935. },
  8936. 78,
  8937. )
  8938. };
  8939. let at = self.begin_guarded(guard);
  8940. let r = self
  8941. .s
  8942. .op(self.cur, intrinsic, Attr::NoUnwind, ty, opcode, &args);
  8943. if cache.glc {
  8944. let old = self.end_guarded(at, &[(r, original)])[0];
  8945. if wide {
  8946. let (lo, hi) = self.split64(old);
  8947. self.write(inst, Reg::V(reg), lo, None);
  8948. self.write(inst, Reg::V(reg + 1), hi, None);
  8949. } else {
  8950. self.write(inst, Reg::V(reg), old, None);
  8951. }
  8952. } else {
  8953. self.end_guarded(at, &[]);
  8954. }
  8955. return Ok(());
  8956. }
  8957. if store {
  8958. if name != "image_store" {
  8959. return Err("an image store to a mip level");
  8960. }
  8961. // shortcut: stores are taken to write all four channels of a
  8962. // float format (the console converts by the view's format).
  8963. if *dmask != 0xF {
  8964. return Err("an image store of some channels");
  8965. }
  8966. let iu = self.s.m.undef(self.s.t.i32);
  8967. let mut cs = vec![iu; 3];
  8968. for (k, slot) in cs.iter_mut().enumerate().take(coords) {
  8969. *slot = addr_val(self, k)?;
  8970. }
  8971. let Operand::Vector { reg, .. } = *data else {
  8972. return Err("image store data");
  8973. };
  8974. let mut vals = Vec::new();
  8975. for k in 0..4u8 {
  8976. // d16: two f16 channels per VGPR, low half first.
  8977. let r = if *d16 { k / 2 } else { k };
  8978. let v = inst.read(Reg::V(reg + r)).ok_or("image store data")?;
  8979. vals.push(if *d16 {
  8980. let mut x = self.i32_of(v)?;
  8981. if k % 2 == 1 {
  8982. let k16 = self.s.m.i32(16);
  8983. x = self.s.m.bin(self.cur, Bin::LShr, x, k16);
  8984. }
  8985. let f32t = self.s.t.f32;
  8986. self.s
  8987. .op(self.cur, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x])
  8988. } else {
  8989. self.float_of(v)?
  8990. });
  8991. }
  8992. let h = self.handle(site, src, false, props)?;
  8993. let at = self.begin_guarded(guard);
  8994. let mut args = vec![h];
  8995. args.extend(cs);
  8996. args.extend(vals);
  8997. args.push(self.s.m.i8(0xF));
  8998. let void = self.s.t.void;
  8999. self.s.op(
  9000. self.cur,
  9001. "textureStore.f32",
  9002. Attr::NoUnwind,
  9003. void,
  9004. 67,
  9005. &args,
  9006. );
  9007. self.end_guarded(at, &[]);
  9008. return Ok(());
  9009. }
  9010. let has_cl = name.ends_with("_cl");
  9011. let (op, sample) = match name {
  9012. "image_sample" | "image_sample_o" | "image_sample_cl" => (60, true),
  9013. "image_sample_lz" | "image_sample_l" | "image_sample_lz_o" => (62, true),
  9014. "image_sample_b" | "image_sample_b_cl" => (61, true),
  9015. "image_sample_c_lz" => (65, true),
  9016. "image_sample_d" | "image_sample_d_cl" => (63, true),
  9017. "image_get_lod" if self.s.pixel => (81, true),
  9018. // Implicit derivatives: pixel shaders only.
  9019. "image_sample_c" if self.s.pixel => (64, true),
  9020. "image_sample_c_cl" if self.s.pixel => (64, true),
  9021. "image_gather4" | "image_gather4_lz" | "image_gather4_lz_o" | "image_gather4_l" | "image_gather4_l_o" => (73, true),
  9022. "image_load" | "image_load_mip" => (66, false),
  9023. "image_get_resinfo" => (72, false),
  9024. _ => return Err(name),
  9025. };
  9026. if op == 72 {
  9027. // Width, height, depth or layers, levels (per dmask) of the level
  9028. // in the first address: DXIL's dimensions; a channel DXIL leaves
  9029. // out reads 1 (UAVs: one level).
  9030. let h = self.handle(site, src, false, props)?;
  9031. let mip = if uav {
  9032. self.s.m.undef(self.s.t.i32)
  9033. } else {
  9034. addr_val(self, 0)?
  9035. };
  9036. let i32t = self.s.t.i32;
  9037. let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
  9038. let d = self
  9039. .s
  9040. .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]);
  9041. let one = self.s.m.i32(1);
  9042. let present = match kind {
  9043. 1 => [true, false, false, true],
  9044. 2 | 5 | 6 => [true, true, false, true],
  9045. _ => [true, true, true, true],
  9046. };
  9047. let Operand::Vector { reg, .. } = *data else {
  9048. return Err("an image result");
  9049. };
  9050. for (k, ch) in (0..4u32).filter(|ch| dmask >> ch & 1 != 0).enumerate() {
  9051. let x = if ch == 3 && uav || !present[ch as usize] {
  9052. one
  9053. } else {
  9054. self.s.m.extract(c, d, ch)
  9055. };
  9056. self.write(inst, Reg::V(reg + k as u8), x, guard);
  9057. }
  9058. return Ok(());
  9059. }
  9060. if uav && op != 66 {
  9061. return Err("sampling a UAV");
  9062. }
  9063. let h = self.handle(site, src, false, props)?;
  9064. let fu = self.s.m.undef(self.s.t.f32);
  9065. let iu = self.s.m.undef(self.s.t.i32);
  9066. // A gather at a named level, done as four texel reads (below).
  9067. let mut gathered: Option<[V; 4]> = None;
  9068. let r = if sample {
  9069. let ss = self
  9070. .descriptors
  9071. .get(&(site, true))
  9072. .copied()
  9073. .ok_or("an untracked sampler")?;
  9074. // Comparison: the reference value is the first address after
  9075. // the bias, and the sampler is a comparison sampler.
  9076. let cmp = matches!(op, 64 | 65);
  9077. if cmp && (*a16 || dmask.count_ones() != 1) {
  9078. return Err("a comparison sample of 16-bit coordinates or several channels");
  9079. }
  9080. let sh = self.handle(site, ss, true, (14 | if cmp { 0x8000 } else { 0 }, 0))?;
  9081. // Texel offsets (`_o`) come first: x in bits 0-5, y in 8-13,
  9082. // signed (programmable offsets: gathers only).
  9083. let offset_word = name.ends_with("_o");
  9084. let first = usize::from(offset_word)
  9085. + usize::from(name.starts_with("image_sample_b"))
  9086. + usize::from(cmp);
  9087. // Coordinates the size divides (not the array slice); explicit
  9088. // gradients (x then y) come before the coordinates.
  9089. let spatial = coords - usize::from(kind == 6 || kind == 7);
  9090. // A cube's gradients are the two of its face coordinates.
  9091. let grads = if kind == 5 { 2 } else { spatial };
  9092. let deriv_regs = if op == 63 {
  9093. if *a16 {
  9094. grads.div_ceil(2)
  9095. } else {
  9096. grads
  9097. }
  9098. } else {
  9099. 0
  9100. };
  9101. let coord_base = first + 2 * deriv_regs;
  9102. let mut cs = vec![fu; 4];
  9103. // With a16, sampling coordinates, gradients, LOD and clamp are f16.
  9104. let to_float = |l: &mut Self, x: V| {
  9105. if *a16 {
  9106. let f = l.s.t.f32;
  9107. l.s.op(l.cur, "legacyF16ToF32", Attr::ReadNone, f, 131, &[x])
  9108. } else {
  9109. l.as_float(x)
  9110. }
  9111. };
  9112. if kind == 5 && (*unorm || op == 81) {
  9113. return Err("a cube sample with texel coordinates or a level query");
  9114. }
  9115. for (k, slot) in cs.iter_mut().enumerate().take(coords) {
  9116. let x = addr_packed(self, coord_base, k)?;
  9117. *slot = to_float(self, x);
  9118. }
  9119. if kind == 5 {
  9120. let dir = self.cube_direction(cs[0], cs[1], cs[2]);
  9121. cs[..3].copy_from_slice(&dir);
  9122. }
  9123. if *unorm {
  9124. // Texel coordinates: divided by the size of level 0.
  9125. let i32t = self.s.t.i32;
  9126. let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
  9127. let z = self.s.m.i32(0);
  9128. let d = self
  9129. .s
  9130. .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, z]);
  9131. for (k, slot) in cs.iter_mut().enumerate().take(spatial) {
  9132. let n = self.s.m.extract(c, d, k as u32);
  9133. let n = self.s.m.cast(c, Cast::UiToFp, n, self.s.t.f32);
  9134. *slot = self.s.m.bin(c, Bin::SDiv, *slot, n);
  9135. }
  9136. }
  9137. if op == 81 {
  9138. // The clamped then the unclamped level of detail.
  9139. let Operand::Vector { reg, .. } = *data else {
  9140. return Err("an image result");
  9141. };
  9142. let f32t = self.s.t.f32;
  9143. for (k, ch) in (0..2u32).filter(|ch| dmask >> ch & 1 != 0).enumerate() {
  9144. let clamped = self.s.m.bool(ch == 0);
  9145. let lod = self.s.op(
  9146. c,
  9147. "calculateLOD.f32",
  9148. Attr::ReadOnly,
  9149. f32t,
  9150. 81,
  9151. &[h, sh, cs[0], cs[1], cs[2], clamped],
  9152. );
  9153. let x = self.as_int(lod);
  9154. self.write(inst, Reg::V(reg + k as u8), x, guard);
  9155. }
  9156. return Ok(());
  9157. }
  9158. let offsets = if kind == 5 {
  9159. 0
  9160. } else {
  9161. (coords - usize::from(kind == 6 || kind == 7)).min(3)
  9162. };
  9163. let zero = self.s.m.i32(0);
  9164. let mut os = vec![iu; 3];
  9165. for o in os.iter_mut().take(offsets) {
  9166. *o = zero;
  9167. }
  9168. if offset_word && offsets > 0 {
  9169. let w = addr_val(self, 0)?;
  9170. for (k, at) in [(0, 26), (1, 18)].into_iter().take(offsets.min(2)) {
  9171. // Bits at..at+5 sign-extended: shift up, then down.
  9172. let left = self.s.m.i32(at);
  9173. let t = self.s.m.bin(c, Bin::Shl, w, left);
  9174. let k26 = self.s.m.i32(26);
  9175. os[k] = self.s.m.bin(c, Bin::AShr, t, k26);
  9176. }
  9177. }
  9178. let mut args = vec![h, sh];
  9179. args.extend(&cs);
  9180. let clamp = if has_cl {
  9181. let x = addr_packed(self, coord_base, coords)?;
  9182. to_float(self, x)
  9183. } else {
  9184. fu
  9185. };
  9186. match op {
  9187. // Outside a pixel shader there are no screen derivatives:
  9188. // the validator refuses `sample` there ("features
  9189. // incompatible with the shader stage": 730 compute programs,
  9190. // among them the G-buffer resolves and the sky), and what a
  9191. // driver does with it is its own affair.
  9192. // shortcut: such a sample reads level 0 (a bias: that
  9193. // level). The console takes derivatives from neighbouring
  9194. // lanes there; compute them from the lanes if a resolve
  9195. // shows the wrong mip.
  9196. 60 if !self.s.pixel => {
  9197. args.extend(&os);
  9198. args.push(self.s.m.f32(0));
  9199. self.s.op(
  9200. c,
  9201. "sampleLevel.f32",
  9202. Attr::ReadOnly,
  9203. self.s.t.res_ret,
  9204. 62,
  9205. &args,
  9206. )
  9207. }
  9208. 60 => {
  9209. if offset_word {
  9210. // DXIL wants immediate offsets in -8..=7 here; the
  9211. // console's are 6-bit and may be computed. A
  9212. // constant word in range becomes immediates
  9213. // (upstream PR #634); anything else keeps the
  9214. // offsets computed above (upstream refuses those).
  9215. let w = addr_val(self, 0)?;
  9216. if let Some(w) = self.s.m.int_value(w) {
  9217. let w = w as u32;
  9218. let field = |k: usize| {
  9219. let x = (w >> (8 * k) & 0x3F) as i32;
  9220. if x >= 32 { x - 64 } else { x }
  9221. };
  9222. let n = offsets.min(2);
  9223. if (0..n).all(|k| (-8..=7).contains(&field(k))) {
  9224. for (k, o) in os.iter_mut().enumerate().take(n) {
  9225. *o = self.s.m.i32(field(k) as u32);
  9226. }
  9227. }
  9228. }
  9229. }
  9230. args.extend(&os);
  9231. args.push(clamp);
  9232. self.s
  9233. .op(c, "sample.f32", Attr::ReadOnly, self.s.t.res_ret, 60, &args)
  9234. }
  9235. 61 => {
  9236. // With a16 the bias is an f16 in the low half of its
  9237. // word (the word is whole, the value is not).
  9238. let bias = addr_u32(self, usize::from(offset_word))?;
  9239. let bias = if *a16 {
  9240. let low = self.s.m.i32(0xFFFF);
  9241. let bias = self.s.m.bin(c, Bin::And, bias, low);
  9242. to_float(self, bias)
  9243. } else {
  9244. self.as_float(bias)
  9245. };
  9246. args.extend(&os);
  9247. if self.s.pixel {
  9248. args.extend([bias, clamp]);
  9249. self.s.op(
  9250. c,
  9251. "sampleBias.f32",
  9252. Attr::ReadOnly,
  9253. self.s.t.res_ret,
  9254. 61,
  9255. &args,
  9256. )
  9257. } else {
  9258. // As above: the bias is the level.
  9259. args.push(bias);
  9260. self.s.op(
  9261. c,
  9262. "sampleLevel.f32",
  9263. Attr::ReadOnly,
  9264. self.s.t.res_ret,
  9265. 62,
  9266. &args,
  9267. )
  9268. }
  9269. }
  9270. 63 if kind == 5 => {
  9271. // A cube with explicit gradients: the host wants them
  9272. // as changes of the direction, the console gives the
  9273. // changes of the face coordinates (the face is one
  9274. // unit wide). The level they select is taken from the
  9275. // longer of the two, in texels, and sampled directly.
  9276. // shortcut: no anisotropic filtering for these samples
  9277. // (the longer axis alone decides the level).
  9278. let mut len = [fu; 2];
  9279. for (axis, slot) in len.iter_mut().enumerate() {
  9280. let mut sum = self.s.m.f32(0);
  9281. for k in 0..2 {
  9282. let x = addr_packed(self, first + axis * deriv_regs, k)?;
  9283. let x = to_float(self, x);
  9284. let sq = self.s.m.bin(c, Bin::Mul, x, x);
  9285. sum = self.s.m.bin(c, Bin::Add, sum, sq);
  9286. }
  9287. *slot = self.unary(24, sum); // square root
  9288. }
  9289. let longer = self.binary(35, len[0], len[1]); // maximum
  9290. let i32t = self.s.t.i32;
  9291. let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
  9292. let z = self.s.m.i32(0);
  9293. let d = self
  9294. .s
  9295. .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, z]);
  9296. let width = self.s.m.extract(c, d, 0);
  9297. let width = self.s.m.cast(c, Cast::UiToFp, width, self.s.t.f32);
  9298. let texels = self.s.m.bin(c, Bin::Mul, longer, width);
  9299. // log2 = natural logarithm / ln 2; a length of 0 gives
  9300. // minus infinity, which the sampler clamps to level 0.
  9301. let ln = self.unary(23, texels);
  9302. let per_ln2 = self.s.m.f32(std::f32::consts::LOG2_E.to_bits());
  9303. let lod = self.s.m.bin(c, Bin::Mul, ln, per_ln2);
  9304. args.extend(&os);
  9305. args.push(lod);
  9306. self.s.op(
  9307. c,
  9308. "sampleLevel.f32",
  9309. Attr::ReadOnly,
  9310. self.s.t.res_ret,
  9311. 62,
  9312. &args,
  9313. )
  9314. }
  9315. 63 => {
  9316. let mut g = vec![fu; 6];
  9317. for k in 0..spatial {
  9318. let x = addr_packed(self, first, k)?;
  9319. g[k] = to_float(self, x);
  9320. let y = addr_packed(self, first + deriv_regs, k)?;
  9321. g[3 + k] = to_float(self, y);
  9322. }
  9323. args.extend(&os);
  9324. args.extend(g);
  9325. args.push(clamp);
  9326. self.s.op(
  9327. c,
  9328. "sampleGrad.f32",
  9329. Attr::ReadOnly,
  9330. self.s.t.res_ret,
  9331. 63,
  9332. &args,
  9333. )
  9334. }
  9335. 64 | 65 => {
  9336. let reference = addr_u32(self, first - 1)?;
  9337. let reference = self.as_float(reference);
  9338. args.extend(&os);
  9339. args.push(reference);
  9340. let name = if op == 64 {
  9341. args.push(clamp);
  9342. "sampleCmp.f32"
  9343. } else {
  9344. "sampleCmpLevelZero.f32"
  9345. };
  9346. self.s
  9347. .op(c, name, Attr::ReadOnly, self.s.t.res_ret, op, &args)
  9348. }
  9349. 62 => {
  9350. let lod = if name == "image_sample_l" {
  9351. let x = addr_packed(self, coord_base, coords)?;
  9352. to_float(self, x)
  9353. } else {
  9354. self.s.m.f32(0)
  9355. };
  9356. args.extend(&os);
  9357. args.push(lod);
  9358. self.s.op(
  9359. c,
  9360. "sampleLevel.f32",
  9361. Attr::ReadOnly,
  9362. self.s.t.res_ret,
  9363. 62,
  9364. &args,
  9365. )
  9366. }
  9367. _ => {
  9368. if name == "image_gather4" {
  9369. return Err("a gather with implicit level");
  9370. }
  9371. if dmask.count_ones() != 1 {
  9372. return Err("a gather of several channels");
  9373. }
  9374. if matches!(name, "image_gather4_l" | "image_gather4_l_o")
  9375. && coords == 2
  9376. && spatial == 2
  9377. {
  9378. // The host's gather has no level: it read level 0
  9379. // where the title names one (the depth pyramid its
  9380. // occlusion tests read: most of the world was
  9381. // culled against the wrong depths). The four texels
  9382. // are read at the level instead, in the gather's
  9383. // order: (u0,v1) (u1,v1) (u1,v0) (u0,v0).
  9384. // With an offset too (`image_gather4_l_o`): the
  9385. // offset is in texels of that level. Grand Theft
  9386. // Auto VI's meshlet culling takes a 4x4 block of
  9387. // the pyramid as one gather and three offset ones
  9388. // ((2,0), (0,2), (2,2)); the three read level 0,
  9389. // two texels beside the first one's place, so a
  9390. // meshlet three or four texels wide was tested
  9391. // against a quarter of what it covers.
  9392. // shortcut: the level is rounded to a whole one and
  9393. // coordinates past the edge are clamped, whatever
  9394. // the sampler says.
  9395. let lod = addr_packed(self, coord_base, coords)?;
  9396. let lod = to_float(self, lod);
  9397. let (i32t, f32t) = (self.s.t.i32, self.s.t.f32);
  9398. let zero = self.s.m.f32(0);
  9399. let lod = self.binary(35, lod, zero); // maximum
  9400. let lod = self.unary(26, lod); // round to nearest
  9401. let mip = self.s.m.cast(c, Cast::FpToUi, lod, i32t);
  9402. let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
  9403. let d = self
  9404. .s
  9405. .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]);
  9406. let half = self.s.m.f32(0.5f32.to_bits());
  9407. let one = self.s.m.f32(1.0f32.to_bits());
  9408. let (mut lo, mut hi) = ([iu; 2], [iu; 2]);
  9409. for k in 0..2 {
  9410. let n = self.s.m.extract(c, d, k as u32);
  9411. let n = self.s.m.cast(c, Cast::UiToFp, n, f32t);
  9412. let last = self.s.m.bin(c, Bin::Sub, n, one);
  9413. let t = self.s.m.bin(c, Bin::Mul, cs[k], n);
  9414. let t = self.s.m.bin(c, Bin::Sub, t, half);
  9415. let first = self.unary(27, t); // round down
  9416. // The offset word's field (0 without one).
  9417. let by = self.s.m.cast(c, Cast::SiToFp, os[k], f32t);
  9418. let first = self.s.m.bin(c, Bin::Add, first, by);
  9419. let next = self.s.m.bin(c, Bin::Add, first, one);
  9420. for (slot, x) in [(&mut lo[k], first), (&mut hi[k], next)] {
  9421. let x = self.binary(35, x, zero); // maximum
  9422. let x = self.binary(36, x, last); // minimum
  9423. *slot = self.s.m.cast(c, Cast::FpToSi, x, i32t);
  9424. }
  9425. }
  9426. let ch = dmask.trailing_zeros();
  9427. let mut g = [fu; 4];
  9428. let mut read = None;
  9429. let texels = [(lo[0], hi[1]), (hi[0], hi[1]), (hi[0], lo[1]), (lo[0], lo[1])];
  9430. for (slot, (x, y)) in g.iter_mut().zip(texels) {
  9431. let r = self.s.op(
  9432. c,
  9433. "textureLoad.f32",
  9434. Attr::ReadOnly,
  9435. self.s.t.res_ret,
  9436. 66,
  9437. &[h, mip, x, y, iu, iu, iu, iu],
  9438. );
  9439. *slot = self.s.m.extract(c, r, ch);
  9440. read = Some(r);
  9441. }
  9442. gathered = Some(g);
  9443. read.expect("four reads")
  9444. } else {
  9445. args.extend(&os[..2]);
  9446. args.push(self.s.m.i32(dmask.trailing_zeros()));
  9447. self.s.op(
  9448. c,
  9449. "textureGather.f32",
  9450. Attr::ReadOnly,
  9451. self.s.t.res_ret,
  9452. 73,
  9453. &args,
  9454. )
  9455. }
  9456. }
  9457. }
  9458. } else {
  9459. let mut cs = vec![iu; 3];
  9460. for (k, slot) in cs.iter_mut().enumerate().take(coords) {
  9461. *slot = addr_val(self, k)?;
  9462. }
  9463. let mip = if name == "image_load_mip" {
  9464. addr_val(self, coords)?
  9465. } else if uav {
  9466. // Our declarations have four channels.
  9467. self.s.flags |= flags::TYPED_UAV_LOADS;
  9468. iu
  9469. } else {
  9470. self.s.m.i32(0)
  9471. };
  9472. let mut args = vec![h, mip];
  9473. args.extend(&cs);
  9474. args.extend([iu, iu, iu]);
  9475. self.s.op(
  9476. c,
  9477. "textureLoad.f32",
  9478. Attr::ReadOnly,
  9479. self.s.t.res_ret,
  9480. 66,
  9481. &args,
  9482. )
  9483. };
  9484. let Operand::Vector { reg, .. } = *data else {
  9485. return Err("an image result");
  9486. };
  9487. let channels: Vec<u32> = if op == 73 {
  9488. vec![0, 1, 2, 3]
  9489. } else {
  9490. (0..4).filter(|ch| dmask >> ch & 1 != 0).collect()
  9491. };
  9492. let mut xs = Vec::new();
  9493. for ch in channels {
  9494. let x = match gathered {
  9495. Some(g) => g[ch as usize],
  9496. None => self.s.m.extract(c, r, ch),
  9497. };
  9498. xs.push(if *d16 {
  9499. // shortcut: d16 results are taken as floats (rounded to
  9500. // nearest even); integer formats would keep 16 bits.
  9501. let i32t = self.s.t.i32;
  9502. self.s
  9503. .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[x])
  9504. } else {
  9505. self.as_int(x)
  9506. });
  9507. }
  9508. if *d16 {
  9509. // Two channels per VGPR, low half first (an odd last high half 0).
  9510. let k16 = self.s.m.i32(16);
  9511. xs = xs
  9512. .chunks(2)
  9513. .map(|p| match *p {
  9514. [lo, hi] => {
  9515. let hi = self.s.m.bin(c, Bin::Shl, hi, k16);
  9516. self.s.m.bin(c, Bin::Or, lo, hi)
  9517. }
  9518. _ => p[0],
  9519. })
  9520. .collect();
  9521. }
  9522. for (k, x) in xs.into_iter().enumerate() {
  9523. self.write(inst, Reg::V(reg + k as u8), x, guard);
  9524. }
  9525. Ok(())
  9526. }
  9527. /// The direction a cube sample's face coordinates stand for: the
  9528. /// console takes s and t in [1, 2] (`v_cubesc`/`v_cubetc` over
  9529. /// `|v_cubema|`, plus 1.5) and the face id (`v_cubeid`), which the
  9530. /// host's cube sampling turns back into the same texel.
  9531. // shortcut: the view is taken as a cube, not a cube array (whose face
  9532. // operand adds 8 × the slice).
  9533. fn cube_direction(&mut self, s: V, t: V, face: V) -> [V; 3] {
  9534. let c = self.cur;
  9535. let k = |l: &mut Self, v: f32| l.s.m.f32(v.to_bits());
  9536. let (two, three) = (k(self, 2.0), k(self, 3.0));
  9537. let u = self.s.m.bin(c, Bin::Mul, s, two);
  9538. let u = self.s.m.bin(c, Bin::Sub, u, three);
  9539. let v = self.s.m.bin(c, Bin::Mul, t, two);
  9540. let v = self.s.m.bin(c, Bin::Sub, v, three);
  9541. let z = self.s.m.f32(0x8000_0000);
  9542. let (nu, nv) = (
  9543. self.s.m.bin(c, Bin::Sub, z, u),
  9544. self.s.m.bin(c, Bin::Sub, z, v),
  9545. );
  9546. let (one, mone) = (k(self, 1.0), k(self, -1.0));
  9547. let f = self.s.m.cast(c, Cast::FpToUi, face, self.s.t.i32);
  9548. // Per face +x, -x, +y, -y, +z, -z.
  9549. let table = [
  9550. [one, mone, u, u, u, nu],
  9551. [nv, nv, one, mone, nv, nv],
  9552. [nu, u, v, nv, one, mone],
  9553. ];
  9554. table.map(|row| {
  9555. let mut r = row[0];
  9556. for (n, &x) in row.iter().enumerate().skip(1) {
  9557. let kn = self.s.m.i32(n as u32);
  9558. let is = self.s.m.cmp(c, pred::EQ, f, kn);
  9559. r = self.s.m.select(c, is, x, r);
  9560. }
  9561. r
  9562. })
  9563. }
  9564. fn buffer(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  9565. let Fields::Buffer {
  9566. data,
  9567. addr,
  9568. soffset,
  9569. offset,
  9570. offen,
  9571. idxen,
  9572. format,
  9573. lds,
  9574. tfe,
  9575. ..
  9576. } = &inst.fields
  9577. else {
  9578. unreachable!()
  9579. };
  9580. let name = inst.name();
  9581. if name == "buffer_gl0_inv" || name == "buffer_gl1_inv" {
  9582. // The host has no console buffer cache to invalidate.
  9583. return Ok(());
  9584. }
  9585. if *lds || *tfe {
  9586. return Err("a buffer access to LDS or with tfe");
  9587. }
  9588. if format.is_some() && !name.starts_with("tbuffer_load_format_") {
  9589. return Err(name);
  9590. }
  9591. let site = (b, i);
  9592. let guard = self.guard(b, i)?;
  9593. let c = self.cur;
  9594. let store = name.starts_with("buffer_store_");
  9595. // DXIL atomic operations: add, and, or, xor, signed and unsigned
  9596. // min and max, exchange; compare-exchange apart.
  9597. let atomic = match name.strip_prefix("buffer_atomic_") {
  9598. None => None,
  9599. Some("add") => Some(0),
  9600. Some("and") => Some(1),
  9601. Some("or") => Some(2),
  9602. Some("xor") => Some(3),
  9603. Some("smin") => Some(4),
  9604. Some("smax") => Some(5),
  9605. Some("umin") => Some(6),
  9606. Some("umax") => Some(7),
  9607. Some("swap") => Some(8),
  9608. Some("cmpswap") => Some(u32::MAX),
  9609. Some(_) => return Err(name),
  9610. };
  9611. // Byte and 16-bit accesses: bits, and whether a load sign-extends.
  9612. let narrow = match name {
  9613. "buffer_load_ubyte" | "buffer_store_byte" => Some((8, false)),
  9614. "buffer_load_sbyte" => Some((8, true)),
  9615. "buffer_load_ushort" | "buffer_store_short" => Some((16, false)),
  9616. "buffer_load_sshort" => Some((16, true)),
  9617. _ => None,
  9618. };
  9619. // d16: two 16-bit channels per VGPR, low half first.
  9620. let d16 = name.starts_with("buffer_") && name.contains("_format_d16_");
  9621. let plain = name.replace("_format_d16_", "_format_");
  9622. let (typed, count) = match plain
  9623. .strip_prefix("buffer_load_")
  9624. .or(plain.strip_prefix("buffer_store_"))
  9625. .or(plain.strip_prefix("tbuffer_load_"))
  9626. {
  9627. _ if atomic.is_some() || narrow.is_some() => (false, 1),
  9628. Some("dword") => (false, 1),
  9629. Some("dwordx2") => (false, 2),
  9630. Some("dwordx3") => (false, 3),
  9631. Some("dwordx4") => (false, 4),
  9632. Some("format_x") => (true, 1),
  9633. Some("format_xy") => (true, 2),
  9634. Some("format_xyz") => (true, 3),
  9635. Some("format_xyzw") => (true, 4),
  9636. _ => return Err(name),
  9637. };
  9638. let Operand::Vector { reg: areg, .. } = *addr else {
  9639. return Err("a buffer address");
  9640. };
  9641. let vaddr = |l: &mut Self, k: u8| -> Result<V, Why> {
  9642. let v = inst.read(Reg::V(areg + k)).ok_or("a buffer address")?;
  9643. l.i32_of(v)
  9644. };
  9645. let index = if *idxen { Some(vaddr(self, 0)?) } else { None };
  9646. let mut off = self.s.m.i32(u32::from(*offset));
  9647. if *offen {
  9648. let o = vaddr(self, u8::from(*idxen))?;
  9649. off = self.s.m.bin(c, Bin::Add, off, o);
  9650. }
  9651. if !matches!(
  9652. soffset,
  9653. Operand::Scalar { code: NULL, .. } | Operand::Const(128)
  9654. ) {
  9655. let so = self.operand(inst, soffset)?;
  9656. off = self.s.m.bin(c, Bin::Add, off, so);
  9657. }
  9658. let src = self
  9659. .descriptors
  9660. .get(&(site, false))
  9661. .copied()
  9662. .ok_or("an untracked buffer")?;
  9663. let used = self.used_kind(src);
  9664. let (base, extra) = self.built_offset(src)?;
  9665. if base != 0 {
  9666. let b = self.s.m.i32(base);
  9667. off = self.s.m.bin(c, Bin::Add, off, b);
  9668. }
  9669. if let Some(x) = extra {
  9670. off = self.s.m.bin(c, Bin::Add, off, x);
  9671. }
  9672. // A buffer the program picks from the view heap by an index it
  9673. // computes: no used-resource entry gives its stride, the host's
  9674. // table by heap slot does; the access becomes a raw one at the
  9675. // element's byte. (Also tells the host this shader reads such
  9676. // buffers.)
  9677. let mut index = index;
  9678. if let Some(stride) = self.slot_stride(src)?
  9679. && let Some(element) = index
  9680. && !typed
  9681. && used.is_none()
  9682. {
  9683. let at = self.s.m.bin(c, Bin::Mul, element, stride);
  9684. off = self.s.m.bin(c, Bin::Add, at, off);
  9685. index = None;
  9686. }
  9687. // A structured buffer by its used-resource entry's stride: raw
  9688. // bytes too. The host makes its buffer views raw (a raw read
  9689. // through a structured view gives zeros on NVIDIA), and one kind
  9690. // of view can then serve every shader that reads the buffer.
  9691. if let (Some(element), Some(u)) = (index, used)
  9692. && !typed
  9693. && u.kind != ResourceType::Cbv
  9694. && u.stride >= 4
  9695. && u.stride.is_multiple_of(4)
  9696. {
  9697. let k = self.s.m.i32(u.stride);
  9698. let at = self.s.m.bin(c, Bin::Mul, element, k);
  9699. off = self.s.m.bin(c, Bin::Add, at, off);
  9700. index = None;
  9701. }
  9702. if used.is_some_and(|u| u.kind == ResourceType::Cbv) && !typed {
  9703. // A constant buffer read per lane (a dynamically indexed array).
  9704. // shortcut: the console's CBV descriptor is taken to have a 16-byte
  9705. // stride, as the vector loads of whole rows suggest.
  9706. let h = self.handle(site, src, false, (13, 0x1_0000))?;
  9707. let byte = match index {
  9708. Some(i) => {
  9709. let sixteen = self.s.m.i32(16);
  9710. let rows = self.s.m.bin(c, Bin::Mul, i, sixteen);
  9711. self.s.m.bin(c, Bin::Add, rows, off)
  9712. }
  9713. None => off,
  9714. };
  9715. let Some(Operand::Vector { reg, .. }) = *data else {
  9716. return Err("a buffer result");
  9717. };
  9718. for k in 0..count {
  9719. let four = self.s.m.i32(4 * k);
  9720. let a = self.s.m.bin(c, Bin::Add, byte, four);
  9721. let x = self.cbuffer_dword(h, a);
  9722. self.write(inst, Reg::V(reg + k as u8), x, guard);
  9723. }
  9724. return Ok(());
  9725. }
  9726. let uav = store || atomic.is_some() || used.is_some_and(|u| u.kind == ResourceType::Uav);
  9727. let u = if uav { 0x1000 } else { 0 };
  9728. let iu = self.s.m.undef(self.s.t.i32);
  9729. if let Some((bits, signed)) = narrow {
  9730. // Below a dword: raw buffers are read and written in dwords on
  9731. // 4 bytes, so the dword that holds the value is read and
  9732. // shifted, or changed with two atomic operations that touch
  9733. // only the value's own bits (other lanes may write the rest of
  9734. // the dword at the same time). A 16-bit value at a dword's
  9735. // last byte continues in the next dword.
  9736. let byte = match index {
  9737. None => off,
  9738. Some(index) if used.is_some_and(|u| u.stride == 1) => {
  9739. self.s.m.bin(c, Bin::Add, index, off)
  9740. }
  9741. Some(_) => return Err("a byte or 16-bit buffer access by index"),
  9742. };
  9743. let h = self.handle(site, src, false, (11 | u, 0))?;
  9744. let k3 = self.s.m.i32(3);
  9745. let within = self.s.m.bin(c, Bin::And, byte, k3);
  9746. let aligned = self.s.m.bin(c, Bin::Sub, byte, within);
  9747. let shift = self.s.m.bin(c, Bin::Shl, within, k3);
  9748. let four = self.s.m.i32(4);
  9749. let next = self.s.m.bin(c, Bin::Add, aligned, four);
  9750. let ones = self.s.m.i32(if bits == 8 { 0xff } else { 0xffff });
  9751. let zero = self.s.m.i32(0);
  9752. let k8 = self.s.m.i32(8);
  9753. let straddles = self.s.m.cmp(c, pred::EQ, within, k3);
  9754. if !store {
  9755. let mask = self.s.m.i8(1);
  9756. let align = self.s.m.i32(4);
  9757. let dword = |l: &mut Self, at: V| {
  9758. let r = l.s.op(
  9759. c,
  9760. "rawBufferLoad.f32",
  9761. Attr::ReadOnly,
  9762. l.s.t.res_ret,
  9763. 139,
  9764. &[h, at, iu, mask, align],
  9765. );
  9766. let f = l.s.m.extract(c, r, 0);
  9767. l.as_int(f)
  9768. };
  9769. let low = dword(self, aligned);
  9770. let mut x = self.s.m.bin(c, Bin::LShr, low, shift);
  9771. if bits == 16 {
  9772. let high = dword(self, next);
  9773. let high = self.s.m.bin(c, Bin::Shl, high, k8);
  9774. let high = self.s.m.select(c, straddles, high, zero);
  9775. x = self.s.m.bin(c, Bin::Or, x, high);
  9776. }
  9777. x = self.s.m.bin(c, Bin::And, x, ones);
  9778. if signed {
  9779. let up = self.s.m.i32(32 - bits);
  9780. x = self.s.m.bin(c, Bin::Shl, x, up);
  9781. x = self.s.m.bin(c, Bin::AShr, x, up);
  9782. }
  9783. let Some(Operand::Vector { reg, .. }) = *data else {
  9784. return Err("a buffer result");
  9785. };
  9786. self.write(inst, Reg::V(reg), x, guard);
  9787. return Ok(());
  9788. }
  9789. let d = data.as_ref().ok_or("buffer store data")?;
  9790. let v = self.vgprs(inst, d, 1)?[0];
  9791. let v = self.s.m.bin(c, Bin::And, v, ones);
  9792. let all = self.s.m.i32(u32::MAX);
  9793. let clear = self.s.m.bin(c, Bin::Shl, ones, shift);
  9794. let keep = self.s.m.bin(c, Bin::Xor, clear, all);
  9795. let set = self.s.m.bin(c, Bin::Shl, v, shift);
  9796. let keep_next = self.s.m.i32(0xffff_ff00);
  9797. let set_next = self.s.m.bin(c, Bin::LShr, v, k8);
  9798. let (and, or) = (self.s.m.i32(1), self.s.m.i32(2));
  9799. let i32t = self.s.t.i32;
  9800. let at = self.begin_guarded(guard);
  9801. for (op, x) in [(and, keep), (or, set)] {
  9802. let args = [h, op, aligned, iu, iu, x];
  9803. self.s
  9804. .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args);
  9805. }
  9806. if bits == 16 {
  9807. let second = self.begin_guarded(Some(straddles));
  9808. for (op, x) in [(and, keep_next), (or, set_next)] {
  9809. let args = [h, op, next, iu, iu, x];
  9810. self.s
  9811. .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args);
  9812. }
  9813. self.end_guarded(second, &[]);
  9814. }
  9815. self.end_guarded(at, &[]);
  9816. return Ok(());
  9817. }
  9818. if let Some(op) = atomic {
  9819. let d = data.as_ref().ok_or("buffer atomic data")?;
  9820. let vals = self.vgprs(inst, d, if op == u32::MAX { 2 } else { 1 })?;
  9821. let (h, coords) = match index {
  9822. // A raw buffer (stride 1) read by index: the index is the byte.
  9823. Some(index) if used.is_some_and(|u| u.stride == 1) => {
  9824. let byte = self.s.m.bin(c, Bin::Add, index, off);
  9825. (self.handle(site, src, false, (11 | u, 0))?, [byte, iu, iu])
  9826. }
  9827. Some(index) => {
  9828. let stride = used.map_or(0, |u| u.stride);
  9829. if stride < 4 || !stride.is_multiple_of(4) {
  9830. return Err("a structured buffer of unknown stride");
  9831. }
  9832. let h = self.handle(site, src, false, (12 | u, stride))?;
  9833. (h, [index, off, iu])
  9834. }
  9835. None => (self.handle(site, src, false, (11 | u, 0))?, [off, iu, iu]),
  9836. };
  9837. let Operand::Vector { reg, .. } = *d else {
  9838. return Err("buffer atomic data");
  9839. };
  9840. let returns = matches!(inst.fields, Fields::Buffer { cache, .. } if cache.glc);
  9841. let old = match inst.read(Reg::V(reg)) {
  9842. Some(v) if returns => self.i32_of(v)?,
  9843. _ => self.s.m.i32(0),
  9844. };
  9845. let at = self.begin_guarded(guard);
  9846. let i32t = self.s.t.i32;
  9847. let r = if op == u32::MAX {
  9848. // cmpswap: data is (new, compare).
  9849. let mut args = vec![h];
  9850. args.extend(coords);
  9851. args.extend([vals[1], vals[0]]);
  9852. self.s.op(
  9853. self.cur,
  9854. "atomicCompareExchange.i32",
  9855. Attr::NoUnwind,
  9856. i32t,
  9857. 79,
  9858. &args,
  9859. )
  9860. } else {
  9861. let mut args = vec![h, self.s.m.i32(op)];
  9862. args.extend(coords);
  9863. args.push(vals[0]);
  9864. self.s
  9865. .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args)
  9866. };
  9867. let r = self.end_guarded(at, &[(r, old)])[0];
  9868. if returns {
  9869. self.write(inst, Reg::V(reg), r, None);
  9870. }
  9871. return Ok(());
  9872. }
  9873. if store {
  9874. let regs = if d16 { count.div_ceil(2) } else { count };
  9875. let mut vals =
  9876. self.vgprs(inst, data.as_ref().ok_or("buffer store data")?, regs as u8)?;
  9877. if d16 {
  9878. // shortcut: d16 data is taken as f16 (integer formats would
  9879. // keep 16 bits), widened for the 32-bit float store.
  9880. let mut wide = Vec::new();
  9881. for k in 0..count {
  9882. let mut x = vals[(k / 2) as usize];
  9883. if k % 2 == 1 {
  9884. let k16 = self.s.m.i32(16);
  9885. x = self.s.m.bin(c, Bin::LShr, x, k16);
  9886. }
  9887. let f32t = self.s.t.f32;
  9888. let f = self
  9889. .s
  9890. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]);
  9891. wide.push(self.as_int(f));
  9892. }
  9893. vals = wide;
  9894. }
  9895. let mut args = Vec::new();
  9896. let (op, name) = if typed {
  9897. // shortcut: typed stores are taken to write all four channels
  9898. // of a float format.
  9899. if count != 4 || *offen || *offset != 0 {
  9900. return Err("a typed buffer store of some channels or at an offset");
  9901. }
  9902. args.push(self.handle(site, src, false, (10 | u, 0x409))?);
  9903. args.extend([index.unwrap_or(self.s.m.i32(0)), iu]);
  9904. for x in vals {
  9905. args.push(self.as_float(x));
  9906. }
  9907. (69, "bufferStore.f32")
  9908. } else {
  9909. match index {
  9910. // A raw buffer (stride 1) written by index: the index is the byte.
  9911. Some(index) if used.is_some_and(|u| u.stride == 1) => {
  9912. let byte = self.s.m.bin(c, Bin::Add, index, off);
  9913. args.push(self.handle(site, src, false, (11 | u, 0))?);
  9914. args.extend([byte, iu]);
  9915. }
  9916. Some(index) => {
  9917. let stride = used.map_or(0, |u| u.stride);
  9918. if stride < 4 || !stride.is_multiple_of(4) {
  9919. return Err("a structured buffer of unknown stride");
  9920. }
  9921. args.push(self.handle(site, src, false, (12 | u, stride))?);
  9922. args.extend([index, off]);
  9923. }
  9924. None => {
  9925. args.push(self.handle(site, src, false, (11 | u, 0))?);
  9926. args.extend([off, iu]);
  9927. }
  9928. }
  9929. args.extend(&vals);
  9930. args.resize(3 + 4, iu);
  9931. (140, "rawBufferStore.i32")
  9932. };
  9933. args.push(self.s.m.i8(if typed { 0xF } else { (1u8 << count) - 1 }));
  9934. if !typed {
  9935. args.push(self.s.m.i32(4));
  9936. }
  9937. let at = self.begin_guarded(guard);
  9938. let void = self.s.t.void;
  9939. self.s.op(self.cur, name, Attr::NoUnwind, void, op, &args);
  9940. self.end_guarded(at, &[]);
  9941. return Ok(());
  9942. }
  9943. if let Some(f) = *format {
  9944. if index.is_some() {
  9945. return Err("a typed-format load by index");
  9946. }
  9947. let h = self.handle(site, src, false, (11 | u, 0))?;
  9948. let Some(Operand::Vector { reg, .. }) = *data else {
  9949. return Err("a buffer result");
  9950. };
  9951. for (k, x) in self.format_load(h, off, f, count)?.into_iter().enumerate() {
  9952. self.write(inst, Reg::V(reg + k as u8), x, guard);
  9953. }
  9954. return Ok(());
  9955. }
  9956. let r = if typed {
  9957. if *offen || matches!(off, V::Inst(_)) || *offset != 0 {
  9958. return Err("a typed buffer load at an offset");
  9959. }
  9960. if uav {
  9961. self.s.flags |= flags::TYPED_UAV_LOADS;
  9962. }
  9963. let h = self.handle(site, src, false, (10 | u, 0x409))?;
  9964. let index = index.unwrap_or(self.s.m.i32(0));
  9965. self.s.op(
  9966. c,
  9967. "bufferLoad.f32",
  9968. Attr::ReadOnly,
  9969. self.s.t.res_ret,
  9970. 68,
  9971. &[h, index, iu],
  9972. )
  9973. } else {
  9974. let mask = self.s.m.i8((1u8 << count) - 1);
  9975. let align = self.s.m.i32(4);
  9976. match index {
  9977. // A raw buffer (stride 1) read by index: the index is the byte.
  9978. Some(index) if used.is_some_and(|u| u.stride == 1) => {
  9979. let byte = self.s.m.bin(c, Bin::Add, index, off);
  9980. let h = self.handle(site, src, false, (11 | u, 0))?;
  9981. self.s.op(
  9982. c,
  9983. "rawBufferLoad.f32",
  9984. Attr::ReadOnly,
  9985. self.s.t.res_ret,
  9986. 139,
  9987. &[h, byte, iu, mask, align],
  9988. )
  9989. }
  9990. Some(index) => {
  9991. let stride = used.map_or(0, |u| u.stride);
  9992. if stride < 4 || !stride.is_multiple_of(4) {
  9993. return Err("a structured buffer of unknown stride");
  9994. }
  9995. let h = self.handle(site, src, false, (12 | u, stride))?;
  9996. self.s.op(
  9997. c,
  9998. "rawBufferLoad.f32",
  9999. Attr::ReadOnly,
  10000. self.s.t.res_ret,
  10001. 139,
  10002. &[h, index, off, mask, align],
  10003. )
  10004. }
  10005. None => {
  10006. let h = self.handle(site, src, false, (11 | u, 0))?;
  10007. self.s.op(
  10008. c,
  10009. "rawBufferLoad.f32",
  10010. Attr::ReadOnly,
  10011. self.s.t.res_ret,
  10012. 139,
  10013. &[h, off, iu, mask, align],
  10014. )
  10015. }
  10016. }
  10017. };
  10018. let Some(Operand::Vector { reg, .. }) = *data else {
  10019. return Err("a buffer result");
  10020. };
  10021. if d16 {
  10022. // Two f16 channels per VGPR (an odd last high half 0).
  10023. let k16 = self.s.m.i32(16);
  10024. let i32t = self.s.t.i32;
  10025. for k in 0..count.div_ceil(2) {
  10026. let mut x = None;
  10027. for ch in (2 * k..(2 * k + 2).min(count)).rev() {
  10028. let f = self.s.m.extract(c, r, ch);
  10029. let h = self
  10030. .s
  10031. .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]);
  10032. x = Some(match x {
  10033. Some(hi) => {
  10034. let hi = self.s.m.bin(c, Bin::Shl, hi, k16);
  10035. self.s.m.bin(c, Bin::Or, h, hi)
  10036. }
  10037. None => h,
  10038. });
  10039. }
  10040. self.write(inst, Reg::V(reg + k as u8), x.expect("a channel"), guard);
  10041. }
  10042. return Ok(());
  10043. }
  10044. for k in 0..count {
  10045. let x = self.s.m.extract(c, r, k);
  10046. let x = self.as_int(x);
  10047. self.write(inst, Reg::V(reg + k as u8), x, guard);
  10048. }
  10049. Ok(())
  10050. }
  10051. fn export(&mut self, b: usize, i: usize) -> Result<(), Why> {
  10052. let e = *self
  10053. .exports
  10054. .get(&(b, i))
  10055. .ok_or("an export I/O raising did not see")?;
  10056. if e.compressed {
  10057. return Err("a compressed export");
  10058. }
  10059. let guard = self.guard(b, i)?;
  10060. let mesh = self.s.mesh.is_some();
  10061. let c = self.cur;
  10062. if let Some(g) = guard
  10063. && !mesh
  10064. {
  10065. if !(e.done && self.s.pixel) {
  10066. return Err("a conditional export");
  10067. }
  10068. let t = self.s.m.bool(true);
  10069. let kill = self.s.m.bin(c, Bin::Xor, g, t);
  10070. self.s
  10071. .op(c, "discard", Attr::NoUnwind, self.s.t.void, 82, &[kill]);
  10072. }
  10073. if mesh && e.target == Target::Primitive {
  10074. return self.emit_indices(e, guard);
  10075. }
  10076. let param_row = |usage: Usage, row: u8| match usage {
  10077. // The 2020 compiler leaves a mesh program's first entry zeroed
  10078. // (usage "position"): its row is the one no other entry names.
  10079. Usage::Other(0) if mesh => self.unnamed_row(),
  10080. _ => Some(row),
  10081. };
  10082. // (output element, channel) per exported channel; per-primitive
  10083. // outputs are elements of `prims`.
  10084. let mut stores = Vec::new();
  10085. let primitive = matches!(e.target, Target::PrimitiveParam { .. });
  10086. let outputs = if primitive {
  10087. &self.s.prims
  10088. } else {
  10089. &self.s.outputs
  10090. };
  10091. let by_kind = |kind: u8| outputs.iter().position(|o| o.kind == kind);
  10092. // 16-bit vertex outputs: the halves each dword carries, as (output
  10093. // element, channel, high half) per channel.
  10094. let halves = match e.target {
  10095. Target::Param { usage, row } => {
  10096. param_row(usage, row).and_then(|r| self.half_outputs.get(&r).map(|&h| (r, h)))
  10097. }
  10098. _ => None,
  10099. };
  10100. if let Some((row, (pack2, _))) = halves {
  10101. let packs: Vec<(u8, Option<u8>)> = self
  10102. .half_outputs
  10103. .iter()
  10104. .filter(|(_, h)| h.0)
  10105. .map(|(&r, h)| (r, h.1))
  10106. .collect();
  10107. for ch in 0..4u8 {
  10108. let Some(value) = e.values[usize::from(ch)] else {
  10109. continue;
  10110. };
  10111. for high in [false, true] {
  10112. let h = 2 * ch + u8::from(high);
  10113. let src = if pack2 {
  10114. packed_half(outputs, &packs, row, h)
  10115. } else {
  10116. (!high).then_some((row, ch))
  10117. };
  10118. let found = src.and_then(|(r, c)| {
  10119. outputs.iter().position(|o| {
  10120. o.row == Some(u32::from(r)) && c >= o.col && c < o.col + o.cols
  10121. })
  10122. });
  10123. if let Some(id) = found {
  10124. let col = src.expect("found").1 - outputs[id].col;
  10125. stores.push((id, col, value, Some(high)));
  10126. }
  10127. }
  10128. }
  10129. }
  10130. for ch in 0..4u8 {
  10131. let Some(value) = e.values[usize::from(ch)] else {
  10132. continue;
  10133. };
  10134. if halves.is_some() {
  10135. break;
  10136. }
  10137. let found = match e.target {
  10138. Target::Color(n) => outputs
  10139. .iter()
  10140. .position(|o| o.kind == 16 && o.row == Some(u32::from(n)))
  10141. .map(|id| (id, ch)),
  10142. Target::Position(0) => by_kind(3).map(|id| (id, ch)),
  10143. Target::Depth => match ch {
  10144. 0 => by_kind(17)
  10145. .or(by_kind(18))
  10146. .or(by_kind(19))
  10147. .map(|id| (id, 0)),
  10148. 1 => by_kind(20).map(|id| (id, 0)),
  10149. 2 => by_kind(14).map(|id| (id, 0)),
  10150. _ => None,
  10151. },
  10152. Target::Param { usage, row } | Target::PrimitiveParam { usage, row } => {
  10153. let row = param_row(usage, row);
  10154. outputs
  10155. .iter()
  10156. .position(|o| {
  10157. row.is_some_and(|r| o.row == Some(u32::from(r)))
  10158. && ch >= o.col
  10159. && ch < o.col + o.cols
  10160. })
  10161. .map(|id| (id, ch - outputs[id].col))
  10162. }
  10163. Target::Null | Target::Unread => None,
  10164. Target::Position(n @ 1..=2) => {
  10165. // shortcut: without the misc vector (point size, render
  10166. // target or viewport index) pos1 and pos2 carry the clip
  10167. // then cull distances, in semantic order.
  10168. if outputs.iter().any(|o| matches!(o.kind, 4 | 5)) {
  10169. return Err("render-target or viewport index exports");
  10170. }
  10171. let mut dists: Vec<usize> = (0..outputs.len())
  10172. .filter(|&i| matches!(outputs[i].kind, 6 | 7))
  10173. .collect();
  10174. dists.sort_by_key(|&i| (outputs[i].kind, outputs[i].index));
  10175. let flat: Vec<(usize, u8)> = dists
  10176. .iter()
  10177. .flat_map(|&i| (0..outputs[i].cols).map(move |c| (i, c)))
  10178. .collect();
  10179. // Channels past the distances the signature declares are
  10180. // ones the clipper does not enable (`PA_CL_VS_OUT_CNTL`).
  10181. let k = usize::from(n - 1) * 4 + usize::from(ch);
  10182. flat.get(k).copied()
  10183. }
  10184. Target::Position(_) => return Err("clip, cull or point-size exports"),
  10185. Target::Primitive => return Err("a primitive export"),
  10186. };
  10187. if let Some((id, col)) = found {
  10188. stores.push((id, col, value, None));
  10189. }
  10190. }
  10191. fn elements<'l>(l: &'l mut Lower, primitive: bool) -> &'l mut Vec<SigElement> {
  10192. if primitive {
  10193. &mut l.s.prims
  10194. } else {
  10195. &mut l.s.outputs
  10196. }
  10197. }
  10198. if stores
  10199. .iter()
  10200. .any(|s| s.3.is_none() && elements(self, primitive)[s.0].half)
  10201. {
  10202. return Err("a 16-bit output the stage data does not mark");
  10203. }
  10204. // A mesh lane writes its own vertex or primitive, where it exports.
  10205. let at = if mesh {
  10206. let flat = self.mesh_thread();
  10207. let limit = if let Some(m) = self.s.mesh {
  10208. if primitive {
  10209. m.max_primitives
  10210. } else {
  10211. m.max_vertices
  10212. }
  10213. } else {
  10214. 0
  10215. };
  10216. let threads = self.s.threads.map(|t| t[0]).unwrap_or(u32::MAX);
  10217. let mesh_guard = if limit > 0 && threads > limit {
  10218. let lim = self.s.m.i32(limit);
  10219. let in_bounds = self.s.m.cmp(self.cur, pred::IULT, flat, lim);
  10220. match guard {
  10221. Some(g) => Some(self.s.m.bin(self.cur, Bin::And, g, in_bounds)),
  10222. None => Some(in_bounds),
  10223. }
  10224. } else {
  10225. guard
  10226. };
  10227. self.begin_guarded(mesh_guard)
  10228. } else {
  10229. None
  10230. };
  10231. let (name, opcode) = match (mesh, primitive) {
  10232. (false, _) => ("storeOutput", 5),
  10233. (true, false) => ("storeVertexOutput", 171),
  10234. (true, true) => ("storePrimitiveOutput", 172),
  10235. };
  10236. for (id, col, value, half) in stores {
  10237. let mut x = self.i32_of(value)?;
  10238. if let Some(high) = half {
  10239. // An f16 half, declared a 32-bit float on the host.
  10240. let c = self.cur;
  10241. if high {
  10242. let k16 = self.s.m.i32(16);
  10243. x = self.s.m.bin(c, Bin::LShr, x, k16);
  10244. }
  10245. let f32t = self.s.t.f32;
  10246. let f = self
  10247. .s
  10248. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]);
  10249. x = self.as_int(f);
  10250. }
  10251. let el = &mut elements(self, primitive)[id];
  10252. el.usage |= 1 << col;
  10253. let (suffix, x) = match el.comp {
  10254. 9 if half.is_some() => (".f32", self.as_float(x)),
  10255. 9 => {
  10256. let f = match self.floats.get(&value) {
  10257. Some(&f) => f,
  10258. None => self.as_float(x),
  10259. };
  10260. (".f32", f)
  10261. }
  10262. _ => (".i32", x),
  10263. };
  10264. let mut args = vec![
  10265. self.s.m.i32(id as u32),
  10266. self.s.m.i32(0),
  10267. self.s.m.i8(col),
  10268. x,
  10269. ];
  10270. if mesh {
  10271. args.push(self.mesh_thread());
  10272. }
  10273. let void = self.s.t.void;
  10274. self.s.op(
  10275. self.cur,
  10276. &format!("{name}{suffix}"),
  10277. Attr::NoUnwind,
  10278. void,
  10279. opcode,
  10280. &args,
  10281. );
  10282. }
  10283. self.end_guarded(at, &[]);
  10284. Ok(())
  10285. }
  10286. /// Mesh: `exp prim` as the lane's primitive. Bit 31 culls it (all
  10287. /// indices 0: no area).
  10288. fn emit_indices(&mut self, e: &Export, guard: Option<V>) -> Result<(), Why> {
  10289. let v = e.values[0].ok_or("a primitive export without its indices")?;
  10290. let x = self.i32_of(v)?;
  10291. let flat = self.mesh_thread();
  10292. let guard = if let Some(mesh) = self.s.mesh {
  10293. let threads = self.s.threads.map(|t| t[0]).unwrap_or(u32::MAX);
  10294. if threads > mesh.max_primitives {
  10295. let p = self.s.m.i32(mesh.max_primitives);
  10296. let in_bounds = self.s.m.cmp(self.cur, pred::IULT, flat, p);
  10297. match guard {
  10298. Some(g) => Some(self.s.m.bin(self.cur, Bin::And, g, in_bounds)),
  10299. None => Some(in_bounds),
  10300. }
  10301. } else {
  10302. guard
  10303. }
  10304. } else {
  10305. guard
  10306. };
  10307. let at = self.begin_guarded(guard);
  10308. let c = self.cur;
  10309. let z = self.s.m.i32(0);
  10310. let mut culled = self.s.m.cmp(c, pred::SLT, x, z);
  10311. // A primitive that names a vertex past the declared count, or one
  10312. // no lane writes (lane n writes vertex n alone), is culled too: the
  10313. // host would read a vertex nothing set, at any position.
  10314. let written = self.s.mesh.map(|m| {
  10315. m.max_vertices
  10316. .min(self.s.threads.map_or(u32::MAX, |t| t[0]))
  10317. });
  10318. let mut indices = [z; 3];
  10319. for (k, slot) in indices.iter_mut().enumerate() {
  10320. let (shift, mask) = (self.s.m.i32(10 * k as u32), self.s.m.i32(0x3FF));
  10321. let i = self.s.m.bin(c, Bin::LShr, x, shift);
  10322. let i = self.s.m.bin(c, Bin::And, i, mask);
  10323. if let Some(n) = written {
  10324. let n = self.s.m.i32(n);
  10325. let past = self.s.m.cmp(c, pred::IUGE, i, n);
  10326. culled = self.s.m.bin(c, Bin::Or, culled, past);
  10327. }
  10328. *slot = i;
  10329. }
  10330. let mut args = vec![flat];
  10331. for i in indices {
  10332. args.push(self.s.m.select(c, culled, z, i));
  10333. }
  10334. let void = self.s.t.void;
  10335. self.s
  10336. .op(c, "emitIndices", Attr::NoUnwind, void, 169, &args);
  10337. self.end_guarded(at, &[]);
  10338. Ok(())
  10339. }
  10340. /// The per-vertex arbitrary row no mesh output entry names but one
  10341. /// (the 2020 compiler's zeroed entry).
  10342. fn unnamed_row(&self) -> Option<u8> {
  10343. let StageIo::Ms(ms) = &self.x.native.io else {
  10344. return None;
  10345. };
  10346. let named = |r: u32| {
  10347. ms.outputs
  10348. .iter()
  10349. .any(|o| o.param & 0x80 == 0 && o.usage != Usage::Other(0) && u32::from(o.row) == r)
  10350. };
  10351. let free: std::collections::BTreeSet<u32> = self
  10352. .s
  10353. .outputs
  10354. .iter()
  10355. .filter(|o| o.kind == 0)
  10356. .filter_map(|o| o.row)
  10357. .filter(|&r| !named(r))
  10358. .collect();
  10359. match free.into_iter().collect::<Vec<_>>()[..] {
  10360. [r] => u8::try_from(r).ok(),
  10361. _ => None,
  10362. }
  10363. }
  10364. fn exit(&mut self, b: usize) -> Result<(), Stop> {
  10365. let offset = self.x.p.blocks[b]
  10366. .insts
  10367. .last()
  10368. .map_or(self.x.p.blocks[b].offset, |i| i.machine.offset);
  10369. let term = match self.x.st.exits[b] {
  10370. LaneExit::Jump(t) if self.counters.contains_key(&t) && self.rpo[t] <= self.rpo[b] => {
  10371. let ok = self.count_iteration(t, pred::IULT);
  10372. let abort = self.abort_block();
  10373. Term::CondBr(ok, self.block[t].expect("reachable"), abort)
  10374. }
  10375. LaneExit::Jump(t) => {
  10376. self.enter_loop(b, t, self.cur);
  10377. Term::Br(self.block[t].expect("reachable"))
  10378. }
  10379. LaneExit::Branch {
  10380. when,
  10381. taken,
  10382. not_taken,
  10383. } => {
  10384. // A negated condition branches the other way round.
  10385. let (cond, taken, not_taken) = match self.x.st.bools.node(when) {
  10386. _ if self.x.st.wide.contains(&b) => {
  10387. let c = self.wave_wide(b, when).map_err(|w| unsupported(offset, w))?;
  10388. (c, taken, not_taken)
  10389. }
  10390. Some((atom, Bool::TRUE, Bool::FALSE)) => {
  10391. let a = self
  10392. .atom(atom, self.cur)
  10393. .map_err(|w| unsupported(offset, w))?;
  10394. (a, not_taken, taken)
  10395. }
  10396. _ => {
  10397. let c = self
  10398. .boolean(when, self.cur)
  10399. .map_err(|w| unsupported(offset, w))?;
  10400. (c, taken, not_taken)
  10401. }
  10402. };
  10403. // A back edge is taken only below the iteration limit.
  10404. let back =
  10405. |l: &Self, to: usize| l.counters.contains_key(&to) && l.rpo[to] <= l.rpo[b];
  10406. // (No `xor` of a compare: a loop exit testing one hung the
  10407. // AMD driver.)
  10408. let cond = if back(self, taken) {
  10409. let ok = self.count_iteration(taken, pred::IULT);
  10410. self.s.m.bin(self.cur, Bin::And, cond, ok)
  10411. } else if back(self, not_taken) {
  10412. let stop = self.count_iteration(not_taken, pred::IUGE);
  10413. self.s.m.bin(self.cur, Bin::Or, cond, stop)
  10414. } else {
  10415. cond
  10416. };
  10417. // Critical edges get a block of their own, so loops have
  10418. // dedicated exits and preheaders as DXC emits them.
  10419. let (t, f) = (self.edge(b, taken), self.edge(b, not_taken));
  10420. for (to, via) in [(taken, t), (not_taken, f)] {
  10421. if !back(self, to) {
  10422. // From an edge block, or from here.
  10423. let from = if Some(via) == self.block[to] {
  10424. self.cur
  10425. } else {
  10426. via
  10427. };
  10428. self.enter_loop(b, to, from);
  10429. }
  10430. }
  10431. Term::CondBr(cond, t, f)
  10432. }
  10433. LaneExit::End => {
  10434. if self.s.pixel && !self.exported[b] && !self.has_done_export(b) {
  10435. // A lane leaving without its final export was killed.
  10436. let t = self.s.m.bool(true);
  10437. self.s
  10438. .op(self.cur, "discard", Attr::NoUnwind, self.s.t.void, 82, &[t]);
  10439. }
  10440. Term::Ret
  10441. }
  10442. LaneExit::Indirect => return Err(unsupported(offset, "an indirect jump")),
  10443. };
  10444. let _ = Exit::End;
  10445. self.s.m.terminate(self.cur, term);
  10446. Ok(())
  10447. }
  10448. /// A forward edge into loop header `to` (from DXIL block `via`) starts
  10449. /// its count at 0.
  10450. fn enter_loop(&mut self, _from: usize, to: usize, via: usize) {
  10451. if let Some((_, incoming)) = self.counters.get_mut(&to) {
  10452. let z = self.s.m.i32(0);
  10453. incoming.push((z, via));
  10454. }
  10455. }
  10456. /// A back edge to header `to` (a back edge keeps its block, no
  10457. /// critical-edge block): the count goes up; the result compares it with
  10458. /// [`LOOP_LIMIT`] by `p` (below: go on; at or above: stop).
  10459. fn count_iteration(&mut self, to: usize, p: u8) -> V {
  10460. let c = self.cur;
  10461. let (phi, _) = self.counters[&to];
  10462. let one = self.s.m.i32(1);
  10463. let next = self.s.m.bin(c, Bin::Add, phi, one);
  10464. // Per stage unless the switch names one: a loop that never meets its
  10465. // exit (a count read from a buffer the host has not got yet, say)
  10466. // runs to the limit in every lane. A million iterations a pixel
  10467. // hung the GPU for seconds a draw until Windows reset it
  10468. // (PS_Textured_Eight, 2026-11-24, run 12).
  10469. // shortcut: a pixel loop past 128 iterations, a vertex or mesh loop
  10470. // past 256 or a compute loop past 4,096 is cut short. (They were
  10471. // 1,024, 4,096 and 65,536: the opening cutscene then lost the card
  10472. // 14-25 frames in, in a minimap or shadow mesh draw; with every
  10473. // loop cut at 64 it ran 90 frames. Raise them again once shaders
  10474. // stop reading data that is not there yet.)
  10475. let limit = match super::loop_limit() {
  10476. LOOP_LIMIT if self.s.pixel => 1 << 7,
  10477. LOOP_LIMIT if self.s.mesh.is_some() || self.s.threads.is_none() => 1 << 8,
  10478. LOOP_LIMIT => 1 << 12,
  10479. named => named,
  10480. };
  10481. let limit = self.s.m.i32(limit);
  10482. self.counters
  10483. .get_mut(&to)
  10484. .expect("header")
  10485. .1
  10486. .push((next, c));
  10487. self.s.m.cmp(c, p, next, limit)
  10488. }
  10489. /// The block a lane stopped by [`LOOP_LIMIT`] leaves through.
  10490. fn abort_block(&mut self) -> usize {
  10491. if let Some(a) = self.abort {
  10492. return a;
  10493. }
  10494. let a = self.s.m.new_block();
  10495. if self.s.pixel {
  10496. let t = self.s.m.bool(true);
  10497. self.s
  10498. .op(a, "discard", Attr::NoUnwind, self.s.t.void, 82, &[t]);
  10499. }
  10500. self.s.m.terminate(a, Term::Ret);
  10501. self.abort = Some(a);
  10502. a
  10503. }
  10504. /// The DXIL block a branch from IR block `from` to `to` goes to.
  10505. fn edge(&mut self, from: usize, to: usize) -> usize {
  10506. let target = self.block[to].expect("reachable");
  10507. let preds = self.x.p.blocks[to]
  10508. .preds
  10509. .iter()
  10510. .filter(|&&q| self.block[q].is_some())
  10511. .count();
  10512. // Back edges stay as they are: the exiting block is the latch.
  10513. if preds < 2 || self.rpo[to] <= self.rpo[from] {
  10514. return target;
  10515. }
  10516. let e = self.s.m.new_block();
  10517. self.s.m.terminate(e, Term::Br(target));
  10518. self.edges.insert((from, to), e);
  10519. e
  10520. }
  10521. fn fill_phis(&mut self) -> Result<(), Stop> {
  10522. let p = self.x.p;
  10523. // Lane-mask joins first (what an edge brings may ask for more joins,
  10524. // of masks and of numbers): each edge's mask as the structure
  10525. // tracked it, a constant or a scalar-built one included.
  10526. let st = self.x.st;
  10527. while let Some((v, b, i)) = self.pending_masks.pop() {
  10528. let phi = &p.blocks[b].phis[i];
  10529. let offset = p.blocks[b].offset;
  10530. let args = st
  10531. .phi_masks
  10532. .get(&phi.value)
  10533. .ok_or_else(|| unsupported(offset, "a lane-mask join of an untracked mask"))?;
  10534. let mut incoming = Vec::new();
  10535. for (n, &q) in p.blocks[b].preds.iter().enumerate() {
  10536. let Some(qb) = self.tail[q] else { continue };
  10537. let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb);
  10538. let x = self.boolean(args[n], qb).map_err(|w| unsupported(offset, w))?;
  10539. incoming.push((x, qb));
  10540. }
  10541. self.s.m.set_phi(v, incoming);
  10542. }
  10543. // A join that only another join reads is read wherever that one is. Left
  10544. // unmarked, a value without a DXIL form coming into it became zero without a
  10545. // word (the looked-up tint of the material resolve programs, whose size
  10546. // computation had no value, was zero in every lane that way).
  10547. // shortcut: only with `VICTORY_STRICT_JOINS` set (the offline pack
  10548. // listing sets it to count them): 40 programs that translate today
  10549. // stop by name with it (vehicle paint pixel shaders at "the first
  10550. // half of an interpolation", foliage mesh shaders); until those are
  10551. // lowered they keep drawing with that zero.
  10552. static STRICT: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  10553. let strict = *STRICT.get_or_init(|| std::env::var_os("VICTORY_STRICT_JOINS").is_some());
  10554. let mut work: Vec<Value> = if strict {
  10555. self.read_phis.iter().copied().collect()
  10556. } else {
  10557. Vec::new()
  10558. };
  10559. while let Some(v) = work.pop() {
  10560. let Some(&(b, i)) = self.phi_at.get(&v) else {
  10561. continue;
  10562. };
  10563. for &a in &p.blocks[b].phis[i].args {
  10564. if self.phi_at.contains_key(&a) && self.read_phis.insert(a) {
  10565. work.push(a);
  10566. }
  10567. }
  10568. }
  10569. for (v, b, i) in std::mem::take(&mut self.data_phis) {
  10570. let phi = &p.blocks[b].phis[i];
  10571. let bit = phi.reg == Reg::Scc;
  10572. // A join of numbers with dead registers (`dead`): the paths that bring those
  10573. // never read the result, so they bring zero. Not for a join that is itself a
  10574. // lane mask (a ballot gives that one as data).
  10575. let st = self.x.st;
  10576. let numbers = !bit
  10577. && !st.masks.contains_key(&phi.value)
  10578. && !st.highs.contains_key(&phi.value)
  10579. && phi
  10580. .args
  10581. .iter()
  10582. .any(|a| matches!(self.vals.get(a), Some(Val::I32(_))));
  10583. let mut incoming = Vec::new();
  10584. for (n, &q) in p.blocks[b].preds.iter().enumerate() {
  10585. let Some(qb) = self.tail[q] else { continue };
  10586. let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb);
  10587. let arg = phi.args[n];
  10588. if self.read_phis.contains(&phi.value) && !self.vals.contains_key(&arg) {
  10589. let _ = self.lazy_barycentric(arg);
  10590. // A root parameter nothing read before the join (user
  10591. // data is loaded on first use, in the entry block).
  10592. if !self.vals.contains_key(&arg)
  10593. && let Some(&(param, dword)) = self.params.get(&arg)
  10594. {
  10595. let val = self.user(param, dword);
  10596. self.vals.insert(arg, val);
  10597. }
  10598. }
  10599. let x = match (self.vals.get(&arg).copied(), bit) {
  10600. (Some(Val::I32(x)), false) | (Some(Val::Bit(x)), true) => x,
  10601. (Some(Val::Missing(_)) | None, false)
  10602. if numbers && self.dead(arg, &mut Vec::new()) =>
  10603. {
  10604. self.s.m.i32(0)
  10605. }
  10606. // A lane mask joined with numbers (a traversal that keeps its lanes' masks on
  10607. // a stack with its node numbers): the mask comes as the number it is, the
  10608. // ballot of its lanes where it is written.
  10609. (Some(Val::Missing(_)) | None, false)
  10610. if self.read_phis.contains(&phi.value)
  10611. && self.mask_data == MaskData::Console
  10612. && (st.masks.contains_key(&arg) || st.highs.contains_key(&arg)) =>
  10613. {
  10614. match self.mask_dword(arg) {
  10615. Ok(x) => x,
  10616. Err(why) => return Err(Stop::Retry(phi.value, why)),
  10617. }
  10618. }
  10619. // SCC of a mask operation ("some lane is left") joined with a scalar test:
  10620. // the compiler branches around code that sets SCC and tests SCC after it,
  10621. // the skip bringing "no lane" along. As data it is "some lane of the wave
  10622. // has the bit" - right only if the wave took that skip together, as the
  10623. // console does: a lane that skipped alone would bring "some lane" where the
  10624. // console has the skipped code's SCC. So the branch must be one the wave
  10625. // takes together; else its region is named for `emit`'s retry to widen it.
  10626. (Some(Val::Missing(_)) | None, true)
  10627. if self.read_phis.contains(&phi.value)
  10628. && self.mask_data == MaskData::Console
  10629. && st.scc_some.contains_key(&arg) =>
  10630. {
  10631. let per_lane = !st.wide.contains(&q)
  10632. && matches!(st.exits[q], LaneExit::Branch { when, .. }
  10633. if !st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_))));
  10634. if per_lane {
  10635. for &other in p.blocks[b].preds.iter().filter(|&&o| o != q) {
  10636. need(other);
  10637. }
  10638. return Err(Stop::Retry(phi.value, LANE_MASK));
  10639. }
  10640. match self.scc_some(arg) {
  10641. Ok(x) => x,
  10642. Err(why) => return Err(Stop::Retry(phi.value, why)),
  10643. }
  10644. }
  10645. (Some(Val::Bit(_)), false) if self.read_phis.contains(&phi.value) => {
  10646. return Err(Stop::Retry(phi.value, "an SCC joined with SGPR values"));
  10647. }
  10648. (Some(Val::Missing(why)), _) if self.read_phis.contains(&phi.value) => {
  10649. return Err(Stop::Retry(phi.value, why));
  10650. }
  10651. _ if self.read_phis.contains(&phi.value) => {
  10652. return Err(Stop::Retry(phi.value, "a join of mismatched values"));
  10653. }
  10654. _ if bit => self.s.m.bool(false),
  10655. _ => self.s.m.i32(0),
  10656. };
  10657. incoming.push((x, qb));
  10658. }
  10659. self.s.m.set_phi(v, incoming);
  10660. }
  10661. for (phi, incoming) in std::mem::take(&mut self.counters).into_values() {
  10662. self.s.m.set_phi(phi, incoming);
  10663. }
  10664. Ok(())
  10665. }
  10666. }
  10667. /// The DXIL interpolation mode of a kind of barycentrics (none for the
  10668. /// pull model).
  10669. fn interp_mode(kind: Barycentric) -> Option<u8> {
  10670. Some(match kind {
  10671. Barycentric::PerspectiveCenter => 2,
  10672. Barycentric::PerspectiveCentroid => 3,
  10673. Barycentric::PerspectiveSample => 6,
  10674. Barycentric::LinearCenter => 4,
  10675. Barycentric::LinearCentroid => 5,
  10676. Barycentric::LinearSample => 7,
  10677. Barycentric::PerspectivePullModel => return None,
  10678. })
  10679. }
  10680. #[cfg(test)]
  10681. mod tests {
  10682. use super::{Lowered, Numeric, Parts, buffer_format, half_shift, lower};
  10683. use crate::native::{
  10684. ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource,
  10685. };
  10686. use crate::{io, ir, resource, structure};
  10687. const S_ENDPGM: u32 = 0xBF81_0000;
  10688. #[test]
  10689. fn packed_pixel_inputs_find_their_second_row() {
  10690. use super::super::container::SigElement;
  10691. use super::half_input_partners;
  10692. use crate::native::{PsInput, Usage};
  10693. let entry = |row, row2, pack2| PsInput {
  10694. usage: Usage::Generic,
  10695. row,
  10696. mask: 0xF,
  10697. attr: row,
  10698. flat: false,
  10699. fp16: true,
  10700. pack2,
  10701. row2,
  10702. };
  10703. let element = |row| SigElement {
  10704. name: "TEXCOORD".into(),
  10705. index: row,
  10706. kind: 0,
  10707. comp: 9,
  10708. interp: 2,
  10709. row: Some(row),
  10710. col: 0,
  10711. cols: 4,
  10712. usage: 0,
  10713. half: true,
  10714. };
  10715. // Rows 0 and 3 pack and leave their second row out; 5 names its
  10716. // own (6). Unnamed 16-bit rows: 1, 4, 6, 7.
  10717. let io = StageIo::Ps {
  10718. inputs: vec![entry(0, 0, true), entry(3, 3, true), entry(5, 6, true)],
  10719. input_addr: 0,
  10720. db_shader_control: 0,
  10721. patches: vec![],
  10722. };
  10723. let sig: Vec<_> = [0, 1, 3, 4, 5, 6, 7].map(element).into();
  10724. let p = half_input_partners(&io, &sig);
  10725. assert_eq!(p.get(&0), Some(&1));
  10726. assert_eq!(p.get(&3), Some(&4));
  10727. assert_eq!(p.get(&5), None);
  10728. }
  10729. /// The packed pedestrian layouts of Grand Theft Auto VI: an element
  10730. /// behind another one in its register follows in the first parameter
  10731. /// with a dword left, and is not a half of its register's row.
  10732. #[test]
  10733. fn packed_elements_behind_another_take_the_first_free_dword() {
  10734. use super::super::container::SigElement;
  10735. use super::packed_half;
  10736. let element = |index, row, col, cols| SigElement {
  10737. name: "TEXCOORD".into(),
  10738. index,
  10739. kind: 0,
  10740. comp: 9,
  10741. interp: 2,
  10742. row: Some(row),
  10743. col,
  10744. cols,
  10745. usage: 0,
  10746. half: true,
  10747. };
  10748. // MS_VS_PedTransformPreSkinD_Packed 005fe88ec1bdc0c7 and its pixel
  10749. // shader 93667197d3d05e1c: TEXCOORD6 is one value at register 4
  10750. // column 3; parameter 3 (rows 6 and 7) carries it in dword 3.
  10751. let sig = vec![
  10752. element(1, 2, 0, 4),
  10753. element(2, 3, 0, 4),
  10754. element(4, 4, 0, 3),
  10755. element(6, 4, 3, 1),
  10756. element(3, 5, 0, 4),
  10757. element(5, 6, 0, 4),
  10758. element(7, 7, 0, 2),
  10759. element(9, 9, 0, 3),
  10760. element(11, 10, 0, 3),
  10761. element(15, 12, 0, 4),
  10762. ];
  10763. let packs = [
  10764. (2, Some(3)),
  10765. (4, Some(5)),
  10766. (6, Some(7)),
  10767. (9, Some(10)),
  10768. (12, None),
  10769. ];
  10770. let at = |a, h| packed_half(&sig, &packs, a, h);
  10771. // Parameter 2: TEXCOORD4's three values, a zero half, TEXCOORD3.
  10772. assert_eq!(at(4, 2), Some((4, 2)));
  10773. assert_eq!(at(4, 3), None);
  10774. assert_eq!(at(4, 4), Some((5, 0)));
  10775. assert_eq!(at(4, 7), Some((5, 3)));
  10776. // Parameter 3: TEXCOORD5, TEXCOORD7, then TEXCOORD6 alone.
  10777. assert_eq!(at(6, 3), Some((6, 3)));
  10778. assert_eq!(at(6, 5), Some((7, 1)));
  10779. assert_eq!(at(6, 6), Some((4, 3)));
  10780. assert_eq!(at(6, 7), None);
  10781. // Parameters without such an element are as before.
  10782. assert_eq!(at(9, 3), None);
  10783. assert_eq!(at(9, 4), Some((10, 0)));
  10784. assert_eq!(at(12, 3), Some((12, 3)));
  10785. assert_eq!(at(12, 4), None);
  10786. // The common layout (29805d23a495cdf8): TEXCOORD7 is two values at
  10787. // register 1 columns 2-3; parameter 0 is TEXCOORD0, TEXCOORD1,
  10788. // TEXCOORD7.
  10789. let sig = vec![
  10790. element(0, 1, 0, 2),
  10791. element(7, 1, 2, 2),
  10792. element(1, 2, 0, 4),
  10793. element(2, 3, 0, 4),
  10794. element(4, 4, 0, 3),
  10795. ];
  10796. let packs = [(3, Some(4)), (1, Some(2))];
  10797. let at = |a, h| packed_half(&sig, &packs, a, h);
  10798. assert_eq!(at(1, 1), Some((1, 1)));
  10799. assert_eq!(at(1, 2), Some((2, 0)));
  10800. assert_eq!(at(1, 5), Some((2, 3)));
  10801. assert_eq!(at(1, 6), Some((1, 2)));
  10802. assert_eq!(at(1, 7), Some((1, 3)));
  10803. assert_eq!(at(3, 6), Some((4, 2)));
  10804. assert_eq!(at(3, 7), None);
  10805. // A row no element holds gives nothing, as before.
  10806. assert_eq!(packed_half(&sig, &[(8, None)], 8, 0), None);
  10807. }
  10808. /// Whether a synthetic compute program translates with these input registers.
  10809. fn lowers(words: &[u32], rsrc2: u32) -> Result<(), crate::ShaderError> {
  10810. let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
  10811. let native = NativeProgram {
  10812. stage: HwStage::Cs,
  10813. wave64: false,
  10814. vgprs: 256,
  10815. layout: vec![],
  10816. used: vec![],
  10817. io: StageIo::Cs(ComputeIo {
  10818. rsrc2,
  10819. threads: [1, 1, 1],
  10820. }),
  10821. code,
  10822. };
  10823. let p = ir::build(&native.code, false, 256).unwrap();
  10824. let st = structure::structure(&p).unwrap();
  10825. let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
  10826. let io = io::raise(&p, &native).unwrap();
  10827. lower(&Parts {
  10828. native: &native,
  10829. p: &p,
  10830. st: &st,
  10831. io: &io,
  10832. res: &res,
  10833. inputs: vec![],
  10834. outputs: vec![],
  10835. prims: vec![],
  10836. mesh_stride: 0,
  10837. })
  10838. .map(|_| ())
  10839. }
  10840. /// Lowers a compute program with the root parameters `layout` (in user
  10841. /// SGPRs from s0 on) and the used resources `used`.
  10842. fn lower_with(
  10843. words: &[u32],
  10844. layout: Vec<RootParam>,
  10845. used: Vec<UsedResource>,
  10846. ) -> Result<Lowered, crate::ShaderError> {
  10847. lower_wave(words, layout, used, false)
  10848. }
  10849. /// [`lower_with`] in wave64 if `wave64`.
  10850. fn lower_wave(
  10851. words: &[u32],
  10852. layout: Vec<RootParam>,
  10853. used: Vec<UsedResource>,
  10854. wave64: bool,
  10855. ) -> Result<Lowered, crate::ShaderError> {
  10856. let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
  10857. let sgprs: u32 = layout.iter().map(|p| p.sgprs).sum();
  10858. let native = NativeProgram {
  10859. stage: HwStage::Cs,
  10860. wave64,
  10861. vgprs: 256,
  10862. layout,
  10863. used,
  10864. io: StageIo::Cs(ComputeIo {
  10865. // The layout's user SGPRs (at least two), 512 bytes of LDS.
  10866. rsrc2: 1 << 15 | sgprs.max(2) << 1,
  10867. threads: [1, 1, 1],
  10868. }),
  10869. code,
  10870. };
  10871. let p = ir::build(&native.code, wave64, 256).unwrap();
  10872. let st = structure::structure(&p).unwrap();
  10873. let res = resource::track(&p, &native.layout, native.stage, Some(&st))?;
  10874. let io = io::raise(&p, &native).unwrap();
  10875. lower(&Parts {
  10876. native: &native,
  10877. p: &p,
  10878. st: &st,
  10879. io: &io,
  10880. res: &res,
  10881. inputs: vec![],
  10882. outputs: vec![],
  10883. prims: vec![],
  10884. mesh_stride: 0,
  10885. })
  10886. }
  10887. /// Root parameter `slot` in user SGPRs from `user_data` on.
  10888. fn root(root: RootType, user_data: u8, slot: u8) -> RootParam {
  10889. RootParam {
  10890. root,
  10891. table_offset_dwords: 0,
  10892. sgprs: if root == RootType::Descriptor { 2 } else { 1 },
  10893. base_register: 0,
  10894. user_data,
  10895. slot,
  10896. }
  10897. }
  10898. #[test]
  10899. fn buffer_cache_invalidations_lower_as_no_ops() {
  10900. // MUBUF opcode 0x071/0x072 with no data operand: the title asks the
  10901. // host to invalidate its cached view of a buffer.
  10902. assert!(lowers(&[0xE1C4_0000, 0, S_ENDPGM], 0).is_ok(), "buffer_gl0_inv");
  10903. assert!(lowers(&[0xE1C8_0000, 0, S_ENDPGM], 0).is_ok(), "buffer_gl1_inv");
  10904. }
  10905. #[test]
  10906. fn a_scalar_carry_chain_reaches_the_select() {
  10907. // The high dword of a 64-bit add or subtract, then a select on the
  10908. // carry (borrow) the high half leaves in SCC, and a branch on it
  10909. // (only code with an effect needs its operands).
  10910. let add = [
  10911. 0xBE80_03C1, // s_mov_b32 s0, -1
  10912. 0xBE81_0380, // s_mov_b32 s1, 0
  10913. 0x8000_8100, // s_add_u32 s0, s0, 1
  10914. 0x8201_8001, // s_addc_u32 s1, s1, 0
  10915. 0x8502_0001, // s_cselect_b32 s2, s1, s0
  10916. 0xBF07_8002, // s_cmp_lg_u32 s2, 0
  10917. 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm
  10918. 0xBE83_0380, // s_mov_b32 s3, 0
  10919. S_ENDPGM,
  10920. ];
  10921. let sub = [
  10922. 0xBE80_0380, // s_mov_b32 s0, 0
  10923. 0xBE81_0380, // s_mov_b32 s1, 0
  10924. 0x8080_8100, // s_sub_u32 s0, s0, 1
  10925. 0x8281_8001, // s_subb_u32 s1, s1, 0
  10926. 0x8502_0001, // s_cselect_b32 s2, s1, s0
  10927. 0xBF07_8002, // s_cmp_lg_u32 s2, 0
  10928. 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm
  10929. 0xBE83_0380, // s_mov_b32 s3, 0
  10930. S_ENDPGM,
  10931. ];
  10932. for words in [add, sub] {
  10933. lowers(&words, 0).unwrap();
  10934. }
  10935. }
  10936. fn perm_features(selector: u32) -> u64 {
  10937. // Synthetic compute shader:
  10938. // v0 is the thread ID and can supply a dynamic selector.
  10939. // Store the result in LDS to keep the permutation live.
  10940. let words = [
  10941. 0x7E02_02FFu32,
  10942. 0x817F_34AB,
  10943. 0x7E04_02FF,
  10944. 0xFE01_56CD,
  10945. 0xD744_0003,
  10946. 257 | (258 << 9) | (selector << 18),
  10947. 0x3408_0082,
  10948. 0xD834_0000,
  10949. 0x0000_0304,
  10950. S_ENDPGM,
  10951. ];
  10952. let code: Vec<u8> = words.iter()
  10953. .flat_map(|w| w.to_le_bytes())
  10954. .collect();
  10955. let native = NativeProgram {
  10956. stage: HwStage::Cs,
  10957. wave64: false,
  10958. vgprs: 256,
  10959. layout: vec![],
  10960. used: vec![],
  10961. io: StageIo::Cs(ComputeIo {
  10962. rsrc2: 1 << 15,
  10963. threads: [64, 1, 1],
  10964. }),
  10965. code,
  10966. };
  10967. let p = ir::build(&native.code, false, 256).unwrap();
  10968. assert!(p.blocks.iter()
  10969. .flat_map(|b| &b.insts)
  10970. .any(|i| i.name() == "v_perm_b32"));
  10971. let st = structure::structure(&p).unwrap();
  10972. let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
  10973. let io = io::raise(&p, &native).unwrap();
  10974. let emitted = lower(&Parts {
  10975. native: &native,
  10976. p: &p,
  10977. st: &st,
  10978. io: &io,
  10979. res: &res,
  10980. inputs: vec![],
  10981. outputs: vec![],
  10982. prims: vec![],
  10983. mesh_stride: 0,
  10984. }).unwrap();
  10985. let container =
  10986. crate::Container::parse(&emitted.dxil).unwrap();
  10987. let features =
  10988. container.part(crate::FourCC::SFI0).unwrap();
  10989. u64::from_le_bytes(features.data.try_into().unwrap())
  10990. }
  10991. #[test]
  10992. fn perm_constant_selector_needs_no_int64() {
  10993. assert_eq!(perm_features(128) & 0x8000, 0);
  10994. }
  10995. #[test]
  10996. fn perm_dynamic_selector_needs_no_int64() {
  10997. assert_eq!(
  10998. perm_features(256) & 0x8000,
  10999. 0,
  11000. "dynamic v_perm_b32 must not require INT64"
  11001. );
  11002. }
  11003. #[test]
  11004. fn a_descriptor_selected_by_scc_picks_its_heap_index() {
  11005. // Two buffer descriptors loaded from the table at s0, one picked by
  11006. // a root constant (s1) with s_cselect_b64 per half, and loaded
  11007. // through by index and stored to LDS so the load is needed.
  11008. let words = [
  11009. 0xBE84_0300, // s_mov_b32 s4, s0
  11010. 0xBE85_0380, // s_mov_b32 s5, 0
  11011. 0xF408_0202,
  11012. 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null
  11013. 0xF408_0302,
  11014. 0xFA00_0010, // s_load_dwordx4 s[12:15], s[4:5], 0x10
  11015. 0xBF06_8001, // s_cmp_eq_u32 s1, 0
  11016. 0x8590_0C08, // s_cselect_b64 s[16:17], s[8:9], s[12:13]
  11017. 0x8592_0E0A, // s_cselect_b64 s[18:19], s[10:11], s[14:15]
  11018. 0xE030_2000,
  11019. 0x8004_0100, // buffer_load_dword v1, v0, s[16:19], 0 idxen
  11020. 0xD834_0000,
  11021. 0x0000_0100, // ds_write_b32 v0, v1
  11022. S_ENDPGM,
  11023. ];
  11024. let layout = || vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)];
  11025. // Both are structured buffers of dwords in the table's range.
  11026. let used = || {
  11027. vec![UsedResource {
  11028. kind: ResourceType::Srv,
  11029. root: RootType::Table,
  11030. table_offset_dwords: 0,
  11031. lower_bound: 0,
  11032. stride: 4,
  11033. dwords: 4,
  11034. user_data: 0,
  11035. slot: 0,
  11036. }]
  11037. };
  11038. lower_with(&words, layout(), used()).unwrap();
  11039. }
  11040. /// Tables of 2D textures at s0 and samplers at s1.
  11041. fn texture_tables() -> (Vec<RootParam>, Vec<UsedResource>) {
  11042. let range = |kind, user_data, slot| UsedResource {
  11043. kind,
  11044. root: RootType::Table,
  11045. table_offset_dwords: 0,
  11046. lower_bound: 0,
  11047. stride: 0,
  11048. dwords: if kind == ResourceType::Sampler { 4 } else { 8 },
  11049. user_data,
  11050. slot,
  11051. };
  11052. (
  11053. vec![root(RootType::Table, 0, 0), root(RootType::Table, 1, 1)],
  11054. vec![
  11055. range(ResourceType::Srv, 0, 0),
  11056. range(ResourceType::Sampler, 1, 1),
  11057. ],
  11058. )
  11059. }
  11060. #[test]
  11061. fn waterfall_loops_over_per_lane_descriptors_sample_with_each_lanes_own() {
  11062. use crate::resource::tests::{
  11063. WATERFALL_FETCHED_WAVE32, WATERFALL_FETCHED_WAVE64, WATERFALL_PICKED_WAVE32,
  11064. };
  11065. for (words, wave64) in [
  11066. (WATERFALL_FETCHED_WAVE32, false),
  11067. (WATERFALL_FETCHED_WAVE64, true),
  11068. (WATERFALL_PICKED_WAVE32, false),
  11069. ] {
  11070. let (layout, used) = texture_tables();
  11071. let l = lower_wave(words, layout, used, wave64).unwrap();
  11072. // The loop's reads of the first lane became each lane's own
  11073. // dwords: no wave operation is left.
  11074. assert_eq!(l.nonuniform_handles, 1);
  11075. assert!(!l.wave_ops);
  11076. }
  11077. }
  11078. /// [`texture_tables`] with a raw buffer UAV at dword 16 of the first.
  11079. pub(crate) fn texture_and_uav_tables() -> (Vec<RootParam>, Vec<UsedResource>) {
  11080. let (layout, mut used) = texture_tables();
  11081. used.push(UsedResource {
  11082. kind: ResourceType::Uav,
  11083. root: RootType::Table,
  11084. table_offset_dwords: 16,
  11085. lower_bound: 0,
  11086. stride: 0,
  11087. dwords: 4,
  11088. user_data: 0,
  11089. slot: 0,
  11090. });
  11091. (layout, used)
  11092. }
  11093. #[test]
  11094. fn waterfall_loops_over_descriptors_joined_per_lane_sample_with_each_lanes_own() {
  11095. use crate::resource::tests::{WATERFALL_JOINED_MIXED_WAVE32, WATERFALL_JOINED_WAVE32};
  11096. for words in [WATERFALL_JOINED_WAVE32, WATERFALL_JOINED_MIXED_WAVE32] {
  11097. let (layout, used) = texture_and_uav_tables();
  11098. let l = lower_wave(words, layout, used, false).unwrap();
  11099. // One image handle, from the join's per-lane heap index.
  11100. assert_eq!(l.nonuniform_handles, 1);
  11101. assert!(!l.wave_ops);
  11102. }
  11103. }
  11104. #[test]
  11105. fn scalar_bit_tests_lower() {
  11106. // Each tests one bit of a constant into SCC and branches on it (only
  11107. // code with an effect needs its operands).
  11108. let tail = [
  11109. 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm
  11110. 0xBE84_0380, // s_mov_b32 s4, 0
  11111. S_ENDPGM,
  11112. ];
  11113. let bit_tests: [&[u32]; 4] = [
  11114. &[0xBE81_0387, 0xBF0C_8301], // s_mov_b32 s1, 7; s_bitcmp0_b32 s1, 3
  11115. &[0xBE81_0387, 0xBF0D_8301], // s_mov_b32 s1, 7; s_bitcmp1_b32 s1, 3
  11116. &[
  11117. 0xBE80_0387, // s_mov_b32 s0, 7
  11118. 0xBE81_0380, // s_mov_b32 s1, 0
  11119. 0xBF0E_8300, // s_bitcmp0_b64 s[0:1], 3
  11120. ],
  11121. &[
  11122. 0xBE80_0387, // s_mov_b32 s0, 7
  11123. 0xBE81_0380, // s_mov_b32 s1, 0
  11124. 0xBF0F_8300, // s_bitcmp1_b64 s[0:1], 3
  11125. ],
  11126. ];
  11127. for head in bit_tests {
  11128. let words: Vec<u32> = head.iter().chain(&tail).copied().collect();
  11129. lowers(&words, 0).unwrap();
  11130. }
  11131. }
  11132. #[test]
  11133. #[ignore = "ours marks joins read through joins only with VICTORY_STRICT_JOINS (40 programs stop otherwise)"]
  11134. fn a_missing_value_stays_missing_through_two_live_joins() {
  11135. let mut words = [
  11136. 0xF490_0180,
  11137. 0, // s_memtime s[6:7]
  11138. 0xBF06_8000, // s_cmp_eq_u32 s0, 0 (s0 = group id X)
  11139. 0xBF85_0001, // skip the first overwrite
  11140. 0xBE86_0380, // s_mov_b32 s6, 0
  11141. 0xBF06_8101, // s_cmp_eq_u32 s1, 1 (s1 = group id Y)
  11142. 0xBF85_0001, // skip the second overwrite
  11143. 0xBE86_0381, // s_mov_b32 s6, 1
  11144. 0xBF07_8006, // s_cmp_lg_u32 s6, 0
  11145. 0xBF85_0001, // use the result to branch
  11146. 0xBE83_0380,
  11147. S_ENDPGM,
  11148. ];
  11149. let group_ids_xy = 3 << 7;
  11150. // Compare to a direct read so future timestamp support works in both cases.
  11151. let refusal = |code: &[u32]| match lowers(code, group_ids_xy) {
  11152. Ok(()) => None,
  11153. Err(crate::ShaderError::Unsupported { what, .. }) => Some(what),
  11154. Err(error) => panic!("{error}"),
  11155. };
  11156. let direct = [&words[..2], &words[8..]].concat();
  11157. assert_eq!(refusal(&words), refusal(&direct));
  11158. words[8] = 0xBF07_8000; // read the group id instead; the timestamp is dead
  11159. lowers(&words, group_ids_xy).expect("dead timestamp");
  11160. }
  11161. #[test]
  11162. fn buffer_formats_by_number() {
  11163. // The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM,
  11164. // 2_10_10_10_UNORM, 16_FLOAT, 32_32_32_32_FLOAT.
  11165. assert_eq!(buffer_format(56), Some((&[8, 8, 8, 8][..], Numeric::Unorm)));
  11166. assert_eq!(buffer_format(24), Some((&[16, 16][..], Numeric::Snorm)));
  11167. assert_eq!(
  11168. buffer_format(50),
  11169. Some((&[10, 10, 10, 2][..], Numeric::Unorm))
  11170. );
  11171. assert_eq!(buffer_format(13), Some((&[16][..], Numeric::Float)));
  11172. assert_eq!(
  11173. buffer_format(77),
  11174. Some((&[32, 32, 32, 32][..], Numeric::Float))
  11175. );
  11176. // Invalid, past the table.
  11177. assert_eq!(buffer_format(0), None);
  11178. assert_eq!(buffer_format(78), None);
  11179. }
  11180. #[test]
  11181. fn packed_buffer_formats_by_number() {
  11182. // LLVM's `UfmtGFX10`: 10_11_11 is 30-36, 11_11_10 37-43,
  11183. // 10_10_10_2 44-49. Channels from the lowest bits: R11G11B10_FLOAT
  11184. // is 10_11_11 (Mesa), 10_10_10_2 has the 2-bit channel first.
  11185. assert_eq!(buffer_format(30), Some((&[11, 11, 10][..], Numeric::Unorm)));
  11186. assert_eq!(buffer_format(36), Some((&[11, 11, 10][..], Numeric::Float)));
  11187. assert_eq!(buffer_format(37), Some((&[10, 11, 11][..], Numeric::Unorm)));
  11188. assert_eq!(buffer_format(43), Some((&[10, 11, 11][..], Numeric::Float)));
  11189. assert_eq!(
  11190. buffer_format(44),
  11191. Some((&[2, 10, 10, 10][..], Numeric::Unorm))
  11192. );
  11193. assert_eq!(
  11194. buffer_format(45),
  11195. Some((&[2, 10, 10, 10][..], Numeric::Snorm))
  11196. );
  11197. assert_eq!(
  11198. buffer_format(46),
  11199. Some((&[2, 10, 10, 10][..], Numeric::Uscaled))
  11200. );
  11201. assert_eq!(
  11202. buffer_format(47),
  11203. Some((&[2, 10, 10, 10][..], Numeric::Sscaled))
  11204. );
  11205. assert_eq!(
  11206. buffer_format(48),
  11207. Some((&[2, 10, 10, 10][..], Numeric::Uint))
  11208. );
  11209. assert_eq!(
  11210. buffer_format(49),
  11211. Some((&[2, 10, 10, 10][..], Numeric::Sint))
  11212. );
  11213. }
  11214. /// A half's value (sign, 5-bit exponent biased 15, 10-bit mantissa), as
  11215. /// `legacyF16ToF32` widens it.
  11216. fn half(h: u32) -> f32 {
  11217. let (s, e, m) = ((h >> 15) & 1, (h >> 10) & 31, h & 1023);
  11218. let v = match e {
  11219. 0 => m as f32 * 2f32.powi(-24),
  11220. 31 if m == 0 => f32::INFINITY,
  11221. 31 => f32::NAN,
  11222. _ => (1024 + m) as f32 * 2f32.powi(e as i32 - 25),
  11223. };
  11224. if s == 1 { -v } else { v }
  11225. }
  11226. #[test]
  11227. fn small_floats_widen_as_halves() {
  11228. // Unsigned 11- and 10-bit floats: a 5-bit exponent biased 15 over a
  11229. // 6- or 5-bit mantissa, no sign; values from the D3D/GL spec.
  11230. let f11 = |x: u32| half(x << half_shift(11));
  11231. let f10 = |x: u32| half(x << half_shift(10));
  11232. assert_eq!(f11(0), 0.0);
  11233. assert_eq!(f11(0x001), 2f32.powi(-20)); // smallest denormal
  11234. assert_eq!(f11(0x03F), 63.0 * 2f32.powi(-20)); // largest denormal
  11235. assert_eq!(f11(0x040), 2f32.powi(-14)); // smallest normal
  11236. assert_eq!(f11(0x3C0), 1.0);
  11237. assert_eq!(f11(0x3E0), 1.5);
  11238. assert_eq!(f11(0x7BF), 65024.0); // largest
  11239. assert_eq!(f11(0x7C0), f32::INFINITY);
  11240. assert!(f11(0x7C1).is_nan());
  11241. assert_eq!(f10(0x001), 2f32.powi(-19));
  11242. assert_eq!(f10(0x020), 2f32.powi(-14));
  11243. assert_eq!(f10(0x1E0), 1.0);
  11244. assert_eq!(f10(0x3DF), 64512.0);
  11245. assert_eq!(f10(0x3E0), f32::INFINITY);
  11246. assert!(f10(0x3FF).is_nan());
  11247. // A 16-bit float is a half already, sign included.
  11248. assert_eq!(half(0xBC00 << half_shift(16)), -1.0);
  11249. }
  11250. }