lower.rs 562 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205
  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, Tag, 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 a comparison sampler.
  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. lower_counted(parts, counted_in_threads(parts))
  81. }
  82. /// Whether the title dispatches the program by a count of threads whose last
  83. /// group may be partial: the structure builder's programs of one dimension.
  84. /// Their lanes past the count must not run (they count the lanes of a wave
  85. /// and store). Not where a group barrier would wait for lanes that left, nor
  86. /// where two host waves of 32 stand for a console wave (they exchange, which
  87. /// takes all lanes).
  88. fn counted_in_threads(parts: &Parts) -> bool {
  89. let crate::native::StageIo::Cs(cs) = &parts.native.io else {
  90. return false;
  91. };
  92. cs.threads[0] > 1
  93. && cs.threads[1..] == [1, 1]
  94. && crate::spill::is_spilled(parts.native)
  95. && (!parts.native.wave64 || host_max_wave() >= 64)
  96. && !parts.p.blocks.iter().flat_map(|b| &b.insts).any(|i| i.name() == "s_barrier")
  97. }
  98. /// [`lower`]; `counted`: the lanes past a dispatch's count of threads leave
  99. /// at once (`shader.rs` `USER_DISPATCH_THREADS_X`; after DexNom/VIctory
  100. /// bc3cd4b0, which does so for two of the programs by their digests).
  101. pub(super) fn lower_counted(parts: &Parts, counted: bool) -> Result<Lowered, ShaderError> {
  102. let mut bad = HashMap::new();
  103. loop {
  104. match Lower::new(parts, &bad).run(counted) {
  105. Ok(l) => return Ok(l),
  106. Err(Stop::Retry(v, why)) => {
  107. if bad.insert(v, why).is_some() {
  108. return Err(ShaderError::Unsupported {
  109. offset: 0,
  110. what: "a phi that does not settle",
  111. });
  112. }
  113. }
  114. Err(Stop::Fail(e)) => return Err(e),
  115. }
  116. }
  117. }
  118. const TWO_PI: f32 = std::f32::consts::TAU;
  119. /// `s_sendmsg` id of a mesh or NGG stage's output allocation request.
  120. const GS_ALLOC_REQ: u16 = 9;
  121. /// `s_sendmsg` id that ends a pixel wave's ordered section.
  122. const ORDERED_PS_DONE: u16 = 7;
  123. /// Hardware register (of `s_setreg_b32`) a pixel wave names its packer in
  124. /// before it waits for the waves it overlaps.
  125. const POPS_PACKER: u16 = 25;
  126. /// The operand `src_pops_exiting_wave_id`.
  127. const POPS_EXITING: u8 = 239;
  128. /// The instructions inside a pixel program's ordered section
  129. /// (primitive-ordered pixel shading, which the console compiler makes of
  130. /// rasterizer ordered views): from the write of `POPS_PACKER`, along every
  131. /// path, to the message that ends the section or the program's end. The
  132. /// console waits there until the waves holding earlier primitives' samples
  133. /// of the same pixels have left their sections; a host's rasterizer ordered
  134. /// views wait by themselves, at their first access. Empty for a program
  135. /// without such a section.
  136. fn ordered_section(p: &Program) -> HashSet<Site> {
  137. let starts = |i: &Inst| {
  138. i.name() == "s_setreg_b32"
  139. && matches!(i.fields, Fields::Sop { imm: Some(imm), .. } if imm & 0x3F == POPS_PACKER)
  140. };
  141. let ends = |i: &Inst| {
  142. i.name() == "s_sendmsg"
  143. && matches!(i.fields, Fields::Sopp { imm } if imm & 0xF == ORDERED_PS_DONE)
  144. };
  145. let mut section = HashSet::new();
  146. let mut entered = vec![false; p.blocks.len()];
  147. let mut work: Vec<Site> = p
  148. .blocks
  149. .iter()
  150. .enumerate()
  151. .flat_map(|(b, block)| {
  152. (0..block.insts.len())
  153. .filter(|&i| starts(&block.insts[i]))
  154. .map(move |i| (b, i))
  155. })
  156. .collect();
  157. while let Some((b, from)) = work.pop() {
  158. let block = &p.blocks[b];
  159. let mut done = false;
  160. for i in from..block.insts.len() {
  161. if ends(&block.insts[i]) {
  162. done = true;
  163. break;
  164. }
  165. section.insert((b, i));
  166. }
  167. if done {
  168. continue;
  169. }
  170. for (t, next) in p.blocks.iter().enumerate() {
  171. if next.preds.contains(&b) && !std::mem::replace(&mut entered[t], true) {
  172. work.push((t, 0));
  173. }
  174. }
  175. }
  176. section
  177. }
  178. /// The f16 bits of inline float constant `c` (240..=248: 0.5, -0.5, 1.0,
  179. /// -1.0, 2.0, -2.0, 4.0, -4.0, 1/(2 pi)).
  180. fn inline_f16(c: u8) -> u32 {
  181. [
  182. 0x3800, 0xB800, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x4400, 0xC400, 0x3118,
  183. ][usize::from(c - 240)]
  184. }
  185. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  186. enum Numeric {
  187. Unorm,
  188. Snorm,
  189. Uscaled,
  190. Sscaled,
  191. Uint,
  192. Sint,
  193. Float,
  194. }
  195. /// A GFX10 buffer format (the unified format of typed buffer loads): the
  196. /// channel widths from the lowest bits up, and how the channels convert.
  197. /// Formats are numbered in families (`8`, `16`, `8_8`, ...: AMD names
  198. /// list channels from the highest bits), each with its numeric formats in
  199. /// the order unorm, snorm, uscaled, sscaled, uint, sint, float.
  200. fn buffer_format(format: u8) -> Option<(&'static [u32], Numeric)> {
  201. use Numeric::*;
  202. const NORM: &[Numeric] = &[Unorm, Snorm, Uscaled, Sscaled, Uint, Sint];
  203. const ALL: &[Numeric] = &[Unorm, Snorm, Uscaled, Sscaled, Uint, Sint, Float];
  204. const WIDE: &[Numeric] = &[Uint, Sint, Float];
  205. // Numbers and order from LLVM's `UfmtGFX10` (`SIDefines.h`); the GFX10
  206. // buffer formats have no 5_9_9_9. Channel order from Mesa
  207. // (`ac_formats.c`): R11G11B10_FLOAT is 10_11_11, and 10_10_10_2 has
  208. // its 2-bit channel in the lowest bits.
  209. const FAMILIES: [(&[u32], &[Numeric]); 14] = [
  210. (&[8], NORM),
  211. (&[16], ALL),
  212. (&[8, 8], NORM),
  213. (&[32], WIDE),
  214. (&[16, 16], ALL),
  215. (&[11, 11, 10], ALL), // 10_11_11
  216. (&[10, 11, 11], ALL), // 11_11_10
  217. (&[2, 10, 10, 10], NORM), // 10_10_10_2
  218. (&[10, 10, 10, 2], NORM), // 2_10_10_10
  219. (&[8, 8, 8, 8], NORM),
  220. (&[32, 32], WIDE),
  221. (&[16, 16, 16, 16], ALL),
  222. (&[32, 32, 32], WIDE),
  223. (&[32, 32, 32, 32], WIDE),
  224. ];
  225. let mut n = usize::from(format.checked_sub(1)?);
  226. for (bits, numerics) in FAMILIES {
  227. if n < numerics.len() {
  228. return Some((bits, numerics[n]));
  229. }
  230. n -= numerics.len();
  231. }
  232. None
  233. }
  234. /// How far a float channel of `width` bits (16, or the unsigned 11- and
  235. /// 10-bit floats of the packed formats) shifts up to be a half:
  236. /// the small floats are a half's exponent (5 bits, biased 15) and the top
  237. /// of its mantissa, without the sign, so `legacyF16ToF32` widens them
  238. /// exactly, denormals, infinities and NaNs included.
  239. fn half_shift(width: u32) -> u32 {
  240. debug_assert!(matches!(width, 10 | 11 | 16), "{width}-bit float");
  241. if width == 16 { 0 } else { 15 - width }
  242. }
  243. struct Lower<'a> {
  244. s: Shader,
  245. x: &'a Parts<'a>,
  246. bad: &'a HashMap<Value, Why>,
  247. lane_fail: HashMap<Value, Why>,
  248. vals: HashMap<Value, Val>,
  249. floats: HashMap<Value, V>,
  250. /// DXIL block per IR block (unreachable: none).
  251. block: Vec<Option<usize>>,
  252. cur: usize,
  253. bools: HashMap<(usize, Bool), V>,
  254. lane_bits: HashMap<Value, V>,
  255. /// IR phi location by value.
  256. phi_at: HashMap<Value, (usize, usize)>,
  257. /// Descriptor dwords with no host value (addresses, formats, all of a constant
  258. /// buffer's): no program reads them as numbers ([`Self::dead`]).
  259. stale: HashSet<Value>,
  260. /// See [`ordered_section`] (pixel programs).
  261. ordered: HashSet<Site>,
  262. /// Raw UAV buffers (see [`Lower::entry`]) the program loads from past its
  263. /// wave's cache (GLC): other groups write what it waits for. On the host
  264. /// they are globally coherent; a load in a loop that only waits would
  265. /// be made once otherwise.
  266. coherent: HashSet<(usize, u32)>,
  267. /// In the instruction being lowered: the host copy its root view's bytes
  268. /// are in ([`Lower::root_memory`]).
  269. root_copy: Option<V>,
  270. /// Whether the page [`Lower::memory`] last looked for has a copy.
  271. page_there: Option<V>,
  272. mask_phis: HashMap<Value, V>,
  273. pending_masks: Vec<(V, usize, usize)>,
  274. data_phis: Vec<(V, usize, usize)>,
  275. read_phis: HashSet<Value>,
  276. params: HashMap<Value, (usize, u32)>,
  277. user_data: Option<V>,
  278. user_reads: BTreeMap<u32, UserData>,
  279. samplers: Vec<[u32; 4]>,
  280. descriptors: HashMap<(Site, bool), &'a Source>,
  281. scalar: HashMap<Site, Address>,
  282. exports: HashMap<Site, &'a Export>,
  283. interps: HashMap<Site, &'a Interp>,
  284. handles: HashMap<(usize, Site, u8, bool, (u32, u32)), V>,
  285. /// Element strides read from the host's table by heap slot
  286. /// ([`super::shader::SLOT_STRIDES`]), by block and descriptor load.
  287. strides: HashMap<(usize, Site, u8), V>,
  288. /// Blocks splitting the edge from one IR block to another.
  289. edges: HashMap<(usize, usize), usize>,
  290. /// Per IR block: a `done` export is behind every lane entering it.
  291. exported: Vec<bool>,
  292. /// Reverse-postorder index per IR block.
  293. rpo: Vec<usize>,
  294. /// DXIL block each IR block ends in (guarded stores split blocks).
  295. tail: Vec<Option<usize>>,
  296. /// The program writes UAVs: barriers fence them too.
  297. writes_uavs: bool,
  298. /// src0 of the current instruction as DPP fetched it.
  299. src0: Option<V>,
  300. /// Compute code that reads other lanes: thread ids follow the host
  301. /// lanes, so lane n is console lane n.
  302. console_lanes: bool,
  303. /// Mesh: the thread index in the group (made in the entry block).
  304. flat: Option<V>,
  305. /// Mesh: IR blocks whose `s_barrier` is left out.
  306. no_barrier: HashSet<usize>,
  307. /// IR blocks whose `s_barrier` not every lane is sure to reach (a lane
  308. /// branch lies between the entry and the block, or the program has a
  309. /// loop a lane can be cut out of): the barrier there keeps its fences
  310. /// and does not wait for the group ([`super::group_sync`]).
  311. fence_only: HashSet<usize>,
  312. /// A group barrier before every LDS access (a console wave run as two host waves).
  313. split_lds: bool,
  314. /// With `split_lds`, LDS accesses in lane branches: per IR block whether every lane runs
  315. /// it, and whether the host waves meet at its start and before its exit ([`lds_meetings`]).
  316. lds_meet: Option<(Vec<bool>, Vec<(bool, bool)>)>,
  317. /// A console wave64 program run as two host waves of 32 that exchange through LDS: the first
  318. /// of two exchange dwords, whether the group has no upper half (32 threads or fewer), and per
  319. /// IR block whether every lane runs it (exchanges need both halves there).
  320. exchange: Option<(u32, bool, Vec<bool>)>,
  321. /// With `exchange`: nothing is exchanged, each host wave acts as a wave
  322. /// of its own ([`with_local_waves`]).
  323. local: bool,
  324. /// The instruction being lowered may read a lane mask as a number under
  325. /// `local` (a bit count, a first set bit, `v_mbcnt`).
  326. local_ok: bool,
  327. /// With `local`: every mask read and lane read is taken per host wave
  328. /// ([`with_local_waves_any`]).
  329. local_any: bool,
  330. /// With `exchange`: VGPR values every lane holds alike ([`lane_uniform`]); a first-lane
  331. /// read of one needs nothing from the other host wave.
  332. uniform: HashSet<Value>,
  333. /// With `exchange`: the wave ORs that only steer a loop over each lane's own bits, which
  334. /// a host wave takes over its own lanes wherever they stand ([`super::own_bits`]).
  335. own_bits: super::own_bits::OwnBits,
  336. /// The console lane (0..63) of this thread, made in the entry block.
  337. clane: Option<V>,
  338. /// The first exchange dword of this thread's console wave ([`Self::exchange_pair`]).
  339. pair: Option<V>,
  340. /// A console wave64 program in host waves of 32: the LDS dword counting the console threads
  341. /// handed to host waves (`wave_base`), and the base made in the entry block.
  342. halves: Option<u32>,
  343. wave_base: Option<V>,
  344. /// Vertex and mesh outputs holding 16-bit values: row, whether two per
  345. /// dword, and the row packed after it.
  346. half_outputs: HashMap<u8, (bool, Option<u8>)>,
  347. /// How lane masks become data.
  348. mask_data: MaskData,
  349. /// The instruction being lowered may read lane masks as data.
  350. mask_ok: bool,
  351. /// Ballots of masks read as data, by low dword: (low, high).
  352. ballots: HashMap<Value, (V, V)>,
  353. /// Masks whose ballot is being built: a mask whose lane bit needs its
  354. /// own value as a number (an opaque mask keyed by a dword it shares
  355. /// with another) would otherwise recurse until the stack overflows.
  356. balloting: HashSet<Value>,
  357. /// Block writing each value.
  358. def_block: HashMap<Value, usize>,
  359. /// IR block being lowered.
  360. cur_ir: usize,
  361. /// Whole-wave sections by block and start index.
  362. sections: HashMap<usize, HashMap<usize, super::wave::Section>>,
  363. /// Values written in a section that code outside it reads.
  364. section_out: HashSet<Value>,
  365. /// The program's constant table (the code from the first byte read
  366. /// through `s_getpc_b64` on): global, first byte, dwords.
  367. code_table: Option<(V, u32, u32)>,
  368. /// Loop headers' iteration counters (see [`LOOP_LIMIT`]): the phi by
  369. /// IR block, and its incoming (value, DXIL block) pairs.
  370. counters: HashMap<usize, (V, Vec<(V, usize)>)>,
  371. /// The block a loop stopped by [`LOOP_LIMIT`] leaves the program from.
  372. abort: Option<usize>,
  373. }
  374. /// Iterations after which a loop is left (per entry into it), unless
  375. /// [`super::loop_limit`] says otherwise. The console runs a loop as long as
  376. /// its data says; data the host has not mirrored yet (a null view reads
  377. /// zeros) can make that four billion iterations, which hangs the host GPU
  378. /// until the driver resets it. A lane that reaches the limit leaves the
  379. /// program as killed (a pixel discards).
  380. // shortcut: a genuine loop of more iterations than this is cut short too.
  381. pub(super) const LOOP_LIMIT: u32 = 1 << 20;
  382. /// Lane masks read as numbers (`s_bcnt1`, `s_ff1`, `v_mbcnt`, scalar
  383. /// compares, bit tests) are ballots of the lanes' booleans, taken where the
  384. /// mask is written: structurisation's `active` masks hold only lanes that
  385. /// reach that block, so the ballot misses none.
  386. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  387. enum MaskData {
  388. /// Compute: host lane n is console lane n (the program declares the
  389. /// console's wave size), so ballots are the console's masks bit for bit
  390. /// and any use is exact.
  391. Console,
  392. /// Pixel and vertex programs: ballots over the host's wave, whatever its
  393. /// size. Only uses that mean the same on any wave are allowed: counts,
  394. /// the first lane, the count below a lane, equality (the HLSL wave
  395. /// operations the console compiler expands). Lane numbers stay host
  396. /// lanes throughout (`v_mbcnt`, `v_readlane` at a computed lane).
  397. Host,
  398. /// Mesh programs: their lanes and waves (LDS per console wave) are the
  399. /// console's but no host wave size can be declared.
  400. None,
  401. }
  402. /// What a value holding a lane mask read as a number stops with.
  403. pub(super) const LANE_MASK: Why = "a lane mask read as data";
  404. /// A mask with lanes outside EXEC where it is written, read as a number where the lanes that
  405. /// run that block are not all of the wave.
  406. pub(super) const MASK_ELSEWHERE: Why = "a lane mask holding lanes elsewhere read as data";
  407. /// Instructions that read a lane mask (not EXEC implicitly, not a lane's
  408. /// bit) as a number.
  409. /// Per IR block: every lane of the wave that started the program runs it – no per-lane branch
  410. /// separates it from the entry (it lies in no lane branch's region: the blocks reachable from
  411. /// the branch that do not post-dominate it). None with an indirect exit (not followed).
  412. fn all_lane_blocks(st: &Structured) -> Option<Vec<bool>> {
  413. let n = st.exits.len();
  414. let mut all = vec![true; n];
  415. for (_, region) in lane_regions(st)? {
  416. for b in (0..n).filter(|&b| region[b]) {
  417. all[b] = false;
  418. }
  419. }
  420. Some(all)
  421. }
  422. /// Every per-lane branch (by its block) with its region: the blocks reachable from it that do
  423. /// not post-dominate it, which only some lanes run. Not the branches the wave takes together
  424. /// ([`Structured::wide`]), nor those on scalar conditions. None with an indirect exit.
  425. fn lane_regions(st: &Structured) -> Option<Vec<(usize, Vec<bool>)>> {
  426. let n = st.exits.len();
  427. let mut succ: Vec<Vec<usize>> = vec![Vec::new(); n];
  428. for (b, e) in st.exits.iter().enumerate() {
  429. match *e {
  430. LaneExit::Jump(t) => succ[b].push(t),
  431. LaneExit::Branch { taken, not_taken, .. } => {
  432. succ[b].push(taken);
  433. succ[b].push(not_taken);
  434. }
  435. LaneExit::End => {}
  436. LaneExit::Indirect => return None,
  437. }
  438. }
  439. // post-dominators (bitsets; a virtual exit after every End)
  440. let words = n.div_ceil(64);
  441. let full = vec![u64::MAX; words];
  442. 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();
  443. let mut changed = true;
  444. while changed {
  445. changed = false;
  446. for b in (0..n).rev() {
  447. if succ[b].is_empty() {
  448. continue;
  449. }
  450. let mut v = full.clone();
  451. for &t in &succ[b] {
  452. for w in 0..words {
  453. v[w] &= pdom[t][w];
  454. }
  455. }
  456. v[b / 64] |= 1 << (b % 64);
  457. if v != pdom[b] {
  458. pdom[b] = v;
  459. changed = true;
  460. }
  461. }
  462. }
  463. let mut regions = Vec::new();
  464. for (d, e) in st.exits.iter().enumerate() {
  465. let LaneExit::Branch { when, .. } = *e else { continue };
  466. if st.wide.contains(&d) || st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_))) {
  467. continue; // a wave-wide or uniform branch: all lanes go the same way
  468. }
  469. // blocks reachable from the lane branch that do not post-dominate it
  470. let mut seen = vec![false; n];
  471. let mut stack: Vec<usize> = succ[d].clone();
  472. while let Some(b) = stack.pop() {
  473. if seen[b] || pdom[d][b / 64] >> (b % 64) & 1 == 1 {
  474. continue;
  475. }
  476. seen[b] = true;
  477. stack.extend(succ[b].iter().copied());
  478. }
  479. regions.push((d, seen));
  480. }
  481. Some(regions)
  482. }
  483. /// The per-lane branches (by block) whose regions hold a block of `needs` (blocks where two
  484. /// host waves must meet, [`take_needs`]): the ones to take wave-wide
  485. /// ([`crate::structure::structure_wide`]) so that every lane runs those blocks. None if one
  486. /// of them is a branch whose wave-wide meaning is not known ([`Structured::wave_any`]).
  487. pub(super) fn branches_around(st: &Structured, needs: &[usize]) -> Option<Vec<usize>> {
  488. let mut out = Vec::new();
  489. for (d, region) in lane_regions(st)? {
  490. if needs.iter().any(|&b| region.get(b).copied().unwrap_or(false)) {
  491. st.wave_any.get(d).copied().flatten()?;
  492. out.push(d);
  493. }
  494. }
  495. Some(out)
  496. }
  497. /// Whether a refusal is of code that needs every lane of the wave where it stands (two host
  498. /// waves meeting there), which the other forms of the program may give it.
  499. pub(super) fn needs_every_lane(what: &str) -> bool {
  500. what.ends_with("where not every lane runs") || what == MASK_ELSEWHERE
  501. }
  502. /// The blocks where the last lowering on this thread wanted every lane and did not have it
  503. /// (its "... where not every lane runs" refusals), which it forgets.
  504. pub(super) fn take_needs() -> Vec<usize> {
  505. NEEDS.take()
  506. }
  507. fn need(block: usize) {
  508. NEEDS.with_borrow_mut(|n| {
  509. if !n.contains(&block) {
  510. n.push(block);
  511. }
  512. });
  513. }
  514. /// VGPR values that are the same in every lane holding them (`all` is [`all_lane_blocks`]):
  515. /// written by an instruction every arriving lane runs (no guard), lane by lane, from scalars,
  516. /// constants and such values; or loaded from an address made of them. The compiler keeps
  517. /// wave-uniform data in VGPRs and fetches it with `v_readfirstlane`.
  518. /// shortcut: a value joined by a phi counts only where every predecessor is a block all lanes
  519. /// run (no lane branch can have split the arriving lanes); loop-carried values never do.
  520. fn lane_uniform(p: &Program, st: &Structured, all: &[bool]) -> HashSet<Value> {
  521. let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v);
  522. let mut same: HashSet<Value> = HashSet::new();
  523. for b in crate::ir::reverse_postorder(&p.blocks) {
  524. let block = &p.blocks[b];
  525. let whole = block.preds.iter().all(|&q| all.get(q).copied().unwrap_or(false));
  526. for phi in &block.phis {
  527. if matches!(phi.reg, Reg::V(_)) && whole && phi.args.iter().all(|a| same.contains(a)) {
  528. same.insert(phi.value);
  529. }
  530. }
  531. for (i, inst) in block.insts.iter().enumerate() {
  532. let name = inst.name();
  533. let ops: Vec<Operand> = match &inst.fields {
  534. Fields::Valu(v)
  535. if v.dpp.is_none()
  536. && v.sdwa.is_none()
  537. && !name.starts_with("v_mbcnt")
  538. && !name.starts_with("v_cmpx")
  539. && !name.contains("lane") =>
  540. {
  541. v.src.clone()
  542. }
  543. _ => continue,
  544. };
  545. if st.guards[b][i].is_some() {
  546. continue; // lanes outside EXEC keep another value
  547. }
  548. let alike = ops.iter().all(|op| match *op {
  549. Operand::Vector { reg, .. } => {
  550. // every dword of the operand the instruction reads from that register on
  551. let read: Vec<Value> =
  552. inst.reads.iter().filter(|r| matches!(r.0, Reg::V(x) if x >= reg)).map(|r| r.1).collect();
  553. !read.is_empty() && read.iter().all(|x| same.contains(x))
  554. }
  555. // a scalar is one value; a lane mask is not, unless a compare of such values made it
  556. Operand::Scalar { code, .. } if code != NULL => {
  557. inst.read(Reg::S(code)).is_none_or(|x| !is_mask(x) || same.contains(&x))
  558. }
  559. _ => true,
  560. });
  561. if alike {
  562. same.extend(inst.writes.iter().filter(|w| w.0 != Reg::Scc).map(|w| w.1));
  563. }
  564. }
  565. }
  566. same
  567. }
  568. /// What a register value holds, for [`wave_local`].
  569. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  570. enum Wave {
  571. /// Nothing that depends on how the threads are divided into waves.
  572. Plain,
  573. /// The number of the wave's first lane in a mask (`s_ff1`).
  574. First,
  575. /// A reduction over the wave's lanes: a count, a sum, a minimum...
  576. Total(super::wave::Op),
  577. /// A count or sum over the lanes below this one.
  578. Prefix,
  579. /// Derived from what a first-lane atomic returned: the slots the wave reserved.
  580. Base,
  581. /// A mix the idiom does not make.
  582. Mixed,
  583. }
  584. /// Whether a console wave64 program may run with each host wave as a wave of its own
  585. /// ([`with_local_waves`]): its wave-wide values are used only as the allocation idiom uses
  586. /// them, which does not care how the threads are divided into waves. A first-lane number only
  587. /// picks the first lane; a count or sum only goes into that lane's atomic on a shared counter;
  588. /// a prefix only goes onto the base that atomic returned; the first lane does nothing else.
  589. /// Anything else done with them takes one wave to be the whole thread group (a tile's result,
  590. /// say) and is refused, with the offset and what was found.
  591. /// Lane masks read as numbers by other instructions and lane reads outside whole-wave sections
  592. /// are stopped by the lowering itself.
  593. // shortcut: `v_readfirstlane` of a value that differs between lanes is taken as it is (this
  594. // host wave's first lane), and a guarded write of a plain value over a wave-dependent one is
  595. // the only mix of old and new lanes that is looked at.
  596. pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'static str)> {
  597. use super::wave::{Op, Shape};
  598. const FIRST: Why = "a wave's first-lane number used as data";
  599. const TOTAL: Why = "a count or sum over the wave used as data";
  600. const PREFIX: Why = "a count or sum over the lanes below used without a reserved base";
  601. const MIXED: Why = "a value that depends on the wave on some paths only";
  602. const EFFECT: Why = "a write by the wave's first lane other than its reservation";
  603. fn of(kind: &HashMap<Value, Wave>, v: Option<Value>) -> Wave {
  604. v.and_then(|v| kind.get(&v).copied()).unwrap_or(Wave::Plain)
  605. }
  606. fn put(kind: &mut HashMap<Value, Wave>, v: Value, k: Wave) {
  607. if k == Wave::Plain {
  608. kind.remove(&v);
  609. } else {
  610. kind.insert(v, k);
  611. }
  612. }
  613. let wild = |k: Wave| !matches!(k, Wave::Plain | Wave::Base);
  614. let why = |k: Wave| match k {
  615. Wave::First => FIRST,
  616. Wave::Total(_) => TOTAL,
  617. Wave::Prefix => PREFIX,
  618. _ => MIXED,
  619. };
  620. // a mask (by its low dword) under which only a wave's first lane runs
  621. let first_mask = |firsts: &HashSet<Value>, m: Option<Value>| {
  622. m.and_then(|m| st.masks.get(&m)).is_some_and(|&b| {
  623. st.bools
  624. .support(b)
  625. .iter()
  626. .any(|a| matches!(a, Atom::Lane(v) if firsts.contains(v)))
  627. })
  628. };
  629. // One instruction outside a section: the kind of what it writes, and whether it is a
  630. // first lane's reservation.
  631. let step = |inst: &Inst, kind: &HashMap<Value, Wave>, firsts: &mut HashSet<Value>| -> Result<(Wave, bool), Why> {
  632. let name = inst.name();
  633. let val = |op: &Operand| match *op {
  634. Operand::Vector { reg, .. } => inst.read(Reg::V(reg)),
  635. Operand::Scalar { code, .. } if code != NULL => inst.read(Reg::S(code)),
  636. _ => None,
  637. };
  638. let ops: Vec<Operand> = match &inst.fields {
  639. Fields::Valu(v) => v.src.clone(),
  640. Fields::Sop { dst, src, .. } => {
  641. let mut o = src.clone();
  642. if matches!(name, "s_addk_i32" | "s_mulk_i32") {
  643. o.extend(dst.iter().copied());
  644. }
  645. o
  646. }
  647. Fields::Buffer { data, .. } if name.contains("_atomic_") || name.contains("_store_") => {
  648. data.iter().copied().collect()
  649. }
  650. _ => Vec::new(),
  651. };
  652. let kinds: Vec<Wave> = ops.iter().map(|o| of(kind, val(o))).collect();
  653. // Everything else it reads (addresses, descriptors, SCC, the high dwords of wide
  654. // operands) must not depend on the wave. Not EXEC, and not the old value of a VGPR it
  655. // writes, which only the lanes outside EXEC keep.
  656. let named: Vec<Value> = ops.iter().filter_map(&val).collect();
  657. for &(r, v) in &inst.reads {
  658. let kept = matches!(r, Reg::V(_)) && inst.writes.iter().any(|w| w.0 == r);
  659. if matches!(r, Reg::S(c) if c == EXEC || c == EXEC + 1) || kept || named.contains(&v) {
  660. continue;
  661. }
  662. let k = of(kind, Some(v));
  663. if wild(k) {
  664. return Err(why(k));
  665. }
  666. }
  667. let w = kinds.iter().copied().find(|&k| wild(k)).unwrap_or(Wave::Mixed);
  668. let sum = |k: Wave| k == Wave::Total(Op::AddU);
  669. let is_mask = |o: &Operand| {
  670. val(o).is_some_and(|v| st.masks.contains_key(&v) || st.highs.contains_key(&v))
  671. };
  672. let mut reserved = false;
  673. let out = match (name, &kinds[..]) {
  674. ("s_ff1_i32_b64" | "s_ff1_i32_b32", _) if ops.first().is_some_and(is_mask) => Wave::First,
  675. ("s_bcnt1_i32_b64" | "s_bcnt1_i32_b32", _) if ops.first().is_some_and(is_mask) => {
  676. Wave::Total(Op::AddU)
  677. }
  678. // bits of a mask below the lane; with -1 for the mask, the lane's number
  679. ("v_mbcnt_lo_u32_b32" | "v_mbcnt_hi_u32_b32", [_, b]) => {
  680. match (matches!(ops[0], Operand::Scalar { .. }), *b) {
  681. (_, Wave::Prefix) | (true, Wave::Plain | Wave::Base) => Wave::Prefix,
  682. (false, Wave::Plain | Wave::Base) => Wave::Plain,
  683. (_, k) => return Err(why(k)),
  684. }
  685. }
  686. // nothing wave-dependent goes in; what derives from a reserved base stays marked
  687. _ if !kinds.iter().any(|&k| wild(k)) => {
  688. let derives = matches!(inst.fields, Fields::Valu(_) | Fields::Sop { .. });
  689. if derives && kinds.contains(&Wave::Base) { Wave::Base } else { Wave::Plain }
  690. }
  691. ("v_mov_b32" | "s_mov_b32", [k]) => *k,
  692. ("v_cmp_eq_i32" | "v_cmp_eq_u32" | "v_cmpx_eq_i32" | "v_cmpx_eq_u32", [a, b]) => {
  693. // the lane whose own number is the first lane's
  694. let lane = match (*a, *b) {
  695. (Wave::First, k) if !wild(k) => &ops[1],
  696. (k, Wave::First) if !wild(k) => &ops[0],
  697. _ => return Err(why(w)),
  698. };
  699. if !matches!(lane, Operand::Vector { .. }) {
  700. return Err(FIRST);
  701. }
  702. let mask = match &inst.fields {
  703. _ if name.starts_with("v_cmpx") => inst.write(Reg::S(EXEC)),
  704. Fields::Valu(v) => match v.dst {
  705. Some(Operand::Scalar { code, .. }) => inst.write(Reg::S(code)),
  706. _ => None,
  707. },
  708. _ => None,
  709. };
  710. firsts.extend(mask);
  711. Wave::Plain
  712. }
  713. ("v_add_nc_u32" | "s_add_i32", [a, b]) => match (*a, *b) {
  714. (Wave::Prefix, Wave::Base) | (Wave::Base, Wave::Prefix) => Wave::Base,
  715. (Wave::Prefix, Wave::Plain | Wave::Prefix) | (Wave::Plain, Wave::Prefix) => Wave::Prefix,
  716. (x, y) if sum(x) && sum(y) => x,
  717. _ => return Err(why(w)),
  718. },
  719. ("v_sub_nc_u32" | "s_sub_i32", [a, b]) => match (*a, *b) {
  720. (Wave::Base, Wave::Prefix) => Wave::Base,
  721. (Wave::Prefix, Wave::Plain) => Wave::Prefix,
  722. (Wave::Plain, y) if sum(y) && matches!(ops[0], Operand::Const(128)) => y,
  723. _ => return Err(why(w)),
  724. },
  725. ("s_mul_i32" | "v_mul_lo_u32" | "v_mul_u32_u24", [a, b]) => match (*a, *b) {
  726. (x, Wave::Plain) | (Wave::Plain, x) if sum(x) || x == Wave::Prefix => x,
  727. _ => return Err(why(w)),
  728. },
  729. ("s_lshl_b32", [x, Wave::Plain]) | ("v_lshlrev_b32", [Wave::Plain, x])
  730. if sum(*x) || *x == Wave::Prefix =>
  731. {
  732. *x
  733. }
  734. ("v_lshl_add_u32", [Wave::Prefix, Wave::Plain, c]) if !wild(*c) => {
  735. if *c == Wave::Base { Wave::Base } else { Wave::Prefix }
  736. }
  737. // the reservation: the first lane adds its wave's total to a shared counter
  738. (_, [Wave::Total(op)]) if name.contains("_atomic_") => {
  739. let want = match op {
  740. Op::AddU => "buffer_atomic_add",
  741. Op::MinU => "buffer_atomic_umin",
  742. Op::MaxU => "buffer_atomic_umax",
  743. Op::MinI => "buffer_atomic_smin",
  744. Op::MaxI => "buffer_atomic_smax",
  745. Op::Or => "buffer_atomic_or",
  746. Op::And => "buffer_atomic_and",
  747. Op::Xor => "buffer_atomic_xor",
  748. _ => "",
  749. };
  750. if name != want || !first_mask(firsts, inst.read(Reg::S(EXEC))) {
  751. return Err(TOTAL);
  752. }
  753. reserved = true;
  754. Wave::Base
  755. }
  756. _ => return Err(why(w)),
  757. };
  758. Ok((out, reserved))
  759. };
  760. let sections: Vec<_> = (0..p.blocks.len()).map(|b| super::wave::sections(p, b)).collect();
  761. let order = crate::ir::reverse_postorder(&p.blocks);
  762. let pass = |kind: &mut HashMap<Value, Wave>, firsts: &mut HashSet<Value>, check: bool| -> Result<(), (usize, Why)> {
  763. for &b in &order {
  764. let block = &p.blocks[b];
  765. for phi in &block.phis {
  766. let mut k = Wave::Plain;
  767. for (n, &a) in phi.args.iter().enumerate() {
  768. let x = of(kind, Some(a));
  769. k = match (k, x) {
  770. _ if n == 0 => x,
  771. (k, x) if k == x => k,
  772. (Wave::Plain, m @ (Wave::Base | Wave::Prefix))
  773. | (m @ (Wave::Base | Wave::Prefix), Wave::Plain) => m,
  774. _ => Wave::Mixed,
  775. };
  776. }
  777. put(kind, phi.value, k);
  778. }
  779. for (i, inst) in block.insts.iter().enumerate() {
  780. // inside a whole-wave section: what the simulation found each value to be
  781. if let Some((_, sec)) = sections[b].iter().find(|(s, sec)| i > **s && i < sec.end) {
  782. for &(_, w) in &inst.writes {
  783. let k = match sec.shapes.get(&w) {
  784. None => Wave::Mixed,
  785. Some(&Shape::K(_)) => Wave::Plain,
  786. Some(&Shape::Value(v)) => of(kind, Some(v)),
  787. Some(&Shape::Masked(src, _, _)) => of(kind, Some(src)),
  788. Some(&Shape::Active(op, src, mask, _)) => match of(kind, Some(src)) {
  789. Wave::Plain | Wave::Base => Wave::Total(op),
  790. // the first lane's own sum of a total is that total
  791. Wave::Total(o) if o == op && first_mask(firsts, Some(mask)) => Wave::Total(op),
  792. _ => Wave::Mixed,
  793. },
  794. Some(&Shape::Prefix(Op::AddU, src, mask, _, _)) => match of(kind, Some(src)) {
  795. Wave::Plain | Wave::Base => Wave::Prefix,
  796. Wave::Total(Op::AddU) if first_mask(firsts, Some(mask)) => Wave::Prefix,
  797. _ => Wave::Mixed,
  798. },
  799. Some(_) => Wave::Mixed,
  800. };
  801. put(kind, w, k);
  802. }
  803. continue;
  804. }
  805. let name = inst.name();
  806. if name.starts_with("s_cbranch") {
  807. continue; // with the block's exit, below
  808. }
  809. let (k, reserved) = match step(inst, kind, firsts) {
  810. Ok(r) => r,
  811. Err(why) if check => return Err((inst.machine.offset, why)),
  812. Err(_) => (Wave::Mixed, false),
  813. };
  814. // the same test as `Lower::inst`'s `effect`
  815. let effect = matches!(inst.fields, Fields::Exp { .. })
  816. || matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_")
  817. || name.contains("store")
  818. || name.contains("atomic")
  819. || matches!(inst.fields, Fields::Ds { .. })
  820. && !(name.starts_with("ds_read")
  821. || name.starts_with("ds_swizzle")
  822. || name.contains("permute"));
  823. if check && effect && !reserved && first_mask(firsts, inst.read(Reg::S(EXEC))) {
  824. return Err((inst.machine.offset, EFFECT));
  825. }
  826. let guarded = st.guards[b][i].is_some();
  827. for &(r, w) in &inst.writes {
  828. let mut kw = match r {
  829. // "some lane is counted" keeps the count's kind; any other SCC is one bit of data
  830. Reg::Scc if !name.starts_with("s_bcnt1") => {
  831. if wild(k) { Wave::Mixed } else { Wave::Plain }
  832. }
  833. _ => k,
  834. };
  835. // a guarded write leaves the old value in the lanes outside EXEC
  836. if guarded
  837. && matches!(r, Reg::V(_))
  838. && kw == Wave::Plain
  839. && matches!(of(kind, inst.read(r)), Wave::First | Wave::Total(_) | Wave::Prefix)
  840. {
  841. kw = Wave::Mixed;
  842. }
  843. put(kind, w, kw);
  844. }
  845. }
  846. // a branch on "some lane is counted": fine where the structure made it the lane's
  847. // own bit (the mask is EXEC under a scalar condition)
  848. if check
  849. && let Some(last) = block.insts.last()
  850. && last.name().starts_with("s_cbranch_scc")
  851. && let Some(scc) = last.read(Reg::Scc)
  852. && wild(of(kind, Some(scc)))
  853. {
  854. let own = matches!(st.exits[b], LaneExit::Branch { when, .. }
  855. if !st.bools.support(when).iter().any(|a| matches!(a, Atom::Uniform(v) if *v == scc)));
  856. if !own {
  857. return Err((last.machine.offset, TOTAL));
  858. }
  859. }
  860. }
  861. Ok(())
  862. };
  863. let mut kind: HashMap<Value, Wave> = HashMap::new();
  864. let mut firsts: HashSet<Value> = HashSet::new();
  865. // to a fixpoint (values carried around loops), then once more to say what is wrong
  866. let mut settled = false;
  867. for _ in 0..16 {
  868. let before = (kind.clone(), firsts.len());
  869. pass(&mut kind, &mut firsts, false)?;
  870. if (&before.0, before.1) == (&kind, firsts.len()) {
  871. settled = true;
  872. break;
  873. }
  874. }
  875. if !settled {
  876. return Err((0, MIXED));
  877. }
  878. pass(&mut kind, &mut firsts, true)
  879. }
  880. /// The mode of a group barrier the translation adds (host waves meeting):
  881. /// a wait for the group with a shared-memory fence; the fence alone with
  882. /// `VICTORY_GROUP_SYNC=0` ([`super::group_sync`]).
  883. fn meeting_mode() -> u32 {
  884. if super::group_sync() == 0 { 8 } else { 1 | 8 }
  885. }
  886. /// LDS accesses of a console wave run as two host waves, where some sit in blocks that only
  887. /// some lanes run (`all` is [`all_lane_blocks`]): per IR block, whether the host waves meet (a
  888. /// group barrier) at its start and before its exit. `None` if barriers cannot keep the
  889. /// console's order.
  890. ///
  891. /// The console runs the wave's lanes in step, so an LDS write is seen by every later read. Two
  892. /// host waves keep that order if they meet between any two accesses of which one writes. A
  893. /// barrier must be run by every thread, so it cannot stand in a lane branch's region; but
  894. /// every way into and out of such a region passes a block all lanes run, and the waves meet
  895. /// there: before the exit of an all-lane block into a region with LDS accesses, and at the
  896. /// start of an all-lane block entered from one. Accesses in all-lane blocks get their own
  897. /// barrier as before. What that cannot order is a write and a read inside one region (blocks
  898. /// joined without an all-lane block between them): refused.
  899. /// shortcut: two writes in one region are taken not to hit the same dword from both halves.
  900. fn lds_meetings(p: &crate::ir::Program, st: &Structured, all: &[bool]) -> Option<Vec<(bool, bool)>> {
  901. let n = st.exits.len();
  902. let succ = |b: usize| -> Vec<usize> {
  903. match st.exits[b] {
  904. LaneExit::Jump(t) => vec![t],
  905. LaneExit::Branch { taken, not_taken, .. } => vec![taken, not_taken],
  906. LaneExit::End | LaneExit::Indirect => Vec::new(),
  907. }
  908. };
  909. // regions: blocks not every lane runs, joined by the edges between them
  910. let mut region: Vec<usize> = (0..n).collect();
  911. fn find(region: &mut [usize], mut b: usize) -> usize {
  912. while region[b] != b {
  913. region[b] = region[region[b]];
  914. b = region[b];
  915. }
  916. b
  917. }
  918. for b in 0..n {
  919. for t in succ(b) {
  920. if !all[b] && !all[t] {
  921. let (x, y) = (find(&mut region, b), find(&mut region, t));
  922. region[x] = y;
  923. }
  924. }
  925. }
  926. // per region: LDS reads, LDS writes
  927. let mut reads = vec![false; n];
  928. let mut writes = vec![false; n];
  929. for (b, block) in p.blocks.iter().enumerate().take(n) {
  930. if all[b] {
  931. continue;
  932. }
  933. let r = find(&mut region, b);
  934. for i in &block.insts {
  935. let name = i.name();
  936. if !matches!(i.fields, Fields::Ds { .. }) || name.starts_with("ds_swizzle") || name.contains("permute") {
  937. continue;
  938. }
  939. if name.starts_with("ds_read") {
  940. reads[r] = true;
  941. } else {
  942. writes[r] = true;
  943. }
  944. }
  945. }
  946. if (0..n).any(|r| reads[r] && writes[r]) {
  947. return None;
  948. }
  949. let mut meet = vec![(false, false); n];
  950. for b in 0..n {
  951. for t in succ(b) {
  952. if all[b] && !all[t] {
  953. let r = find(&mut region, t);
  954. meet[b].1 |= reads[r] || writes[r];
  955. } else if !all[b] && all[t] {
  956. let r = find(&mut region, b);
  957. meet[t].0 |= reads[r] || writes[r];
  958. }
  959. }
  960. }
  961. Some(meet)
  962. }
  963. /// Masks held as numbers or constant lane sets in guards or lane branches: the lane tests its
  964. /// own bit by its console lane.
  965. fn lane_constant_masks(st: &Structured) -> bool {
  966. let whens = st.exits.iter().filter_map(|e| match *e {
  967. LaneExit::Branch { when, .. } => Some(when),
  968. _ => None,
  969. });
  970. let mut work: Vec<Bool> = st.guards.iter().flatten().flatten().copied().chain(whens).collect();
  971. // Through lane-mask joins too: an edge that brings a number or a constant lane set needs
  972. // the lane's own bit of it.
  973. // shortcut: masks only selects read (`v_cndmask_b32`, carries in) are not followed; such
  974. // a program still stops with "a constant lane mask" or "an opaque lane mask".
  975. let (mut seen, mut joins) = (HashSet::new(), HashSet::new());
  976. while let Some(g) = work.pop() {
  977. if !seen.insert(g) {
  978. continue;
  979. }
  980. for a in st.bools.support(g) {
  981. match a {
  982. Atom::Opaque(_) | Atom::Constant(_) => return true,
  983. Atom::Phi(id) if joins.insert(id) => {
  984. if let Some(edges) = st.phi_masks.get(&id) {
  985. work.extend(edges.iter().copied());
  986. }
  987. }
  988. _ => {}
  989. }
  990. }
  991. }
  992. false
  993. }
  994. /// The widest wave the host GPU runs (0: not known – no host-specific forms); see
  995. /// [`set_host_max_wave`].
  996. static HOST_MAX_WAVE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
  997. /// The host GPU's `WaveLaneCountMax`: 32 lets console wave64 compute programs whose cross-lane
  998. /// code stays inside 32-lane halves run in waves of 32 instead of being refused.
  999. pub fn set_host_max_wave(lanes: u32) {
  1000. HOST_MAX_WAVE.store(lanes, std::sync::atomic::Ordering::Relaxed);
  1001. }
  1002. thread_local! {
  1003. /// See [`take_needs`].
  1004. static NEEDS: std::cell::RefCell<Vec<usize>> = const { std::cell::RefCell::new(Vec::new()) };
  1005. /// See [`with_local_waves`].
  1006. static LOCAL_WAVES: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
  1007. /// See [`with_local_waves_any`].
  1008. static LOCAL_ANY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
  1009. }
  1010. /// As [`with_local_waves`], with every other use of a lane mask as a number
  1011. /// and every lane read and write taken per host wave too: the program runs
  1012. /// as it would on a console of 32-lane waves, lanes numbered 0..31 or
  1013. /// 32..63 by half. Right for code that only relies on what HLSL's wave
  1014. /// operations promise; a program that takes one wave to be its whole
  1015. /// thread group gets per-half results. The last resort for programs that
  1016. /// do not translate otherwise.
  1017. pub(super) fn with_local_waves_any<R>(f: impl FnOnce() -> R) -> R {
  1018. let was = LOCAL_ANY.replace(true);
  1019. let r = with_local_waves(f);
  1020. LOCAL_ANY.set(was);
  1021. r
  1022. }
  1023. /// Runs `f` with console wave64 programs on 32-lane hosts lowered with each
  1024. /// host wave as a wave of its own ("local"): no exchange between the two
  1025. /// halves of a console wave, so no barriers and no need for every lane to
  1026. /// reach the code. What HLSL's wave operations promise holds for any
  1027. /// division of the threads into waves, and the idiom the title's compute
  1028. /// programs use them for does not care which wave a thread is in: count or
  1029. /// sum over the wave, the first lane reserves that many slots with an atomic
  1030. /// add, every lane takes the base (`WaveReadLaneFirst`) plus its prefix.
  1031. /// Each lane still gets a slot of its own; only the order differs.
  1032. /// Only that idiom's operations are lowered this way: a lane mask read as
  1033. /// a number by anything but a bit count, a first-set-bit or `v_mbcnt`, and
  1034. /// lane reads and writes outside whole-wave sections, stop the translation.
  1035. /// shortcut: where a count or sum goes is not checked. A program that uses
  1036. /// a wave-wide result as data for the whole console wave (a tile's maximum,
  1037. /// say, with one wave per thread group) gets its half's result. It is used
  1038. /// only for programs that do not translate otherwise.
  1039. pub(super) fn with_local_waves<R>(f: impl FnOnce() -> R) -> R {
  1040. let was = LOCAL_WAVES.replace(true);
  1041. let r = f();
  1042. LOCAL_WAVES.set(was);
  1043. r
  1044. }
  1045. /// `VICTORY_F16_NEAREST=1`: the results of 16-bit float operations (`v_add_f16`,
  1046. /// `v_mul_f16`, `v_cvt_f16_f32` ...) are rounded to nearest as the console rounds them
  1047. /// ([`Lower::f16_nearest`]) instead of as the host's `f32tof16` does (toward zero on NVIDIA:
  1048. /// the last place of a result that is not exact is then one lower than the console's).
  1049. /// Off by default: it is exact but untried in a game run, and adds instructions to every
  1050. /// such operation. The wave sum of 16-bit floats ([`Lower::half_sum`]) is always exact.
  1051. fn f16_nearest_on() -> bool {
  1052. #[cfg(test)]
  1053. if let Some(on) = TEST_F16_NEAREST.get() {
  1054. return on;
  1055. }
  1056. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1057. *ON.get_or_init(|| std::env::var_os("VICTORY_F16_NEAREST").is_some_and(|v| v == "1"))
  1058. }
  1059. #[cfg(test)]
  1060. thread_local! {
  1061. /// A test's choice for [`f16_nearest_on`], for its thread only.
  1062. pub(super) static TEST_F16_NEAREST: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
  1063. }
  1064. /// `VICTORY_WAVE_OWN_BITS=0`: a wave OR where not every lane runs is refused as before
  1065. /// ([`super::own_bits`]).
  1066. fn own_bits_on() -> bool {
  1067. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1068. *ON.get_or_init(|| std::env::var_os("VICTORY_WAVE_OWN_BITS").is_none_or(|v| v != "0"))
  1069. }
  1070. /// What the translator was told of the host, for a cache's key: the widest
  1071. /// wave, the view heap's limit and where the raw twins of its views start.
  1072. pub fn host_settings() -> [u32; 3] {
  1073. [host_max_wave(), super::shader::view_heap_limit(), super::shader::raw_views()]
  1074. }
  1075. /// The refusal of a first half of an interpolation whose result is read
  1076. /// as data ([`Lower::interp`]).
  1077. pub(super) const FIRST_HALF: &str = "the first half of an interpolation";
  1078. thread_local! {
  1079. /// Whether first halves of interpolations are evaluated as the pair
  1080. /// they start ([`with_first_half_pairs`]).
  1081. static FIRST_HALF_PAIRS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
  1082. }
  1083. /// Runs `translate` with first halves of interpolations evaluated as the
  1084. /// pair they start: the translation of a program refused with
  1085. /// [`FIRST_HALF`] (`VICTORY_FIRST_HALF=0`: refused again, as before).
  1086. pub(super) fn with_first_half_pairs<R>(translate: impl FnOnce() -> R) -> R {
  1087. let before = FIRST_HALF_PAIRS.replace(true);
  1088. let result = translate();
  1089. FIRST_HALF_PAIRS.set(before);
  1090. result
  1091. }
  1092. pub(super) fn host_max_wave() -> u32 {
  1093. #[cfg(test)]
  1094. if let Some(lanes) = TEST_HOST_WAVE.get() {
  1095. return lanes;
  1096. }
  1097. HOST_MAX_WAVE.load(std::sync::atomic::Ordering::Relaxed)
  1098. }
  1099. #[cfg(test)]
  1100. thread_local! {
  1101. /// A test's host wave size, for its thread only ([`set_host_max_wave`] is the process's).
  1102. pub(super) static TEST_HOST_WAVE: std::cell::Cell<Option<u32>> = const { std::cell::Cell::new(None) };
  1103. }
  1104. pub(super) fn reads_mask_as_data(st: &Structured, i: &Inst) -> bool {
  1105. let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v);
  1106. let ops: Vec<&Operand> = match &i.fields {
  1107. // A mask operation (its result a mask) is no data use.
  1108. Fields::Sop { .. }
  1109. if i.writes
  1110. .iter()
  1111. .any(|&(r, w)| matches!(r, Reg::S(_)) && is_mask(w)) =>
  1112. {
  1113. return false;
  1114. }
  1115. Fields::Sop { src, .. } => src.iter().collect(),
  1116. Fields::Valu(v)
  1117. if !matches!(i.name(), "v_cndmask_b32") && !i.name().contains("_co_ci_") =>
  1118. {
  1119. v.src.iter().collect()
  1120. }
  1121. _ => return false,
  1122. };
  1123. ops.into_iter().any(|op| match *op {
  1124. Operand::Scalar { code, .. } if code != NULL => i.read(Reg::S(code)).is_some_and(is_mask),
  1125. _ => false,
  1126. })
  1127. }
  1128. /// The parameters packing 16-bit rows two per dword and where each lays
  1129. /// its elements out: (first row, [(dword, register, column, columns)]).
  1130. ///
  1131. /// The console gives every 16-bit element whole dwords. A parameter leads
  1132. /// with the first element of its first row, then the first element of its
  1133. /// second row. An element that shares a register behind another one (the
  1134. /// signature packs a short element into the free columns of an earlier
  1135. /// register) is NOT in that row's halves: it follows in the first
  1136. /// parameter, in row order, that has whole dwords left.
  1137. /// The title's packed pedestrian shaders show both cases: TEXCOORD7 (register 1,
  1138. /// columns 2-3, behind the two columns of TEXCOORD0) is exported in dword 3
  1139. /// of parameter 0, after TEXCOORD1's two dwords; TEXCOORD6 (register 4,
  1140. /// column 3, behind the three columns of TEXCOORD4) in dword 3 of
  1141. /// parameter 3, after TEXCOORD5 and TEXCOORD7, while the high half of
  1142. /// TEXCOORD4's second dword stays zero.
  1143. type PackedLayout = Vec<(u8, Vec<(u8, u8, u8, u8)>)>;
  1144. fn packed_layout(elements: &[SigElement], packs: &[(u8, Option<u8>)]) -> PackedLayout {
  1145. let of_row = |r: u8| {
  1146. let mut of: Vec<&SigElement> = elements
  1147. .iter()
  1148. .filter(|e| e.row == Some(u32::from(r)))
  1149. .collect();
  1150. of.sort_by_key(|e| e.col);
  1151. of
  1152. };
  1153. let mut packs = packs.to_vec();
  1154. packs.sort_unstable();
  1155. packs.dedup_by_key(|p| p.0);
  1156. // Per parameter: its first row, the dwords used, the elements.
  1157. let mut layout: Vec<(u8, u8, Vec<(u8, u8, u8, u8)>)> = Vec::new();
  1158. let mut behind = Vec::new();
  1159. for &(a, b) in &packs {
  1160. let mut placed = Vec::new();
  1161. let mut at = 0u8;
  1162. if !of_row(a).is_empty() {
  1163. for r in [Some(a), b].into_iter().flatten() {
  1164. let of = of_row(r);
  1165. let Some((lead, more)) = of.split_first() else {
  1166. continue;
  1167. };
  1168. placed.push((at, r, lead.col, lead.cols));
  1169. at += lead.cols.div_ceil(2);
  1170. behind.extend(more.iter().map(|e| (r, e.col, e.cols)));
  1171. }
  1172. }
  1173. layout.push((a, at, placed));
  1174. }
  1175. behind.sort_unstable();
  1176. for (r, col, cols) in behind {
  1177. let need = cols.div_ceil(2);
  1178. if let Some(p) = layout.iter_mut().find(|p| p.1 + need <= 4) {
  1179. p.2.push((p.1, r, col, cols));
  1180. p.1 += need;
  1181. }
  1182. }
  1183. layout.into_iter().map(|(a, _, of)| (a, of)).collect()
  1184. }
  1185. /// Where half `h` (dword h / 2, the high half when odd) of the parameter
  1186. /// whose first 16-bit row is `a` comes from: a register and column of
  1187. /// `elements`, none for padding ([`packed_layout`]; `packs` lists every
  1188. /// parameter packing two 16-bit rows per dword).
  1189. fn packed_half(
  1190. elements: &[SigElement],
  1191. packs: &[(u8, Option<u8>)],
  1192. a: u8,
  1193. h: u8,
  1194. ) -> Option<(u8, u8)> {
  1195. let layout = packed_layout(elements, packs);
  1196. let (_, of) = layout.iter().find(|p| p.0 == a)?;
  1197. of.iter().find_map(|&(dword, row, col, cols)| {
  1198. let k = h.checked_sub(2 * dword)?;
  1199. (k < cols).then_some((row, col + k))
  1200. })
  1201. }
  1202. /// The pixel inputs packing two 16-bit rows per dword, as (first row,
  1203. /// second row) ([`packed_layout`]).
  1204. fn input_packs(io: &StageIo, inputs: &[SigElement]) -> Vec<(u8, Option<u8>)> {
  1205. let StageIo::Ps {
  1206. inputs: entries, ..
  1207. } = io
  1208. else {
  1209. return Vec::new();
  1210. };
  1211. let partners = half_input_partners(io, inputs);
  1212. entries
  1213. .iter()
  1214. .filter(|i| i.fp16 && i.pack2)
  1215. .map(|i| {
  1216. let b = if i.row2 != i.row {
  1217. Some(i.row2)
  1218. } else {
  1219. partners.get(&i.row).copied()
  1220. };
  1221. (i.row, b)
  1222. })
  1223. .collect()
  1224. }
  1225. /// Vertex or mesh outputs of 16-bit values (see [`Lower::half_outputs`]):
  1226. /// a packed row's partner is the next 16-bit row of the signature that no
  1227. /// output entry names, taken in row order.
  1228. fn half_outputs(io: &StageIo, outputs: &[SigElement]) -> HashMap<u8, (bool, Option<u8>)> {
  1229. let entries = match io {
  1230. StageIo::Vs { outputs, .. } => outputs,
  1231. StageIo::Ms(ms) => &ms.outputs,
  1232. _ => return HashMap::new(),
  1233. };
  1234. let per_vertex = || entries.iter().filter(|o| o.param & 0x80 == 0);
  1235. let mut free: Vec<u8> = outputs
  1236. .iter()
  1237. .filter(|e| e.half && e.kind == 0)
  1238. .filter_map(|e| u8::try_from(e.row?).ok())
  1239. .filter(|&r| !per_vertex().any(|o| o.row == r))
  1240. .collect();
  1241. free.sort_unstable();
  1242. free.dedup();
  1243. let mut halves: Vec<_> = per_vertex().filter(|o| o.fp16).collect();
  1244. halves.sort_by_key(|o| o.row);
  1245. halves
  1246. .into_iter()
  1247. .map(|o| {
  1248. let b = o
  1249. .pack2
  1250. .then(|| free.iter().position(|&r| r > o.row))
  1251. .flatten();
  1252. (o.row, (o.pack2, b.map(|i| free.remove(i))))
  1253. })
  1254. .collect()
  1255. }
  1256. /// Pixel inputs packing two 16-bit rows per dword whose second row the
  1257. /// metadata leaves out (`row2` = `row`): as for outputs
  1258. /// ([`half_outputs`]), the next 16-bit row of the signature that no input
  1259. /// entry names, taken in row order (rows the metadata does give are taken
  1260. /// first).
  1261. fn half_input_partners(io: &StageIo, inputs: &[SigElement]) -> HashMap<u8, u8> {
  1262. let StageIo::Ps {
  1263. inputs: entries, ..
  1264. } = io
  1265. else {
  1266. return HashMap::new();
  1267. };
  1268. let packed = || entries.iter().filter(|i| i.fp16 && i.pack2);
  1269. let mut free: Vec<u8> = inputs
  1270. .iter()
  1271. .filter(|e| e.half && e.kind == 0)
  1272. .filter_map(|e| u8::try_from(e.row?).ok())
  1273. .filter(|&r| !entries.iter().any(|i| i.row == r))
  1274. .filter(|&r| !packed().any(|i| i.row2 != i.row && i.row2 == r))
  1275. .collect();
  1276. free.sort_unstable();
  1277. free.dedup();
  1278. let mut missing: Vec<_> = packed().filter(|i| i.row2 == i.row).collect();
  1279. missing.sort_by_key(|i| i.row);
  1280. let mut partners = HashMap::new();
  1281. for i in missing {
  1282. if let Some(k) = free.iter().position(|&r| r > i.row) {
  1283. partners.insert(i.row, free.remove(k));
  1284. }
  1285. }
  1286. partners
  1287. }
  1288. fn unsupported(offset: usize, what: Why) -> Stop {
  1289. Stop::Fail(ShaderError::Unsupported { offset, what })
  1290. }
  1291. impl<'a> Lower<'a> {
  1292. fn new(x: &'a Parts<'a>, bad: &'a HashMap<Value, Why>) -> Self {
  1293. let p = x.p;
  1294. let mut phi_at = HashMap::new();
  1295. for (b, block) in p.blocks.iter().enumerate() {
  1296. for (i, phi) in block.phis.iter().enumerate() {
  1297. phi_at.insert(phi.value, (b, i));
  1298. }
  1299. }
  1300. let mut s = Shader::new(x.native.stage == HwStage::Ps);
  1301. s.inputs = x.inputs.clone();
  1302. s.outputs = x.outputs.clone();
  1303. let insts = || p.blocks.iter().flat_map(|b| &b.insts);
  1304. let writes_uavs = insts().any(|i| {
  1305. matches!(i.fields, Fields::Image { .. } | Fields::Buffer { .. })
  1306. && (i.name().contains("store") || i.name().contains("atomic"))
  1307. });
  1308. let mut console_lanes = false;
  1309. // LDS accesses get a group barrier each (a console wave split in two host waves)
  1310. let mut split_lds = false;
  1311. // with `split_lds`, LDS accesses in lane branches: the blocks every lane runs, and
  1312. // where the host waves meet around those branches (`lds_meetings`)
  1313. let mut lds_meet: Option<(Vec<bool>, Vec<(bool, bool)>)> = None;
  1314. // a console wave64 program in two host waves of 32 (`exchange`)
  1315. let mut exchange: Option<(u32, bool, Vec<bool>)> = None;
  1316. // a console wave64 program in host waves of 32: the LDS dword of `wave_base`'s counter
  1317. let mut halves: Option<u32> = None;
  1318. if let StageIo::Cs(cs) = x.native.io {
  1319. s.threads = Some(cs.threads);
  1320. s.lds_dwords = cs.lds_bytes() / 4;
  1321. // Code reading other lanes needs the console's wave size and
  1322. // lane order; so do lane masks read as numbers, and LDS shared
  1323. // within one wave, where the console compiler leaves out barriers.
  1324. console_lanes = insts().any(|i| {
  1325. let n = i.name();
  1326. n.starts_with("ds_swizzle")
  1327. || n.contains("permute")
  1328. || n.starts_with("v_permlane")
  1329. || n.starts_with("v_mbcnt")
  1330. || matches!(n, "v_readlane_b32" | "v_writelane_b32")
  1331. || matches!(&i.fields, Fields::Valu(v) if v.dpp.is_some())
  1332. || reads_mask_as_data(x.st, i)
  1333. }) || lane_constant_masks(x.st)
  1334. // (a branch the wave takes together asks the wave)
  1335. || !x.st.wide.is_empty();
  1336. let mut wave = if x.native.wave64 { 64 } else { 32 };
  1337. let group = cs.threads.iter().product::<u32>();
  1338. let one_wave = group <= wave;
  1339. // A host whose waves are at most 32 lanes (NVIDIA) refuses `WaveSize(64)`. A console
  1340. // wave64 program whose cross-lane code stays inside 32-lane halves – DPP rows,
  1341. // `ds_swizzle`, `v_permlane16` / `v_permlanex16`, which the ISA confines there – runs
  1342. // exactly in waves of 32: the thread relabelling makes each host wave one half of a
  1343. // console wave (lanes 32k..32k+31). Not when it crosses halves (`v_mbcnt`,
  1344. // `v_readlane`, `v_writelane`, `ds_(b)permute`, masks as numbers or lane-constant
  1345. // masks), nor when LDS may be shared within the console wave without barriers (a
  1346. // group over 32 threads with LDS): those still need 64-lane waves.
  1347. if wave == 64 && host_max_wave() == 32 && (console_lanes || one_wave && s.lds_dwords > 0) {
  1348. let crosses = insts().any(|i| {
  1349. let n = i.name();
  1350. n.starts_with("v_mbcnt")
  1351. || matches!(n, "v_readlane_b32" | "v_writelane_b32")
  1352. || n.starts_with("ds_permute")
  1353. || n.starts_with("ds_bpermute")
  1354. || reads_mask_as_data(x.st, i)
  1355. }) || lane_constant_masks(x.st)
  1356. || !x.st.wide.is_empty();
  1357. if !crosses && (s.lds_dwords == 0 || group <= 32) {
  1358. wave = 32;
  1359. } else {
  1360. // (Groups of several console waves too: each console wave is two host
  1361. // waves, which exchange through their own pair of dwords.)
  1362. // LDS the console shares within its one wave without barriers: split into
  1363. // two waves of 32, a group barrier before every LDS access keeps their order
  1364. // – where every thread of the group gets there (no lane branch around it,
  1365. // no guard), else a barrier would hang the group
  1366. let lds = |i: &Inst| {
  1367. matches!(i.fields, Fields::Ds { .. })
  1368. && !(i.name().starts_with("ds_swizzle") || i.name().contains("permute"))
  1369. };
  1370. if let Some(all) = all_lane_blocks(x.st) {
  1371. let ok = p.blocks.iter().enumerate().all(|(b, blk)| {
  1372. blk.insts.iter().all(|inst| {
  1373. !lds(inst) || all.get(b).copied().unwrap_or(false)
  1374. })
  1375. });
  1376. let mut lds_ok = !(s.lds_dwords > 0 && group > 32) || ok;
  1377. if !lds_ok && let Some(meet) = lds_meetings(p, x.st, &all) {
  1378. lds_meet = Some((all.clone(), meet));
  1379. lds_ok = true;
  1380. }
  1381. if !lds_ok {
  1382. // (the blocks whose LDS accesses not every lane runs: with the
  1383. // branches around them taken wave-wide they get their barriers)
  1384. for (b, blk) in p.blocks.iter().enumerate() {
  1385. if !all.get(b).copied().unwrap_or(false) && blk.insts.iter().any(lds) {
  1386. need(b);
  1387. }
  1388. }
  1389. }
  1390. if lds_ok {
  1391. wave = 32;
  1392. split_lds = s.lds_dwords > 0 && group > 32;
  1393. if crosses {
  1394. // lanes 32..63 are the other host wave: masks, lane reads and lane
  1395. // numbers go through two exchange dwords past the program's LDS
  1396. exchange = Some((s.lds_dwords, group <= 32, all));
  1397. s.lds_dwords += 2 * group.div_ceil(64);
  1398. }
  1399. }
  1400. }
  1401. }
  1402. // `VICTORY_WAVE_WHY=1`: why a program keeps 64-lane waves (one line per reason)
  1403. if wave == 64 && std::env::var_os("VICTORY_WAVE_WHY").is_some() {
  1404. let mut why: Vec<&str> = Vec::new();
  1405. for i in insts() {
  1406. let n = i.name();
  1407. let r = if n.starts_with("v_mbcnt") {
  1408. "v_mbcnt"
  1409. } else if n == "v_readlane_b32" {
  1410. "v_readlane"
  1411. } else if n == "v_writelane_b32" {
  1412. "v_writelane"
  1413. } else if n.starts_with("ds_permute") || n.starts_with("ds_bpermute") {
  1414. "ds_(b)permute"
  1415. } else if reads_mask_as_data(x.st, i) {
  1416. "mask as data"
  1417. } else {
  1418. continue;
  1419. };
  1420. if !why.contains(&r) {
  1421. why.push(r);
  1422. }
  1423. }
  1424. if lane_constant_masks(x.st) {
  1425. why.push("lane-constant mask");
  1426. }
  1427. if s.lds_dwords > 0 && group > 32 {
  1428. why.push("LDS in a group over 32");
  1429. match all_lane_blocks(x.st) {
  1430. None => why.push("an indirect exit"),
  1431. Some(all) if lds_meetings(p, x.st, &all).is_none() => {
  1432. why.push("an LDS read and write in one lane-branch region")
  1433. }
  1434. Some(_) => {}
  1435. }
  1436. }
  1437. why.sort_unstable();
  1438. eprintln!("WAVE64-WHY group={group} lds={} [{}]", s.lds_dwords > 0, why.join(", "));
  1439. }
  1440. }
  1441. if wave == 32 && x.native.wave64 {
  1442. // console threads go to host waves in the order the waves take them (`wave_base`)
  1443. halves = Some(s.lds_dwords);
  1444. s.lds_dwords += 1;
  1445. }
  1446. if console_lanes || one_wave && s.lds_dwords > 0 {
  1447. s.wave_size = Some(wave);
  1448. }
  1449. }
  1450. // The title's barriers a thread of the group may never reach, which
  1451. // leaves the others waiting on the host: those in blocks some lanes
  1452. // do not run, and all of them in a program with a loop closed by a
  1453. // plain jump (a lane still in it at the iteration limit leaves the
  1454. // program there, `abort_block`).
  1455. let fence_only: HashSet<usize> = if insts().any(|i| i.name() == "s_barrier") {
  1456. let order = crate::ir::reverse_postorder(&p.blocks);
  1457. let mut place = vec![usize::MAX; p.blocks.len()];
  1458. for (n, &b) in order.iter().enumerate() {
  1459. place[b] = n;
  1460. }
  1461. let back = |from: usize, to: usize| {
  1462. let at = |b: usize| place.get(b).copied().unwrap_or(usize::MAX);
  1463. at(from) != usize::MAX && at(to) <= at(from)
  1464. };
  1465. let cut_short = x
  1466. .st
  1467. .exits
  1468. .iter()
  1469. .enumerate()
  1470. .any(|(b, e)| matches!(*e, LaneExit::Jump(t) if back(b, t)));
  1471. let all = all_lane_blocks(x.st);
  1472. (0..p.blocks.len())
  1473. .filter(|&b| p.blocks[b].insts.iter().any(|i| i.name() == "s_barrier"))
  1474. .filter(|&b| {
  1475. cut_short
  1476. || all
  1477. .as_ref()
  1478. .is_none_or(|all| !all.get(b).copied().unwrap_or(false))
  1479. })
  1480. .collect()
  1481. } else {
  1482. HashSet::new()
  1483. };
  1484. let mut no_barrier = HashSet::new();
  1485. if let StageIo::Ms(ms) = &x.native.io {
  1486. s.prims = x.prims.clone();
  1487. s.threads = Some([ms.threads, 1, 1]);
  1488. s.lds_dwords = ms.lds_bytes.div_ceil(4);
  1489. s.mesh = Some(super::shader::Mesh {
  1490. max_vertices: ms.max_vertices,
  1491. max_primitives: ms.max_primitives,
  1492. topology: ms.topology,
  1493. });
  1494. // Barriers order the lanes' LDS accesses; the console's
  1495. // allocation request needs them too, but the host does not. One
  1496. // lane sends that request, and what it dominates (the path for
  1497. // counts out of range) runs in that lane alone, so its barrier
  1498. // would hang the host.
  1499. let order = crate::ir::reverse_postorder(&p.blocks);
  1500. let mut index = vec![usize::MAX; p.blocks.len()];
  1501. for (n, &b) in order.iter().enumerate() {
  1502. index[b] = n;
  1503. }
  1504. let idom = crate::ir::idoms(&p.blocks, &order, &index);
  1505. let alloc: Vec<usize> = (0..p.blocks.len())
  1506. .filter(|&b| {
  1507. p.blocks[b].insts.iter().any(|i| {
  1508. i.name() == "s_sendmsg"
  1509. && matches!(i.fields, Fields::Sopp { imm } if imm & 0xF == GS_ALLOC_REQ)
  1510. })
  1511. })
  1512. .collect();
  1513. for &b in &order {
  1514. let mut d = b;
  1515. let dominated = loop {
  1516. if alloc.contains(&d) {
  1517. break true;
  1518. }
  1519. if idom[d] == d || idom[d] == usize::MAX {
  1520. break false;
  1521. }
  1522. d = idom[d];
  1523. };
  1524. if ms.lds_bytes == 0 || dominated {
  1525. no_barrier.insert(b);
  1526. }
  1527. }
  1528. }
  1529. Lower {
  1530. s,
  1531. x,
  1532. bad,
  1533. lane_fail: HashMap::new(),
  1534. vals: HashMap::new(),
  1535. floats: HashMap::new(),
  1536. block: vec![None; p.blocks.len()],
  1537. cur: 0,
  1538. bools: HashMap::new(),
  1539. lane_bits: HashMap::new(),
  1540. phi_at,
  1541. mask_phis: HashMap::new(),
  1542. pending_masks: Vec::new(),
  1543. data_phis: Vec::new(),
  1544. read_phis: HashSet::new(),
  1545. stale: HashSet::new(),
  1546. coherent: HashSet::new(),
  1547. root_copy: None,
  1548. page_there: None,
  1549. ordered: if x.native.stage == HwStage::Ps {
  1550. ordered_section(p)
  1551. } else {
  1552. HashSet::new()
  1553. },
  1554. params: x.res.params.iter().map(|&(v, p, d)| (v, (p, d))).collect(),
  1555. user_data: None,
  1556. user_reads: BTreeMap::new(),
  1557. samplers: Vec::new(),
  1558. descriptors: x
  1559. .res
  1560. .descriptors
  1561. .iter()
  1562. .map(|d| ((d.site, d.role == Role::Sampler), &d.source))
  1563. .collect(),
  1564. scalar: x.res.scalar.iter().copied().collect(),
  1565. exports: x.io.exports.iter().map(|e| (e.site, e)).collect(),
  1566. interps: {
  1567. let mut m: HashMap<Site, &Interp> = x.io.interps.iter().map(|(s, i)| (*s, i)).collect();
  1568. // A first half whose result is also read as data (an f16 second half keeps
  1569. // the other half of its dst, PS_DeferredTextured): evaluated as the pair it
  1570. // starts. Approximate for those other bits (P0 + i P10 on the console); a
  1571. // first half only the second half reads is gone before lowering.
  1572. // Only in the second translation of a program the first
  1573. // one refused for it ([`with_first_half_pairs`]).
  1574. if FIRST_HALF_PAIRS.get() && std::env::var_os("VICTORY_FIRST_HALF").is_none_or(|v| v != "0") {
  1575. for (_, i) in &x.io.interps {
  1576. if let Interp::Interpolated { first, .. } = i {
  1577. for s in first {
  1578. m.entry(*s).or_insert(i);
  1579. }
  1580. }
  1581. }
  1582. }
  1583. m
  1584. },
  1585. handles: HashMap::new(),
  1586. strides: HashMap::new(),
  1587. edges: HashMap::new(),
  1588. exported: vec![false; p.blocks.len()],
  1589. rpo: vec![usize::MAX; p.blocks.len()],
  1590. tail: vec![None; p.blocks.len()],
  1591. writes_uavs,
  1592. src0: None,
  1593. console_lanes,
  1594. split_lds,
  1595. lds_meet,
  1596. local: exchange.is_some() && LOCAL_WAVES.get(),
  1597. local_ok: false,
  1598. local_any: LOCAL_ANY.get(),
  1599. uniform: match &exchange {
  1600. Some((_, false, all)) if !LOCAL_WAVES.get() => lane_uniform(p, x.st, all),
  1601. _ => HashSet::new(),
  1602. },
  1603. own_bits: match &exchange {
  1604. Some((_, false, _)) if !LOCAL_WAVES.get() && own_bits_on() => {
  1605. super::own_bits::find(p, x.st, std::env::var_os("VICTORY_WAVE_WHY").is_some())
  1606. }
  1607. _ => Default::default(),
  1608. },
  1609. exchange,
  1610. clane: None,
  1611. pair: None,
  1612. halves,
  1613. wave_base: None,
  1614. flat: None,
  1615. no_barrier,
  1616. fence_only,
  1617. half_outputs: half_outputs(&x.native.io, &x.outputs),
  1618. mask_data: match x.native.stage {
  1619. HwStage::Cs => MaskData::Console,
  1620. HwStage::Ps | HwStage::Vs => MaskData::Host,
  1621. _ => MaskData::None,
  1622. },
  1623. mask_ok: false,
  1624. ballots: HashMap::new(),
  1625. balloting: HashSet::new(),
  1626. def_block: p
  1627. .blocks
  1628. .iter()
  1629. .enumerate()
  1630. .flat_map(|(b, block)| {
  1631. block
  1632. .insts
  1633. .iter()
  1634. .flat_map(move |i| i.writes.iter().map(move |w| (w.1, b)))
  1635. .chain(block.phis.iter().map(move |phi| (phi.value, b)))
  1636. })
  1637. .collect(),
  1638. cur_ir: 0,
  1639. sections: HashMap::new(),
  1640. section_out: HashSet::new(),
  1641. code_table: None,
  1642. counters: HashMap::new(),
  1643. abort: None,
  1644. }
  1645. }
  1646. /// The dword of the program's code at byte `byte` (a constant table
  1647. /// the compiler appends to the code), as an internal constant array.
  1648. // shortcut: an index outside the table reads its last dword (the
  1649. // console would read whatever memory follows the code).
  1650. fn code_dword(&mut self, byte: V) -> Result<V, Why> {
  1651. let (g, base, len) = match self.code_table {
  1652. Some(t) => t,
  1653. None => {
  1654. let first = self
  1655. .x
  1656. .res
  1657. .scalar
  1658. .iter()
  1659. .map(|s| s.1)
  1660. .chain(self.x.res.descriptors.iter().flat_map(|d| {
  1661. d.source.leaves().into_iter().filter_map(|l| match l {
  1662. Source::Built { address, .. } => Some(*address),
  1663. _ => None,
  1664. })
  1665. }))
  1666. .filter(|a| a.param == CODE)
  1667. .map(|a| a.offset & !3)
  1668. .min()
  1669. .ok_or("a code table")?;
  1670. let code = &self.x.native.code;
  1671. let words: Vec<u32> = code
  1672. .get(first as usize..)
  1673. .ok_or("a code table past the code")?
  1674. .chunks(4)
  1675. .map(|c| {
  1676. let mut w = [0u8; 4];
  1677. w[..c.len()].copy_from_slice(c);
  1678. u32::from_le_bytes(w)
  1679. })
  1680. .collect();
  1681. if words.is_empty() {
  1682. return Err("a code table past the code");
  1683. }
  1684. let elems: Vec<V> = words.iter().map(|&w| self.s.m.i32(w)).collect();
  1685. let arr = self.s.m.array(words.len() as u32, self.s.t.i32);
  1686. let init = self.s.m.aggregate(arr, &elems);
  1687. let g = self.s.m.constant_global("code", init);
  1688. let t = (g, first, words.len() as u32);
  1689. self.code_table = Some(t);
  1690. t
  1691. }
  1692. };
  1693. let c = self.cur;
  1694. let k = self.s.m.i32(base);
  1695. let rel = self.s.m.bin(c, Bin::Sub, byte, k);
  1696. let two = self.s.m.i32(2);
  1697. let index = self.s.m.bin(c, Bin::LShr, rel, two);
  1698. let last = self.s.m.i32(len - 1);
  1699. let over = self.s.m.cmp(c, pred::IUGT, index, last);
  1700. let index = self.s.m.select(c, over, last, index);
  1701. let at = self.s.m.element(c, g, index);
  1702. Ok(self.s.m.load(c, at))
  1703. }
  1704. /// A global memory load (`global_load_*`): from the program's constant
  1705. /// table, or from a root SRV at the address the title sets.
  1706. fn flat(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  1707. let Fields::Flat { dst, .. } = &inst.fields else {
  1708. unreachable!()
  1709. };
  1710. self.root_copy = None;
  1711. let name = inst.name();
  1712. if self.scalar.get(&(b, i)).is_some_and(|a| a.param == MEMORY) {
  1713. return self.memory_flat(inst, b, i);
  1714. }
  1715. let rest = name
  1716. .strip_prefix("global_load_")
  1717. .ok_or("a global memory write")?;
  1718. let (n, sub) = match rest {
  1719. "dword" => (1, None),
  1720. "dwordx2" => (2, None),
  1721. "dwordx3" => (3, None),
  1722. "dwordx4" => (4, None),
  1723. "ubyte" => (1, Some((8, false))),
  1724. "sbyte" => (1, Some((8, true))),
  1725. "ushort" => (1, Some((16, false))),
  1726. "sshort" => (1, Some((16, true))),
  1727. _ => return Err(name),
  1728. };
  1729. let a = *self
  1730. .scalar
  1731. .get(&(b, i))
  1732. .ok_or("an untracked global address")?;
  1733. let guard = self.guard(b, i)?;
  1734. let Some(Operand::Vector { reg, .. }) = *dst else {
  1735. return Err("a global load result");
  1736. };
  1737. let c = self.cur;
  1738. let mut off = self.s.m.i32(a.offset);
  1739. if let Some(d) = a.dynamic {
  1740. let d = self.i32_of(d)?;
  1741. off = self.s.m.bin(c, Bin::Add, off, d);
  1742. }
  1743. let h = if a.param == CODE {
  1744. None
  1745. } else {
  1746. let src = Source::Built {
  1747. address: a,
  1748. bits: 0,
  1749. words: [0, 0],
  1750. };
  1751. if let Some(bias) = self.root_bias(a.param) {
  1752. off = self.s.m.bin(c, Bin::Add, off, bias);
  1753. }
  1754. match self.root_memory(&src, off, guard, false) {
  1755. Some((h, byte)) => {
  1756. off = byte;
  1757. Some(h)
  1758. }
  1759. None => Some(self.handle((b, i), &src, false, (11, 0))?),
  1760. }
  1761. };
  1762. let c = self.cur;
  1763. let dword = |l: &mut Self, byte: V| -> Result<V, Why> {
  1764. match h {
  1765. None => l.code_dword(byte),
  1766. Some(h) => {
  1767. let c = l.cur;
  1768. let (u, mask, al) = (l.s.m.undef(l.s.t.i32), l.s.m.i8(1), l.s.m.i32(4));
  1769. let r = l.s.op(
  1770. c,
  1771. "rawBufferLoad.f32",
  1772. Attr::ReadOnly,
  1773. l.s.t.res_ret,
  1774. 139,
  1775. &[h, byte, u, mask, al],
  1776. );
  1777. let x = l.s.m.extract(c, r, 0);
  1778. Ok(l.as_int(x))
  1779. }
  1780. }
  1781. };
  1782. for k in 0..n {
  1783. let x = match sub {
  1784. None => {
  1785. let four = self.s.m.i32(4 * k);
  1786. let at = self.s.m.bin(c, Bin::Add, off, four);
  1787. dword(self, at)?
  1788. }
  1789. Some((width, signed)) => {
  1790. // shortcut: the field is taken not to cross a dword.
  1791. let (not3, three) = (self.s.m.i32(!3), self.s.m.i32(3));
  1792. let at = self.s.m.bin(c, Bin::And, off, not3);
  1793. let w = dword(self, at)?;
  1794. let byte = self.s.m.bin(c, Bin::And, off, three);
  1795. let sh = self.s.m.bin(c, Bin::Shl, byte, three);
  1796. let x = self.s.m.bin(c, Bin::LShr, w, sh);
  1797. let left = self.s.m.i32(32 - width);
  1798. let x = self.s.m.bin(c, Bin::Shl, x, left);
  1799. self.s
  1800. .m
  1801. .bin(c, if signed { Bin::AShr } else { Bin::LShr }, x, left)
  1802. }
  1803. };
  1804. self.write(inst, Reg::V(reg + k as u8), x, guard);
  1805. }
  1806. Ok(())
  1807. }
  1808. /// Finds the whole-wave sections and the values they leave.
  1809. fn find_sections(&mut self) {
  1810. let p = self.x.p;
  1811. let mut inside: HashMap<Value, (usize, usize, usize)> = HashMap::new();
  1812. for b in 0..p.blocks.len() {
  1813. let found = super::wave::sections(p, b);
  1814. for (&start, sec) in &found {
  1815. for i in start + 1..sec.end {
  1816. for &(_, w) in &p.blocks[b].insts[i].writes {
  1817. inside.insert(w, (b, start, sec.end));
  1818. }
  1819. }
  1820. }
  1821. if !found.is_empty() {
  1822. self.sections.insert(b, found);
  1823. }
  1824. }
  1825. if inside.is_empty() {
  1826. return;
  1827. }
  1828. for (b, block) in p.blocks.iter().enumerate() {
  1829. for phi in &block.phis {
  1830. self.section_out
  1831. .extend(phi.args.iter().filter(|a| inside.contains_key(a)));
  1832. }
  1833. for (i, inst) in block.insts.iter().enumerate() {
  1834. for &(_, r) in &inst.reads {
  1835. if let Some(&(sb, start, end)) = inside.get(&r)
  1836. && !(sb == b && i > start && i < end)
  1837. {
  1838. self.section_out.insert(r);
  1839. }
  1840. }
  1841. }
  1842. }
  1843. }
  1844. /// An instruction inside a whole-wave section: the values that leave
  1845. /// the section are made from what the simulation found them to be.
  1846. fn section_inst(&mut self, b: usize, i: usize, start: usize) {
  1847. const UNKNOWN: Why = "a whole-wave section step the simulation does not follow";
  1848. let inst = &self.x.p.blocks[b].insts[i];
  1849. for &(_, w) in &inst.writes {
  1850. let val = if self.section_out.contains(&w) {
  1851. let shape = self.sections[&b][&start].shapes.get(&w).copied();
  1852. let own = self.own_bits.totals.contains(&w);
  1853. match shape.ok_or(UNKNOWN).and_then(|sh| self.shape(sh, own)) {
  1854. Ok(x) => Val::I32(x),
  1855. Err(why) => Val::Missing(why),
  1856. }
  1857. } else {
  1858. Val::Missing(UNKNOWN)
  1859. };
  1860. self.vals.insert(w, val);
  1861. }
  1862. }
  1863. /// A value a whole-wave section leaves, as DXIL wave operations over the
  1864. /// host's active lanes: the console's result with console lanes; on
  1865. /// another wave size, what the HLSL wave operation the console compiler
  1866. /// expanded gives on that wave.
  1867. ///
  1868. /// `own`: a wave OR that only steers a loop over each lane's own bits
  1869. /// ([`super::own_bits`]); where two host waves cannot exchange their halves' ORs it is
  1870. /// this host wave's.
  1871. fn shape(&mut self, shape: super::wave::Shape, own: bool) -> Result<V, Why> {
  1872. use super::wave::{Op, Shape};
  1873. let (op, src, mask, ident, prefix) = match shape {
  1874. Shape::K(k) => return Ok(self.s.m.i32(k)),
  1875. Shape::Value(v) => return self.i32_of(v),
  1876. Shape::Active(op, src, mask, ident) => (op, src, mask, ident, None),
  1877. Shape::ActiveF64(lo, hi, mask, high) => {
  1878. return self.active_f64_sum(lo, hi, mask, high);
  1879. }
  1880. Shape::Masked(src, mask, ident) => {
  1881. let c = self.cur;
  1882. let &m = self
  1883. .x
  1884. .st
  1885. .masks
  1886. .get(&mask)
  1887. .ok_or("a wave reduction's untracked mask")?;
  1888. let on = self.boolean(m, c)?;
  1889. let x = self.i32_of(src)?;
  1890. let id = self.s.m.i32(ident);
  1891. return Ok(self.s.m.select(c, on, x, id));
  1892. }
  1893. Shape::Prefix(op, src, mask, ident, inclusive) => {
  1894. (op, src, mask, ident, Some(inclusive))
  1895. }
  1896. };
  1897. // Mesh: no host wave size can be declared, so a reduction is over this host wave
  1898. // only. A minimum or maximum is taken that way: the compiler's "next distinct
  1899. // value" loop (the wave's minimum, then the lanes that hold it) serves every
  1900. // lane however the lanes are divided into waves. A sum, a bit reduction or a
  1901. // prefix would be of part of a console wave: still refused.
  1902. if self.mask_data == MaskData::None
  1903. && (prefix.is_some()
  1904. || !matches!(
  1905. op,
  1906. Op::MinU | Op::MaxU | Op::MinI | Op::MaxI | Op::MinF | Op::MaxF
  1907. ))
  1908. {
  1909. return Err("a wave reduction in a mesh shader");
  1910. }
  1911. let c = self.cur;
  1912. let &m = self
  1913. .x
  1914. .st
  1915. .masks
  1916. .get(&mask)
  1917. .ok_or("a wave reduction's untracked mask")?;
  1918. let on = self.boolean(m, c)?;
  1919. let x = self.i32_of(src)?;
  1920. let id = self.s.m.i32(ident);
  1921. let x = self.s.m.select(c, on, x, id);
  1922. self.s.flags |= flags::WAVE_OPS;
  1923. if op == Op::AddH {
  1924. return match prefix {
  1925. Some(_) => Err("a wave prefix of an operation other than a sum"),
  1926. None => self.half_sum(x),
  1927. };
  1928. }
  1929. let float = matches!(op, Op::AddF | Op::MinF | Op::MaxF);
  1930. let (i32t, f32t) = (self.s.t.i32, self.s.t.f32);
  1931. let arg = if float { self.as_float(x) } else { x };
  1932. let ty = if float { f32t } else { i32t };
  1933. let sfx = if float { "f32" } else { "i32" };
  1934. let r = match (op, prefix) {
  1935. (Op::AddU | Op::AddF, Some(inclusive)) => {
  1936. let (k0, k1) = (self.s.m.i8(0), self.s.m.i8(1));
  1937. let r = self.s.op(
  1938. c,
  1939. &format!("wavePrefixOp.{sfx}"),
  1940. Attr::NoUnwind,
  1941. ty,
  1942. 121,
  1943. &[arg, k0, k1],
  1944. );
  1945. if inclusive {
  1946. self.s.m.bin(c, Bin::Add, r, arg)
  1947. } else {
  1948. r
  1949. }
  1950. }
  1951. (_, Some(_)) => return Err("a wave prefix of an operation other than a sum"),
  1952. (Op::Or | Op::And | Op::Xor, None) => {
  1953. let k = self.s.m.i8(match op {
  1954. Op::And => 0,
  1955. Op::Or => 1,
  1956. _ => 2,
  1957. });
  1958. self.s
  1959. .op(c, "waveActiveBit.i32", Attr::NoUnwind, i32t, 120, &[arg, k])
  1960. }
  1961. (_, None) => {
  1962. let (code, unsigned) = match op {
  1963. Op::AddU => (0, 1),
  1964. Op::AddF => (0, 0),
  1965. Op::MinU => (2, 1),
  1966. Op::MaxU => (3, 1),
  1967. Op::MinI | Op::MinF => (2, 0),
  1968. _ => (3, 0),
  1969. };
  1970. let (k, u) = (self.s.m.i8(code), self.s.m.i8(unsigned));
  1971. self.s.op(
  1972. c,
  1973. &format!("waveActiveOp.{sfx}"),
  1974. Attr::NoUnwind,
  1975. ty,
  1976. 119,
  1977. &[arg, k, u],
  1978. )
  1979. }
  1980. };
  1981. // two host waves of 32 hold the console's 64 lanes: their results combine
  1982. let r = if self.local || self.exchange.as_ref().is_some_and(|e| e.1) {
  1983. // this host wave's own result (and prefix): each wave on its own, or a group of
  1984. // 32 threads or fewer, which one host wave holds whole (combining with the 0 a
  1985. // missing half "gives" broke AND, MIN and signed MAX)
  1986. r
  1987. } else if own && prefix.is_none() && op == Op::Or && !self.all_lanes(self.cur_ir) {
  1988. // each thread walks the bits of this value and works only at its own, which the
  1989. // host wave's OR holds: the same run as with the console wave's OR
  1990. r
  1991. } else if self.exchange.is_some() {
  1992. if !self.all_lanes(self.cur_ir) {
  1993. need(self.cur_ir);
  1994. return Err("a wave reduction where not every lane runs");
  1995. }
  1996. let bits = |l: &mut Self, v: V| if float { l.as_int(v) } else { v };
  1997. let back = |l: &mut Self, v: V| if float { l.as_float(v) } else { v };
  1998. match prefix {
  1999. Some(_) => {
  2000. // the upper half adds the lower half's total to its prefix
  2001. let (k0, ku) = (self.s.m.i8(0), self.s.m.i8(u8::from(!float)));
  2002. let total = self.s.op(c, &format!("waveActiveOp.{sfx}"), Attr::NoUnwind, ty, 119, &[arg, k0, ku]);
  2003. let tb = bits(self, total);
  2004. let c = self.cur;
  2005. let (lo, _) = self.exchange_halves(c, tb);
  2006. let lo = back(self, lo);
  2007. let cl = self.console_lane();
  2008. let k32 = self.s.m.i32(32);
  2009. let upper = self.s.m.cmp(c, pred::IUGE, cl, k32);
  2010. let zero = if float { self.s.m.f32(0) } else { self.s.m.i32(0) };
  2011. let add = self.s.m.select(c, upper, lo, zero);
  2012. self.s.m.bin(c, Bin::Add, r, add)
  2013. }
  2014. None => {
  2015. let rb = bits(self, r);
  2016. let c = self.cur;
  2017. let (lo, hi) = self.exchange_halves(c, rb);
  2018. let (lo, hi) = (back(self, lo), back(self, hi));
  2019. match op {
  2020. Op::AddU | Op::AddF => self.s.m.bin(c, Bin::Add, lo, hi),
  2021. Op::Or => self.s.m.bin(c, Bin::Or, lo, hi),
  2022. Op::And => self.s.m.bin(c, Bin::And, lo, hi),
  2023. Op::Xor => self.s.m.bin(c, Bin::Xor, lo, hi),
  2024. _ => {
  2025. // FMax 35, FMin 36, IMax 37, IMin 38, UMax 39, UMin 40
  2026. let code = match op {
  2027. Op::MaxF => 35,
  2028. Op::MinF => 36,
  2029. Op::MinU => 40,
  2030. Op::MaxU => 39,
  2031. Op::MinI => 38,
  2032. _ => 37,
  2033. };
  2034. self.s.op(c, &format!("binary.{sfx}"), Attr::ReadNone, ty, code, &[lo, hi])
  2035. }
  2036. }
  2037. }
  2038. }
  2039. } else {
  2040. r
  2041. };
  2042. Ok(if float { self.as_int(r) } else { r })
  2043. }
  2044. /// `WaveActiveSum` of 64-bit floats (`f64(lo, hi)` in active lanes, `+0.0` elsewhere),
  2045. /// returning the low (`!high`) or high (`high`) 32-bit word.
  2046. fn active_f64_sum(
  2047. &mut self,
  2048. lo: Value,
  2049. hi: Value,
  2050. mask: Value,
  2051. high: bool,
  2052. ) -> Result<V, Why> {
  2053. if self.mask_data == MaskData::None {
  2054. return Err("a wave reduction in a mesh shader");
  2055. }
  2056. let c = self.cur;
  2057. let &m = self
  2058. .x
  2059. .st
  2060. .masks
  2061. .get(&mask)
  2062. .ok_or("a wave reduction's untracked mask")?;
  2063. let on = self.boolean(m, c)?;
  2064. let lo = self.i32_of(lo)?;
  2065. let hi = self.i32_of(hi)?;
  2066. let z = self.s.m.i32(0);
  2067. let lo = self.s.m.select(c, on, lo, z);
  2068. let hi = self.s.m.select(c, on, hi, z);
  2069. self.s.flags |= flags::WAVE_OPS | flags::DOUBLES;
  2070. let f64t = self.s.m.double();
  2071. let i32t = self.s.t.i32;
  2072. let split_ty = self
  2073. .s
  2074. .m
  2075. .named_struct("dx.types.splitdouble", vec![i32t, i32t]);
  2076. let arg = self
  2077. .s
  2078. .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo, hi]);
  2079. let (k0, k0b) = (self.s.m.i8(0), self.s.m.i8(0));
  2080. let sum = self
  2081. .s
  2082. .op(c, "waveActiveOp.f64", Attr::NoUnwind, f64t, 119, &[arg, k0, k0b]);
  2083. let split = self
  2084. .s
  2085. .op(c, "splitDouble.f64", Attr::ReadNone, split_ty, 102, &[sum]);
  2086. let mut r_lo = self.s.m.extract(c, split, 0);
  2087. let mut r_hi = self.s.m.extract(c, split, 1);
  2088. if self.exchange.is_some() {
  2089. if !self.all_lanes(self.cur_ir) {
  2090. need(self.cur_ir);
  2091. return Err("a wave reduction where not every lane runs");
  2092. }
  2093. let (lo0, lo1) = self.exchange_halves(self.cur, r_lo);
  2094. let (hi0, hi1) = self.exchange_halves(self.cur, r_hi);
  2095. let c = self.cur;
  2096. let d0 = self
  2097. .s
  2098. .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo0, hi0]);
  2099. let d1 = self
  2100. .s
  2101. .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo1, hi1]);
  2102. let total = self.s.m.bin(c, Bin::Add, d0, d1);
  2103. let split = self
  2104. .s
  2105. .op(c, "splitDouble.f64", Attr::ReadNone, split_ty, 102, &[total]);
  2106. r_lo = self.s.m.extract(c, split, 0);
  2107. r_hi = self.s.m.extract(c, split, 1);
  2108. }
  2109. Ok(if high { r_hi } else { r_lo })
  2110. }
  2111. /// The sum of two 16-bit floats (the low halves of `a` and `b`) as the console's
  2112. /// `v_add_f16` gives it: added in f32 and rounded to 16 bits, to nearest
  2113. /// ([`Self::f16_nearest`]).
  2114. fn add_halves(&mut self, a: V, b: V) -> V {
  2115. let c = self.cur;
  2116. let f32t = self.s.t.f32;
  2117. let low = self.s.m.i32(0xFFFF);
  2118. let wide = |l: &mut Self, x: V| {
  2119. let h = l.s.m.bin(c, Bin::And, x, low);
  2120. l.s.op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h])
  2121. };
  2122. let (fa, fb) = (wide(self, a), wide(self, b));
  2123. let f = self.s.m.bin(c, Bin::Add, fa, fb);
  2124. self.f16_nearest(f)
  2125. }
  2126. /// `WaveActiveSum` of 16-bit floats (`x`: each lane's term in its low half, +0 in the
  2127. /// lanes outside the mask), bit for bit as the console adds it: every addition rounds to
  2128. /// 16 bits, so the order counts, and the compiler's is the balanced tree over the lanes
  2129. /// in their order (lanes 2k and 2k+1, then pairs, ... then the wave's two halves;
  2130. /// [`super::wave::buddies`]). Each lane adds its partner's partial sum, read from the
  2131. /// lane whose number differs in one bit, step by step; two host waves of 32 then exchange
  2132. /// their halves' sums for the last addition. The high half of the result is lane 0's,
  2133. /// which no `v_add_f16` writes.
  2134. /// On a host wave of 64 lanes where not every lane runs, the lanes that are elsewhere
  2135. /// count as the console's do (it masks them to +0): a partner's partial sum is read from
  2136. /// the first lane there is of the partner's run of lanes, and is +0 without one. Two host
  2137. /// waves of 32 can only exchange where every lane runs: refused elsewhere, in a thread
  2138. /// group that does not fill its waves, and for each half-wave on its own (half a sum is
  2139. /// no sum).
  2140. fn half_sum(&mut self, x: V) -> Result<V, Why> {
  2141. const WHERE: Why = "a wave sum of 16-bit floats where not every lane runs";
  2142. let threads = self.s.threads.ok_or("a wave sum of 16-bit floats outside compute")?;
  2143. if threads.iter().product::<u32>() % 64 != 0 {
  2144. return Err("a wave sum of 16-bit floats in a wave that is not full");
  2145. }
  2146. if self.local {
  2147. return Err("a wave sum of 16-bit floats in a half-wave");
  2148. }
  2149. // two host waves of 32 that exchange, or one host wave of 64 lanes
  2150. let halves = match (&self.exchange, self.s.wave_size) {
  2151. (Some((_, false, _)), _) => true,
  2152. (None, Some(64)) if self.x.p.wave64 => false,
  2153. _ => return Err("a wave sum of 16-bit floats on these waves"),
  2154. };
  2155. let every = if halves {
  2156. self.all_lanes(self.cur_ir)
  2157. } else {
  2158. all_lane_blocks(self.x.st).is_some_and(|all| all.get(self.cur_ir).copied().unwrap_or(false))
  2159. };
  2160. if !every && halves {
  2161. need(self.cur_ir);
  2162. return Err(WHERE);
  2163. }
  2164. let c = self.cur;
  2165. let i32t = self.s.t.i32;
  2166. let lane = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
  2167. let (high, low, zero) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF), self.s.m.i32(0));
  2168. // the lanes that are here, when not all are
  2169. let here = (!every).then(|| {
  2170. self.s.flags |= flags::WAVE_OPS;
  2171. let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]);
  2172. let yes = self.s.m.bool(true);
  2173. let r = self.s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[yes]);
  2174. (self.s.m.extract(c, r, 0), self.s.m.extract(c, r, 1))
  2175. });
  2176. // `v` of the first lane here of the `n` (a power of two) lanes from `base`: +0 of none
  2177. let first_of = |l: &mut Self, v: V, base: V, n: u32| {
  2178. let Some((lo, hi)) = here else {
  2179. return l.read_lane(v, base);
  2180. };
  2181. let (k31, k32) = (l.s.m.i32(31), l.s.m.i32(32));
  2182. let lower = l.s.m.cmp(c, pred::IULT, base, k32);
  2183. let word = l.s.m.select(c, lower, lo, hi);
  2184. let shift = l.s.m.bin(c, Bin::And, base, k31);
  2185. let word = l.s.m.bin(c, Bin::LShr, word, shift);
  2186. let run = l.s.m.i32(u32::MAX >> (32 - n));
  2187. let word = l.s.m.bin(c, Bin::And, word, run);
  2188. let any = l.s.m.cmp(c, pred::NE, word, zero);
  2189. let nth = l.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[word]);
  2190. let from = l.s.m.bin(c, Bin::Add, base, nth);
  2191. // (no lane there: this one, which is here; the read is not used)
  2192. let from = l.s.m.select(c, any, from, lane);
  2193. let got = l.read_lane(v, from);
  2194. l.s.m.select(c, any, got, zero)
  2195. };
  2196. let mut sum = x;
  2197. for step in 0..if halves { 5 } else { 6 } {
  2198. let bit = self.s.m.i32(1 << step);
  2199. let mut partner = self.s.m.bin(c, Bin::Xor, lane, bit);
  2200. if !every {
  2201. let run = self.s.m.i32(!((1 << step) - 1));
  2202. partner = self.s.m.bin(c, Bin::And, partner, run);
  2203. }
  2204. let theirs = first_of(self, sum, partner, 1 << step);
  2205. sum = self.add_halves(sum, theirs);
  2206. }
  2207. let first = first_of(self, x, zero, 1);
  2208. let first = self.s.m.bin(c, Bin::And, first, high);
  2209. let sum = self.s.m.bin(c, Bin::And, sum, low);
  2210. let mine = self.s.m.bin(c, Bin::Or, first, sum);
  2211. if !halves {
  2212. return Ok(mine);
  2213. }
  2214. let (lo, hi) = self.exchange_halves(c, mine);
  2215. let c = self.cur;
  2216. let total = self.add_halves(lo, hi);
  2217. let total = self.s.m.bin(c, Bin::And, total, low);
  2218. let first = self.s.m.bin(c, Bin::And, lo, high);
  2219. Ok(self.s.m.bin(c, Bin::Or, first, total))
  2220. }
  2221. fn run(mut self, counted: bool) -> Result<Lowered, Stop> {
  2222. let p = self.x.p;
  2223. if counted {
  2224. // Before anything else, so that wave counts, reads of the first
  2225. // lane and stores know only the lanes that run.
  2226. let original = self.s.entry;
  2227. let width = self.s.threads.expect("compute thread count")[0];
  2228. let limit = self.host_word(RootType::Other(super::shader::USER_DISPATCH_THREADS_X), 0, width);
  2229. let Val::I32(group) = self.compute_id("groupId.i32", 94, 0) else {
  2230. unreachable!()
  2231. };
  2232. let Val::I32(thread) = self.thread_id(0) else {
  2233. unreachable!()
  2234. };
  2235. let width = self.s.m.i32(width);
  2236. let first = self.s.m.bin(original, Bin::Mul, group, width);
  2237. let x = self.s.m.bin(original, Bin::Add, first, thread);
  2238. let zero = self.s.m.i32(0);
  2239. let all = self.s.m.cmp(original, pred::EQ, limit, zero);
  2240. let inside = self.s.m.cmp(original, pred::IULT, x, limit);
  2241. let runs = self.s.m.bin(original, Bin::Or, all, inside);
  2242. let (body, done) = (self.s.m.new_block(), self.s.m.new_block());
  2243. self.s.m.terminate(original, Term::CondBr(runs, body, done));
  2244. self.s.m.terminate(done, Term::Ret);
  2245. self.s.entry = body;
  2246. }
  2247. self.find_coherent();
  2248. let order = crate::ir::reverse_postorder(&p.blocks);
  2249. for (n, &b) in order.iter().enumerate() {
  2250. self.rpo[b] = n;
  2251. }
  2252. for (n, &b) in order.iter().enumerate() {
  2253. self.block[b] = Some(if n == 0 {
  2254. self.s.entry
  2255. } else {
  2256. self.s.m.new_block()
  2257. });
  2258. }
  2259. // Loop headers count iterations (`LOOP_LIMIT`).
  2260. for &b in &order {
  2261. let header = p.blocks[b]
  2262. .preds
  2263. .iter()
  2264. .any(|&q| self.block[q].is_some() && self.rpo[b] <= self.rpo[q]);
  2265. if header {
  2266. let blk = self.block[b].expect("reachable");
  2267. let phi = self.s.m.phi(blk, self.s.t.i32);
  2268. self.counters.insert(b, (phi, Vec::new()));
  2269. }
  2270. }
  2271. self.cur = self.s.entry;
  2272. self.find_sections();
  2273. self.inputs()?;
  2274. if let Some(mesh) = self.s.mesh {
  2275. self.mesh_prologue(mesh).map_err(|w| unsupported(0, w))?;
  2276. self.block[order[0]] = Some(self.cur);
  2277. }
  2278. for &b in &order {
  2279. self.cur = self.block[b].expect("reachable");
  2280. self.cur_ir = b;
  2281. let preds: Vec<usize> = p.blocks[b]
  2282. .preds
  2283. .iter()
  2284. .copied()
  2285. .filter(|&q| self.block[q].is_some())
  2286. .collect();
  2287. self.exported[b] = !preds.is_empty() && preds.iter().all(|&q| self.exported_out(q));
  2288. for (i, phi) in p.blocks[b].phis.iter().enumerate() {
  2289. let val = match phi.reg {
  2290. Reg::S(c) if c == EXEC || c == EXEC + 1 => Val::Missing("a lane mask"),
  2291. _ if self.bad.contains_key(&phi.value) => Val::Missing(self.bad[&phi.value]),
  2292. Reg::Scc => {
  2293. let v = self.s.m.phi(self.cur, self.s.t.i1);
  2294. self.data_phis.push((v, b, i));
  2295. Val::Bit(v)
  2296. }
  2297. _ => {
  2298. let v = self.s.m.phi(self.cur, self.s.t.i32);
  2299. self.data_phis.push((v, b, i));
  2300. Val::I32(v)
  2301. }
  2302. };
  2303. self.vals.insert(phi.value, val);
  2304. }
  2305. if self.lds_meet.as_ref().is_some_and(|(_, meet)| meet[b].0) {
  2306. self.lds_meeting();
  2307. }
  2308. let mut i = 0;
  2309. while i < p.blocks[b].insts.len() {
  2310. self.inst(b, i)?;
  2311. if let Some(end) = self.sections.get(&b).and_then(|s| s.get(&i)).map(|s| s.end) {
  2312. for j in i + 1..end {
  2313. self.section_inst(b, j, i);
  2314. }
  2315. i = end;
  2316. continue;
  2317. }
  2318. i += 1;
  2319. }
  2320. self.mask_ok = self.mask_data == MaskData::Console;
  2321. if self.lds_meet.as_ref().is_some_and(|(_, meet)| meet[b].1) {
  2322. self.lds_meeting();
  2323. }
  2324. self.tail[b] = Some(self.cur);
  2325. self.exit(b)?;
  2326. }
  2327. self.fill_phis()?;
  2328. let user_data = self.user_reads.values().copied().collect();
  2329. self.s.samplers = self.samplers.len() as u32;
  2330. let root_cbvs = self.s.root_cbvs.iter().map(|r| r.0).collect();
  2331. let root_srvs = self.s.root_srvs.iter().map(|r| r.0).collect();
  2332. let root_uavs = self.s.root_uavs.iter().map(|r| r.0).collect();
  2333. let cmp_samplers = self.s.cmp_samplers;
  2334. let wave_size = self.s.wave_size;
  2335. Ok(Lowered {
  2336. wave_size,
  2337. cmp_samplers,
  2338. root_cbvs,
  2339. root_srvs,
  2340. root_uavs,
  2341. #[cfg(test)]
  2342. nonuniform_handles: self.s.nonuniform_handles,
  2343. #[cfg(test)]
  2344. wave_ops: self.s.flags & flags::WAVE_OPS != 0,
  2345. dxil: self.s.finish(),
  2346. user_data,
  2347. samplers: self.samplers,
  2348. })
  2349. }
  2350. fn exported_out(&self, b: usize) -> bool {
  2351. self.exported[b] || self.has_done_export(b)
  2352. }
  2353. fn has_done_export(&self, b: usize) -> bool {
  2354. (0..self.x.p.blocks[b].insts.len())
  2355. .any(|i| self.exports.get(&(b, i)).is_some_and(|e| e.done))
  2356. }
  2357. /// Values of the program's input registers.
  2358. fn inputs(&mut self) -> Result<(), Stop> {
  2359. let io_inputs: HashMap<Value, Input> = self.x.io.inputs.iter().copied().collect();
  2360. for &(reg, v) in &self.x.p.inputs {
  2361. let val = match reg {
  2362. Reg::S(_) if self.params.contains_key(&v) => continue, // loaded on first use
  2363. // Most programs only interpolate with them: loaded on first
  2364. // use as a value (`get`).
  2365. Reg::V(_) if matches!(io_inputs.get(&v), Some(Input::Barycentric { .. })) => {
  2366. continue;
  2367. }
  2368. Reg::S(n) => match io_inputs.get(&v) {
  2369. Some(&input) => self.input(input),
  2370. // Above the SGPRs the hardware initializes, a register
  2371. // holds what the last wave left, so no program depends
  2372. // on it: a read the paths only seem to allow (a branch
  2373. // past the write, taken only with one past the read)
  2374. // reads zero, as VGPRs do.
  2375. None if n <= 105 && self.x.io.initialized_sgprs.is_some_and(|k| n >= k) => {
  2376. Val::I32(self.s.m.i32(0))
  2377. }
  2378. // A scalar parked in a VGPR lane (`ir::unspill`), read where the
  2379. // paths only seem to allow it before any save: the lane of a VGPR
  2380. // nobody wrote, and VGPRs nobody set read as zero.
  2381. None if n >= crate::ir::PARKED => Val::I32(self.s.m.i32(0)),
  2382. // No wave overlaps this one (see `ordered_section`).
  2383. None if self.pops_collision(v) => Val::I32(self.s.m.i32(0)),
  2384. None => Val::Missing("a hardware SGPR input"),
  2385. },
  2386. Reg::Scc => Val::Missing("SCC on entry"),
  2387. Reg::V(_) => match io_inputs.get(&v) {
  2388. Some(&input) => self.input(input),
  2389. // Registers no one set read as zero (the validator
  2390. // refuses reads of undef).
  2391. None => Val::I32(self.s.m.i32(0)),
  2392. },
  2393. };
  2394. self.vals.insert(v, val);
  2395. }
  2396. Ok(())
  2397. }
  2398. /// Whether the input SGPR `v` is the POPS collision wave id: a program
  2399. /// with an ordered section only takes its fields apart (bit 31 says
  2400. /// that the wave overlaps another, the others which packer and waves).
  2401. fn pops_collision(&self, v: Value) -> bool {
  2402. if self.ordered.is_empty() {
  2403. return false;
  2404. }
  2405. let mut packer = false;
  2406. for block in &self.x.p.blocks {
  2407. if block.phis.iter().any(|p| p.args.contains(&v)) {
  2408. return false;
  2409. }
  2410. for i in &block.insts {
  2411. if !i.reads.iter().any(|r| r.1 == v) {
  2412. continue;
  2413. }
  2414. let Fields::Sop { src, .. } = &i.fields else {
  2415. return false;
  2416. };
  2417. match (i.name(), src.get(1)) {
  2418. // bits 28 and 29: the packer
  2419. ("s_bfe_u32", Some(Operand::Literal(0x0002_001C))) => packer = true,
  2420. ("s_bfe_u32" | "s_lshr_b32", _) => {}
  2421. _ => return false,
  2422. }
  2423. }
  2424. }
  2425. packer
  2426. }
  2427. fn input(&mut self, input: Input) -> Val {
  2428. let (kind, col) = match input {
  2429. Input::VertexId => (1, 0),
  2430. Input::InstanceId => (2, 0),
  2431. Input::Position(c) => (3, c),
  2432. Input::Attribute { row, channel } => {
  2433. return match self.find_input(row, channel) {
  2434. Some((id, col)) => self.load_input(id, col),
  2435. None => Val::Missing("a vertex input the signature lacks"),
  2436. };
  2437. }
  2438. Input::Barycentric { kind, index } => return self.barycentric(kind, index),
  2439. Input::PrimitiveId => return Val::Missing("the primitive id"),
  2440. // The console code tests it against 0 (`v_cmp_ne_u32`), as the
  2441. // host's value can be.
  2442. Input::FrontFace => (13, 0),
  2443. Input::ThreadIdInGroup(c) => return self.thread_id(c),
  2444. Input::GroupId(c) => return self.compute_id("groupId.i32", 94, c),
  2445. Input::GroupInfo => return Val::Missing("the thread-group info SGPR"),
  2446. Input::MeshGroup => {
  2447. let Val::I32(g) = self.compute_id("groupId.i32", 94, 0) else {
  2448. unreachable!()
  2449. };
  2450. let n = self.s.m.i32(self.x.mesh_stride);
  2451. return Val::I32(self.s.m.bin(self.s.entry, Bin::Mul, g, n));
  2452. }
  2453. Input::MergedWaveInfo => {
  2454. // shortcut: only the wave index (bits 24-27) is set; the
  2455. // console's other bits (lane counts) are read by no program.
  2456. let f = self.mesh_thread();
  2457. let shift = self.s.m.i32(self.wave().trailing_zeros());
  2458. let w = self.s.m.bin(self.s.entry, Bin::LShr, f, shift);
  2459. let k24 = self.s.m.i32(24);
  2460. return Val::I32(self.s.m.bin(self.s.entry, Bin::Shl, w, k24));
  2461. }
  2462. _ => return Val::Missing("a pixel system input"),
  2463. };
  2464. let free = self
  2465. .s
  2466. .inputs
  2467. .iter()
  2468. .filter_map(|e| e.row)
  2469. .map(|r| r + 1)
  2470. .max()
  2471. .unwrap_or(0);
  2472. let id = match self.s.inputs.iter().position(|e| e.kind == kind) {
  2473. Some(id) => {
  2474. if kind != 3 {
  2475. self.s.inputs[id].row.get_or_insert(free);
  2476. }
  2477. id
  2478. }
  2479. None if kind >= 3 => return Val::Missing("a pixel system input the signature lacks"),
  2480. None => {
  2481. // The console signature leaves out vertex and instance ids; PC
  2482. // gives them a row after the others.
  2483. let row = self
  2484. .s
  2485. .inputs
  2486. .iter()
  2487. .filter_map(|e| e.row)
  2488. .map(|r| r + 1)
  2489. .max()
  2490. .unwrap_or(0);
  2491. self.s.inputs.push(SigElement {
  2492. name: ["", "SV_VertexID", "SV_InstanceID"][kind as usize].into(),
  2493. index: 0,
  2494. kind,
  2495. comp: 5,
  2496. interp: 0,
  2497. row: Some(row),
  2498. col: 0,
  2499. cols: 1,
  2500. usage: 0,
  2501. half: false,
  2502. });
  2503. self.s.inputs.len() - 1
  2504. }
  2505. };
  2506. self.load_input(id, col)
  2507. }
  2508. /// A component of a compute thread or group id, read in the entry block.
  2509. fn compute_id(&mut self, name: &str, opcode: u32, c: u8) -> Val {
  2510. let (entry, c) = (self.s.entry, self.s.m.i32(u32::from(c)));
  2511. Val::I32(
  2512. self.s
  2513. .op(entry, name, Attr::ReadNone, self.s.t.i32, opcode, &[c]),
  2514. )
  2515. }
  2516. fn find_input(&self, row: u8, channel: u8) -> Option<(usize, u8)> {
  2517. self.s.inputs.iter().enumerate().find_map(|(id, e)| {
  2518. let r = e.row?;
  2519. // `then`, not `then_some`: the channel is only past `col` when
  2520. // the condition holds.
  2521. (r == u32::from(row) && channel >= e.col && channel < e.col + e.cols)
  2522. .then(|| (id, channel - e.col))
  2523. })
  2524. }
  2525. fn load_input(&mut self, id: usize, col: u8) -> Val {
  2526. if self.s.inputs[id].half {
  2527. // shortcut: 16-bit vertex inputs (the fetch routine's) are not
  2528. // unpacked; pixel inputs are (`interp`).
  2529. return Val::Missing("a 16-bit input");
  2530. }
  2531. self.load_any_input(id, col)
  2532. }
  2533. /// An input element's channel as declared (16-bit ones as 32-bit floats).
  2534. fn load_any_input(&mut self, id: usize, col: u8) -> Val {
  2535. let e = &mut self.s.inputs[id];
  2536. e.usage |= 1 << col;
  2537. let (int, bit) = (e.comp != 9, e.comp == 1);
  2538. let ty = if bit {
  2539. self.s.t.i1
  2540. } else if int {
  2541. self.s.t.i32
  2542. } else {
  2543. self.s.t.f32
  2544. };
  2545. let suffix = if bit {
  2546. ".i1"
  2547. } else if int {
  2548. ".i32"
  2549. } else {
  2550. ".f32"
  2551. };
  2552. let entry = self.s.entry;
  2553. let args = [
  2554. self.s.m.i32(id as u32),
  2555. self.s.m.i32(0),
  2556. self.s.m.i8(col),
  2557. self.s.m.undef(self.s.t.i32),
  2558. ];
  2559. let v = self.s.op(
  2560. entry,
  2561. &format!("loadInput{suffix}"),
  2562. Attr::ReadNone,
  2563. ty,
  2564. 4,
  2565. &args,
  2566. );
  2567. if bit {
  2568. let z = self.s.m.cast(entry, Cast::ZExt, v, self.s.t.i32);
  2569. Val::I32(z)
  2570. } else if int {
  2571. Val::I32(v)
  2572. } else {
  2573. Val::I32(self.s.m.cast(entry, Cast::Bitcast, v, self.s.t.i32))
  2574. }
  2575. }
  2576. /// The DXIL form of an IR value.
  2577. fn get(&mut self, v: Value) -> Result<Val, Why> {
  2578. if self.phi_at.contains_key(&v) {
  2579. self.read_phis.insert(v);
  2580. }
  2581. let is_mask = self.x.st.masks.contains_key(&v) || self.x.st.highs.contains_key(&v);
  2582. match self.vals.get(&v) {
  2583. Some(&Val::Missing(_)) | None if self.mask_ok && is_mask => {
  2584. return self.mask_dword(v).map(Val::I32);
  2585. }
  2586. Some(&Val::Missing(w)) => return Err(w),
  2587. Some(&val) => return Ok(val),
  2588. None => {}
  2589. }
  2590. if let Some(&(param, dword)) = self.params.get(&v) {
  2591. let val = self.user(param, dword);
  2592. self.vals.insert(v, val);
  2593. return Ok(val);
  2594. }
  2595. if let Some(loaded) = self.lazy_barycentric(v) {
  2596. loaded?;
  2597. return Ok(self.vals[&v]);
  2598. }
  2599. Err("a value defined after its use")
  2600. }
  2601. /// Loads `v` if it is a barycentric input VGPR not loaded yet (see
  2602. /// `inputs`): `None` if it is not one.
  2603. fn lazy_barycentric(&mut self, v: Value) -> Option<Result<(), Why>> {
  2604. let (kind, index) = self.x.io.inputs.iter().find_map(|&(w, i)| match i {
  2605. Input::Barycentric { kind, index } if w == v => Some((kind, index)),
  2606. _ => None,
  2607. })?;
  2608. let val = self.barycentric(kind, index);
  2609. self.vals.insert(v, val);
  2610. Some(match val {
  2611. Val::Missing(w) => Err(w),
  2612. _ => Ok(()),
  2613. })
  2614. }
  2615. /// Barycentric `index` (0 i, 1 j) of `kind` as a value: a channel of
  2616. /// `SV_Barycentrics` declared with the same interpolation mode.
  2617. ///
  2618. /// GFX10 interpolates P0 + i (P1 - P0) + j (P2 - P0), so i and j are
  2619. /// the weights of vertices 1 and 2. The host's weights (x, y, z) are
  2620. /// those of vertices 0, 1 and 2, vertex 0 being the provoking vertex,
  2621. /// which is the console's P0 (`v_interp_mov` P0 is lowered to a flat
  2622. /// input): i is y and j is z.
  2623. /// shortcut: triangles only; on lines and points the console's i and j
  2624. /// are not checked against the host's weights.
  2625. fn barycentric(&mut self, kind: Barycentric, index: u8) -> Val {
  2626. let Some(mode) = interp_mode(kind) else {
  2627. return Val::Missing("pull-model barycentrics");
  2628. };
  2629. if index > 1 {
  2630. return Val::Missing("pull-model barycentrics");
  2631. }
  2632. // One element per interpolation mode (the console's own, if its
  2633. // signature declares one): DXIL allows two.
  2634. let bary = |e: &SigElement| e.kind == 28;
  2635. let id = match self
  2636. .s
  2637. .inputs
  2638. .iter()
  2639. .position(|e| bary(e) && (e.interp == mode || e.usage == 0))
  2640. {
  2641. Some(id) => id,
  2642. None => {
  2643. let index = self.s.inputs.iter().filter(|e| bary(e)).count() as u32;
  2644. if index >= 2 {
  2645. return Val::Missing("barycentrics of a third interpolation mode");
  2646. }
  2647. // A system value the validator wants unpacked (packing
  2648. // location -1), like other non-packed system values.
  2649. self.s.inputs.push(SigElement {
  2650. name: "SV_Barycentrics".into(),
  2651. index,
  2652. kind: 28,
  2653. comp: 9,
  2654. interp: mode,
  2655. row: None,
  2656. col: 0,
  2657. cols: 3,
  2658. usage: 0,
  2659. half: false,
  2660. });
  2661. self.s.inputs.len() - 1
  2662. }
  2663. };
  2664. let e = &mut self.s.inputs[id];
  2665. if e.col != 0 || e.cols < 3 {
  2666. return Val::Missing("a console barycentrics element without i and j");
  2667. }
  2668. e.row = None;
  2669. e.interp = mode;
  2670. self.s.flags |= flags::BARYCENTRICS;
  2671. self.load_any_input(id, index + 1)
  2672. }
  2673. fn i32_of(&mut self, v: Value) -> Result<V, Why> {
  2674. match self.get(v)? {
  2675. Val::I32(x) => Ok(x),
  2676. Val::Bit(x) => Ok(self.s.m.cast(self.cur, Cast::ZExt, x, self.s.t.i32)),
  2677. Val::Missing(w) => Err(w),
  2678. }
  2679. }
  2680. /// A user-data dword: a root parameter's value.
  2681. fn user(&mut self, param: usize, dword: u32) -> Val {
  2682. let rp = self.x.native.layout[param];
  2683. match rp.root {
  2684. RootType::ResourceHeap | RootType::SamplerHeap => return Val::I32(self.s.m.i32(0)),
  2685. RootType::Constants | RootType::Table => {}
  2686. _ => return Val::Missing("a root descriptor"),
  2687. }
  2688. let index = u32::from(rp.user_data) + dword - self.user_first();
  2689. self.user_reads.insert(
  2690. index,
  2691. UserData {
  2692. index,
  2693. slot: rp.slot,
  2694. root: rp.root,
  2695. dword,
  2696. },
  2697. );
  2698. Val::I32(self.user_at(index))
  2699. }
  2700. /// The user-data index that is dword 0 of the host's user data: 0, or
  2701. /// 16 for a program with a spilled user-data table, whose parameters
  2702. /// all sit at 16 and above. (The host's root signature has 64 dwords:
  2703. /// a builder stage with constants up to index 45, eight root views,
  2704. /// their biases and the memory directory would not fit with 16 dwords
  2705. /// nothing reads in front.)
  2706. fn user_first(&self) -> u32 {
  2707. if crate::spill::is_spilled(self.x.native) {
  2708. 16
  2709. } else {
  2710. 0
  2711. }
  2712. }
  2713. /// A user-data dword no register of the console's holds: one the host
  2714. /// computes when it binds (`root` says what, an `Other` code of
  2715. /// `shader.rs`), placed after the layout's own dwords.
  2716. fn host_word(&mut self, root: RootType, slot: u8, dword: u32) -> V {
  2717. let known = self
  2718. .user_reads
  2719. .values()
  2720. .find(|u| u.root == root && u.slot == slot && u.dword == dword)
  2721. .map(|u| u.index);
  2722. let index = match known {
  2723. Some(index) => index,
  2724. None => {
  2725. let first = self.user_first();
  2726. let layout = &self.x.native.layout;
  2727. let mut index = layout
  2728. .iter()
  2729. .map(|e| u32::from(e.user_data) + e.sgprs)
  2730. .max()
  2731. .unwrap_or(0)
  2732. .saturating_sub(first);
  2733. while self.user_reads.contains_key(&index) {
  2734. index += 1;
  2735. }
  2736. self.user_reads.insert(
  2737. index,
  2738. UserData {
  2739. index,
  2740. slot,
  2741. root,
  2742. dword,
  2743. },
  2744. );
  2745. index
  2746. }
  2747. };
  2748. self.user_at(index)
  2749. }
  2750. /// User-data dword `index`, loaded in the entry block.
  2751. fn user_at(&mut self, index: u32) -> V {
  2752. self.s.user_data = self.s.user_data.max(index + 1);
  2753. let h = match self.user_data {
  2754. Some(h) => h,
  2755. None => {
  2756. let h = self.s.user_data_handle();
  2757. self.user_data = Some(h);
  2758. h
  2759. }
  2760. };
  2761. let entry = self.s.entry;
  2762. let row = self.s.m.i32(index / 4);
  2763. let r = self.s.op(
  2764. entry,
  2765. "cbufferLoadLegacy.i32",
  2766. Attr::ReadOnly,
  2767. self.s.t.cbuf_ret,
  2768. 59,
  2769. &[h, row],
  2770. );
  2771. self.s.m.extract(entry, r, index % 4)
  2772. }
  2773. /// Whether some instruction reads `v` as a number (or may, through a
  2774. /// join), rather than in a descriptor operand.
  2775. fn read_as_number(&self, v: Value) -> bool {
  2776. self.x.p.blocks.iter().any(|b| {
  2777. b.phis.iter().any(|p| p.args.contains(&v))
  2778. || b.insts.iter().any(|i| {
  2779. matches!(i.fields, Fields::Sop { .. } | Fields::Valu(_))
  2780. && i.reads.iter().any(|r| r.1 == v)
  2781. })
  2782. })
  2783. }
  2784. /// Whether some instruction computes with `v` (scalar or vector
  2785. /// arithmetic), rather than only naming it in a descriptor operand,
  2786. /// moving it (at most `depth` moves are followed) or comparing it: a
  2787. /// waterfall loop keeps a descriptor's dwords per lane, reads the first
  2788. /// lane's back and compares the lanes' with them.
  2789. fn computed_with(&self, v: Value, depth: u32) -> bool {
  2790. self.x.p.blocks.iter().flat_map(|b| &b.insts).any(|i| {
  2791. if !i.reads.iter().any(|r| r.1 == v) {
  2792. return false;
  2793. }
  2794. let name = i.name();
  2795. let moves = matches!(
  2796. name,
  2797. "s_mov_b32"
  2798. | "s_mov_b64"
  2799. | "v_mov_b32"
  2800. | "v_readfirstlane_b32"
  2801. | "v_readlane_b32"
  2802. | "v_writelane_b32"
  2803. | "v_cndmask_b32"
  2804. );
  2805. match &i.fields {
  2806. Fields::Sop { .. } | Fields::Valu(_) if moves => {
  2807. depth > 0 && i.writes.iter().any(|w| self.computed_with(w.1, depth - 1))
  2808. }
  2809. Fields::Sop { .. } | Fields::Valu(_) => {
  2810. !(name.starts_with("v_cmp") || name.starts_with("s_cmp"))
  2811. }
  2812. _ => false,
  2813. }
  2814. })
  2815. }
  2816. /// Whether the image `src` names is one of 32-bit integers (one channel):
  2817. /// the program has an integer atomic on the same table entry, which
  2818. /// takes no other view.
  2819. fn is_counter(&self, src: &Source) -> bool {
  2820. let Some(this) = self.entry(src) else {
  2821. return false;
  2822. };
  2823. self.x.res.descriptors.iter().any(|d| {
  2824. let i = &self.x.p.blocks[d.site.0].insts[d.site.1];
  2825. d.role == Role::Resource
  2826. && matches!(i.fields, Fields::Image { dmask: 1, .. })
  2827. && matches!(
  2828. i.name(),
  2829. "image_atomic_add"
  2830. | "image_atomic_sub"
  2831. | "image_atomic_and"
  2832. | "image_atomic_or"
  2833. | "image_atomic_xor"
  2834. | "image_atomic_smin"
  2835. | "image_atomic_smax"
  2836. | "image_atomic_umin"
  2837. | "image_atomic_umax"
  2838. )
  2839. && self.entry(&d.source) == Some(this)
  2840. })
  2841. }
  2842. /// Which table entry `src` is loaded from: its root parameter and byte.
  2843. fn entry(&self, src: &Source) -> Option<(usize, u32)> {
  2844. let Source::Loaded { load, first } = src else {
  2845. return None;
  2846. };
  2847. let a = self.scalar.get(load).filter(|a| a.dynamic.is_none())?;
  2848. Some((a.param, a.offset + 4 * u32::from(*first)))
  2849. }
  2850. /// See [`Lower::coherent`].
  2851. fn find_coherent(&mut self) {
  2852. let found: Vec<_> = self
  2853. .x
  2854. .res
  2855. .descriptors
  2856. .iter()
  2857. .filter(|d| {
  2858. let i = &self.x.p.blocks[d.site.0].insts[d.site.1];
  2859. matches!(&i.fields, Fields::Buffer { cache, .. } if cache.glc)
  2860. && i.name().starts_with("buffer_load_dword")
  2861. && self.used_kind(&d.source).is_some_and(|u| u.kind == ResourceType::Uav)
  2862. })
  2863. .filter_map(|d| self.entry(&d.source))
  2864. .collect();
  2865. self.coherent.extend(found);
  2866. }
  2867. /// The kind of a view no instruction uses (in this program, or through
  2868. /// another load of its address), by what the code reads of the
  2869. /// descriptor the load `inst` at `site` writes to the SGPRs from `code`:
  2870. /// `Some(true)` for a 2D image, read only for its size, `Some(false)`
  2871. /// for a structured buffer, read only for its record count.
  2872. ///
  2873. /// - Eight dwords are an image's. `GetDimensions` of a 2D one reads the
  2874. /// width (dwords 1 and 2), the height (dword 2, bits 14-29, with one
  2875. /// `s_bfe_u32`) and the base level or the last (dword 3); of an array,
  2876. /// a cube or a volume also dword 4.
  2877. /// - Four dwords at a table entry the used resources list as an SRV or
  2878. /// UAV are a buffer's. A stride above 4 bytes there is an element's
  2879. /// (a typed or raw view has at most 4): a test for a null view reads
  2880. /// the record count, nothing else.
  2881. fn sized_view(&self, inst: &Inst, site: Site, code: u8, count: u32) -> Option<bool> {
  2882. let dword = |k: u8| inst.write(Reg::S(code + k));
  2883. let read = |v: Value| {
  2884. self.x.p.blocks.iter().any(|b| {
  2885. b.insts.iter().any(|i| i.reads.iter().any(|r| r.1 == v))
  2886. || b.phis.iter().any(|p| p.args.contains(&v))
  2887. })
  2888. };
  2889. let only = |allowed: &[u8]| {
  2890. (0..count as u8).all(|k| allowed.contains(&k) || !dword(k).is_some_and(read))
  2891. };
  2892. match count {
  2893. 8 => {
  2894. const HEIGHT: u32 = 16 << 16 | 14;
  2895. let v = dword(2)?;
  2896. let height = self.x.p.blocks.iter().flat_map(|b| &b.insts).any(|i| {
  2897. i.name() == "s_bfe_u32"
  2898. && i.reads.iter().any(|r| r.1 == v)
  2899. && matches!(&i.fields, Fields::Sop { src, .. }
  2900. if matches!(src.get(1), Some(Operand::Literal(HEIGHT))))
  2901. });
  2902. (height && only(&[1, 2, 3])).then_some(true)
  2903. }
  2904. 4 => {
  2905. let used = self.used_kind(&Source::Loaded { load: site, first: 0 })?;
  2906. let a = self.scalar.get(&site)?;
  2907. let buffer = used.dwords == 4
  2908. && a.dynamic.is_none()
  2909. && used.table_offset_dwords == a.offset / 4
  2910. && matches!(used.kind, ResourceType::Srv | ResourceType::Uav)
  2911. && used.stride > 4
  2912. && used.stride.is_multiple_of(4);
  2913. (buffer && only(&[2])).then_some(false)
  2914. }
  2915. _ => None,
  2916. }
  2917. }
  2918. /// The title address (low dword, bits from 32 up) of the buffer view
  2919. /// whose descriptor the scalar load at `site` reads from the start of
  2920. /// a table entry, as the host tells it when it binds (`shader.rs`
  2921. /// `USER_VIEW_ADDRESS`); none for anything else. (The console's
  2922. /// descriptor holds more in the second dword, the stride from bit 16
  2923. /// up; code that takes the address masks those away.)
  2924. fn view_address(&mut self, site: Site) -> Option<(V, V)> {
  2925. use super::shader::USER_VIEW_ADDRESS;
  2926. let a = self.scalar.get(&site).copied()?;
  2927. let rp = *self.x.native.layout.get(a.param)?;
  2928. if rp.root != RootType::Table || a.dynamic.is_some() || a.offset % 32 != 0 {
  2929. return None;
  2930. }
  2931. let dword = a.offset / 4;
  2932. let used = self
  2933. .x
  2934. .native
  2935. .used
  2936. .iter()
  2937. .filter(|u| {
  2938. u.root == RootType::Table
  2939. && u.user_data == rp.user_data
  2940. && u.table_offset_dwords <= dword
  2941. })
  2942. .max_by_key(|u| u.table_offset_dwords)?;
  2943. if used.dwords != 4 || !matches!(used.kind, ResourceType::Srv | ResourceType::Uav) {
  2944. return None;
  2945. }
  2946. let lo = self.host_word(RootType::Other(USER_VIEW_ADDRESS), rp.slot, dword);
  2947. let hi = self.host_word(RootType::Other(USER_VIEW_ADDRESS + 1), rp.slot, dword);
  2948. Some((lo, hi))
  2949. }
  2950. /// `lo`, `hi` plus the instruction's byte offset `off`, with the carry.
  2951. fn address_plus(&mut self, lo: V, hi: V, off: i32) -> (V, V) {
  2952. if off == 0 {
  2953. return (lo, hi);
  2954. }
  2955. let c = self.cur;
  2956. let i32t = self.s.t.i32;
  2957. let k = self.s.m.i32(off as u32);
  2958. let sum = self.s.m.bin(c, Bin::Add, lo, k);
  2959. // Up: a carry when the sum wrapped below `lo`. Down: a borrow when
  2960. // it wrapped above.
  2961. let wrapped = self
  2962. .s
  2963. .m
  2964. .cmp(c, if off > 0 { pred::IULT } else { pred::IUGT }, sum, lo);
  2965. let one = self.s.m.cast(c, Cast::ZExt, wrapped, i32t);
  2966. let hi = self.s.m.bin(c, if off > 0 { Bin::Add } else { Bin::Sub }, hi, one);
  2967. (sum, hi)
  2968. }
  2969. /// Title memory at the 40-bit address `lo`, `hi` (`shader.rs`
  2970. /// `SLOT_MEMORY`): the handle of the raw view of the host copy holding
  2971. /// it and the byte in that view. A page without a copy reads zeros
  2972. /// (and drops writes) through the null view at the first slot, and its
  2973. /// number is left for the host, for lanes that run (`guard`). Goes on in
  2974. /// another block.
  2975. /// With `store`, a page that is not to be written ([`super::shader::MEMORY_READ_ONLY`])
  2976. /// is the null view.
  2977. fn memory(&mut self, lo: V, hi: V, guard: Option<V>, store: bool) -> (V, V) {
  2978. use super::shader::{MEMORY_FAULTS, MEMORY_PAGES, MEMORY_READ_ONLY, SLOT_FAULTS, SLOT_MEMORY, USER_MEMORY_BASE};
  2979. let c = self.cur;
  2980. let (i32t, res) = (self.s.t.i32, self.s.t.res_ret);
  2981. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  2982. let (k16, k8) = (k(self, 16), k(self, 0xFF));
  2983. let low = self.s.m.bin(c, Bin::LShr, lo, k16);
  2984. let high = self.s.m.bin(c, Bin::And, hi, k8);
  2985. let high = self.s.m.bin(c, Bin::Shl, high, k16);
  2986. let page = self.s.m.bin(c, Bin::Or, low, high);
  2987. // Inside the directory whatever the address (lanes that do not run
  2988. // compute one too); its last entry is never filled.
  2989. let last = k(self, MEMORY_PAGES - 1);
  2990. let page = self
  2991. .s
  2992. .op(c, "binary.i32", Attr::ReadNone, i32t, 40, &[page, last]);
  2993. self.s.m.tag(page, Tag::Clamp);
  2994. let k3 = k(self, 3);
  2995. let at = self.s.m.bin(c, Bin::Shl, page, k3);
  2996. let directory = self.s.root_srv_handle(SLOT_MEMORY);
  2997. let (iu, both, align) = (self.s.m.undef(i32t), self.s.m.i8(3), k(self, 4));
  2998. let entry = self.s.op(
  2999. c,
  3000. "rawBufferLoad.f32",
  3001. Attr::ReadOnly,
  3002. res,
  3003. 139,
  3004. &[directory, at, iu, both, align],
  3005. );
  3006. let (copy, start) = (self.s.m.extract(c, entry, 0), self.s.m.extract(c, entry, 1));
  3007. let (number, start) = (self.as_int(copy), self.as_int(start));
  3008. let mask = k(self, !MEMORY_READ_ONLY);
  3009. let copy = self.s.m.bin(c, Bin::And, number, mask);
  3010. // A page without a copy: its number, at a place by the number. In a
  3011. // branch: the notes lie in the PC's memory, and a store there with
  3012. // every node of every ray would be most of what a trace does.
  3013. let zero = k(self, 0);
  3014. let mut missing = self.s.m.cmp(c, pred::EQ, copy, zero);
  3015. if let Some(g) = guard {
  3016. missing = self.s.m.bin(c, Bin::And, missing, g);
  3017. }
  3018. let places = k(self, MEMORY_FAULTS - 1);
  3019. let faults = self.s.root_uav_handle(SLOT_FAULTS);
  3020. let noting = self.begin_guarded(Some(missing));
  3021. let c = self.cur;
  3022. let place = self.s.m.bin(c, Bin::URem, page, places);
  3023. let one = k(self, 1);
  3024. let place = self.s.m.bin(c, Bin::Add, place, one);
  3025. let k2 = k(self, 2);
  3026. let place = self.s.m.bin(c, Bin::Shl, place, k2);
  3027. let void = self.s.t.void;
  3028. let mask = self.s.m.i8(1);
  3029. self.s.op(
  3030. c,
  3031. "rawBufferStore.i32",
  3032. Attr::NoUnwind,
  3033. void,
  3034. 140,
  3035. &[faults, place, iu, page, iu, iu, iu, mask, align],
  3036. );
  3037. self.end_guarded(noting, &[]);
  3038. let c = self.cur;
  3039. self.page_there = Some(self.s.m.cmp(c, pred::NE, copy, zero));
  3040. let copy = if store {
  3041. let closed = self.s.m.cmp(c, pred::SLT, number, zero);
  3042. self.s.m.select(c, closed, zero, copy)
  3043. } else {
  3044. copy
  3045. };
  3046. let base = self.host_word(RootType::Other(USER_MEMORY_BASE), 0, 0);
  3047. let slot = self.s.m.bin(c, Bin::Add, base, copy);
  3048. // The builder's threads read what others of the dispatch wrote (a
  3049. // refit climbs from children to parents): globally coherent.
  3050. let coherent = if crate::spill::is_spilled(self.x.native) { 0x4000 } else { 0 };
  3051. let h = self.s.heap_handle(c, slot, false, true, (11 | 0x1000 | coherent, 0));
  3052. let k64k = k(self, 0xFFFF);
  3053. let within = self.s.m.bin(c, Bin::And, lo, k64k);
  3054. let byte = self.s.m.bin(c, Bin::Add, start, within);
  3055. (h, byte)
  3056. }
  3057. /// The title address in the root view `src` is built around, in a program
  3058. /// with a spilled user-data table (`shader.rs` `USER_ROOT_ADDRESS`).
  3059. fn root_address(&mut self, src: &Source) -> Option<(V, V)> {
  3060. use super::shader::USER_ROOT_ADDRESS;
  3061. let Source::Built { address, .. } = src else {
  3062. return None;
  3063. };
  3064. let rp = *self.x.native.layout.get(address.param)?;
  3065. if rp.root != RootType::Descriptor || !crate::spill::is_spilled(self.x.native) {
  3066. return None;
  3067. }
  3068. let used = self.x.native.used.iter().find(|u| u.user_data == rp.user_data)?;
  3069. if !matches!(used.kind, ResourceType::Srv | ResourceType::Uav) {
  3070. return None;
  3071. }
  3072. let lo = self.host_word(RootType::Other(USER_ROOT_ADDRESS), rp.slot, 0);
  3073. let hi = self.host_word(RootType::Other(USER_ROOT_ADDRESS + 1), rp.slot, 0);
  3074. Some((lo, hi))
  3075. }
  3076. /// For an access through such a root view: the raw view of the host copy
  3077. /// and the byte in it of the view's byte `off` (signed: an offset below
  3078. /// the address stays below it). [`Lower::handle`] gives the same view for
  3079. /// the rest of the instruction. None for any other source. Goes on in
  3080. /// another block.
  3081. /// shortcut: an access of several dwords is taken not to cross the end
  3082. /// of a host copy (the builder's records lie on their size).
  3083. fn root_memory(&mut self, src: &Source, off: V, guard: Option<V>, store: bool) -> Option<(V, V)> {
  3084. let (lo, hi) = self.root_address(src)?;
  3085. let c = self.cur;
  3086. let i32t = self.s.t.i32;
  3087. let sum = self.s.m.bin(c, Bin::Add, lo, off);
  3088. let wrapped = self.s.m.cmp(c, pred::IULT, sum, lo);
  3089. let carry = self.s.m.cast(c, Cast::ZExt, wrapped, i32t);
  3090. let k31 = self.s.m.i32(31);
  3091. let sign = self.s.m.bin(c, Bin::AShr, off, k31);
  3092. let hi = self.s.m.bin(c, Bin::Add, hi, carry);
  3093. let hi = self.s.m.bin(c, Bin::Add, hi, sign);
  3094. let (h, byte) = self.memory(sum, hi, guard, store);
  3095. self.root_copy = Some(h);
  3096. Some((h, byte))
  3097. }
  3098. /// `global_load_*`, `global_store_*` and `global_atomic_*` on title
  3099. /// memory by address (`resource::MEMORY`): the address is the VGPR
  3100. /// pair, each lane its own.
  3101. fn memory_flat(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  3102. let Fields::Flat {
  3103. dst,
  3104. addr,
  3105. data,
  3106. saddr,
  3107. offset,
  3108. lds,
  3109. cache,
  3110. } = &inst.fields
  3111. else {
  3112. unreachable!()
  3113. };
  3114. if *lds || !matches!(saddr, None | Some(Operand::Scalar { code: NULL, .. })) {
  3115. return Err("a global address with a scalar base");
  3116. }
  3117. let Some(Operand::Vector { reg: areg, .. }) = *addr else {
  3118. return Err("a global address not in VGPRs");
  3119. };
  3120. let word = |l: &mut Self, k: u8| -> Result<V, Why> {
  3121. let v = inst.read(Reg::V(areg + k)).ok_or("a global address")?;
  3122. l.i32_of(v)
  3123. };
  3124. let (lo, hi) = (word(self, 0)?, word(self, 1)?);
  3125. let (lo, hi) = self.address_plus(lo, hi, i32::from(*offset));
  3126. let guard = self.guard(b, i)?;
  3127. let (i32t, res, void) = (self.s.t.i32, self.s.t.res_ret, self.s.t.void);
  3128. let iu = self.s.m.undef(i32t);
  3129. let align = self.s.m.i32(4);
  3130. let name = inst.name();
  3131. let count = |rest: &str| match rest {
  3132. "dword" => Ok(1u8),
  3133. "dwordx2" => Ok(2),
  3134. "dwordx3" => Ok(3),
  3135. "dwordx4" => Ok(4),
  3136. _ => Err(name),
  3137. };
  3138. if let Some(rest) = name.strip_prefix("global_load_") {
  3139. let n = count(rest)?;
  3140. let Some(Operand::Vector { reg, .. }) = *dst else {
  3141. return Err("a global load result");
  3142. };
  3143. let (h, byte) = self.memory(lo, hi, guard, false);
  3144. let c = self.cur;
  3145. let mask = self.s.m.i8((1u8 << n) - 1);
  3146. let r = self.s.op(
  3147. c,
  3148. "rawBufferLoad.f32",
  3149. Attr::ReadOnly,
  3150. res,
  3151. 139,
  3152. &[h, byte, iu, mask, align],
  3153. );
  3154. for k in 0..n {
  3155. let x = self.s.m.extract(c, r, u32::from(k));
  3156. let x = self.as_int(x);
  3157. self.write(inst, Reg::V(reg + k), x, guard);
  3158. }
  3159. return Ok(());
  3160. }
  3161. if let Some(rest) = name.strip_prefix("global_store_") {
  3162. let n = count(rest)?;
  3163. let d = data.as_ref().ok_or("global store data")?;
  3164. let vals = self.vgprs(inst, d, n)?;
  3165. let (h, byte) = self.memory(lo, hi, guard, true);
  3166. let mut args = vec![h, byte, iu];
  3167. args.extend(&vals);
  3168. args.resize(3 + 4, iu);
  3169. args.push(self.s.m.i8((1u8 << n) - 1));
  3170. args.push(align);
  3171. let at = self.begin_guarded(guard);
  3172. self.s
  3173. .op(self.cur, "rawBufferStore.i32", Attr::NoUnwind, void, 140, &args);
  3174. self.end_guarded(at, &[]);
  3175. return Ok(());
  3176. }
  3177. let Some(op) = name.strip_prefix("global_atomic_") else {
  3178. return Err(name);
  3179. };
  3180. let d = data.as_ref().ok_or("global atomic data")?;
  3181. let v = self.vgprs(inst, d, 1)?[0];
  3182. // With `glc` the value from before comes back, in the result
  3183. // register the instruction names.
  3184. let back = match (*dst, cache.glc) {
  3185. (Some(Operand::Vector { reg, .. }), true) => Some(reg),
  3186. _ => None,
  3187. };
  3188. let old = match back.and_then(|reg| inst.read(Reg::V(reg))) {
  3189. Some(x) => self.i32_of(x)?,
  3190. None => self.s.m.i32(0),
  3191. };
  3192. let (h, byte) = self.memory(lo, hi, guard, true);
  3193. let c = self.cur;
  3194. // DXIL's atomic operations: add 0, and 1, or 2, xor 3, signed
  3195. // minimum 4 and maximum 5, unsigned 6 and 7, exchange 8.
  3196. let simple = match op {
  3197. "add" => Some((0, v)),
  3198. "sub" => {
  3199. let zero = self.s.m.i32(0);
  3200. Some((0, self.s.m.bin(c, Bin::Sub, zero, v)))
  3201. }
  3202. "and" => Some((1, v)),
  3203. "or" => Some((2, v)),
  3204. "xor" => Some((3, v)),
  3205. "smin" => Some((4, v)),
  3206. "smax" => Some((5, v)),
  3207. "umin" => Some((6, v)),
  3208. "umax" => Some((7, v)),
  3209. "swap" => Some((8, v)),
  3210. "fmin" | "fmax" => None,
  3211. _ => return Err(name),
  3212. };
  3213. let at = self.begin_guarded(guard);
  3214. let was = match simple {
  3215. Some((code, x)) => {
  3216. let code = self.s.m.i32(code);
  3217. self.s.op(
  3218. self.cur,
  3219. "atomicBinOp.i32",
  3220. Attr::NoUnwind,
  3221. i32t,
  3222. 78,
  3223. &[h, code, byte, iu, iu, x],
  3224. )
  3225. }
  3226. None => {
  3227. // A float minimum or maximum has no atomic operation on
  3228. // the host: the dword is exchanged for the smaller (larger)
  3229. // of itself and the value until no other thread got in
  3230. // between. Each failed pass means another one's succeeded;
  3231. // the limit only keeps a broken card from hanging.
  3232. let head = self.cur;
  3233. let mask = self.s.m.i8(1);
  3234. let first = self.s.op(
  3235. head,
  3236. "rawBufferLoad.f32",
  3237. Attr::ReadOnly,
  3238. res,
  3239. 139,
  3240. &[h, byte, iu, mask, align],
  3241. );
  3242. let first = self.s.m.extract(head, first, 0);
  3243. let first = self.as_int(first);
  3244. let (pass, done) = (self.s.m.new_block(), self.s.m.new_block());
  3245. self.s.m.terminate(head, Term::Br(pass));
  3246. self.cur = pass;
  3247. let seen = self.s.m.phi(pass, i32t);
  3248. let n = self.s.m.phi(pass, i32t);
  3249. let (f32t, fv) = (self.s.t.f32, self.as_float(v));
  3250. let fseen = self.as_float(seen);
  3251. // `dx.op.binary`: FMax 35, FMin 36.
  3252. let pick = if op == "fmin" { 36 } else { 35 };
  3253. let wanted = self
  3254. .s
  3255. .op(pass, "binary.f32", Attr::ReadNone, f32t, pick, &[fseen, fv]);
  3256. let wanted = self.as_int(wanted);
  3257. let found = self.s.op(
  3258. pass,
  3259. "atomicCompareExchange.i32",
  3260. Attr::NoUnwind,
  3261. i32t,
  3262. 79,
  3263. &[h, byte, iu, iu, seen, wanted],
  3264. );
  3265. let one = self.s.m.i32(1);
  3266. let n1 = self.s.m.bin(pass, Bin::Add, n, one);
  3267. let lost = self.s.m.cmp(pass, pred::NE, found, seen);
  3268. let limit = self.s.m.i32(1 << 16);
  3269. let more = self.s.m.cmp(pass, pred::IULT, n1, limit);
  3270. let again = self.s.m.bin(pass, Bin::And, lost, more);
  3271. self.s.m.terminate(pass, Term::CondBr(again, pass, done));
  3272. let zero = self.s.m.i32(0);
  3273. self.s.m.set_phi(seen, vec![(first, head), (found, pass)]);
  3274. self.s.m.set_phi(n, vec![(zero, head), (n1, pass)]);
  3275. self.cur = done;
  3276. found
  3277. }
  3278. };
  3279. let was = self.end_guarded(at, &[(was, old)])[0];
  3280. if let Some(reg) = back {
  3281. self.write(inst, Reg::V(reg), was, None);
  3282. }
  3283. Ok(())
  3284. }
  3285. /// `s_load_dword*` from title memory by address (`resource::MEMORY`):
  3286. /// the SGPR pair plus the instruction's offsets.
  3287. fn memory_smem(&mut self, inst: &Inst) -> Result<(), Why> {
  3288. let Fields::Smem {
  3289. data: Some(Operand::Scalar { code, .. }),
  3290. base: Operand::Scalar { code: base, .. },
  3291. offset,
  3292. soffset,
  3293. ..
  3294. } = inst.fields
  3295. else {
  3296. return Err("a scalar load from memory");
  3297. };
  3298. let count = match inst.name().strip_prefix("s_load_dword") {
  3299. Some("") => 1u8,
  3300. Some("x2") => 2,
  3301. Some("x4") => 4,
  3302. Some("x8") => 8,
  3303. Some("x16") => 16,
  3304. _ => return Err("a scalar memory access by address"),
  3305. };
  3306. let word = |l: &mut Self, k: u8| -> Result<V, Why> {
  3307. let v = inst.read(Reg::S(base + k)).ok_or("an address not in SGPRs")?;
  3308. l.i32_of(v)
  3309. };
  3310. let (mut lo, mut hi) = (word(self, 0)?, word(self, 1)?);
  3311. let c = self.cur;
  3312. let (i32t, res) = (self.s.t.i32, self.s.t.res_ret);
  3313. if !matches!(soffset, Operand::Scalar { code: NULL, .. }) {
  3314. // An offset register counts up from the address.
  3315. let so = self.operand(inst, &soffset)?;
  3316. let sum = self.s.m.bin(c, Bin::Add, lo, so);
  3317. let carry = self.s.m.cmp(c, pred::IULT, sum, lo);
  3318. let carry = self.s.m.cast(c, Cast::ZExt, carry, i32t);
  3319. hi = self.s.m.bin(c, Bin::Add, hi, carry);
  3320. lo = sum;
  3321. }
  3322. let (iu, align) = (self.s.m.undef(i32t), self.s.m.i32(4));
  3323. for first in (0..count).step_by(4) {
  3324. let n = (count - first).min(4);
  3325. let (lo, hi) = self.address_plus(lo, hi, offset + 4 * i32::from(first));
  3326. let (h, byte) = self.memory(lo, hi, None, false);
  3327. let c = self.cur;
  3328. let mask = self.s.m.i8((1u8 << n) - 1);
  3329. let r = self.s.op(
  3330. c,
  3331. "rawBufferLoad.f32",
  3332. Attr::ReadOnly,
  3333. res,
  3334. 139,
  3335. &[h, byte, iu, mask, align],
  3336. );
  3337. for k in 0..n {
  3338. let x = self.s.m.extract(c, r, u32::from(k));
  3339. let x = self.as_int(x);
  3340. self.write(inst, Reg::S(code + first + k), x, None);
  3341. }
  3342. }
  3343. Ok(())
  3344. }
  3345. /// A dword of a lane mask as a number: the ballot of the lanes' bits,
  3346. /// taken in the block that writes the mask (see [`MaskData`]).
  3347. fn mask_dword(&mut self, v: Value) -> Result<V, Why> {
  3348. let (lo, high) = match self.x.st.highs.get(&v) {
  3349. Some(&lo) => (lo, true),
  3350. None => (v, false),
  3351. };
  3352. let &m = self.x.st.masks.get(&lo).ok_or(LANE_MASK)?;
  3353. // A mask that holds lanes outside EXEC where it is written (the complement of one,
  3354. // say) is the ballot of the lanes that are there: all of them, where two exchanging
  3355. // host waves know every lane runs that block.
  3356. let made = self.def_block.get(&lo).copied();
  3357. let whole = self.exchange.is_some() && !self.local && made.is_none_or(|b| self.all_lanes(b));
  3358. if !self.x.st.active.contains(&lo) && !whole {
  3359. if self.exchange.is_some() && !self.local {
  3360. need(made.unwrap_or(0));
  3361. }
  3362. return Err(MASK_ELSEWHERE);
  3363. }
  3364. let (x, y) = match self.ballots.get(&lo) {
  3365. Some(&xy) => xy,
  3366. None => {
  3367. let at = match self.def_block.get(&lo) {
  3368. // Program inputs (EXEC on entry).
  3369. None => self.s.entry,
  3370. Some(&b) if b == self.cur_ir => self.cur,
  3371. Some(&b) => self.tail[b].ok_or("a lane mask written after its use")?,
  3372. };
  3373. if !self.balloting.insert(lo) {
  3374. return Err("a lane mask whose lanes depend on its own value");
  3375. }
  3376. let bit = self.boolean(m, at);
  3377. self.balloting.remove(&lo);
  3378. let bit = bit?;
  3379. let i32t = self.s.t.i32;
  3380. let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]);
  3381. let r = self
  3382. .s
  3383. .op(at, "waveActiveBallot", Attr::NoUnwind, four, 116, &[bit]);
  3384. self.s.flags |= flags::WAVE_OPS;
  3385. let mut xy = (self.s.m.extract(at, r, 0), self.s.m.extract(at, r, 1));
  3386. if self.exchange.is_some() {
  3387. // a host wave's ballot is its half's 32 bits: the halves exchange them
  3388. let b = self.def_block.get(&lo).copied();
  3389. if self.local {
  3390. if !self.local_ok && !self.local_any {
  3391. return Err("a lane mask read as data in a half-wave");
  3392. }
  3393. } else if !self.exchange.as_ref().is_some_and(|e| e.1) && !b.is_none_or(|b| self.all_lanes(b)) {
  3394. // (a group of 32 or fewer has no other half to exchange with)
  3395. need(b.unwrap_or(0));
  3396. return Err("a lane mask exchanged where not every lane runs");
  3397. }
  3398. xy = self.exchange_halves(at, xy.0);
  3399. }
  3400. self.ballots.insert(lo, xy);
  3401. xy
  3402. }
  3403. };
  3404. Ok(if high { y } else { x })
  3405. }
  3406. // ---- operands ----
  3407. fn operand(&mut self, inst: &Inst, op: &Operand) -> Result<V, Why> {
  3408. match *op {
  3409. Operand::Scalar { code: NULL, .. } => Ok(self.s.m.i32(0)),
  3410. Operand::Scalar { code, .. } => {
  3411. let v = inst.read(Reg::S(code)).ok_or("an unread operand")?;
  3412. self.i32_of(v)
  3413. }
  3414. Operand::Vector { reg, .. } => {
  3415. let v = inst.read(Reg::V(reg)).ok_or("an unread operand")?;
  3416. self.i32_of(v)
  3417. }
  3418. // src_scc: SCC as 0 or 1 (VIctory upstream 0b35b7f, as the dot
  3419. // products and packed multiply-adds below).
  3420. Operand::Const(253) => {
  3421. let bit = self.scc_in(inst)?;
  3422. Ok(self.s.m.cast(self.cur, Cast::ZExt, bit, self.s.t.i32))
  3423. }
  3424. // Nothing to wait for (see `ordered_section`).
  3425. Operand::Const(POPS_EXITING) if !self.ordered.is_empty() => Ok(self.s.m.i32(0)),
  3426. Operand::Const(c) => crate::resource::inline(c)
  3427. .map(|x| self.s.m.i32(x))
  3428. .ok_or("a special operand (vccz, execz, scc, lds_direct)"),
  3429. Operand::Literal(x) => Ok(self.s.m.i32(x)),
  3430. Operand::Attr { .. } => Err("an attribute operand"),
  3431. }
  3432. }
  3433. /// An operand read as f16 data: GFX10 puts an inline f16 constant in
  3434. /// the low half of the operand (upstream PR #637, checked there against
  3435. /// the instruction encodings; the half-and-half reading taken from PR
  3436. /// #458 gave the high half the constant too).
  3437. fn f16_operand(&mut self, inst: &Inst, op: &Operand) -> Result<V, Why> {
  3438. match *op {
  3439. Operand::Const(c @ 240..=248) => Ok(self.s.m.i32(inline_f16(c))),
  3440. _ => self.operand(inst, op),
  3441. }
  3442. }
  3443. fn as_float(&mut self, x: V) -> V {
  3444. self.s.m.cast(self.cur, Cast::Bitcast, x, self.s.t.f32)
  3445. }
  3446. fn as_int(&mut self, f: V) -> V {
  3447. self.s.m.cast(self.cur, Cast::Bitcast, f, self.s.t.i32)
  3448. }
  3449. /// The SDWA operand selection of source `k`: a byte or word of the
  3450. /// dword, zero- or sign-extended (none: the whole dword).
  3451. fn sdwa_src(inst: &Inst, k: usize) -> Option<(u8, bool)> {
  3452. let Fields::Valu(v) = &inst.fields else {
  3453. return None;
  3454. };
  3455. let s = v.sdwa?;
  3456. let sel = *s.src_sel.get(k)?;
  3457. let sext = s.sext >> k & 1 != 0;
  3458. (sel < 6).then_some((sel, sext))
  3459. }
  3460. /// Bits `sel` (0-3 a byte, 4-5 a word) of `x`, extended.
  3461. fn select_bits(&mut self, x: V, sel: u8, sext: bool) -> V {
  3462. let c = self.cur;
  3463. let (width, at) = if sel < 4 {
  3464. (8, 8 * sel)
  3465. } else {
  3466. (16, 16 * (sel - 4))
  3467. };
  3468. let left = self.s.m.i32(u32::from(32 - width - at));
  3469. let t = self.s.m.bin(c, Bin::Shl, x, left);
  3470. let right = self.s.m.i32(32 - u32::from(width));
  3471. let op = if sext { Bin::AShr } else { Bin::LShr };
  3472. self.s.m.bin(c, op, t, right)
  3473. }
  3474. /// A float source with its abs/neg modifiers.
  3475. fn fsrc(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  3476. let Fields::Valu(v) = &inst.fields else {
  3477. unreachable!()
  3478. };
  3479. let op = *v.src.get(k).ok_or("a missing operand")?;
  3480. let selected = Self::sdwa_src(inst, k);
  3481. let mut f = match op {
  3482. _ if selected.is_some() => {
  3483. let (sel, sext) = selected.expect("checked");
  3484. let x = self.operand(inst, &op)?;
  3485. let x = self.select_bits(x, sel, sext);
  3486. self.as_float(x)
  3487. }
  3488. _ if k == 0 && self.src0.is_some() => {
  3489. let x = self.src0.expect("checked");
  3490. self.as_float(x)
  3491. }
  3492. Operand::Vector { reg, .. } | Operand::Scalar { code: reg, .. }
  3493. if !matches!(op, Operand::Scalar { code: NULL, .. }) =>
  3494. {
  3495. let r = if matches!(op, Operand::Vector { .. }) {
  3496. Reg::V(reg)
  3497. } else {
  3498. Reg::S(reg)
  3499. };
  3500. let val = inst.read(r).ok_or("an unread operand")?;
  3501. match self.floats.get(&val) {
  3502. Some(&f) => f,
  3503. None => {
  3504. let x = self.i32_of(val)?;
  3505. self.as_float(x)
  3506. }
  3507. }
  3508. }
  3509. _ => {
  3510. let x = self.operand(inst, &op)?;
  3511. self.as_float(x)
  3512. }
  3513. };
  3514. if v.abs >> k & 1 != 0 {
  3515. f = self.unary(6, f);
  3516. }
  3517. if v.neg >> k & 1 != 0 {
  3518. let z = self.s.m.f32(0x8000_0000);
  3519. f = self.s.m.bin(self.cur, Bin::Sub, z, f);
  3520. }
  3521. Ok(f)
  3522. }
  3523. fn src(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  3524. let Fields::Valu(v) = &inst.fields else {
  3525. unreachable!()
  3526. };
  3527. let op = *v.src.get(k).ok_or("a missing operand")?;
  3528. if v.abs >> k & 1 != 0 || v.neg >> k & 1 != 0 {
  3529. return Err("integer operand modifiers");
  3530. }
  3531. match self.src0 {
  3532. Some(x) if k == 0 => Ok(x),
  3533. _ => {
  3534. let x = self.operand(inst, &op)?;
  3535. Ok(match Self::sdwa_src(inst, k) {
  3536. Some((sel, sext)) => self.select_bits(x, sel, sext),
  3537. None => x,
  3538. })
  3539. }
  3540. }
  3541. }
  3542. fn unary(&mut self, op: u32, f: V) -> V {
  3543. self.s.op(
  3544. self.cur,
  3545. "unary.f32",
  3546. Attr::ReadNone,
  3547. self.s.t.f32,
  3548. op,
  3549. &[f],
  3550. )
  3551. }
  3552. fn binary(&mut self, op: u32, a: V, b: V) -> V {
  3553. self.s.op(
  3554. self.cur,
  3555. "binary.f32",
  3556. Attr::ReadNone,
  3557. self.s.t.f32,
  3558. op,
  3559. &[a, b],
  3560. )
  3561. }
  3562. /// The hardware's maximum (`max`) or minimum of two floats: as DXIL's
  3563. /// FMax/FMin, but -0 orders below +0 (RDNA2 ISA, `v_max_f32`), where
  3564. /// the compare and select DXIL specifies gives either zero.
  3565. fn max_min(&mut self, max: bool, a: V, b: V) -> V {
  3566. let c = self.cur;
  3567. let r = self.binary(if max { 35 } else { 36 }, a, b);
  3568. let (ia, ib) = (self.as_int(a), self.as_int(b));
  3569. let either = self.s.m.bin(c, Bin::Or, ia, ib);
  3570. let magnitude = self.s.m.i32(0x7FFF_FFFF);
  3571. let either = self.s.m.bin(c, Bin::And, either, magnitude);
  3572. let zero = self.s.m.i32(0);
  3573. let zeros = self.s.m.cmp(c, pred::EQ, either, zero);
  3574. // Of two zeros, +0 unless both are -0 (max), -0 unless neither (min).
  3575. let op = if max { Bin::And } else { Bin::Or };
  3576. let sign = self.s.m.bin(c, op, ia, ib);
  3577. let signed = self.as_float(sign);
  3578. self.s.m.select(c, zeros, signed, r)
  3579. }
  3580. fn fmad(&mut self, a: V, b: V, c: V) -> V {
  3581. self.s.op(
  3582. self.cur,
  3583. "tertiary.f32",
  3584. Attr::ReadNone,
  3585. self.s.t.f32,
  3586. 46,
  3587. &[a, b, c],
  3588. )
  3589. }
  3590. /// `f` as an f16 in the low bits, rounded toward zero: the nearest-even
  3591. /// conversion, one step back toward zero where it rounded away (which
  3592. /// also turns an overflow to infinity into the largest finite half).
  3593. fn f16_toward_zero(&mut self, f: V) -> V {
  3594. let c = self.cur;
  3595. let i32t = self.s.t.i32;
  3596. let h = self
  3597. .s
  3598. .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]);
  3599. let back = self
  3600. .s
  3601. .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[h]);
  3602. let (fa, ba) = (self.unary(6, f), self.unary(6, back));
  3603. // Ordered: never for NaN.
  3604. let away = self.s.m.cmp(c, pred::OGT, ba, fa);
  3605. let one = self.s.m.i32(1);
  3606. let stepped = self.s.m.bin(c, Bin::Sub, h, one);
  3607. self.s.m.select(c, away, stepped, h)
  3608. }
  3609. /// `f` as an f16 in the low bits, rounded to nearest, ties to even, as the console's
  3610. /// 16-bit float operations round, whatever the host's own conversion does: D3D lets
  3611. /// `f32tof16` round toward zero, and the NVIDIA driver's does (measured on an RTX 4070:
  3612. /// `wave64_tests`). The conversion toward zero, or the next half away from zero where
  3613. /// that one is nearer, or as near and the first one odd. Past the largest half the next
  3614. /// one counts as 2^16, the bound IEEE rounds by, so 65520 and up become infinity.
  3615. /// (`f` is an f32 result of two halves here; rounding it again to 16 bits gives the
  3616. /// rounding of the exact result, 24 bits being more than twice 11 and two.)
  3617. fn f16_nearest(&mut self, f: V) -> V {
  3618. let c = self.cur;
  3619. let f32t = self.s.t.f32;
  3620. let lo = self.f16_toward_zero(f);
  3621. let (one, zero) = (self.s.m.i32(1), self.s.m.i32(0));
  3622. let hi = self.s.m.bin(c, Bin::Add, lo, one);
  3623. let size = |l: &mut Self, h: V| {
  3624. let w = l.s.op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]);
  3625. l.unary(6, w)
  3626. };
  3627. let (below, above) = (size(self, lo), size(self, hi));
  3628. let (magnitude, infinity) = (self.s.m.i32(0x7FFF), self.s.m.i32(0x7C00));
  3629. let m = self.s.m.bin(c, Bin::And, hi, magnitude);
  3630. let top = self.s.m.cmp(c, pred::EQ, m, infinity);
  3631. let bound = self.s.m.f32(65536.0f32.to_bits());
  3632. let above = self.s.m.select(c, top, bound, above);
  3633. let fa = self.unary(6, f);
  3634. // (both differences are exact: the three values lie within one half's step)
  3635. let under = self.s.m.bin(c, Bin::Sub, fa, below);
  3636. let over = self.s.m.bin(c, Bin::Sub, above, fa);
  3637. // Ordered: never for NaN, which stays what the conversion made of it.
  3638. let nearer = self.s.m.cmp(c, pred::OLT, over, under);
  3639. let tie = self.s.m.cmp(c, pred::OEQ, over, under);
  3640. let odd = self.s.m.bin(c, Bin::And, lo, one);
  3641. let odd = self.s.m.cmp(c, pred::NE, odd, zero);
  3642. let tie = self.s.m.bin(c, Bin::And, tie, odd);
  3643. let up = self.s.m.bin(c, Bin::Or, nearer, tie);
  3644. self.s.m.select(c, up, hi, lo)
  3645. }
  3646. /// `(a >> off[4:0]) & ((1 << width) - 1)`, sign-extended from the field's
  3647. /// top bit when `signed`; widths from 32 on take every bit. A signed
  3648. /// field that runs past bit 31 extends from bit 31, as the hardware
  3649. /// does: the shift is arithmetic then.
  3650. fn bfe(&mut self, a: V, off: V, width: V, signed: bool) -> V {
  3651. let c = self.cur;
  3652. let (k31, k32, zero, one, ones) = (
  3653. self.s.m.i32(31),
  3654. self.s.m.i32(32),
  3655. self.s.m.i32(0),
  3656. self.s.m.i32(1),
  3657. self.s.m.i32(u32::MAX),
  3658. );
  3659. let off = self.s.m.bin(c, Bin::And, off, k31);
  3660. let shift = if signed { Bin::AShr } else { Bin::LShr };
  3661. let shifted = self.s.m.bin(c, shift, a, off);
  3662. let full = self.s.m.cmp(c, pred::IUGE, width, k32);
  3663. let w = self.s.m.bin(c, Bin::And, width, k31);
  3664. let mask = self.s.m.bin(c, Bin::Shl, one, w);
  3665. let mask = self.s.m.bin(c, Bin::Sub, mask, one);
  3666. let mask = self.s.m.select(c, full, ones, mask);
  3667. let r = self.s.m.bin(c, Bin::And, shifted, mask);
  3668. if !signed {
  3669. return r;
  3670. }
  3671. // Sign-extend a field narrower than 32 bits (none for width 0).
  3672. let left = self.s.m.bin(c, Bin::Sub, k32, w);
  3673. let left = self.s.m.bin(c, Bin::And, left, k31);
  3674. let t = self.s.m.bin(c, Bin::Shl, r, left);
  3675. let t = self.s.m.bin(c, Bin::AShr, t, left);
  3676. let is0 = self.s.m.cmp(c, pred::EQ, w, zero);
  3677. let keep = self.s.m.bin(c, Bin::Or, full, is0);
  3678. self.s.m.select(c, keep, r, t)
  3679. }
  3680. /// Whether an f32 value is NaN, tested in integer arithmetic so host
  3681. /// drivers (such as NVIDIA) do not fold `fcmp uno` away under fast-math.
  3682. fn is_nan_f32(&mut self, f: V) -> V {
  3683. let c = self.cur;
  3684. let bits = self.as_int(f);
  3685. let mask = self.s.m.i32(0x7FFF_FFFF);
  3686. let abs = self.s.m.bin(c, Bin::And, bits, mask);
  3687. let inf = self.s.m.i32(0x7F80_0000);
  3688. self.s.m.cmp(c, pred::IUGT, abs, inf)
  3689. }
  3690. /// The median of three. With a NaN among them the hardware gives the
  3691. /// minimum of the three instead (the host's minimum skips NaNs, so that
  3692. /// is the smallest number among them).
  3693. fn med3(&mut self, a: V, b: V, third: V) -> V {
  3694. let c = self.cur;
  3695. let lo = self.binary(36, a, b);
  3696. let hi = self.binary(35, a, b);
  3697. let t = self.binary(36, hi, third);
  3698. let median = self.binary(35, lo, t);
  3699. let least = self.binary(36, lo, third);
  3700. let nan_a = self.is_nan_f32(a);
  3701. let nan_b = self.is_nan_f32(b);
  3702. let nan_3 = self.is_nan_f32(third);
  3703. let nan_ab = self.s.m.bin(c, Bin::Or, nan_a, nan_b);
  3704. let nan = self.s.m.bin(c, Bin::Or, nan_ab, nan_3);
  3705. self.s.m.select(c, nan, least, median)
  3706. }
  3707. /// `a - floor(a)`, which on the hardware never reaches 1.0: where it
  3708. /// would round to it (a tiny negative `a`), the result is `below_one`,
  3709. /// the largest value under 1.0 in the operation's width. Hosts differ
  3710. /// here (some give 1.0). Comparing against a `threshold` distinct from
  3711. /// `below_one` prevents drivers (observed on NVIDIA) from folding
  3712. /// `r > k ? k : r` into `minNum` (`FMNMX`) and swallowing NaN.
  3713. fn fract(&mut self, a: V, threshold: f32, below_one: f32) -> V {
  3714. let c = self.cur;
  3715. let r = self.unary(22, a);
  3716. let limit = self.s.m.f32(threshold.to_bits());
  3717. let k = self.s.m.f32(below_one.to_bits());
  3718. let over = self.s.m.cmp(c, pred::OGE, r, limit);
  3719. self.s.m.select(c, over, k, r)
  3720. }
  3721. /// Sine, or cosine, of an angle in turns, as the hardware takes it. The
  3722. /// whole turns are taken off first (`x - round_even(x)`, exact, within
  3723. /// half a turn), so a large angle keeps its fraction; scaling to radians
  3724. /// first rounds it away. A zero passes unreduced (the sine of -0 is -0).
  3725. /// The sine of a half turn and the cosine of a quarter turn are exactly
  3726. /// +0 on the hardware, where the host's function of the rounded angle
  3727. /// gives about 1e-7. Infinities and NaN give NaN.
  3728. /// shortcut: below 2^-12 turns the hardware scales by a slightly
  3729. /// different constant than 2π (a last-place difference).
  3730. fn trig_turns(&mut self, x: V, cosine: bool) -> V {
  3731. let c = self.cur;
  3732. let zero = self.s.m.f32(0);
  3733. let whole = self.unary(26, x);
  3734. let part = self.s.m.bin(c, Bin::Sub, x, whole);
  3735. let is_zero = self.s.m.cmp(c, pred::OEQ, x, zero);
  3736. let part = self.s.m.select(c, is_zero, x, part);
  3737. let k = self.s.m.f32(TWO_PI.to_bits());
  3738. let angle = self.s.m.bin(c, Bin::Mul, part, k);
  3739. let r = self.unary(if cosine { 12 } else { 13 }, angle);
  3740. let at = if cosine { 0.25f32 } else { 0.5 };
  3741. let at = self.s.m.f32(at.to_bits());
  3742. let size = self.unary(6, part);
  3743. let exact = self.s.m.cmp(c, pred::OEQ, size, at);
  3744. self.s.m.select(c, exact, zero, r)
  3745. }
  3746. /// The high dword of a 32 × 32-bit product.
  3747. fn mul_hi(&mut self, a: V, b: V, signed: bool) -> V {
  3748. let c = self.cur;
  3749. let i64t = self.s.m.int(64);
  3750. let ext = if signed { Cast::SExt } else { Cast::ZExt };
  3751. let a = self.s.m.cast(c, ext, a, i64t);
  3752. let b = self.s.m.cast(c, ext, b, i64t);
  3753. let m = self.s.m.bin(c, Bin::Mul, a, b);
  3754. let k32 = self.s.m.int_const(i64t, 32);
  3755. let hi = self.s.m.bin(c, Bin::LShr, m, k32);
  3756. self.s.flags |= flags::INT64;
  3757. self.s.m.cast(c, Cast::Trunc, hi, self.s.t.i32)
  3758. }
  3759. /// `0 × anything = 0`, as in D3D9.
  3760. fn legacy_mul(&mut self, a: V, b: V) -> V {
  3761. let c = self.cur;
  3762. let m = self.s.m.bin(c, Bin::Mul, a, b);
  3763. let zero = self.s.m.f32(0);
  3764. let az = self.s.m.cmp(c, pred::OEQ, a, zero);
  3765. let bz = self.s.m.cmp(c, pred::OEQ, b, zero);
  3766. let z = self.s.m.bin(c, Bin::Or, az, bz);
  3767. self.s.m.select(c, z, zero, m)
  3768. }
  3769. // ---- lane booleans ----
  3770. fn boolean(&mut self, b: Bool, at: usize) -> Result<V, Why> {
  3771. if b == Bool::TRUE || b == Bool::FALSE {
  3772. return Ok(self.s.m.bool(b == Bool::TRUE));
  3773. }
  3774. if let Some(&v) = self.bools.get(&(at, b)) {
  3775. return Ok(v);
  3776. }
  3777. let (atom, lo, hi) = self.x.st.bools.node(b).expect("not a constant");
  3778. let a = self.atom(atom, at)?;
  3779. let m = &mut self.s.m;
  3780. let v = match (lo, hi) {
  3781. (Bool::FALSE, Bool::TRUE) => a,
  3782. (Bool::TRUE, Bool::FALSE) => {
  3783. let t = m.bool(true);
  3784. m.bin(at, Bin::Xor, a, t)
  3785. }
  3786. (Bool::FALSE, h) => {
  3787. let h = self.boolean(h, at)?;
  3788. self.s.m.bin(at, Bin::And, a, h)
  3789. }
  3790. (l, Bool::TRUE) => {
  3791. let l = self.boolean(l, at)?;
  3792. self.s.m.bin(at, Bin::Or, a, l)
  3793. }
  3794. (l, h) => {
  3795. let l = self.boolean(l, at)?;
  3796. let h = self.boolean(h, at)?;
  3797. self.s.m.select(at, a, h, l)
  3798. }
  3799. };
  3800. self.bools.insert((at, b), v);
  3801. Ok(v)
  3802. }
  3803. fn atom(&mut self, atom: Atom, at: usize) -> Result<V, Why> {
  3804. match atom {
  3805. Atom::Lane(v) => self.lane_bits.get(&v).copied().ok_or_else(|| {
  3806. self.lane_fail
  3807. .get(&v)
  3808. .copied()
  3809. .unwrap_or("a lane mask from a carry")
  3810. }),
  3811. Atom::Uniform(v) => match self.get(v)? {
  3812. Val::Bit(x) => Ok(x),
  3813. Val::I32(x) => {
  3814. let z = self.s.m.i32(0);
  3815. Ok(self.s.m.cmp(at, pred::NE, x, z))
  3816. }
  3817. Val::Missing(w) => Err(w),
  3818. },
  3819. Atom::Phi(id) => {
  3820. if let Some(&v) = self.mask_phis.get(&id) {
  3821. return Ok(v);
  3822. }
  3823. let &(b, i) = self
  3824. .phi_at
  3825. .get(&id)
  3826. .ok_or("a lane-mask join without a phi")?;
  3827. let blk = self.block[b].ok_or("an unreachable join")?;
  3828. let v = self.s.m.phi(blk, self.s.t.i1);
  3829. self.mask_phis.insert(id, v);
  3830. self.pending_masks.push((v, b, i));
  3831. Ok(v)
  3832. }
  3833. // shortcut: "some lane of the quad is set" is taken as true: the
  3834. // lanes it adds only feed derivatives, and exports keep their own
  3835. // masks. Wrong if such a section had a side effect.
  3836. Atom::Quad(_) => Ok(self.s.m.bool(true)),
  3837. // With console lanes, a mask held as a number is the console's:
  3838. // the lane tests its own bit.
  3839. Atom::Opaque(v) if self.console_lanes => {
  3840. let hi = match self.pair_high(v) {
  3841. Some(h) => Some(self.get(h)?),
  3842. None => None,
  3843. };
  3844. let lo = self.get(v)?;
  3845. let word = |w: Val| match w {
  3846. Val::I32(x) => Ok(x),
  3847. _ => Err("an opaque lane mask"),
  3848. };
  3849. let lo = word(lo)?;
  3850. let hi = hi.map(word).transpose()?;
  3851. Ok(self.lane_bit(at, lo, hi))
  3852. }
  3853. Atom::Constant(k) if self.console_lanes => {
  3854. let lo = self.s.m.i32(k as u32);
  3855. let hi = self.s.m.i32((k >> 32) as u32);
  3856. Ok(self.lane_bit(at, lo, Some(hi)))
  3857. }
  3858. Atom::Opaque(_) => Err("an opaque lane mask"),
  3859. Atom::Constant(_) => Err("a constant lane mask"),
  3860. }
  3861. }
  3862. /// A console wave64 program in host waves of 32: the first console thread of this host wave
  3863. /// (0, 32, 64, ...). A GPU need not give a host wave consecutive thread indices (NVIDIA's
  3864. /// 8 x 8 groups), so each wave takes the next 32 from an LDS counter instead: every thread
  3865. /// zeroes it, the group meets, each wave's first lane adds 32 and the wave takes what it
  3866. /// found. Branch-free, in the entry block, which every thread runs.
  3867. fn wave_base(&mut self) -> Option<V> {
  3868. let slot = self.halves?;
  3869. if let Some(v) = self.wave_base {
  3870. return Some(v);
  3871. }
  3872. let (e, i32t) = (self.s.entry, self.s.t.i32);
  3873. let lds = self.s.lds();
  3874. let k = self.s.m.i32(slot);
  3875. let ptr = self.s.m.element(e, lds, k);
  3876. let zero = self.s.m.i32(0);
  3877. self.s.m.store(e, ptr, zero);
  3878. self.group_sync(e);
  3879. let lane = self.s.op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
  3880. let first = self.s.m.cmp(e, pred::EQ, lane, zero);
  3881. let k32 = self.s.m.i32(32);
  3882. let add = self.s.m.select(e, first, k32, zero);
  3883. let ptr = self.s.m.element(e, lds, k);
  3884. let old = self.s.m.atomic(e, Rmw::Add, ptr, add);
  3885. let base = self.s.op(e, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[old]);
  3886. self.s.flags |= flags::WAVE_OPS;
  3887. self.wave_base = Some(base);
  3888. Some(base)
  3889. }
  3890. /// The console thread index of this thread in the group: `wave_base` plus the host lane
  3891. /// (host waves of 32), else the wave's first thread index rounded down plus the lane.
  3892. fn console_thread(&mut self) -> V {
  3893. let (e, i32t) = (self.s.entry, self.s.t.i32);
  3894. let lane = self.s.op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
  3895. if let Some(base) = self.wave_base() {
  3896. return self.s.m.bin(e, Bin::Add, base, lane);
  3897. }
  3898. let flat = self.s.op(e, "flattenedThreadIdInGroup.i32", Attr::ReadNone, i32t, 96, &[]);
  3899. let first = self.s.op(e, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[flat]);
  3900. let wave = self.s.wave_size.unwrap_or(32);
  3901. let mask = self.s.m.i32(!(wave - 1));
  3902. let base = self.s.m.bin(e, Bin::And, first, mask);
  3903. self.s.m.bin(e, Bin::Add, base, lane)
  3904. }
  3905. /// This thread's console lane (0..63): its relabelled thread index (`thread_id`), whose host
  3906. /// wave holds a 32-aligned run of console lanes. Without `exchange`: the host lane.
  3907. fn console_lane(&mut self) -> V {
  3908. if self.exchange.is_none() {
  3909. return self.lane_index();
  3910. }
  3911. if let Some(v) = self.clane {
  3912. return v;
  3913. }
  3914. let (e, i32t) = (self.s.entry, self.s.t.i32);
  3915. let f = self.console_thread();
  3916. let _ = i32t;
  3917. let k63 = self.s.m.i32(63);
  3918. let cl = self.s.m.bin(e, Bin::And, f, k63);
  3919. self.s.flags |= flags::WAVE_OPS;
  3920. self.clane = Some(cl);
  3921. cl
  3922. }
  3923. /// A group barrier with an LDS fence in `block`.
  3924. fn group_sync(&mut self, block: usize) {
  3925. let mode = self.s.m.i32(meeting_mode());
  3926. let void = self.s.t.void;
  3927. self.s.op(block, "barrier", Attr::NoDuplicate, void, 80, &[mode]);
  3928. }
  3929. /// `exchange`: each host wave gives `mine` (the same in all its lanes) for its half; both get
  3930. /// (lower half's, upper half's). A group with no upper half gets 0 for it.
  3931. fn exchange_halves(&mut self, at: usize, mine: V) -> (V, V) {
  3932. let Some((slot, small, _)) = self.exchange.as_ref().map(|(a, b, _)| (*a, *b, ())) else {
  3933. let z = self.s.m.i32(0);
  3934. return (mine, z);
  3935. };
  3936. if small {
  3937. let z = self.s.m.i32(0);
  3938. return (mine, z);
  3939. }
  3940. if self.local {
  3941. // each host wave on its own: its half holds `mine`, the other nothing
  3942. let cl = self.console_lane();
  3943. let (k32, z) = (self.s.m.i32(32), self.s.m.i32(0));
  3944. let upper = self.s.m.cmp(at, pred::IUGE, cl, k32);
  3945. let lo = self.s.m.select(at, upper, z, mine);
  3946. let hi = self.s.m.select(at, upper, mine, z);
  3947. return (lo, hi);
  3948. }
  3949. // the pair of dwords of this thread's console wave: its half's, then both
  3950. let pair = self.exchange_pair(slot);
  3951. let cl = self.console_lane();
  3952. let five = self.s.m.i32(5);
  3953. let half = self.s.m.bin(at, Bin::LShr, cl, five);
  3954. let index = self.s.m.bin(at, Bin::Add, pair, half);
  3955. let lds = self.s.lds();
  3956. let ptr = self.s.m.element(at, lds, index);
  3957. self.s.m.store(at, ptr, mine);
  3958. self.group_sync(at);
  3959. let one = self.s.m.i32(1);
  3960. let k1 = self.s.m.bin(at, Bin::Add, pair, one);
  3961. let p0 = self.s.m.element(at, lds, pair);
  3962. let p1 = self.s.m.element(at, lds, k1);
  3963. let lo = self.s.m.load(at, p0);
  3964. let hi = self.s.m.load(at, p1);
  3965. // the slots are written again only after every thread read them
  3966. self.group_sync(at);
  3967. (lo, hi)
  3968. }
  3969. /// The first of the two exchange dwords of this thread's console wave (made in the entry
  3970. /// block): a group of several console waves has a pair for each.
  3971. fn exchange_pair(&mut self, slot: u32) -> V {
  3972. if let Some(v) = self.pair {
  3973. return v;
  3974. }
  3975. let e = self.s.entry;
  3976. let thread = self.console_thread();
  3977. let six = self.s.m.i32(6);
  3978. let wave = self.s.m.bin(e, Bin::LShr, thread, six);
  3979. let one = self.s.m.i32(1);
  3980. let twice = self.s.m.bin(e, Bin::Shl, wave, one);
  3981. let base = self.s.m.i32(slot);
  3982. let v = self.s.m.bin(e, Bin::Add, base, twice);
  3983. self.pair = Some(v);
  3984. v
  3985. }
  3986. /// The console's decision of the branch closing IR block `b`, which the wave takes
  3987. /// together ([`Structured::wide`]): `when` is the lane's own bit, and the branch is taken
  3988. /// when some lane's `when` holds (`execnz`, `vccnz`, SCC of a mask operation set) or
  3989. /// when every lane's does (`execz`, `vccz`, that SCC clear), [`Structured::wave_any`].
  3990. /// Each host wave asks its lanes and the halves exchange the answers, so both go the
  3991. /// same way and can meet again inside the branch.
  3992. /// SCC of a mask operation as data ([`Structured::scc_some`]): whether some lane of the
  3993. /// console wave has its bit of the result, asked where the operation stands. The lanes
  3994. /// that are elsewhere have no bit (the result is ANDed with EXEC or is EXEC), so with
  3995. /// the console's waves the host wave's answer is the console's; two host waves of 32
  3996. /// exchange theirs, which needs every lane there.
  3997. fn scc_some(&mut self, scc: Value) -> Result<V, Why> {
  3998. let &m = self.x.st.scc_some.get(&scc).ok_or(LANE_MASK)?;
  3999. // (not for a console wave cut into host waves that do not exchange)
  4000. if !self.console_lanes || self.local || self.exchange.is_none() && self.halves.is_some() {
  4001. return Err(LANE_MASK);
  4002. }
  4003. let made = self.def_block.get(&scc).copied();
  4004. let at = match made {
  4005. None => self.s.entry,
  4006. Some(b) if b == self.cur_ir => self.cur,
  4007. Some(b) => self.tail[b].ok_or("a lane mask written after its use")?,
  4008. };
  4009. let bit = self.boolean(m, at)?;
  4010. let (i1t, i32t) = (self.s.t.i1, self.s.t.i32);
  4011. let some = self.s.op(at, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[bit]);
  4012. self.s.flags |= flags::WAVE_OPS;
  4013. if !self.exchange.as_ref().is_some_and(|e| !e.1) {
  4014. return Ok(some);
  4015. }
  4016. if !made.is_none_or(|b| self.all_lanes(b)) {
  4017. need(made.unwrap_or(0));
  4018. return Err("a lane mask exchanged where not every lane runs");
  4019. }
  4020. let some = self.s.m.cast(at, Cast::ZExt, some, i32t);
  4021. let (lo, hi) = self.exchange_halves(at, some);
  4022. let both = self.s.m.bin(at, Bin::Or, lo, hi);
  4023. let z = self.s.m.i32(0);
  4024. Ok(self.s.m.cmp(at, pred::NE, both, z))
  4025. }
  4026. fn wave_wide(&mut self, b: usize, when: Bool) -> Result<V, Why> {
  4027. const WHY: Why = "a wave-wide branch where not every lane runs";
  4028. let any = self.x.st.wave_any.get(b).copied().flatten().ok_or("a wave-wide branch on a scalar condition")?;
  4029. if self.exchange.is_none() && self.halves.is_none() && self.console_lanes && self.mask_data == MaskData::Console {
  4030. // The host's waves are the console's: the wave's own answer. The lanes that are
  4031. // elsewhere have no bit set, as on the console, so "some lane" needs no one but
  4032. // the lanes here, and "every lane's bit is clear" is true of the others anyway.
  4033. let c = self.cur;
  4034. let mine = self.boolean(when, c)?;
  4035. let i1t = self.s.t.i1;
  4036. self.s.flags |= flags::WAVE_OPS;
  4037. let (name, code) = if any { ("waveAnyTrue", 113) } else { ("waveAllTrue", 114) };
  4038. return Ok(self.s.op(c, name, Attr::NoUnwind, i1t, code, &[mine]));
  4039. }
  4040. if self.local || !self.exchange.as_ref().is_some_and(|e| !e.1) {
  4041. return Err(WHY);
  4042. }
  4043. if !self.all_lanes(b) {
  4044. need(b);
  4045. return Err(WHY);
  4046. }
  4047. let c = self.cur;
  4048. let mine = self.boolean(when, c)?;
  4049. // what the halves exchange is "some lane speaks against" either way (for `any`:
  4050. // some lane's `when` holds; else: some lane's does not), so a half with no lane says
  4051. // nothing
  4052. let set = if any {
  4053. mine
  4054. } else {
  4055. let t = self.s.m.bool(true);
  4056. self.s.m.bin(c, Bin::Xor, mine, t)
  4057. };
  4058. let (i1t, i32t) = (self.s.t.i1, self.s.t.i32);
  4059. let some = self.s.op(c, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[set]);
  4060. self.s.flags |= flags::WAVE_OPS;
  4061. let some = self.s.m.cast(c, Cast::ZExt, some, i32t);
  4062. let (lo, hi) = self.exchange_halves(c, some);
  4063. let c = self.cur;
  4064. let both = self.s.m.bin(c, Bin::Or, lo, hi);
  4065. let z = self.s.m.i32(0);
  4066. Ok(self.s.m.cmp(c, if any { pred::NE } else { pred::EQ }, both, z))
  4067. }
  4068. /// Whether every lane runs IR block `b` (always true without `exchange`).
  4069. fn all_lanes(&self, b: usize) -> bool {
  4070. self.exchange.as_ref().is_none_or(|(_, _, all)| all.get(b).copied().unwrap_or(false))
  4071. }
  4072. /// This lane's bit of the mask `lo`, `hi` (wave64).
  4073. fn lane_bit(&mut self, at: usize, lo: V, hi: Option<V>) -> V {
  4074. self.s.flags |= flags::WAVE_OPS;
  4075. let lane = if self.exchange.is_some() {
  4076. self.console_lane()
  4077. } else {
  4078. self.s.op(at, "waveGetLaneIndex", Attr::ReadOnly, self.s.t.i32, 111, &[])
  4079. };
  4080. let (k31, k32, one, z) = (
  4081. self.s.m.i32(31),
  4082. self.s.m.i32(32),
  4083. self.s.m.i32(1),
  4084. self.s.m.i32(0),
  4085. );
  4086. let word = match hi {
  4087. Some(hi) => {
  4088. let low = self.s.m.cmp(at, pred::IULT, lane, k32);
  4089. self.s.m.select(at, low, lo, hi)
  4090. }
  4091. None => lo,
  4092. };
  4093. let sh = self.s.m.bin(at, Bin::And, lane, k31);
  4094. let t = self.s.m.bin(at, Bin::LShr, word, sh);
  4095. let t = self.s.m.bin(at, Bin::And, t, one);
  4096. self.s.m.cmp(at, pred::NE, t, z)
  4097. }
  4098. /// The value of the high dword of the wave64 register pair whose low
  4099. /// dword holds `lo` (none in wave32).
  4100. fn pair_high(&self, lo: Value) -> Option<Value> {
  4101. if !self.x.native.wave64 {
  4102. return None;
  4103. }
  4104. let p = self.x.p;
  4105. let pick = |reg: Reg| match reg {
  4106. Reg::S(c) => Some(Reg::S(c + 1)),
  4107. _ => None,
  4108. };
  4109. if let Some(&(reg, _)) = p.inputs.iter().find(|i| i.1 == lo) {
  4110. let h = pick(reg)?;
  4111. return p.inputs.iter().find(|i| i.0 == h).map(|i| i.1);
  4112. }
  4113. if let Some(&(b, i)) = self.phi_at.get(&lo) {
  4114. let h = pick(p.blocks[b].phis[i].reg)?;
  4115. return p.blocks[b]
  4116. .phis
  4117. .iter()
  4118. .find(|q| q.reg == h)
  4119. .map(|q| q.value);
  4120. }
  4121. let b = *self.def_block.get(&lo)?;
  4122. let inst = p.blocks[b]
  4123. .insts
  4124. .iter()
  4125. .find(|i| i.writes.iter().any(|w| w.1 == lo))?;
  4126. let &(reg, _) = inst.writes.iter().find(|w| w.1 == lo)?;
  4127. inst.write(pick(reg)?)
  4128. }
  4129. fn guard(&mut self, b: usize, i: usize) -> Result<Option<V>, Why> {
  4130. match self.x.st.guards[b][i] {
  4131. None => Ok(None),
  4132. Some(g) => Ok(Some(self.boolean(g, self.cur)?)),
  4133. }
  4134. }
  4135. // ---- results ----
  4136. fn set(&mut self, v: Option<Value>, val: Val) {
  4137. if let Some(v) = v {
  4138. self.vals.insert(v, val);
  4139. }
  4140. }
  4141. /// Writes VGPR `reg` (or the SGPR of a lane read), under `guard`.
  4142. fn write(&mut self, inst: &Inst, reg: Reg, x: V, guard: Option<V>) {
  4143. let x = match (Self::sdwa_dst(inst), reg) {
  4144. (Some((sel, unused)), Reg::V(_)) => self.place_bits(inst, reg, x, sel, unused),
  4145. _ => x,
  4146. };
  4147. self.write_placed(inst, reg, x, guard);
  4148. }
  4149. /// [`Self::write`] of a dword already placed (SDWA applied).
  4150. fn write_placed(&mut self, inst: &Inst, reg: Reg, x: V, guard: Option<V>) {
  4151. let Some(new) = inst.write(reg) else { return };
  4152. let x = match (guard, reg) {
  4153. (Some(g), Reg::V(_)) => {
  4154. let old = match inst.read(reg).map(|o| self.i32_of(o)) {
  4155. Some(Ok(o)) => o,
  4156. // The validator refuses reads of undef.
  4157. _ => self.s.m.i32(0),
  4158. };
  4159. let v = self.s.m.select(self.cur, g, x, old);
  4160. self.s.m.tag(v, Tag::Guard);
  4161. v
  4162. }
  4163. _ => x,
  4164. };
  4165. self.vals.insert(new, Val::I32(x));
  4166. }
  4167. /// The SDWA destination selection: a byte or word, and what the other
  4168. /// bits get (0 zeros, 1 the sign above the field, 2 the old bits).
  4169. fn sdwa_dst(inst: &Inst) -> Option<(u8, u8)> {
  4170. let Fields::Valu(v) = &inst.fields else {
  4171. return None;
  4172. };
  4173. let s = v.sdwa?;
  4174. (s.dst_sel < 6).then_some((s.dst_sel, s.dst_unused))
  4175. }
  4176. /// The low byte or word of `x` placed at `sel` in VGPR `reg`.
  4177. fn place_bits(&mut self, inst: &Inst, reg: Reg, x: V, sel: u8, unused: u8) -> V {
  4178. let c = self.cur;
  4179. let (width, at) = if sel < 4 {
  4180. (8u32, 8 * u32::from(sel))
  4181. } else {
  4182. (16, 16 * u32::from(sel - 4))
  4183. };
  4184. let left = self.s.m.i32(32 - width);
  4185. let t = self.s.m.bin(c, Bin::Shl, x, left);
  4186. let right = self.s.m.i32(32 - width - at);
  4187. if unused == 1 {
  4188. // Bits below the field shift in as zeros.
  4189. return self.s.m.bin(c, Bin::AShr, t, right);
  4190. }
  4191. let field = self.s.m.bin(c, Bin::LShr, t, right);
  4192. if unused != 2 {
  4193. return field;
  4194. }
  4195. let old = match inst.read(reg).map(|o| self.i32_of(o)) {
  4196. Some(Ok(o)) => o,
  4197. _ => self.s.m.i32(0),
  4198. };
  4199. let keep = self.s.m.i32(!((((1u64 << width) - 1) as u32) << at));
  4200. let old = self.s.m.bin(c, Bin::And, old, keep);
  4201. self.s.m.bin(c, Bin::Or, old, field)
  4202. }
  4203. fn write_f(&mut self, inst: &Inst, f: V, guard: Option<V>) -> Result<(), Why> {
  4204. let Fields::Valu(v) = &inst.fields else {
  4205. unreachable!()
  4206. };
  4207. let mut f = f;
  4208. match v.omod {
  4209. 0 => {}
  4210. k => {
  4211. let factor = [1.0f32, 2.0, 4.0, 0.5][usize::from(k)];
  4212. let c = self.s.m.f32(factor.to_bits());
  4213. f = self.s.m.bin(self.cur, Bin::Mul, f, c);
  4214. }
  4215. }
  4216. if v.clamp {
  4217. f = self.unary(7, f);
  4218. }
  4219. let Some(Operand::Vector { reg, .. }) = v.dst else {
  4220. return Err("a float result outside a VGPR");
  4221. };
  4222. let x = self.as_int(f);
  4223. self.write(inst, Reg::V(reg), x, guard);
  4224. if guard.is_none()
  4225. && Self::sdwa_dst(inst).is_none()
  4226. && let Some(new) = inst.write(Reg::V(reg))
  4227. {
  4228. self.floats.insert(new, f);
  4229. }
  4230. Ok(())
  4231. }
  4232. fn write_i(&mut self, inst: &Inst, x: V, guard: Option<V>) -> Result<(), Why> {
  4233. let Fields::Valu(v) = &inst.fields else {
  4234. unreachable!()
  4235. };
  4236. if v.clamp || v.omod != 0 {
  4237. return Err("integer output modifiers");
  4238. }
  4239. match v.dst {
  4240. Some(Operand::Vector { reg, .. }) => self.write(inst, Reg::V(reg), x, guard),
  4241. Some(Operand::Scalar { code, .. }) => self.write(inst, Reg::S(code), x, None),
  4242. _ => return Err("a result without a register"),
  4243. }
  4244. Ok(())
  4245. }
  4246. /// Starts code only the lanes where `guard` holds run (a store under a
  4247. /// lane guard): returns where it started and the join block.
  4248. fn begin_guarded(&mut self, guard: Option<V>) -> Option<(usize, usize)> {
  4249. let g = guard?;
  4250. let (then, join) = (self.s.m.new_block(), self.s.m.new_block());
  4251. self.s.m.terminate(self.cur, Term::CondBr(g, then, join));
  4252. let head = self.cur;
  4253. self.cur = then;
  4254. Some((head, join))
  4255. }
  4256. /// Ends guarded code; each (value inside, value outside) becomes a phi.
  4257. fn end_guarded(&mut self, at: Option<(usize, usize)>, values: &[(V, V)]) -> Vec<V> {
  4258. let Some((head, join)) = at else {
  4259. return values.iter().map(|v| v.0).collect();
  4260. };
  4261. let then = self.cur;
  4262. self.s.m.terminate(then, Term::Br(join));
  4263. self.cur = join;
  4264. values
  4265. .iter()
  4266. .map(|&(inside, outside)| {
  4267. let ty = self.s.m.type_of(inside);
  4268. let phi = self.s.m.phi(join, ty);
  4269. self.s.m.set_phi(phi, vec![(inside, then), (outside, head)]);
  4270. phi
  4271. })
  4272. .collect()
  4273. }
  4274. /// Code that depends on the lane layout: wave operations, and in compute
  4275. /// the console's wave size (lanes are thread ids in group order there).
  4276. /// Pixel lanes match only within a quad.
  4277. fn cross_lane(&mut self, quad: bool) -> Result<(), Why> {
  4278. if self.s.mesh.is_some() {
  4279. // shortcut: no wave size for mesh shaders in SM 6.6, so host
  4280. // lanes cannot follow the console's; emulate through group-shared
  4281. // memory if mesh programs turn out to need these.
  4282. return Err("a cross-lane operation in a mesh shader");
  4283. }
  4284. if self.s.threads.is_none() && !(quad && self.s.pixel) {
  4285. return Err("a cross-lane operation outside compute");
  4286. }
  4287. debug_assert!(self.s.threads.is_none() || self.console_lanes);
  4288. self.s.flags |= flags::WAVE_OPS;
  4289. Ok(())
  4290. }
  4291. /// Component `c` of the thread id in the group. With console lanes, the
  4292. /// thread is relabelled so that its host lane is its console lane: the
  4293. /// flat id is the wave's first lane's, rounded down to the wave size,
  4294. /// plus the lane index. (A bijection while each host wave holds a
  4295. /// wave-aligned run of flat ids, as the console's waves do.)
  4296. fn thread_id(&mut self, c: u8) -> Val {
  4297. if !self.console_lanes {
  4298. return self.compute_id("threadIdInGroup.i32", 95, c);
  4299. }
  4300. let [x, y, _] = self.s.threads.expect("compute");
  4301. let e = self.s.entry;
  4302. let i32t = self.s.t.i32;
  4303. if self.halves.is_some() {
  4304. let f = self.console_thread();
  4305. self.s.flags |= flags::WAVE_OPS;
  4306. let (xk, yk, xy) = (self.s.m.i32(x), self.s.m.i32(y), self.s.m.i32(x * y));
  4307. return Val::I32(match c {
  4308. 0 => self.s.m.bin(e, Bin::URem, f, xk),
  4309. 1 => {
  4310. let t = self.s.m.bin(e, Bin::UDiv, f, xk);
  4311. self.s.m.bin(e, Bin::URem, t, yk)
  4312. }
  4313. _ => self.s.m.bin(e, Bin::UDiv, f, xy),
  4314. });
  4315. }
  4316. let flat = self.s.op(
  4317. e,
  4318. "flattenedThreadIdInGroup.i32",
  4319. Attr::ReadNone,
  4320. i32t,
  4321. 96,
  4322. &[],
  4323. );
  4324. let first = self.s.op(
  4325. e,
  4326. "waveReadLaneFirst.i32",
  4327. Attr::NoUnwind,
  4328. i32t,
  4329. 118,
  4330. &[flat],
  4331. );
  4332. let wave = self.s.wave_size.expect("set with console lanes");
  4333. let mask = self.s.m.i32(!(wave - 1));
  4334. let base = self.s.m.bin(e, Bin::And, first, mask);
  4335. let lane = self.lane_index();
  4336. let f = self.s.m.bin(e, Bin::Add, base, lane);
  4337. self.s.flags |= flags::WAVE_OPS;
  4338. let (xk, yk, xy) = (self.s.m.i32(x), self.s.m.i32(y), self.s.m.i32(x * y));
  4339. Val::I32(match c {
  4340. 0 => self.s.m.bin(e, Bin::URem, f, xk),
  4341. 1 => {
  4342. let t = self.s.m.bin(e, Bin::UDiv, f, xk);
  4343. self.s.m.bin(e, Bin::URem, t, yk)
  4344. }
  4345. _ => self.s.m.bin(e, Bin::UDiv, f, xy),
  4346. })
  4347. }
  4348. /// Mesh: the counts and the primitives no lane exports. The console's
  4349. /// counts come from one lane's allocation request, which DXIL cannot
  4350. /// express (one call, dominating every output write).
  4351. // shortcut: the counts are the declared maxima and each lane first culls
  4352. // its primitive (all indices 0, zero area), so primitives past the
  4353. // program's count are culled and vertices past it unused; this costs
  4354. // the host the unused vertex and primitive slots. Pass the program's own
  4355. // counts if that shows in frame time.
  4356. fn mesh_prologue(&mut self, mut mesh: super::shader::Mesh) -> Result<(), Why> {
  4357. let threads = self.s.threads.expect("mesh")[0];
  4358. if mesh.topology != 2 {
  4359. return Err("a mesh shader not drawing triangles");
  4360. }
  4361. if threads > 128 || mesh.max_vertices > 256 || mesh.max_primitives > 256 {
  4362. return Err("a mesh shader beyond the host's limits");
  4363. }
  4364. // D3D12 caps the outputs of the declared maxima at 32 KiB. Lane n
  4365. // writes only vertex n and primitive n, so maxima past the lanes are
  4366. // never reached: they come down to the lane count when the outputs
  4367. // do not fit.
  4368. use super::container::{MESH_OUTPUT_LIMIT, mesh_output_bytes};
  4369. let (outputs, prims) = (&self.s.outputs, &self.s.prims);
  4370. let fits = |m: super::shader::Mesh| {
  4371. mesh_output_bytes(outputs, prims, m.max_vertices, m.max_primitives) <= MESH_OUTPUT_LIMIT
  4372. };
  4373. if !fits(mesh) {
  4374. mesh.max_vertices = mesh.max_vertices.min(threads);
  4375. mesh.max_primitives = mesh.max_primitives.min(threads);
  4376. // shortcut: outputs past the cap even at the lane count are
  4377. // still emitted with the lower maxima (drivers take them);
  4378. // refuse them here if one hangs.
  4379. // Experiment (`VICTORY_MESH_OUTPUT_STRICT=1`): they are refused.
  4380. if !fits(mesh) && std::env::var_os("VICTORY_MESH_OUTPUT_STRICT").is_some() {
  4381. return Err("a mesh shader whose outputs pass the host's 32 KiB");
  4382. }
  4383. self.s.mesh = Some(mesh);
  4384. }
  4385. let e = self.s.entry;
  4386. let void = self.s.t.void;
  4387. let (v, p) = (
  4388. self.s.m.i32(mesh.max_vertices),
  4389. self.s.m.i32(mesh.max_primitives),
  4390. );
  4391. self.s
  4392. .op(e, "setMeshOutputCounts", Attr::NoUnwind, void, 168, &[v, p]);
  4393. let flat = self.mesh_thread();
  4394. let z = self.s.m.i32(0);
  4395. // Every primitive of the declared count starts culled, also those
  4396. // past the lanes (a count of 256 with 128 lanes): lane n culls
  4397. // primitives n, n + lanes, ... The host draws all it was promised,
  4398. // and one never written has whatever indices its memory held: long
  4399. // triangles over the whole target, each pixel of them shaded.
  4400. let passes = mesh.max_primitives.div_ceil(threads.max(1));
  4401. for pass in 0..passes {
  4402. let index = if pass == 0 {
  4403. flat
  4404. } else {
  4405. let past = self.s.m.i32(pass * threads);
  4406. self.s.m.bin(self.cur, Bin::Add, flat, past)
  4407. };
  4408. let guard = ((pass + 1) * threads > mesh.max_primitives)
  4409. .then(|| self.s.m.cmp(self.cur, pred::IULT, index, p));
  4410. let at = self.begin_guarded(guard);
  4411. self.s.op(
  4412. self.cur,
  4413. "emitIndices",
  4414. Attr::NoUnwind,
  4415. void,
  4416. 169,
  4417. &[index, z, z, z],
  4418. );
  4419. self.end_guarded(at, &[]);
  4420. }
  4421. Ok(())
  4422. }
  4423. /// Mesh: the thread's index in the group, which is its vertex and
  4424. /// primitive index.
  4425. fn mesh_thread(&mut self) -> V {
  4426. if let Some(f) = self.flat {
  4427. return f;
  4428. }
  4429. let e = self.s.entry;
  4430. let f = self.s.op(
  4431. e,
  4432. "flattenedThreadIdInGroup.i32",
  4433. Attr::ReadNone,
  4434. self.s.t.i32,
  4435. 96,
  4436. &[],
  4437. );
  4438. self.flat = Some(f);
  4439. f
  4440. }
  4441. /// The console wave size.
  4442. fn wave(&self) -> u32 {
  4443. if self.x.native.wave64 { 64 } else { 32 }
  4444. }
  4445. fn lane_index(&mut self) -> V {
  4446. if self.s.mesh.is_some() {
  4447. // The console's lane: mesh code reads no other lanes, so host
  4448. // waves need not match the console's.
  4449. let f = self.mesh_thread();
  4450. let m = self.s.m.i32(self.wave() - 1);
  4451. return self.s.m.bin(self.s.entry, Bin::And, f, m);
  4452. }
  4453. self.s.op(
  4454. self.cur,
  4455. "waveGetLaneIndex",
  4456. Attr::ReadOnly,
  4457. self.s.t.i32,
  4458. 111,
  4459. &[],
  4460. )
  4461. }
  4462. /// `x` of lane `src` (in this lane's quad) through quad reads, whose
  4463. /// lane must be a constant.
  4464. fn quad_pick(&mut self, x: V, src: V) -> V {
  4465. self.s.flags |= flags::WAVE_OPS;
  4466. let c = self.cur;
  4467. let three = self.s.m.i32(3);
  4468. let q = self.s.m.bin(c, Bin::And, src, three);
  4469. let mut r = x;
  4470. for n in 0..4 {
  4471. let kn = self.s.m.i32(n);
  4472. let read = self.s.op(
  4473. c,
  4474. "quadReadLaneAt.i32",
  4475. Attr::NoUnwind,
  4476. self.s.t.i32,
  4477. 122,
  4478. &[x, kn],
  4479. );
  4480. let is = self.s.m.cmp(c, pred::EQ, q, kn);
  4481. r = self.s.m.select(c, is, read, r);
  4482. }
  4483. r
  4484. }
  4485. /// Whether a quad-local read takes its lane with the host's quad
  4486. /// operations: in a pixel program always. Lanes of a quad the primitive
  4487. /// does not cover, or that were discarded, are helpers on the host;
  4488. /// wave reads leave those out (AMD gives 0 from them), quad reads are
  4489. /// what reaches them.
  4490. fn helpers_read(&self, quad: bool) -> bool {
  4491. quad && self.s.pixel
  4492. }
  4493. /// `x` of the lane of this lane's quad that `lanes` names for each of
  4494. /// the quad's four, by the host's quad operations.
  4495. fn quad_read(&mut self, x: V, lanes: [u8; 4]) -> V {
  4496. self.s.flags |= flags::WAVE_OPS;
  4497. let c = self.cur;
  4498. let i32t = self.s.t.i32;
  4499. if lanes == [0, 1, 2, 3] {
  4500. return x;
  4501. }
  4502. // One lane for all.
  4503. if lanes.iter().all(|&l| l == lanes[0]) {
  4504. let n = self.s.m.i32(lanes[0].into());
  4505. return self.s.op(
  4506. c,
  4507. "quadReadLaneAt.i32",
  4508. Attr::NoUnwind,
  4509. i32t,
  4510. 122,
  4511. &[x, n],
  4512. );
  4513. }
  4514. // Else each lane's own, its neighbour across in x (1) or y (2), or
  4515. // the diagonal one (3).
  4516. let across = |i: usize| i as u8 ^ lanes[i];
  4517. let mut r = None;
  4518. for by in 0..4u8 {
  4519. if !(0..4).any(|i| across(i) == by) {
  4520. continue;
  4521. }
  4522. let read = if by == 0 {
  4523. x
  4524. } else {
  4525. // QuadReadAcrossX, Y, Diagonal.
  4526. let kind = self.s.m.i8(by - 1);
  4527. self.s
  4528. .op(c, "quadOp.i32", Attr::NoUnwind, i32t, 123, &[x, kind])
  4529. };
  4530. r = Some(match r {
  4531. None => read,
  4532. Some(r) => {
  4533. let mut here = self.s.m.bool(false);
  4534. let lane = self.lane_index();
  4535. let three = self.s.m.i32(3);
  4536. let at = self.s.m.bin(c, Bin::And, lane, three);
  4537. for i in (0..4).filter(|&i| across(i) == by) {
  4538. let k = self.s.m.i32(i as u32);
  4539. let is = self.s.m.cmp(c, pred::EQ, at, k);
  4540. here = self.s.m.bin(c, Bin::Or, here, is);
  4541. }
  4542. self.s.m.select(c, here, read, r)
  4543. }
  4544. });
  4545. }
  4546. r.unwrap_or(x)
  4547. }
  4548. /// `x` in the first lane of this host wave where `guard` holds, and whether it has such a
  4549. /// lane: the console reads the first lane of EXEC, and a lane that got here with EXEC clear
  4550. /// (a guard, not a branch) is not one. With none, `x` of the wave's first lane here.
  4551. ///
  4552. /// A helper lane of a pixel shader takes its own value: the console's whole-quad mode has
  4553. /// helper lanes in EXEC, so a waterfall loop serves them too, and the host's wave operations
  4554. /// leave them out. Once only helper lanes are left in such a loop none of them ever matched:
  4555. /// they ran to the iteration limit, and left with no sample for their quad's derivatives,
  4556. /// along every triangle's edges (upstream #908, the fix of #1733 for this tree's form).
  4557. fn first_lane(&mut self, x: V, guard: Option<V>) -> (V, V) {
  4558. let (first, any) = self.first_live_lane(x, guard);
  4559. if !self.s.pixel || !super::helper_own() {
  4560. return (first, any);
  4561. }
  4562. let helper = self.helper_lane();
  4563. let c = self.cur;
  4564. let yes = self.s.m.bool(true);
  4565. (self.s.m.select(c, helper, x, first), self.s.m.select(c, helper, yes, any))
  4566. }
  4567. /// Whether this lane of a pixel shader is a helper lane.
  4568. fn helper_lane(&mut self) -> V {
  4569. let i1t = self.s.t.i1;
  4570. self.s.op(self.cur, "isHelperLane.i1", Attr::ReadOnly, i1t, 221, &[])
  4571. }
  4572. fn first_live_lane(&mut self, x: V, guard: Option<V>) -> (V, V) {
  4573. let c = self.cur;
  4574. let i32t = self.s.t.i32;
  4575. self.s.flags |= flags::WAVE_OPS;
  4576. let first = self.s.op(c, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[x]);
  4577. let Some(g) = guard else {
  4578. return (first, self.s.m.bool(true));
  4579. };
  4580. let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]);
  4581. let r = self.s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[g]);
  4582. let (lo, hi) = (self.s.m.extract(c, r, 0), self.s.m.extract(c, r, 1));
  4583. let (z, k32) = (self.s.m.i32(0), self.s.m.i32(32));
  4584. // FirstbitLo (dx.op 32): the lowest set bit
  4585. let flo = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[lo]);
  4586. let fhi = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[hi]);
  4587. let fhi = self.s.m.bin(c, Bin::Add, fhi, k32);
  4588. let in_lo = self.s.m.cmp(c, pred::NE, lo, z);
  4589. let in_hi = self.s.m.cmp(c, pred::NE, hi, z);
  4590. let any = self.s.m.bin(c, Bin::Or, in_lo, in_hi);
  4591. let lane = self.s.m.select(c, in_lo, flo, fhi);
  4592. // no lane in EXEC: read this lane (one that is here); the read is not used
  4593. let me = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
  4594. let lane = self.s.m.select(c, any, lane, me);
  4595. let at = self.read_lane(x, lane);
  4596. (self.s.m.select(c, any, at, first), any)
  4597. }
  4598. fn read_lane(&mut self, x: V, lane: V) -> V {
  4599. self.s.op(
  4600. self.cur,
  4601. "waveReadLaneAt.i32",
  4602. Attr::NoUnwind,
  4603. self.s.t.i32,
  4604. 117,
  4605. &[x, lane],
  4606. )
  4607. }
  4608. /// The float value of a register value.
  4609. fn float_of(&mut self, v: Value) -> Result<V, Why> {
  4610. if let Some(&f) = self.floats.get(&v) {
  4611. return Ok(f);
  4612. }
  4613. let x = self.i32_of(v)?;
  4614. Ok(self.as_float(x))
  4615. }
  4616. /// The values of VGPRs `reg..reg + n` as `inst` reads them.
  4617. fn vgprs(&mut self, inst: &Inst, op: &Operand, n: u8) -> Result<Vec<V>, Why> {
  4618. let Operand::Vector { reg, .. } = *op else {
  4619. return Err("a vector operand");
  4620. };
  4621. (0..n)
  4622. .map(|k| {
  4623. let v = inst.read(Reg::V(reg + k)).ok_or("an unread operand")?;
  4624. self.i32_of(v)
  4625. })
  4626. .collect()
  4627. }
  4628. /// LDS (thread-group shared memory) and `ds_swizzle`.
  4629. fn ds(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  4630. let Fields::Ds {
  4631. dst,
  4632. addr,
  4633. data,
  4634. offset0,
  4635. offset1,
  4636. gds,
  4637. } = &inst.fields
  4638. else {
  4639. unreachable!()
  4640. };
  4641. if *gds {
  4642. return Err("GDS");
  4643. }
  4644. let name = inst.name();
  4645. let guard = self.guard(b, i)?;
  4646. let c = self.cur;
  4647. let offset = u32::from(*offset0) | u32::from(*offset1) << 8;
  4648. let dst_reg = match dst {
  4649. Some(Operand::Vector { reg, .. }) => Some(*reg),
  4650. _ => None,
  4651. };
  4652. if name == "ds_swizzle_b32" {
  4653. // Bit 15 set: each lane of a quad picks a lane of it; else lanes
  4654. // of each group of 32 combine their index with and/or/xor masks.
  4655. let quad = offset & 0x8000 != 0
  4656. || offset & 0x1C == 0x1C && offset & 0x380 == 0 && offset >> 10 & 0x1F < 4;
  4657. // Mesh: host quads are threads 4n..4n+3 of a 1D group, as the
  4658. // console's, so quad-local swizzles read through quad operations.
  4659. let mesh_quad = self.s.mesh.is_some() && quad;
  4660. if !mesh_quad {
  4661. self.cross_lane(quad)?;
  4662. }
  4663. // The source sits in the address field.
  4664. let x = self.vgprs(inst, addr.as_ref().ok_or("a swizzle source")?, 1)?[0];
  4665. let lane = self.lane_index();
  4666. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  4667. let src = if offset & 0x8000 != 0 {
  4668. let (three, one) = (k(self, 3), k(self, 1));
  4669. let sel = self.s.m.bin(c, Bin::And, lane, three);
  4670. let sh = self.s.m.bin(c, Bin::Shl, sel, one);
  4671. let pattern = k(self, offset & 0xFF);
  4672. let pick = self.s.m.bin(c, Bin::LShr, pattern, sh);
  4673. let pick = self.s.m.bin(c, Bin::And, pick, three);
  4674. let not3 = k(self, !3);
  4675. let base = self.s.m.bin(c, Bin::And, lane, not3);
  4676. self.s.m.bin(c, Bin::Or, base, pick)
  4677. } else {
  4678. let and = k(self, offset & 0x1F | !0x1F);
  4679. let or = k(self, offset >> 5 & 0x1F);
  4680. let xor = k(self, offset >> 10 & 0x1F);
  4681. let t = self.s.m.bin(c, Bin::And, lane, and);
  4682. let t = self.s.m.bin(c, Bin::Or, t, or);
  4683. self.s.m.bin(c, Bin::Xor, t, xor)
  4684. };
  4685. let r = if mesh_quad {
  4686. self.quad_pick(x, src)
  4687. } else if self.helpers_read(quad) {
  4688. let lanes = if offset & 0x8000 != 0 {
  4689. [0, 1, 2, 3].map(|i| (offset >> (2 * i) & 3) as u8)
  4690. } else {
  4691. [0, 1, 2, 3].map(|i| ((i & offset | offset >> 5 & 3) ^ offset >> 10 & 3) as u8 & 3)
  4692. };
  4693. self.quad_read(x, lanes)
  4694. } else {
  4695. self.read_lane(x, src)
  4696. };
  4697. let reg = dst_reg.ok_or("a swizzle result")?;
  4698. self.write(inst, Reg::V(reg), r, guard);
  4699. return Ok(());
  4700. }
  4701. if name == "ds_bpermute_b32" {
  4702. // Backward permute: no LDS is touched. Each lane takes the data
  4703. // register of the lane its address names, (address + offset) / 4
  4704. // within the wave; a source lane outside EXEC gives 0. (
  4705. // the title's checkerboard shadow-mask generators read their
  4706. // neighbours' samples with it; without them every shadowed light
  4707. // was multiplied by an empty mask.)
  4708. // shortcut: a source lane that is not at this instruction on the
  4709. // host (it left through a branch, not a guard) is read as the
  4710. // host gives it; the console reads 0.
  4711. self.cross_lane(false)?;
  4712. if self.exchange.as_ref().is_some_and(|e| !e.1) {
  4713. // a console wave of 64 run as two host waves: the lane named
  4714. // may be in the other one
  4715. return Err("a lane permute across two host waves");
  4716. }
  4717. let at = self.vgprs(inst, addr.as_ref().ok_or("a permute address")?, 1)?[0];
  4718. let x = self.vgprs(inst, data.first().ok_or("a permute source")?, 1)?[0];
  4719. let o = self.s.m.i32(offset);
  4720. let at = self.s.m.bin(c, Bin::Add, at, o);
  4721. let two = self.s.m.i32(2);
  4722. let src = self.s.m.bin(c, Bin::LShr, at, two);
  4723. let last = self.s.m.i32(self.wave() - 1);
  4724. let src = self.s.m.bin(c, Bin::And, src, last);
  4725. let x = match guard {
  4726. Some(g) => {
  4727. let z = self.s.m.i32(0);
  4728. self.s.m.select(c, g, x, z)
  4729. }
  4730. None => x,
  4731. };
  4732. let r = self.read_lane(x, src);
  4733. let reg = dst_reg.ok_or("a permute result")?;
  4734. self.write(inst, Reg::V(reg), r, guard);
  4735. return Ok(());
  4736. }
  4737. if self.s.lds_dwords == 0 {
  4738. return Err("LDS the program does not allocate");
  4739. }
  4740. let a = self.vgprs(inst, addr.as_ref().ok_or("an LDS address")?, 1)?[0];
  4741. // shortcut: LDS addresses are taken as dword-aligned and in bounds
  4742. // (out-of-bounds console accesses read 0 and drop writes).
  4743. let dword = |l: &mut Self, bytes: u32| -> V {
  4744. let c = l.cur;
  4745. let o = l.s.m.i32(bytes);
  4746. let at = l.s.m.bin(c, Bin::Add, a, o);
  4747. let two = l.s.m.i32(2);
  4748. let index = l.s.m.bin(c, Bin::LShr, at, two);
  4749. let lds = l.s.lds();
  4750. l.s.m.element(c, lds, index)
  4751. };
  4752. let width = |n: &str| match n.rsplit('_').next() {
  4753. Some("b64") => 2,
  4754. Some("b96") => 3,
  4755. Some("b128") => 4,
  4756. _ => 1,
  4757. };
  4758. // (byte offset, dwords) per element; read2/write2 scale their two
  4759. // offsets by the element size (×64 for st64).
  4760. let pair = |n: &str| -> Vec<(u32, u32)> {
  4761. let w = width(n);
  4762. let scale = 4 * w * if n.contains("st64") { 64 } else { 1 };
  4763. vec![
  4764. (u32::from(*offset0) * scale, w),
  4765. (u32::from(*offset1) * scale, w),
  4766. ]
  4767. };
  4768. // Bytes and halves: the dword holding them, and their bit position
  4769. // in it (naturally aligned, so they never straddle dwords).
  4770. // `_d16` reads fill a register's low half (`_d16_hi` its high half)
  4771. // and keep the other; `_d16_hi` writes take the data's high half.
  4772. let base = name.trim_end_matches("_hi").trim_end_matches("_d16");
  4773. let sub = match base {
  4774. "ds_read_u8" | "ds_read_i8" | "ds_write_b8" => Some(8u32),
  4775. "ds_read_u16" | "ds_read_i16" | "ds_write_b16" => Some(16),
  4776. _ => None,
  4777. };
  4778. let sub = sub.filter(|_| {
  4779. base == name
  4780. || name.ends_with("_d16") && base.starts_with("ds_read")
  4781. || name.ends_with("_d16_hi")
  4782. });
  4783. if let Some(bits) = sub {
  4784. let p = dword(self, offset);
  4785. let o = self.s.m.i32(offset);
  4786. let at = self.s.m.bin(c, Bin::Add, a, o);
  4787. let three = self.s.m.i32(3);
  4788. let byte = self.s.m.bin(c, Bin::And, at, three);
  4789. let sh = self.s.m.bin(c, Bin::Shl, byte, three);
  4790. let mask = self.s.m.i32((1u32 << bits) - 1);
  4791. if name.starts_with("ds_read") {
  4792. let reg = dst_reg.ok_or("an LDS read result")?;
  4793. let w = self.s.m.load(c, p);
  4794. let x = self.s.m.bin(c, Bin::LShr, w, sh);
  4795. let x = if base.contains("_i") {
  4796. let k = self.s.m.i32(32 - bits);
  4797. let x = self.s.m.bin(c, Bin::Shl, x, k);
  4798. self.s.m.bin(c, Bin::AShr, x, k)
  4799. } else {
  4800. self.s.m.bin(c, Bin::And, x, mask)
  4801. };
  4802. let x = if base == name {
  4803. x
  4804. } else {
  4805. let old = match inst.read(Reg::V(reg)) {
  4806. Some(v) => self.i32_of(v)?,
  4807. None => self.s.m.i32(0),
  4808. };
  4809. let half = self.s.m.i32(0xFFFF);
  4810. let x = self.s.m.bin(c, Bin::And, x, half);
  4811. let (x, keep) = if name.ends_with("_hi") {
  4812. let k16 = self.s.m.i32(16);
  4813. (self.s.m.bin(c, Bin::Shl, x, k16), half)
  4814. } else {
  4815. (x, self.s.m.i32(0xFFFF_0000))
  4816. };
  4817. let old = self.s.m.bin(c, Bin::And, old, keep);
  4818. self.s.m.bin(c, Bin::Or, old, x)
  4819. };
  4820. self.write(inst, Reg::V(reg), x, guard);
  4821. } else {
  4822. // Clear, then set: two atomics, so lanes writing other
  4823. // bytes of the dword keep theirs.
  4824. let mut x = self.vgprs(inst, data.first().ok_or("an LDS write")?, 1)?[0];
  4825. if name != base {
  4826. // The data's high half.
  4827. let k16 = self.s.m.i32(16);
  4828. x = self.s.m.bin(c, Bin::LShr, x, k16);
  4829. }
  4830. let x = self.s.m.bin(c, Bin::And, x, mask);
  4831. let x = self.s.m.bin(c, Bin::Shl, x, sh);
  4832. let m = self.s.m.bin(c, Bin::Shl, mask, sh);
  4833. let ones = self.s.m.i32(u32::MAX);
  4834. let keep = self.s.m.bin(c, Bin::Xor, m, ones);
  4835. use super::bitcode::Rmw;
  4836. let at = self.begin_guarded(guard);
  4837. self.s.m.atomic(self.cur, Rmw::And, p, keep);
  4838. self.s.m.atomic(self.cur, Rmw::Or, p, x);
  4839. self.end_guarded(at, &[]);
  4840. }
  4841. return Ok(());
  4842. }
  4843. if let Some(rest) = name.strip_prefix("ds_read") {
  4844. let elements = if rest.starts_with('2') {
  4845. pair(name)
  4846. } else if matches!(rest, "_b32" | "_b64" | "_b96" | "_b128") {
  4847. vec![(offset, width(name))]
  4848. } else {
  4849. return Err("an LDS read of bytes or halves");
  4850. };
  4851. let reg = dst_reg.ok_or("an LDS read result")?;
  4852. let mut n = 0;
  4853. for (off, w) in elements {
  4854. for k in 0..w {
  4855. let p = dword(self, off + 4 * k);
  4856. let x = self.s.m.load(self.cur, p);
  4857. self.write(inst, Reg::V(reg + n), x, guard);
  4858. n += 1;
  4859. }
  4860. }
  4861. return Ok(());
  4862. }
  4863. if let Some(rest) = name.strip_prefix("ds_write") {
  4864. let elements = if rest.starts_with('2') {
  4865. pair(name)
  4866. } else if matches!(rest, "_b32" | "_b64" | "_b96" | "_b128") {
  4867. vec![(offset, width(name))]
  4868. } else {
  4869. return Err("an LDS write of bytes or halves");
  4870. };
  4871. let mut stores = Vec::new();
  4872. for (e, (off, w)) in elements.into_iter().enumerate() {
  4873. let vals = self.vgprs(inst, data.get(e).ok_or("an LDS write")?, w as u8)?;
  4874. for (k, x) in vals.into_iter().enumerate() {
  4875. stores.push((off + 4 * k as u32, x));
  4876. }
  4877. }
  4878. let at = self.begin_guarded(guard);
  4879. for (off, x) in stores {
  4880. let p = dword(self, off);
  4881. self.s.m.store(self.cur, p, x);
  4882. }
  4883. self.end_guarded(at, &[]);
  4884. return Ok(());
  4885. }
  4886. // Atomics: the old value returns with `_rtn`.
  4887. let op = name
  4888. .strip_prefix("ds_")
  4889. .map(|n| n.replace("_rtn", ""))
  4890. .ok_or("an LDS operation")?;
  4891. use super::bitcode::Rmw;
  4892. let rmw = match op.as_str() {
  4893. "add_u32" => Some(Rmw::Add),
  4894. "sub_u32" => Some(Rmw::Sub),
  4895. "and_b32" => Some(Rmw::And),
  4896. "or_b32" => Some(Rmw::Or),
  4897. "xor_b32" => Some(Rmw::Xor),
  4898. "min_i32" => Some(Rmw::Min),
  4899. "max_i32" => Some(Rmw::Max),
  4900. "min_u32" => Some(Rmw::UMin),
  4901. "max_u32" => Some(Rmw::UMax),
  4902. "wrxchg_b32" => Some(Rmw::Xchg),
  4903. "cmpst_b32" | "max_f32" | "min_f32" => None,
  4904. _ => return Err("an LDS operation"),
  4905. };
  4906. let v0 = self.vgprs(inst, data.first().ok_or("an LDS atomic")?, 1)?[0];
  4907. let v1 = match data.get(1) {
  4908. Some(d) => Some(self.vgprs(inst, d, 1)?[0]),
  4909. None => None,
  4910. };
  4911. let old_reg = dst_reg.and_then(|r| inst.read(Reg::V(r)).map(|v| (r, v)));
  4912. let outside = match old_reg {
  4913. Some((_, v)) => self.i32_of(v).unwrap_or(self.s.m.i32(0)),
  4914. None => self.s.m.i32(0),
  4915. };
  4916. let p = dword(self, offset);
  4917. if let Some(max) = match op.as_str() {
  4918. "max_f32" => Some(true),
  4919. "min_f32" => Some(false),
  4920. _ => None,
  4921. } {
  4922. let at = self.begin_guarded(guard);
  4923. let r = self.lds_float_min_max(p, v0, max);
  4924. let r = self.end_guarded(at, &[(r, outside)])[0];
  4925. if let Some(reg) = dst_reg {
  4926. self.write(inst, Reg::V(reg), r, None);
  4927. }
  4928. return Ok(());
  4929. }
  4930. let at = self.begin_guarded(guard);
  4931. let r = match rmw {
  4932. Some(op) => self.s.m.atomic(self.cur, op, p, v0),
  4933. // Compare with data0, store data1.
  4934. None => self
  4935. .s
  4936. .m
  4937. .cmpxchg(self.cur, p, v0, v1.ok_or("an LDS compare")?),
  4938. };
  4939. let r = self.end_guarded(at, &[(r, outside)])[0];
  4940. if let Some(reg) = dst_reg {
  4941. self.write(inst, Reg::V(reg), r, None);
  4942. }
  4943. Ok(())
  4944. }
  4945. /// `ds_max_f32` (`max`) or `ds_min_f32` on the LDS dword at `p` with
  4946. /// the float bits `data`; the old bits return.
  4947. ///
  4948. /// DXIL has no float atomics on group-shared memory, so this is a
  4949. /// compare-exchange loop around [`Lower::lds_float_pick`], which gives
  4950. /// what RDNA2 writes (measured on gfx1036, reported on the pull
  4951. /// request): an sNaN, data first, then memory, is written quieted;
  4952. /// otherwise a NaN loses to a number (two quiet NaNs give the data);
  4953. /// numbers compare as floats with -0 below +0.
  4954. // shortcut: f32 denormals compare as kept; with the console's MODE
  4955. // flushing them they would order as ±0 first (MODE is not modelled).
  4956. fn lds_float_min_max(&mut self, p: V, data: V, max: bool) -> V {
  4957. let pre = self.cur;
  4958. let init = self.s.m.load(pre, p);
  4959. let (lp, exit) = (self.s.m.new_block(), self.s.m.new_block());
  4960. self.s.m.terminate(pre, Term::Br(lp));
  4961. let i32t = self.s.t.i32;
  4962. let old = self.s.m.phi(lp, i32t);
  4963. self.cur = lp;
  4964. let new = self.lds_float_pick(old, data, max);
  4965. let prev = self.s.m.cmpxchg(lp, p, old, new);
  4966. let done = self.s.m.cmp(lp, pred::EQ, prev, old);
  4967. self.s.m.set_phi(old, vec![(init, pre), (prev, lp)]);
  4968. self.s.m.terminate(lp, Term::CondBr(done, exit, lp));
  4969. self.cur = exit;
  4970. old
  4971. }
  4972. /// What `ds_max_f32` (`max`) or `ds_min_f32` writes over the dword
  4973. /// `mem` with `data` (float bits; see [`Lower::lds_float_min_max`]).
  4974. fn lds_float_pick(&mut self, mem: V, data: V, max: bool) -> V {
  4975. let c = self.cur;
  4976. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  4977. let (abs_mask, inf, quiet, zero) = (
  4978. k(self, 0x7FFF_FFFF),
  4979. k(self, 0x7F80_0000),
  4980. k(self, 0x40_0000),
  4981. k(self, 0),
  4982. );
  4983. let nan = |l: &mut Self, x: V| {
  4984. let m = l.s.m.bin(c, Bin::And, x, abs_mask);
  4985. l.s.m.cmp(c, pred::IUGT, m, inf)
  4986. };
  4987. let snan = |l: &mut Self, x: V| {
  4988. let n = nan(l, x);
  4989. let q = l.s.m.bin(c, Bin::And, x, quiet);
  4990. let sig = l.s.m.cmp(c, pred::EQ, q, zero);
  4991. l.s.m.bin(c, Bin::And, n, sig)
  4992. };
  4993. // A total order of the numbers as signed integers, -0 below +0:
  4994. // negative floats' magnitude bits reversed.
  4995. let key = |l: &mut Self, x: V| {
  4996. let k31 = l.s.m.i32(31);
  4997. let sign = l.s.m.bin(c, Bin::AShr, x, k31);
  4998. let flip = l.s.m.bin(c, Bin::And, sign, abs_mask);
  4999. l.s.m.bin(c, Bin::Xor, x, flip)
  5000. };
  5001. let (dk, mk) = (key(self, data), key(self, mem));
  5002. let take = self
  5003. .s
  5004. .m
  5005. .cmp(c, if max { pred::SGT } else { pred::SLT }, dk, mk);
  5006. let r = self.s.m.select(c, take, data, mem);
  5007. let (dn, mn) = (nan(self, data), nan(self, mem));
  5008. // One NaN: the number; two quiet NaNs: the data.
  5009. let r = self.s.m.select(c, mn, data, r);
  5010. let both = self.s.m.bin(c, Bin::And, dn, mn);
  5011. let only_data = {
  5012. let t = self.s.m.bool(true);
  5013. let not_both = self.s.m.bin(c, Bin::Xor, both, t);
  5014. self.s.m.bin(c, Bin::And, dn, not_both)
  5015. };
  5016. let r = self.s.m.select(c, only_data, mem, r);
  5017. // Signalling NaNs win, quieted: the data's first.
  5018. let qm = self.s.m.bin(c, Bin::Or, mem, quiet);
  5019. let sm = snan(self, mem);
  5020. let r = self.s.m.select(c, sm, qm, r);
  5021. let qd = self.s.m.bin(c, Bin::Or, data, quiet);
  5022. let sd = snan(self, data);
  5023. self.s.m.select(c, sd, qd, r)
  5024. }
  5025. // ---- instructions ----
  5026. // ---- instructions ----
  5027. fn inst(&mut self, b: usize, i: usize) -> Result<(), Stop> {
  5028. let inst: &'a Inst = &self.x.p.blocks[b].insts[i];
  5029. let offset = inst.machine.offset;
  5030. let name = inst.name();
  5031. self.local_ok = name.starts_with("s_bcnt1_i32_")
  5032. || name.starts_with("s_ff1_i32_")
  5033. || name.starts_with("v_mbcnt_");
  5034. self.mask_ok = match self.mask_data {
  5035. MaskData::Console => true,
  5036. MaskData::Host => {
  5037. name.starts_with("s_bcnt1_i32_")
  5038. || name.starts_with("s_ff1_i32_")
  5039. || name.starts_with("v_mbcnt_")
  5040. || matches!(
  5041. name,
  5042. "s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_u64" | "s_cmp_lg_u64"
  5043. )
  5044. }
  5045. // Mesh: only "do all lanes hold the first lane's value?" (`uniform_test`), which
  5046. // each host wave answers for itself.
  5047. MaskData::None => self.uniform_test(inst),
  5048. };
  5049. let effect = matches!(inst.fields, Fields::Exp { .. })
  5050. || matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_")
  5051. || name.contains("store")
  5052. || name.contains("atomic")
  5053. || name == "s_barrier"
  5054. || matches!(inst.fields, Fields::Ds { .. })
  5055. && !(name.starts_with("ds_read")
  5056. || name.starts_with("ds_swizzle")
  5057. || name.contains("permute"));
  5058. if self.split_lds
  5059. && matches!(inst.fields, Fields::Ds { .. })
  5060. && !(name.starts_with("ds_swizzle") || name.contains("permute"))
  5061. && self.lds_meet.as_ref().is_none_or(|(all, _)| all[b])
  5062. {
  5063. // the two host waves of a console wave meet before each LDS access: what the other
  5064. // half wrote is visible, and what it still reads is not overwritten
  5065. let mode = self.s.m.i32(meeting_mode());
  5066. let void = self.s.t.void;
  5067. self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]);
  5068. }
  5069. let r = match &inst.fields {
  5070. Fields::Sop { .. } => self.sop(inst),
  5071. Fields::Sopp { .. } if name == "s_barrier" && self.no_barrier.contains(&b) => Ok(()),
  5072. Fields::Sopp { .. } if name == "s_barrier" => {
  5073. // Thread-group sync with a shared-memory fence, and a UAV
  5074. // fence when the program writes UAVs (the waits before an
  5075. // s_barrier make those writes visible on the console).
  5076. let mut mode = if self.writes_uavs { 1 | 2 | 8 } else { 1 | 8 };
  5077. // Without the wait for the group (bit 0) where not every
  5078. // lane arrives, or where the switch says so.
  5079. let waits = match super::group_sync() {
  5080. 0 => false,
  5081. 1 => !self.fence_only.contains(&b),
  5082. _ => true,
  5083. };
  5084. if !waits {
  5085. mode &= !1;
  5086. }
  5087. let mode = self.s.m.i32(mode);
  5088. let void = self.s.t.void;
  5089. self.s
  5090. .op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]);
  5091. Ok(())
  5092. }
  5093. Fields::Sopp { .. } => Ok(()),
  5094. Fields::Smem { .. } => self.smem(inst, (b, i)),
  5095. Fields::Valu(_) if name.starts_with("v_interp_") => self.interp(inst, (b, i)),
  5096. Fields::Valu(_) => self.valu(inst, b, i),
  5097. Fields::Vintrp { .. } => self.interp(inst, (b, i)),
  5098. // The ray and node test. A failure is a refusal at once: an
  5099. // instruction without a side effect otherwise only stops the
  5100. // program where its results are needed, and two trace programs
  5101. // came out without their test that way.
  5102. Fields::Image { .. } if name.starts_with("image_bvh") => {
  5103. return self
  5104. .bvh(inst, b, i)
  5105. .map_err(|why| unsupported(offset, why));
  5106. }
  5107. Fields::Image { .. } => self.image(inst, b, i),
  5108. Fields::Buffer { .. } => self.buffer(inst, b, i),
  5109. Fields::Exp { .. } => self.export(b, i),
  5110. Fields::Ds { .. } => self.ds(inst, b, i),
  5111. Fields::Flat { .. } if name.starts_with("global_") => self.flat(inst, b, i),
  5112. Fields::Flat { .. } => Err("flat memory"),
  5113. };
  5114. match r {
  5115. Ok(()) => Ok(()),
  5116. Err(why) if effect => Err(unsupported(offset, why)),
  5117. Err(why) => {
  5118. for &(_, v) in &inst.writes {
  5119. self.vals.insert(v, Val::Missing(why));
  5120. }
  5121. Ok(())
  5122. }
  5123. }
  5124. }
  5125. /// The two host waves of a console wave meet (a group barrier with a shared-memory
  5126. /// fence): LDS writes before are seen by reads after.
  5127. fn lds_meeting(&mut self) {
  5128. let mode = self.s.m.i32(meeting_mode());
  5129. let void = self.s.t.void;
  5130. self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]);
  5131. }
  5132. /// Whether `v` is a register no program reads as a number: a descriptor dword without
  5133. /// a host value ([`Self::stale`]), a lane mask's dword (outside compute, where a ballot
  5134. /// gives the mask as data), or a join of only such values. Compiled code joins numbers
  5135. /// with numbers: where one of these meets numbers at a join, the register is dead on
  5136. /// that path (a variable set in one arm of a branch, its use behind a flag kept in a
  5137. /// VGPR).
  5138. fn dead(&self, v: Value, seen: &mut Vec<Value>) -> bool {
  5139. if self.stale.contains(&v) {
  5140. return true;
  5141. }
  5142. let st = self.x.st;
  5143. if self.mask_data != MaskData::Console
  5144. && (st.masks.contains_key(&v) || st.highs.contains_key(&v))
  5145. {
  5146. return true;
  5147. }
  5148. let Some(&(b, i)) = self.phi_at.get(&v) else {
  5149. return false;
  5150. };
  5151. if seen.contains(&v) {
  5152. return true;
  5153. }
  5154. seen.push(v);
  5155. self.x.p.blocks[b].phis[i]
  5156. .args
  5157. .iter()
  5158. .all(|&a| self.dead(a, seen))
  5159. }
  5160. /// `s_bcnt1_i32_b*` of the lanes that differ from the first lane's value:
  5161. /// `v_readfirstlane_b32 s, v`, `v_cmp_eq_u32 m, s, v`, `s_xor_b* d, m, exec`. The
  5162. /// compiler tests a value for being the same in the whole wave this way, to take a
  5163. /// scalar path; both paths give each lane the same result, so the lanes of a host
  5164. /// wave may ask it of their own first lane, whatever the wave's size.
  5165. fn uniform_test(&self, inst: &Inst) -> bool {
  5166. let p = self.x.p;
  5167. let writer = |v: Value| -> Option<&'a Inst> {
  5168. let b = *self.def_block.get(&v)?;
  5169. p.blocks[b]
  5170. .insts
  5171. .iter()
  5172. .find(|i| i.writes.iter().any(|w| w.1 == v))
  5173. };
  5174. let scalar = |i: &Inst, op: &Operand| match *op {
  5175. Operand::Scalar { code, .. } if code != NULL && code != EXEC => i.read(Reg::S(code)),
  5176. _ => None,
  5177. };
  5178. if !inst.name().starts_with("s_bcnt1_i32_") {
  5179. return false;
  5180. }
  5181. let Fields::Sop { src, .. } = &inst.fields else {
  5182. return false;
  5183. };
  5184. let Some(xor) = src.first().and_then(|o| scalar(inst, o)).and_then(writer) else {
  5185. return false;
  5186. };
  5187. let Fields::Sop { src, .. } = &xor.fields else {
  5188. return false;
  5189. };
  5190. if !matches!(xor.name(), "s_xor_b64" | "s_xor_b32")
  5191. || !src
  5192. .iter()
  5193. .any(|o| matches!(o, Operand::Scalar { code: EXEC, .. }))
  5194. {
  5195. return false;
  5196. }
  5197. let Some(cmp) = src.iter().find_map(|o| scalar(xor, o)).and_then(writer) else {
  5198. return false;
  5199. };
  5200. let Fields::Valu(f) = &cmp.fields else {
  5201. return false;
  5202. };
  5203. if !matches!(cmp.name(), "v_cmp_eq_u32" | "v_cmp_eq_i32") || f.sdwa.is_some() || f.dpp.is_some() {
  5204. return false;
  5205. }
  5206. let lanes = f.src.iter().find_map(|o| match *o {
  5207. Operand::Vector { reg, .. } => cmp.read(Reg::V(reg)),
  5208. _ => None,
  5209. });
  5210. let first = f.src.iter().find_map(|o| scalar(cmp, o)).and_then(writer);
  5211. lanes.is_some()
  5212. && first.is_some_and(|fl| {
  5213. fl.name() == "v_readfirstlane_b32"
  5214. && matches!(&fl.fields, Fields::Valu(g)
  5215. if matches!(g.src.first(), Some(&Operand::Vector { reg, .. })
  5216. if fl.read(Reg::V(reg)) == lanes))
  5217. })
  5218. }
  5219. fn is_mask(&self, v: Option<Value>) -> bool {
  5220. v.is_some_and(|v| self.x.st.masks.contains_key(&v))
  5221. }
  5222. fn sop(&mut self, inst: &Inst) -> Result<(), Why> {
  5223. let Fields::Sop { dst, src, imm } = &inst.fields else {
  5224. unreachable!()
  5225. };
  5226. let name = inst.name();
  5227. let scc = inst.write(Reg::Scc);
  5228. let dst_code = match dst {
  5229. Some(Operand::Scalar { code, .. }) => Some(*code),
  5230. _ => None,
  5231. };
  5232. let lo = dst_code.and_then(|c| inst.write(Reg::S(c)));
  5233. if inst.write(Reg::S(EXEC)).is_some() || self.is_mask(lo) {
  5234. return Err(LANE_MASK);
  5235. }
  5236. if matches!(
  5237. name,
  5238. "s_setreg_imm32_b32" | "s_setreg_b32" | "s_swappc_b64" | "s_version"
  5239. ) || name.starts_with("s_waitcnt")
  5240. {
  5241. // shortcut: the float MODE register is not modelled; s_swappc_b64 is the
  5242. // vertex fetch call, whose results arrive as inputs.
  5243. return Err("a register the emitter does not model");
  5244. }
  5245. if name == "s_getpc_b64" {
  5246. // The address of the next instruction is no number the host has: tables in
  5247. // the code are read by their tracked address. As a number the counter is
  5248. // that instruction's offset in the code, so an address paths join before
  5249. // one load is the byte in the code, whichever table each path took
  5250. // (resource tracking gives such a join as the computed term, with no base).
  5251. let z = self.s.m.i32(0);
  5252. let at = self.s.m.i32(inst.machine.offset as u32 + 4);
  5253. let hi = dst_code.and_then(|c| inst.write(Reg::S(c + 1)));
  5254. self.set(lo, Val::I32(at));
  5255. self.set(hi, Val::I32(z));
  5256. return Ok(());
  5257. }
  5258. let c = self.cur;
  5259. let src32 = |l: &mut Self, k: usize| -> Result<V, Why> {
  5260. // SOPK arithmetic reads its destination as the first source.
  5261. if k == 0 && matches!(name, "s_addk_i32" | "s_mulk_i32") {
  5262. let d = dst.as_ref().ok_or("a missing operand")?;
  5263. return l.operand(inst, d);
  5264. }
  5265. let op = src.get(k).ok_or("a missing operand")?;
  5266. l.operand(inst, op)
  5267. };
  5268. let sext16 = |l: &mut Self| l.s.m.i32(i32::from(imm.unwrap_or(0) as i16) as u32);
  5269. // Dword `h` of 64-bit source `k` (inline constants sign-extend).
  5270. let half = |l: &mut Self, k: usize, h: u8| -> Result<V, Why> {
  5271. match src.get(k) {
  5272. Some(&Operand::Scalar { code, .. }) if code != NULL => {
  5273. let v = inst.read(Reg::S(code + h)).ok_or("an unread operand")?;
  5274. l.i32_of(v)
  5275. }
  5276. Some(op) if h == 0 => l.operand(inst, op),
  5277. Some(Operand::Const(k)) => {
  5278. let x = crate::resource::inline(*k).ok_or("a special operand")?;
  5279. Ok(l.s.m.i32(if (x as i32) < 0 { u32::MAX } else { 0 }))
  5280. }
  5281. // Of a signed operand, a literal sign-extends too.
  5282. Some(&Operand::Literal(x)) if name.ends_with("_i64") => {
  5283. Ok(l.s.m.i32(if (x as i32) < 0 { u32::MAX } else { 0 }))
  5284. }
  5285. _ => Ok(l.s.m.i32(0)),
  5286. }
  5287. };
  5288. if let Some(op) = name.strip_prefix("s_bitcmp") {
  5289. // SCC is whether bit src1 (mod 32, or mod 64 for the 64-bit form)
  5290. // of src0 is clear (bitcmp0) or set (bitcmp1).
  5291. let (bit, k31) = (src32(self, 1)?, self.s.m.i32(31));
  5292. let idx = self.s.m.bin(c, Bin::And, bit, k31);
  5293. let word = if op.ends_with("_b64") {
  5294. let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
  5295. let k32 = self.s.m.i32(32);
  5296. let upper = self.s.m.bin(c, Bin::And, bit, k32);
  5297. let z = self.s.m.i32(0);
  5298. let upper = self.s.m.cmp(c, pred::NE, upper, z);
  5299. self.s.m.select(c, upper, b, a)
  5300. } else {
  5301. src32(self, 0)?
  5302. };
  5303. let shifted = self.s.m.bin(c, Bin::LShr, word, idx);
  5304. let one = self.s.m.i32(1);
  5305. let tested = self.s.m.bin(c, Bin::And, shifted, one);
  5306. let want = self.s.m.i32(u32::from(op.starts_with('1')));
  5307. let r = self.s.m.cmp(c, pred::EQ, tested, want);
  5308. self.set(scc, Val::Bit(r));
  5309. return Ok(());
  5310. }
  5311. if let Some(op) = name.strip_prefix("s_cmp_").filter(|o| o.ends_with("_u64")) {
  5312. // eq and lg only: both dwords.
  5313. let mut r = None;
  5314. for h in 0..2 {
  5315. let (a, b) = (half(self, 0, h)?, half(self, 1, h)?);
  5316. let e = self.s.m.cmp(c, pred::EQ, a, b);
  5317. r = Some(match r {
  5318. Some(x) => self.s.m.bin(c, Bin::And, x, e),
  5319. None => e,
  5320. });
  5321. }
  5322. let mut r = r.expect("two dwords");
  5323. if op.starts_with("lg") {
  5324. let t = self.s.m.bool(true);
  5325. r = self.s.m.bin(c, Bin::Xor, r, t);
  5326. }
  5327. self.set(scc, Val::Bit(r));
  5328. return Ok(());
  5329. }
  5330. if let Some(op) = name.strip_prefix("s_cmp_").or(name.strip_prefix("s_cmpk_")) {
  5331. let (a, b) = if name.starts_with("s_cmpk_") {
  5332. let b = if op.ends_with("_i32") {
  5333. sext16(self)
  5334. } else {
  5335. self.s.m.i32(u32::from(imm.unwrap_or(0)))
  5336. };
  5337. (src32(self, 0)?, b)
  5338. } else {
  5339. if op.ends_with("64") {
  5340. return Err("a 64-bit scalar compare");
  5341. }
  5342. (src32(self, 0)?, src32(self, 1)?)
  5343. };
  5344. let signed = op.ends_with("_i32");
  5345. let p = match &op[..2] {
  5346. "eq" => pred::EQ,
  5347. "lg" => pred::NE,
  5348. "gt" if signed => pred::SGT,
  5349. "ge" if signed => pred::SGE,
  5350. "lt" if signed => pred::SLT,
  5351. "le" if signed => pred::SLE,
  5352. "gt" => pred::IUGT,
  5353. "ge" => pred::IUGE,
  5354. "lt" => pred::IULT,
  5355. "le" => pred::IULE,
  5356. _ => return Err("a scalar compare"),
  5357. };
  5358. let r = self.s.m.cmp(c, p, a, b);
  5359. self.set(scc, Val::Bit(r));
  5360. return Ok(());
  5361. }
  5362. let wide = name.ends_with("_b64") || name.ends_with("_u64") || name.ends_with("_i64");
  5363. if wide {
  5364. let hi = dst_code.and_then(|c| inst.write(Reg::S(c + 1)));
  5365. let nonzero = |l: &mut Self, a: V, b: V| {
  5366. let o = l.s.m.bin(c, Bin::Or, a, b);
  5367. let z = l.s.m.i32(0);
  5368. l.s.m.cmp(c, pred::NE, o, z)
  5369. };
  5370. return match name {
  5371. "s_quadmask_b64" => {
  5372. let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
  5373. let low = self.quad_mask(a);
  5374. let high = self.quad_mask(b);
  5375. let k8 = self.s.m.i32(8);
  5376. let high = self.s.m.bin(c, Bin::Shl, high, k8);
  5377. let mask = self.s.m.bin(c, Bin::Or, low, high);
  5378. let zero = self.s.m.i32(0);
  5379. self.set(lo, Val::I32(mask));
  5380. self.set(hi, Val::I32(zero));
  5381. let nonzero = self.s.m.cmp(c, pred::NE, mask, zero);
  5382. self.set(scc, Val::Bit(nonzero));
  5383. Ok(())
  5384. }
  5385. "s_bcnt1_i32_b64" => {
  5386. let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
  5387. let i32t = self.s.t.i32;
  5388. let na = self
  5389. .s
  5390. .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 31, &[a]);
  5391. let nb = self
  5392. .s
  5393. .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 31, &[b]);
  5394. let r = self.s.m.bin(c, Bin::Add, na, nb);
  5395. self.set(lo, Val::I32(r));
  5396. let z = self.s.m.i32(0);
  5397. let s = self.s.m.cmp(c, pred::NE, r, z);
  5398. self.set(scc, Val::Bit(s));
  5399. Ok(())
  5400. }
  5401. "s_ff1_i32_b64" => {
  5402. // The lowest set bit; -1 for none (as DXIL's first bit low).
  5403. let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
  5404. let i32t = self.s.t.i32;
  5405. let fa = self
  5406. .s
  5407. .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[a]);
  5408. let fb = self
  5409. .s
  5410. .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[b]);
  5411. let (z, k32) = (self.s.m.i32(0), self.s.m.i32(32));
  5412. let fb32 = self.s.m.bin(c, Bin::Add, fb, k32);
  5413. let none = self.s.m.cmp(c, pred::EQ, b, z);
  5414. let fb = self.s.m.select(c, none, fb, fb32);
  5415. let low = self.s.m.cmp(c, pred::NE, a, z);
  5416. let r = self.s.m.select(c, low, fa, fb);
  5417. self.set(lo, Val::I32(r));
  5418. Ok(())
  5419. }
  5420. "s_and_b64" | "s_or_b64" | "s_xor_b64" | "s_andn2_b64" | "s_orn2_b64"
  5421. | "s_nand_b64" | "s_nor_b64" | "s_xnor_b64" | "s_not_b64" => {
  5422. let ones = self.s.m.i32(u32::MAX);
  5423. let mut r = Vec::new();
  5424. for h in 0..2u8 {
  5425. let a = half(self, 0, h)?;
  5426. let x = if name == "s_not_b64" {
  5427. self.s.m.bin(c, Bin::Xor, a, ones)
  5428. } else {
  5429. let mut b = half(self, 1, h)?;
  5430. if name.contains("n2") {
  5431. b = self.s.m.bin(c, Bin::Xor, b, ones);
  5432. }
  5433. let op = match &name[2..5] {
  5434. "and" | "nan" => Bin::And,
  5435. "or_" | "orn" | "nor" => Bin::Or,
  5436. _ => Bin::Xor,
  5437. };
  5438. let x = self.s.m.bin(c, op, a, b);
  5439. if matches!(name, "s_nand_b64" | "s_nor_b64" | "s_xnor_b64") {
  5440. self.s.m.bin(c, Bin::Xor, x, ones)
  5441. } else {
  5442. x
  5443. }
  5444. };
  5445. r.push(x);
  5446. }
  5447. self.set(lo, Val::I32(r[0]));
  5448. self.set(hi, Val::I32(r[1]));
  5449. let s = nonzero(self, r[0], r[1]);
  5450. self.set(scc, Val::Bit(s));
  5451. Ok(())
  5452. }
  5453. "s_lshl_b64" | "s_lshr_b64" | "s_ashr_i64" => {
  5454. let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
  5455. let n = src32(self, 1)?;
  5456. let i64t = self.s.m.int(64);
  5457. self.s.flags |= flags::INT64;
  5458. let a = self.s.m.cast(c, Cast::ZExt, a, i64t);
  5459. let b = self.s.m.cast(c, Cast::ZExt, b, i64t);
  5460. let k32 = self.s.m.int_const(i64t, 32);
  5461. let b = self.s.m.bin(c, Bin::Shl, b, k32);
  5462. let x = self.s.m.bin(c, Bin::Or, a, b);
  5463. let k63 = self.s.m.i32(63);
  5464. let n = self.s.m.bin(c, Bin::And, n, k63);
  5465. let n = self.s.m.cast(c, Cast::ZExt, n, i64t);
  5466. let op = match name {
  5467. "s_lshl_b64" => Bin::Shl,
  5468. "s_lshr_b64" => Bin::LShr,
  5469. _ => Bin::AShr,
  5470. };
  5471. let r = self.s.m.bin(c, op, x, n);
  5472. let rl = self.s.m.cast(c, Cast::Trunc, r, self.s.t.i32);
  5473. let rh = self.s.m.bin(c, Bin::LShr, r, k32);
  5474. let rh = self.s.m.cast(c, Cast::Trunc, rh, self.s.t.i32);
  5475. self.set(lo, Val::I32(rl));
  5476. self.set(hi, Val::I32(rh));
  5477. let s = nonzero(self, rl, rh);
  5478. self.set(scc, Val::Bit(s));
  5479. Ok(())
  5480. }
  5481. "s_mov_b64" => {
  5482. // Each half by itself: two numbers that travel as a pair (two scalars
  5483. // parked in neighbouring VGPR lanes, say) need not both have a value.
  5484. for (h, v) in [(0, lo), (1, hi)] {
  5485. let val = match half(self, 0, h) {
  5486. Ok(a) => Val::I32(a),
  5487. Err(why) => Val::Missing(why),
  5488. };
  5489. self.set(v, val);
  5490. }
  5491. Ok(())
  5492. }
  5493. "s_cselect_b64" => {
  5494. let cond = self.scc_in(inst)?;
  5495. for (h, v) in [(0, lo), (1, hi)] {
  5496. let (a, b) = (half(self, 0, h)?, half(self, 1, h)?);
  5497. let r = self.s.m.select(c, cond, a, b);
  5498. self.set(v, Val::I32(r));
  5499. }
  5500. Ok(())
  5501. }
  5502. _ => Err(name),
  5503. };
  5504. }
  5505. let m = &mut self.s.m;
  5506. let _ = m;
  5507. let (r, carry): (V, Option<V>) = match name {
  5508. "s_mov_b32" => (src32(self, 0)?, None),
  5509. "s_movk_i32" => (sext16(self), None),
  5510. "s_quadmask_b32" => {
  5511. let pixels = src32(self, 0)?;
  5512. (self.quad_mask(pixels), None)
  5513. }
  5514. "s_cselect_b32" => {
  5515. let cond = self.scc_in(inst)?;
  5516. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5517. (self.s.m.select(c, cond, a, b), None)
  5518. }
  5519. "s_brev_b32" => {
  5520. let a = src32(self, 0)?;
  5521. let r = self
  5522. .s
  5523. .op(c, "unary.i32", Attr::ReadNone, self.s.t.i32, 30, &[a]);
  5524. (r, None)
  5525. }
  5526. "s_not_b32" => {
  5527. let a = src32(self, 0)?;
  5528. let ones = self.s.m.i32(u32::MAX);
  5529. (self.s.m.bin(c, Bin::Xor, a, ones), None)
  5530. }
  5531. "s_add_u32" | "s_add_i32" | "s_addk_i32" => {
  5532. let a = src32(self, 0)?;
  5533. let b = if name == "s_addk_i32" {
  5534. sext16(self)
  5535. } else {
  5536. src32(self, 1)?
  5537. };
  5538. let r = self.s.m.bin(c, Bin::Add, a, b);
  5539. let carry = if name == "s_add_u32" {
  5540. Some(self.s.m.cmp(c, pred::IULT, r, a))
  5541. } else {
  5542. None
  5543. };
  5544. (r, carry)
  5545. }
  5546. "s_sub_u32" | "s_sub_i32" => {
  5547. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5548. let r = self.s.m.bin(c, Bin::Sub, a, b);
  5549. let carry = (name == "s_sub_u32").then(|| self.s.m.cmp(c, pred::IULT, a, b));
  5550. (r, carry)
  5551. }
  5552. "s_addc_u32" | "s_subb_u32" => {
  5553. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5554. let cin = self.scc_in(inst)?;
  5555. let (r, carry) = self.add_sub_carry(c, name == "s_addc_u32", a, b, Some(cin));
  5556. (r, Some(carry))
  5557. }
  5558. "s_mul_i32" | "s_mulk_i32" => {
  5559. let a = src32(self, 0)?;
  5560. let b = if name == "s_mulk_i32" {
  5561. sext16(self)
  5562. } else {
  5563. src32(self, 1)?
  5564. };
  5565. (self.s.m.bin(c, Bin::Mul, a, b), None)
  5566. }
  5567. "s_mul_hi_u32" | "s_mul_hi_i32" => {
  5568. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5569. (self.mul_hi(a, b, name.ends_with("i32")), None)
  5570. }
  5571. "s_flbit_i32_b32" | "s_flbit_i32" => {
  5572. // The first bit from the top (differing from the sign for
  5573. // the signed form), -1 for none: DXIL's first-bit-high.
  5574. let a = src32(self, 0)?;
  5575. let op = if name == "s_flbit_i32_b32" { 33 } else { 34 };
  5576. let r = self
  5577. .s
  5578. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]);
  5579. (r, None)
  5580. }
  5581. "s_ff1_i32_b32" | "s_bcnt1_i32_b32" => {
  5582. // First set bit (-1 for zero, as DXIL's), or the bit count.
  5583. let a = src32(self, 0)?;
  5584. let op = if name == "s_ff1_i32_b32" { 32 } else { 31 };
  5585. let r = self
  5586. .s
  5587. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]);
  5588. (r, None)
  5589. }
  5590. "s_bfe_u32" | "s_bfe_i32" => {
  5591. // src1: offset in bits 0-4, width in bits 16-22.
  5592. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5593. let (k16, k127) = (self.s.m.i32(16), self.s.m.i32(0x7F));
  5594. let w = self.s.m.bin(c, Bin::LShr, b, k16);
  5595. let w = self.s.m.bin(c, Bin::And, w, k127);
  5596. (self.bfe(a, b, w, name == "s_bfe_i32"), None)
  5597. }
  5598. "s_and_b32" | "s_or_b32" | "s_xor_b32" | "s_andn2_b32" | "s_orn2_b32"
  5599. | "s_nand_b32" | "s_nor_b32" | "s_xnor_b32" => {
  5600. let (a, mut b) = (src32(self, 0)?, src32(self, 1)?);
  5601. let ones = self.s.m.i32(u32::MAX);
  5602. if name.contains("n2") {
  5603. b = self.s.m.bin(c, Bin::Xor, b, ones);
  5604. }
  5605. let op = match &name[2..5] {
  5606. "and" | "nan" => Bin::And,
  5607. "or_" | "orn" | "nor" => Bin::Or,
  5608. _ => Bin::Xor,
  5609. };
  5610. let mut r = self.s.m.bin(c, op, a, b);
  5611. if matches!(name, "s_nand_b32" | "s_nor_b32" | "s_xnor_b32") {
  5612. r = self.s.m.bin(c, Bin::Xor, r, ones);
  5613. }
  5614. (r, None)
  5615. }
  5616. "s_lshl_b32" | "s_lshr_b32" | "s_ashr_i32" => {
  5617. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5618. let k31 = self.s.m.i32(31);
  5619. let b = self.s.m.bin(c, Bin::And, b, k31);
  5620. let op = match name {
  5621. "s_lshl_b32" => Bin::Shl,
  5622. "s_lshr_b32" => Bin::LShr,
  5623. _ => Bin::AShr,
  5624. };
  5625. (self.s.m.bin(c, op, a, b), None)
  5626. }
  5627. "s_lshl1_add_u32" | "s_lshl2_add_u32" | "s_lshl3_add_u32" | "s_lshl4_add_u32" => {
  5628. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5629. let k = self.s.m.i32(u32::from(name.as_bytes()[6] - b'0'));
  5630. let t = self.s.m.bin(c, Bin::Shl, a, k);
  5631. (self.s.m.bin(c, Bin::Add, t, b), None)
  5632. }
  5633. "s_min_u32" | "s_max_u32" | "s_min_i32" | "s_max_i32" => {
  5634. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5635. let p = match name {
  5636. "s_min_u32" => pred::IULT,
  5637. "s_max_u32" => pred::IUGT,
  5638. "s_min_i32" => pred::SLT,
  5639. _ => pred::SGT,
  5640. };
  5641. let t = self.s.m.cmp(c, p, a, b);
  5642. (self.s.m.select(c, t, a, b), None)
  5643. }
  5644. "s_abs_i32" => {
  5645. let a = src32(self, 0)?;
  5646. let z = self.s.m.i32(0);
  5647. let neg = self.s.m.cmp(c, pred::SLT, a, z);
  5648. let n = self.s.m.bin(c, Bin::Sub, z, a);
  5649. (self.s.m.select(c, neg, n, a), None)
  5650. }
  5651. "s_bitset0_b32" | "s_bitset1_b32" => {
  5652. // Sets (clears) bit src[4:0] of the destination it reads.
  5653. let old = self.operand(inst, dst.as_ref().ok_or("a missing operand")?)?;
  5654. let a = src32(self, 0)?;
  5655. let (k31, one) = (self.s.m.i32(31), self.s.m.i32(1));
  5656. let a = self.s.m.bin(c, Bin::And, a, k31);
  5657. let bit = self.s.m.bin(c, Bin::Shl, one, a);
  5658. if name == "s_bitset1_b32" {
  5659. (self.s.m.bin(c, Bin::Or, old, bit), None)
  5660. } else {
  5661. let ones = self.s.m.i32(u32::MAX);
  5662. let nb = self.s.m.bin(c, Bin::Xor, bit, ones);
  5663. (self.s.m.bin(c, Bin::And, old, nb), None)
  5664. }
  5665. }
  5666. "s_bfm_b32" => {
  5667. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5668. let k31 = self.s.m.i32(31);
  5669. let one = self.s.m.i32(1);
  5670. let a = self.s.m.bin(c, Bin::And, a, k31);
  5671. let b = self.s.m.bin(c, Bin::And, b, k31);
  5672. let m = self.s.m.bin(c, Bin::Shl, one, a);
  5673. let m = self.s.m.bin(c, Bin::Sub, m, one);
  5674. (self.s.m.bin(c, Bin::Shl, m, b), None)
  5675. }
  5676. _ => return Err(name),
  5677. };
  5678. self.set(lo, Val::I32(r));
  5679. if let Some(scc) = scc {
  5680. let val = match carry {
  5681. Some(k) => Val::Bit(k),
  5682. None if matches!(
  5683. name,
  5684. "s_mov_b32"
  5685. | "s_movk_i32"
  5686. | "s_cselect_b32"
  5687. | "s_brev_b32"
  5688. | "s_mul_i32"
  5689. | "s_mulk_i32"
  5690. ) =>
  5691. {
  5692. return Ok(());
  5693. }
  5694. None if name.starts_with("s_add") || name.starts_with("s_sub") => {
  5695. Val::Missing("the carry of a scalar operation")
  5696. }
  5697. None => {
  5698. let z = self.s.m.i32(0);
  5699. Val::Bit(self.s.m.cmp(c, pred::NE, r, z))
  5700. }
  5701. };
  5702. self.vals.insert(scc, val);
  5703. }
  5704. Ok(())
  5705. }
  5706. /// Packs whether each consecutive group of four pixels has a set bit.
  5707. fn quad_mask(&mut self, pixels: V) -> V {
  5708. let c = self.cur;
  5709. let one = self.s.m.i32(1);
  5710. let shifted = self.s.m.bin(c, Bin::LShr, pixels, one);
  5711. let mut mask = self.s.m.bin(c, Bin::Or, pixels, shifted);
  5712. // Fold each nibble into its bottom bit, then gather those bits into
  5713. // the low byte in three stages without needing a 64-bit operation.
  5714. for (distance, keep) in [
  5715. (2, 0x1111_1111),
  5716. (3, 0x0303_0303),
  5717. (6, 0x000f_000f),
  5718. (12, 0x0000_00ff),
  5719. ] {
  5720. let distance = self.s.m.i32(distance);
  5721. let shifted = self.s.m.bin(c, Bin::LShr, mask, distance);
  5722. let combined = self.s.m.bin(c, Bin::Or, mask, shifted);
  5723. let keep = self.s.m.i32(keep);
  5724. mask = self.s.m.bin(c, Bin::And, combined, keep);
  5725. }
  5726. mask
  5727. }
  5728. /// `a + b (+ cin)` or `a - b (- cin)` with the carry (borrow) out, as the
  5729. /// scalar and vector add-with-carry instructions set it.
  5730. fn add_sub_carry(&mut self, c: usize, add: bool, a: V, b: V, cin: Option<V>) -> (V, V) {
  5731. let op = if add { Bin::Add } else { Bin::Sub };
  5732. let mut r = self.s.m.bin(c, op, a, b);
  5733. // Without a carry in: a + b wraps below a; a - b borrows when a < b.
  5734. let mut carry = if add {
  5735. self.s.m.cmp(c, pred::IULT, r, a)
  5736. } else {
  5737. self.s.m.cmp(c, pred::IULT, a, b)
  5738. };
  5739. if let Some(cin) = cin {
  5740. let one = self.s.m.cast(c, Cast::ZExt, cin, self.s.t.i32);
  5741. let t = r;
  5742. r = self.s.m.bin(c, op, t, one);
  5743. // The carry in carries on when the partial result is all ones
  5744. // (add) or zero (sub).
  5745. let edge = self.s.m.i32(if add { u32::MAX } else { 0 });
  5746. let at_edge = self.s.m.cmp(c, pred::EQ, t, edge);
  5747. let more = self.s.m.bin(c, Bin::And, cin, at_edge);
  5748. carry = self.s.m.bin(c, Bin::Or, carry, more);
  5749. }
  5750. (r, carry)
  5751. }
  5752. fn scc_in(&mut self, inst: &Inst) -> Result<V, Why> {
  5753. let v = inst.read(Reg::Scc).ok_or("an unread SCC")?;
  5754. match self.get(v) {
  5755. Ok(Val::Bit(x)) => Ok(x),
  5756. Ok(_) => Err("SCC without a value"),
  5757. // Of a mask operation whose result lies within EXEC: whether
  5758. // some lane is left.
  5759. Err(LANE_MASK) if self.within_exec(v) => self.scc_some(v),
  5760. Err(why) => Err(why),
  5761. }
  5762. }
  5763. /// Whether the mask operation that sets the SCC value `scc` gives no
  5764. /// lane outside EXEC a bit.
  5765. fn within_exec(&self, scc: Value) -> bool {
  5766. let Some(&b) = self.def_block.get(&scc) else {
  5767. return false;
  5768. };
  5769. let by = self.x.p.blocks[b].insts.iter().find(|i| i.write(Reg::Scc) == Some(scc));
  5770. by.is_some_and(|i| {
  5771. i.write(Reg::S(EXEC)).is_some()
  5772. || matches!(&i.fields, Fields::Sop { dst: Some(Operand::Scalar { code, .. }), .. }
  5773. if i.write(Reg::S(*code)).is_some_and(|lo| self.x.st.active.contains(&lo)))
  5774. })
  5775. }
  5776. fn smem(&mut self, inst: &Inst, site: Site) -> Result<(), Why> {
  5777. let Fields::Smem {
  5778. data,
  5779. offset,
  5780. soffset,
  5781. ..
  5782. } = &inst.fields
  5783. else {
  5784. unreachable!()
  5785. };
  5786. self.root_copy = None;
  5787. let name = inst.name();
  5788. if let Some(a) = self.scalar.get(&site).copied().filter(|a| a.param == CODE) {
  5789. return self.code_smem(inst, a);
  5790. }
  5791. if self.scalar.get(&site).is_some_and(|a| a.param == MEMORY) {
  5792. return self.memory_smem(inst);
  5793. }
  5794. let Some(rest) = name.strip_prefix("s_buffer_load_dword") else {
  5795. return self.descriptor_data(inst, site);
  5796. };
  5797. let count = match rest {
  5798. "" => 1,
  5799. "x2" => 2,
  5800. "x4" => 4,
  5801. "x8" => 8,
  5802. "x16" => 16,
  5803. _ => return Err("a scalar buffer load"),
  5804. };
  5805. let Some(Operand::Scalar { code, .. }) = *data else {
  5806. return Err("a scalar buffer load");
  5807. };
  5808. let src = self
  5809. .descriptors
  5810. .get(&(site, false))
  5811. .copied()
  5812. .ok_or("an untracked descriptor")?;
  5813. let kind = self.used_kind(src);
  5814. let c = self.cur;
  5815. let (base, extra) = self.built_offset(src)?;
  5816. let offset = &((*offset as u32).wrapping_add(base) as i32);
  5817. let mut addr = self.s.m.i32(*offset as u32);
  5818. if let Some(x) = extra {
  5819. addr = self.s.m.bin(c, Bin::Add, addr, x);
  5820. }
  5821. if !matches!(soffset, Operand::Scalar { code: NULL, .. }) {
  5822. let so = self.operand(inst, soffset)?;
  5823. addr = self.s.m.bin(c, Bin::Add, addr, so);
  5824. }
  5825. if matches!(src, Source::Built { address, .. } if address.param == CODE) {
  5826. // A descriptor built around a table in the code.
  5827. for k in 0..count {
  5828. let off = self.s.m.i32(4 * k);
  5829. let a = self.s.m.bin(c, Bin::Add, addr, off);
  5830. let x = self.code_dword(a)?;
  5831. self.write(inst, Reg::S(code + k as u8), x, None);
  5832. }
  5833. return Ok(());
  5834. }
  5835. // A buffer the program picks from the view heap by an index it
  5836. // computes (`ResourceHeap`) has no used-resource entry, and the
  5837. // heap holds a buffer view there, not a constant buffer: read as
  5838. // raw bytes, as a table's SRV is below. Read as a constant buffer
  5839. // (the host's validation: "Descriptor Type in Heap: SRV, Register
  5840. // Type: CBV", heap index 17) the loads gave nothing:
  5841. // the title's meshlet culling (BatchCullMeshlets,
  5842. // BatchCullPreSkinnedMeshlets, BatchCullBatchCSMeshlets) reads its
  5843. // batch records, mesh headers and instance transforms this way, so
  5844. // it passed no meshlet and every indirect mesh draw ran empty.
  5845. // The host's table of strides by heap slot tells a buffer view
  5846. // (not 0) from anything else, which is still read as a constant
  5847. // buffer; only the load that fits the slot runs.
  5848. let picked = match kind {
  5849. None => self.slot_stride(src)?,
  5850. Some(_) => None,
  5851. };
  5852. if let Some(stride) = picked {
  5853. let zero = self.s.m.i32(0);
  5854. let is_buffer = self.s.m.cmp(self.cur, pred::NE, stride, zero);
  5855. let at = self.begin_guarded(Some(is_buffer));
  5856. let h = self.handle(site, src, false, (11, 0))?;
  5857. let mut raw = Vec::new();
  5858. for k in 0..count {
  5859. let b = self.cur;
  5860. let off = self.s.m.i32(4 * k);
  5861. let a = self.s.m.bin(b, Bin::Add, addr, off);
  5862. let mask = self.s.m.i8(1);
  5863. let (u, al) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
  5864. let r = self.s.op(
  5865. b,
  5866. "rawBufferLoad.f32",
  5867. Attr::ReadOnly,
  5868. self.s.t.res_ret,
  5869. 139,
  5870. &[h, a, u, mask, al],
  5871. );
  5872. let x = self.s.m.extract(b, r, 0);
  5873. let x = self.as_int(x);
  5874. raw.push((x, zero));
  5875. }
  5876. let raw = self.end_guarded(at, &raw);
  5877. let other = self.s.m.cmp(self.cur, pred::EQ, stride, zero);
  5878. let at = self.begin_guarded(Some(other));
  5879. let h = self.handle(site, src, false, (13, 0x1_0000))?;
  5880. let mut both = Vec::new();
  5881. for (k, &r) in raw.iter().enumerate() {
  5882. let b = self.cur;
  5883. let off = self.s.m.i32(4 * k as u32);
  5884. let a = self.s.m.bin(b, Bin::Add, addr, off);
  5885. let x = self.cbuffer_dword(h, a);
  5886. both.push((x, r));
  5887. }
  5888. let both = self.end_guarded(at, &both);
  5889. for (k, x) in both.into_iter().enumerate() {
  5890. self.write(inst, Reg::S(code + k as u8), x, None);
  5891. }
  5892. return Ok(());
  5893. }
  5894. if matches!(kind, Some(u) if u.kind == ResourceType::Srv) {
  5895. let h = match self.root_memory(src, addr, None, false) {
  5896. Some((h, byte)) => {
  5897. addr = byte;
  5898. h
  5899. }
  5900. None => self.handle(site, src, false, (11, 0))?,
  5901. };
  5902. let c = self.cur;
  5903. for k in 0..count {
  5904. let off = self.s.m.i32(4 * k);
  5905. let a = self.s.m.bin(c, Bin::Add, addr, off);
  5906. let mask = self.s.m.i8(1);
  5907. let (u, al) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
  5908. let r = self.s.op(
  5909. c,
  5910. "rawBufferLoad.f32",
  5911. Attr::ReadOnly,
  5912. self.s.t.res_ret,
  5913. 139,
  5914. &[h, a, u, mask, al],
  5915. );
  5916. let x = self.s.m.extract(c, r, 0);
  5917. let x = self.as_int(x);
  5918. self.write(inst, Reg::S(code + k as u8), x, None);
  5919. }
  5920. return Ok(());
  5921. }
  5922. let h = self.handle(site, src, false, (13, 0x1_0000))?;
  5923. let constant = match addr {
  5924. V::Const(_)
  5925. if matches!(soffset, Operand::Scalar { code: NULL, .. }) && extra.is_none() =>
  5926. {
  5927. Some(*offset as u32)
  5928. }
  5929. _ => None,
  5930. };
  5931. let mut rows: HashMap<u32, V> = HashMap::new();
  5932. for k in 0..count {
  5933. let x = match constant {
  5934. Some(base) => {
  5935. let byte = base + 4 * k;
  5936. let row = match rows.get(&(byte >> 4)) {
  5937. Some(&r) => r,
  5938. None => {
  5939. let ri = self.s.m.i32(byte >> 4);
  5940. let r = self.s.op(
  5941. c,
  5942. "cbufferLoadLegacy.i32",
  5943. Attr::ReadOnly,
  5944. self.s.t.cbuf_ret,
  5945. 59,
  5946. &[h, ri],
  5947. );
  5948. rows.insert(byte >> 4, r);
  5949. r
  5950. }
  5951. };
  5952. self.s.m.extract(c, row, (byte >> 2) & 3)
  5953. }
  5954. None => {
  5955. let off = self.s.m.i32(4 * k);
  5956. let a = self.s.m.bin(c, Bin::Add, addr, off);
  5957. self.cbuffer_dword(h, a)
  5958. }
  5959. };
  5960. self.write(inst, Reg::S(code + k as u8), x, None);
  5961. }
  5962. Ok(())
  5963. }
  5964. /// A descriptor load (`s_load_dword*` from a table or heap) whose dwords
  5965. /// the code also reads as numbers: the console compiler computes sizes
  5966. /// from descriptor bits (an image's width, height, depth, levels; a
  5967. /// buffer's record count) instead of querying them. Those fields are
  5968. /// rebuilt from the host view's dimensions in the GFX10 layout (image
  5969. /// dword 1 bits 30-31 and dword 2 bits 0-13 width - 1, dword 2 bits
  5970. /// 14-29 height - 1, dword 3 identity swizzle, last level at 16, type at
  5971. /// 28, dword 4 depth or layers - 1; buffer dword 2 the record count).
  5972. // shortcut: the base level reads 0 (the host view starts at its own
  5973. // level 0, so sizes the code shifts by it come out right) and the other
  5974. // dwords (addresses, formats, tiling) have no host value: reading them
  5975. // stops the program.
  5976. fn descriptor_data(&mut self, inst: &Inst, site: Site) -> Result<(), Why> {
  5977. const OTHER: Why = "a descriptor's address or format read as data";
  5978. let Fields::Smem {
  5979. data: Some(Operand::Scalar { code, .. }),
  5980. ..
  5981. } = inst.fields
  5982. else {
  5983. return Err("a scalar memory read as data");
  5984. };
  5985. let count = match inst.name().strip_prefix("s_load_dword") {
  5986. Some("") => 1u32,
  5987. Some("x2") => 2,
  5988. Some("x4") => 4,
  5989. Some("x8") => 8,
  5990. Some("x16") => 16,
  5991. _ => return Err("a scalar memory read as data"),
  5992. };
  5993. // How the program uses the descriptor tells the view's kind: an image or buffer
  5994. // instruction before a scalar buffer load, which reads any buffer.
  5995. let x = self.x;
  5996. let uses = |of: Site| {
  5997. x.res
  5998. .descriptors
  5999. .iter()
  6000. .filter(|d| d.role == Role::Resource)
  6001. .filter_map(move |d| {
  6002. d.source.leaves().into_iter().find_map(|l| match *l {
  6003. Source::Loaded { load, first } if load == of => Some((d.site, first)),
  6004. _ => None,
  6005. })
  6006. })
  6007. };
  6008. let by_scalar_load = |u: &(Site, u8)| {
  6009. matches!(x.p.blocks[u.0.0].insts[u.0.1].fields, Fields::Smem { .. })
  6010. };
  6011. let use_of = |of: Site| uses(of).find(|u| !by_scalar_load(u)).or_else(|| uses(of).next());
  6012. // The console compiler loads a descriptor again wherever it needs it, and for a
  6013. // size it reads the dwords of a load that nothing uses as a descriptor (a texture
  6014. // picked from the heap by an index held per lane: one load for its width, one for
  6015. // its base level, one for each read of the image). Another load of as many dwords
  6016. // from the same address reads the same descriptor, so what uses that one tells
  6017. // this one's kind. The handle is still made from this load's own operands, which
  6018. // hold here.
  6019. let address = self.scalar.get(&site).copied();
  6020. let twin = || {
  6021. let a = address?;
  6022. let same = |s: Site| x.p.blocks[s.0].insts[s.1].name() == inst.name();
  6023. x.res
  6024. .scalar
  6025. .iter()
  6026. .filter(|(s, b)| *s != site && *b == a && same(*s))
  6027. .find_map(|(s, _)| use_of(*s))
  6028. };
  6029. let use_at = use_of(site).or_else(twin);
  6030. // A view whose kind no use tells, but what is read of it does.
  6031. let sized = match use_at {
  6032. Some(_) => None,
  6033. None => self.sized_view(inst, site, code, count),
  6034. };
  6035. // A descriptor nothing uses as one, whose size the code reads all the same (a
  6036. // texture picked from the heap by an index in a constant buffer, its width and
  6037. // height turned into a texel size): the kind from its dwords and its used-resource
  6038. // entry. Only an image whose layers or depth (dword 4) are not read: those are no 2D
  6039. // texture's; and no buffer `sized_view` did not take (a stride of 4 or less may be a
  6040. // typed view's component count, and the address is `view_address`'s below).
  6041. let layers = inst.write(Reg::S(code + 4)).is_some_and(|v| self.read_as_number(v));
  6042. let unused = if use_at.is_none() && sized.is_none() && count == 8 && !layers {
  6043. self.unused_descriptor_kind(inst, site, code, count)
  6044. } else {
  6045. None
  6046. };
  6047. let (first, props, image, uav, used) = if let Some(kind) = unused {
  6048. kind
  6049. } else {
  6050. let Some((at, first)) = use_at.or(sized.map(|_| (site, 0))) else {
  6051. // A descriptor kept per lane in VGPRs (`Resources::lane_copied`): the code only
  6052. // copies its dwords and compares them, lane against first lane, and every load
  6053. // that reaches those lanes reads one address. Each dword stands in as its place
  6054. // in the table, so the lanes compare equal as they do on the console.
  6055. if self.x.res.lane_copied.contains(&site)
  6056. && let Some(a) = self.scalar.get(&site).copied()
  6057. {
  6058. for k in 0..count {
  6059. let x = self.s.m.i32(a.offset / 4 + k);
  6060. self.write(inst, Reg::S(code + k as u8), x, None);
  6061. }
  6062. return Ok(());
  6063. }
  6064. // A sampler's descriptor: no program reads its dwords as numbers, so where one
  6065. // meets numbers at a join the register is dead on that path (`dead`), as a
  6066. // descriptor's address or format is.
  6067. let sampler = x.res.descriptors.iter().any(|d| {
  6068. d.role == Role::Sampler
  6069. && d.source.leaves().into_iter().any(
  6070. |l| matches!(*l, Source::Loaded { load, .. } if load == site),
  6071. )
  6072. });
  6073. if sampler {
  6074. self.stale.extend(inst.writes.iter().map(|w| w.1));
  6075. return Err("a sampler's descriptor read as data");
  6076. }
  6077. // A buffer view the code only takes the address of, to walk
  6078. // the memory behind it (a ray-tracing structure): the address
  6079. // from the host, the other dwords have no value.
  6080. if count <= 4
  6081. && let Some((lo, hi)) = self.view_address(site)
  6082. {
  6083. for k in 0..count {
  6084. let reg = Reg::S(code + k as u8);
  6085. match k {
  6086. 0 => self.write(inst, reg, lo, None),
  6087. 1 => self.write(inst, reg, hi, None),
  6088. _ => {
  6089. if let Some(v) = inst.write(reg) {
  6090. self.vals.insert(v, Val::Missing(OTHER));
  6091. self.stale.insert(v);
  6092. }
  6093. }
  6094. }
  6095. }
  6096. return Ok(());
  6097. }
  6098. if std::env::var_os("VICTORY_DESC_WHY").is_some() {
  6099. eprintln!(
  6100. "DESC-WHY {:#x} {} scalar={:?} lane_copied={}",
  6101. inst.machine.offset,
  6102. inst.name(),
  6103. address,
  6104. self.x.res.lane_copied.contains(&site)
  6105. );
  6106. }
  6107. return Err("a descriptor read only as data");
  6108. };
  6109. let src = Source::Loaded { load: site, first };
  6110. let used = self.used_kind(&src);
  6111. let ui: &Inst = &self.x.p.blocks[at.0].insts[at.1];
  6112. let un = ui.name();
  6113. let uav = un.contains("store")
  6114. || un.contains("atomic")
  6115. || used.is_some_and(|u| u.kind == ResourceType::Uav);
  6116. let u = if uav { 0x1000 } else { 0 };
  6117. let (props, image) = match &ui.fields {
  6118. _ if sized.is_some_and(|image| image) => ((2 | u, 0x409), Some(2)),
  6119. _ if sized.is_some() => ((11 | u, 0), None),
  6120. // A ray-tracing structure in a buffer of the host: read raw.
  6121. Fields::Image { .. } if un.starts_with("image_bvh") => ((11, 0), None),
  6122. Fields::Image { dim, .. } => {
  6123. let kind = match dim {
  6124. 0 => 1,
  6125. 1 => 2,
  6126. 2 => 4,
  6127. 4 => 6,
  6128. 5 => 7,
  6129. _ => return Err("an image dimension (cube or MSAA)"),
  6130. };
  6131. ((kind | u, 0x409), Some(kind))
  6132. }
  6133. Fields::Buffer { idxen, format, .. } => {
  6134. let stride = used.map_or(0, |u| u.stride);
  6135. let counted = inst
  6136. .write(Reg::S(code + first + 2))
  6137. .is_some_and(|v| self.read_as_number(v));
  6138. let props = if un.starts_with("buffer_load_format")
  6139. || un.starts_with("buffer_store_format")
  6140. {
  6141. (10 | u, 0x409)
  6142. } else if !counted
  6143. && *idxen
  6144. && format.is_none()
  6145. && stride >= 4
  6146. && stride.is_multiple_of(4)
  6147. {
  6148. // Nothing reads the count: the query is cleaned up.
  6149. (12 | u, stride)
  6150. } else {
  6151. // Structured ones too: the host's views of them are raw
  6152. // (see `buffer`), which count bytes, and a size asked
  6153. // for as a structured view's is that count on AMD.
  6154. (11 | u, 0)
  6155. };
  6156. if used.is_some_and(|u| u.kind == ResourceType::Cbv) {
  6157. self.stale.extend(inst.writes.iter().map(|w| w.1));
  6158. return Err("a constant buffer's descriptor read as data");
  6159. }
  6160. (props, None)
  6161. }
  6162. // Read by scalar buffer loads alone: the raw view `smem` reads it through.
  6163. Fields::Smem { .. } if used.is_some_and(|u| u.kind == ResourceType::Srv) => {
  6164. ((11, 0), None)
  6165. }
  6166. // A constant buffer: nothing of its descriptor is a number.
  6167. Fields::Smem { .. } => {
  6168. self.stale.extend(inst.writes.iter().map(|w| w.1));
  6169. return Err("a constant buffer's descriptor read as data");
  6170. }
  6171. _ => return Err("a scalar memory read as data"),
  6172. };
  6173. (first, props, image, uav, used)
  6174. };
  6175. let src = Source::Loaded { load: site, first };
  6176. let h = self.handle(site, &src, false, props)?;
  6177. let c = self.cur;
  6178. let i32t = self.s.t.i32;
  6179. let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
  6180. let mip = if image.is_some() && !uav {
  6181. self.s.m.i32(0)
  6182. } else {
  6183. self.s.m.undef(i32t)
  6184. };
  6185. let d = self
  6186. .s
  6187. .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]);
  6188. let field = |l: &mut Self, k: u32| l.s.m.extract(c, d, k);
  6189. let words: Vec<(u32, V)> = match image {
  6190. Some(kind) => {
  6191. let one = self.s.m.i32(1);
  6192. let w = field(self, 0);
  6193. let (height, depth) = match kind {
  6194. 1 => (one, one),
  6195. 2 => (field(self, 1), one),
  6196. 6 => (one, field(self, 1)),
  6197. _ => (field(self, 1), field(self, 2)),
  6198. };
  6199. let levels = if uav { one } else { field(self, 3) };
  6200. let less = |l: &mut Self, x: V| l.s.m.bin(c, Bin::Sub, x, one);
  6201. let (w, height, depth, levels) = (
  6202. less(self, w),
  6203. less(self, height),
  6204. less(self, depth),
  6205. less(self, levels),
  6206. );
  6207. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  6208. let (k30, k2, k14, k16, mask) = (
  6209. k(self, 30),
  6210. k(self, 2),
  6211. k(self, 14),
  6212. k(self, 16),
  6213. k(self, 0x3FFF),
  6214. );
  6215. let d1 = self.s.m.bin(c, Bin::Shl, w, k30);
  6216. let hi = self.s.m.bin(c, Bin::LShr, w, k2);
  6217. let hi = self.s.m.bin(c, Bin::And, hi, mask);
  6218. let ht = self.s.m.bin(c, Bin::Shl, height, k14);
  6219. let d2 = self.s.m.bin(c, Bin::Or, hi, ht);
  6220. let ty = [0, 8, 9, 0, 10, 0, 12, 13][kind as usize];
  6221. let base = k(self, 0xFAC | ty << 28);
  6222. let last = self.s.m.bin(c, Bin::Shl, levels, k16);
  6223. let d3 = self.s.m.bin(c, Bin::Or, base, last);
  6224. vec![(1, d1), (2, d2), (3, d3), (4, depth)]
  6225. }
  6226. None => {
  6227. // A raw view counts bytes; the descriptor's record count is in elements.
  6228. let n = field(self, 0);
  6229. let stride = used.map_or(0, |u| u.stride);
  6230. let counted = inst
  6231. .write(Reg::S(code + first + 2))
  6232. .is_some_and(|v| self.read_as_number(v));
  6233. let n = if props.0 & 0xFF == 11 && stride > 1 {
  6234. let k = self.s.m.i32(stride);
  6235. self.s.m.bin(c, Bin::UDiv, n, k)
  6236. } else if props.0 & 0xFF == 11
  6237. && counted
  6238. && let Some(stride) = self.slot_stride(&src)?
  6239. {
  6240. // Picked from the heap: the host's table has the stride.
  6241. let (i32t, one) = (self.s.t.i32, self.s.m.i32(1));
  6242. let k = self.s.op(c, "binary.i32", Attr::ReadNone, i32t, 39, &[stride, one]);
  6243. self.s.m.bin(c, Bin::UDiv, n, k)
  6244. } else {
  6245. n
  6246. };
  6247. let mut words = vec![(2, n)];
  6248. // Its address too, where the code computes with it and the
  6249. // host can tell it.
  6250. let computed = (0..2u8).any(|k| {
  6251. inst.write(Reg::S(code + first + k))
  6252. .is_some_and(|v| self.computed_with(v, 6))
  6253. });
  6254. // (A descriptor nothing uses as one gets it whenever the host can tell it, as
  6255. // a buffer whose address alone is read does.)
  6256. if first == 0
  6257. && (computed || unused.is_some())
  6258. && let Some((lo, hi)) = self.view_address(site)
  6259. {
  6260. words.extend([(0, lo), (1, hi)]);
  6261. }
  6262. words
  6263. }
  6264. };
  6265. for k in 0..count {
  6266. let rel = k.wrapping_sub(u32::from(first));
  6267. match words.iter().find(|w| w.0 == rel) {
  6268. Some(&(_, x)) => self.write(inst, Reg::S(code + k as u8), x, None),
  6269. None => {
  6270. if let Some(v) = inst.write(Reg::S(code + k as u8)) {
  6271. self.vals.insert(v, Val::Missing(OTHER));
  6272. self.stale.insert(v);
  6273. }
  6274. }
  6275. }
  6276. }
  6277. Ok(())
  6278. }
  6279. /// What [`Self::descriptor_data`] makes of a descriptor load that nothing uses as a
  6280. /// descriptor but whose dwords the code reads: the first dword, the handle properties,
  6281. /// the image kind (none for a buffer), whether it is an unordered view, and its
  6282. /// used-resource entry. An image's eight dwords read as a 2D texture's, a buffer's four
  6283. /// as a raw view's where the code reads its record count (dword 2); none for anything
  6284. /// else (a constant buffer, a sampler, a buffer whose address alone is read).
  6285. // shortcut: an image whose kind nothing tells is taken for a 2D texture (the title's
  6286. // reads are texel sizes of 2D textures: puddle masks, shadow masks); a host view of
  6287. // another kind would answer its own sizes.
  6288. #[allow(clippy::type_complexity)]
  6289. fn unused_descriptor_kind(
  6290. &self,
  6291. inst: &Inst,
  6292. site: Site,
  6293. code: u8,
  6294. count: u32,
  6295. ) -> Option<(u8, (u32, u32), Option<u32>, bool, Option<&'a UsedResource>)> {
  6296. // Kept per lane and compared (`Resources::lane_copied`), or a sampler's: the cases
  6297. // `descriptor_data` handles on their own.
  6298. if self.x.res.lane_copied.contains(&site)
  6299. || self.x.res.descriptors.iter().any(|d| {
  6300. d.role == Role::Sampler
  6301. && d.source.leaves().into_iter().any(
  6302. |l| matches!(*l, Source::Loaded { load, .. } if load == site),
  6303. )
  6304. })
  6305. {
  6306. return None;
  6307. }
  6308. let used = self.used_kind(&Source::Loaded {
  6309. load: site,
  6310. first: 0,
  6311. });
  6312. if used.is_some_and(|u| !matches!(u.kind, ResourceType::Srv | ResourceType::Uav)) {
  6313. return None;
  6314. }
  6315. let read = |k: u32| {
  6316. inst.write(Reg::S(code + k as u8)).is_some_and(|v| {
  6317. self.x
  6318. .p
  6319. .blocks
  6320. .iter()
  6321. .flat_map(|b| &b.insts)
  6322. .any(|i| i.reads.iter().any(|r| r.1 == v))
  6323. })
  6324. };
  6325. let uav = used.is_some_and(|u| u.kind == ResourceType::Uav);
  6326. let u = if uav { 0x1000 } else { 0 };
  6327. match count {
  6328. // width (dwords 1-2), height (2), levels (3), depth (4)
  6329. 8 if (1..5).any(read) && used.is_none_or(|u| u.dwords == 8) => {
  6330. Some((0, (2 | u, 0x409), Some(2), uav, used))
  6331. }
  6332. // the record count
  6333. 4 if read(2) && used.is_none_or(|u| u.dwords == 4) => {
  6334. Some((0, (11 | u, 0), None, uav, used))
  6335. }
  6336. _ => None,
  6337. }
  6338. }
  6339. /// `s_load_dword*` from the program's constant table.
  6340. fn code_smem(&mut self, inst: &Inst, a: Address) -> Result<(), Why> {
  6341. let Fields::Smem {
  6342. data: Some(Operand::Scalar { code, .. }),
  6343. ..
  6344. } = inst.fields
  6345. else {
  6346. return Err("a scalar load");
  6347. };
  6348. let count = match inst.name().strip_prefix("s_load_dword") {
  6349. Some("") => 1u32,
  6350. Some("x2") => 2,
  6351. Some("x4") => 4,
  6352. Some("x8") => 8,
  6353. Some("x16") => 16,
  6354. _ => return Err("a scalar load from the code"),
  6355. };
  6356. let c = self.cur;
  6357. let mut addr = self.s.m.i32(a.offset);
  6358. if let Some(value) = a.dynamic {
  6359. let mut d = self.i32_of(value)?;
  6360. // A term held per lane reached the address through
  6361. // `v_readfirstlane_b32`: the first lane's.
  6362. let per_lane = self.def_block.get(&value).is_some_and(|&b| {
  6363. let writes = |i: &Inst| i.writes.iter().any(|w| w.1 == value && matches!(w.0, Reg::V(_)));
  6364. self.x.p.blocks[b].insts.iter().any(writes)
  6365. });
  6366. if per_lane {
  6367. self.s.flags |= flags::WAVE_OPS;
  6368. let i32t = self.s.t.i32;
  6369. let first = self.s.op(c, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[d]);
  6370. d = if self.s.pixel && super::helper_own() {
  6371. let helper = self.helper_lane();
  6372. self.s.m.select(c, helper, d, first)
  6373. } else {
  6374. first
  6375. };
  6376. }
  6377. addr = self.s.m.bin(c, Bin::Add, addr, d);
  6378. }
  6379. for k in 0..count {
  6380. let off = self.s.m.i32(4 * k);
  6381. let at = self.s.m.bin(c, Bin::Add, addr, off);
  6382. let x = self.code_dword(at)?;
  6383. self.write(inst, Reg::S(code + k as u8), x, None);
  6384. }
  6385. Ok(())
  6386. }
  6387. /// The dword at a computed byte address of a constant buffer.
  6388. fn cbuffer_dword(&mut self, h: V, a: V) -> V {
  6389. let c = self.cur;
  6390. let four = self.s.m.i32(4);
  6391. let ri = self.s.m.bin(c, Bin::LShr, a, four);
  6392. let r = self.s.op(
  6393. c,
  6394. "cbufferLoadLegacy.i32",
  6395. Attr::ReadOnly,
  6396. self.s.t.cbuf_ret,
  6397. 59,
  6398. &[h, ri],
  6399. );
  6400. let two = self.s.m.i32(2);
  6401. let three = self.s.m.i32(3);
  6402. let comp = self.s.m.bin(c, Bin::LShr, a, two);
  6403. let comp = self.s.m.bin(c, Bin::And, comp, three);
  6404. let mut x = self.s.m.extract(c, r, 0);
  6405. for j in 1..4 {
  6406. let e = self.s.m.extract(c, r, j);
  6407. let jc = self.s.m.i32(j);
  6408. let is = self.s.m.cmp(c, pred::EQ, comp, jc);
  6409. x = self.s.m.select(c, is, e, x);
  6410. }
  6411. x
  6412. }
  6413. /// `channels` channels of the element at byte `off` of raw buffer `h`,
  6414. /// converted from the GFX10 buffer format `format` as the hardware's
  6415. /// typed loads do (channels past the format's read 0, 0, 0, 1).
  6416. // shortcut: the descriptor's channel swizzle is taken as the identity
  6417. // (it is for raw views and the descriptors code builds), elements of 4
  6418. // bytes or more as dword-aligned.
  6419. fn format_load(&mut self, h: V, off: V, format: u8, channels: u32) -> Result<Vec<V>, Why> {
  6420. let (bits, numeric) = buffer_format(format).ok_or("a buffer format")?;
  6421. let c = self.cur;
  6422. let total: u32 = bits.iter().sum();
  6423. let (u, align) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
  6424. let load = |l: &mut Self, at: V, n: u32| -> Vec<V> {
  6425. let mask = l.s.m.i8((1u8 << n) - 1);
  6426. let r = l.s.op(
  6427. c,
  6428. "rawBufferLoad.f32",
  6429. Attr::ReadOnly,
  6430. l.s.t.res_ret,
  6431. 139,
  6432. &[h, at, u, mask, align],
  6433. );
  6434. (0..n)
  6435. .map(|k| {
  6436. let x = l.s.m.extract(c, r, k);
  6437. l.as_int(x)
  6438. })
  6439. .collect()
  6440. };
  6441. let words = if total < 32 {
  6442. // A byte or half inside the dword that holds it.
  6443. let (not3, three) = (self.s.m.i32(!3), self.s.m.i32(3));
  6444. let at = self.s.m.bin(c, Bin::And, off, not3);
  6445. let w = load(self, at, 1)[0];
  6446. let byte = self.s.m.bin(c, Bin::And, off, three);
  6447. let sh = self.s.m.bin(c, Bin::Shl, byte, three);
  6448. vec![self.s.m.bin(c, Bin::LShr, w, sh)]
  6449. } else {
  6450. load(self, off, total / 32)
  6451. };
  6452. let float = |l: &mut Self, f: V| l.as_int(f);
  6453. let mut out = Vec::new();
  6454. let mut at = 0;
  6455. for &w in bits {
  6456. let word = words[(at / 32) as usize];
  6457. let field = if w == 32 {
  6458. word
  6459. } else {
  6460. let sh = self.s.m.i32(at % 32);
  6461. let t = self.s.m.bin(c, Bin::LShr, word, sh);
  6462. let m = self.s.m.i32((1 << w) - 1);
  6463. self.s.m.bin(c, Bin::And, t, m)
  6464. };
  6465. at += w;
  6466. // Sign-extended from the field's top bit.
  6467. let signed = |l: &mut Self| {
  6468. if w == 32 {
  6469. return field;
  6470. }
  6471. let k = l.s.m.i32(32 - w);
  6472. let t = l.s.m.bin(c, Bin::Shl, field, k);
  6473. l.s.m.bin(c, Bin::AShr, t, k)
  6474. };
  6475. let f32t = self.s.t.f32;
  6476. // A normalized format's ends are exactly 1.0 and -1.0. The host
  6477. // may divide through a reciprocal and land just below 1.0: RDNA
  6478. // 4 loaded 16_16_UNORM's 65535 as the half 0x3BFF, not 0x3C00.
  6479. let x = match numeric {
  6480. Numeric::Unorm => {
  6481. let top = (1u64 << w) - 1;
  6482. let q = if w <= 16 {
  6483. let q = self.norm_quotient(field, w);
  6484. self.as_float(q)
  6485. } else {
  6486. let f = self.s.m.cast(c, Cast::UiToFp, field, f32t);
  6487. let max = self.s.m.f32((top as f32).to_bits());
  6488. self.s.m.bin(c, Bin::SDiv, f, max)
  6489. };
  6490. let (high, one) = (self.s.m.i32(top as u32), self.s.m.f32(1.0f32.to_bits()));
  6491. let at_top = self.s.m.cmp(c, pred::EQ, field, high);
  6492. let q = self.s.m.select(c, at_top, one, q);
  6493. float(self, q)
  6494. }
  6495. Numeric::Snorm => {
  6496. let s = signed(self);
  6497. let top = (1u32 << (w - 1)) - 1;
  6498. let q = if w <= 17 {
  6499. // The magnitude's quotient, signed (codes at and
  6500. // below -top are -1.0 below).
  6501. let (zero, sign) = (self.s.m.i32(0), self.s.m.i32(0x8000_0000));
  6502. let neg = self.s.m.cmp(c, pred::SLT, s, zero);
  6503. let minus = self.s.m.bin(c, Bin::Sub, zero, s);
  6504. let m = self.s.m.select(c, neg, minus, s);
  6505. let q = self.norm_quotient(m, w - 1);
  6506. let sign = self.s.m.select(c, neg, sign, zero);
  6507. let q = self.s.m.bin(c, Bin::Or, q, sign);
  6508. self.as_float(q)
  6509. } else {
  6510. let f = self.s.m.cast(c, Cast::SiToFp, s, f32t);
  6511. let max = self.s.m.f32((top as f32).to_bits());
  6512. self.s.m.bin(c, Bin::SDiv, f, max)
  6513. };
  6514. // The lowest value is -1.0 too, as is the one above it.
  6515. let (high, one) = (self.s.m.i32(top), self.s.m.f32(1.0f32.to_bits()));
  6516. let at_top = self.s.m.cmp(c, pred::SGE, s, high);
  6517. let q = self.s.m.select(c, at_top, one, q);
  6518. let low = self.s.m.i32(top.wrapping_neg());
  6519. let minus_one = self.s.m.f32((-1.0f32).to_bits());
  6520. let at_bottom = self.s.m.cmp(c, pred::SLE, s, low);
  6521. let q = self.s.m.select(c, at_bottom, minus_one, q);
  6522. float(self, q)
  6523. }
  6524. Numeric::Uscaled => {
  6525. let f = self.s.m.cast(c, Cast::UiToFp, field, f32t);
  6526. float(self, f)
  6527. }
  6528. Numeric::Sscaled => {
  6529. let s = signed(self);
  6530. let f = self.s.m.cast(c, Cast::SiToFp, s, f32t);
  6531. float(self, f)
  6532. }
  6533. Numeric::Uint => field,
  6534. Numeric::Sint => signed(self),
  6535. Numeric::Float if w == 32 => field,
  6536. Numeric::Float => {
  6537. let h = match half_shift(w) {
  6538. 0 => field,
  6539. k => {
  6540. let sh = self.s.m.i32(k);
  6541. self.s.m.bin(c, Bin::Shl, field, sh)
  6542. }
  6543. };
  6544. let f = self
  6545. .s
  6546. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]);
  6547. float(self, f)
  6548. }
  6549. };
  6550. out.push(x);
  6551. }
  6552. let one = match numeric {
  6553. Numeric::Uint | Numeric::Sint => 1,
  6554. _ => 1.0f32.to_bits(),
  6555. };
  6556. for k in out.len() as u32..channels {
  6557. out.push(self.s.m.i32(if k == 3 { one } else { 0 }));
  6558. }
  6559. out.truncate(channels as usize);
  6560. Ok(out)
  6561. }
  6562. /// The bits of the float nearest to `a / d`, `d = 2^w - 1`, for codes
  6563. /// `0 <= a < d` and `w <= 16`: what the console's buffer unit gives for
  6564. /// a normalized code. The host's division is not exact (the RX 6700 XT
  6565. /// returns 8-bit codes one ulp high and some 16-bit codes one ulp low),
  6566. /// and titles truncate `x * d` back to the code (a material index in a
  6567. /// vertex colour's alpha), which a quotient one ulp low turns into the
  6568. /// code below.
  6569. ///
  6570. /// `Q = floor(a * 2^32 / d) = a * K + floor(a * r / d)` with `K =
  6571. /// floor(2^32 / d)` and `r = 2^32 mod d` (no division when `r` is 1:
  6572. /// widths dividing 32). `a / d` is never exact for `0 < a < d` (`d`
  6573. /// odd, `r` coprime to it), so `Q` rounds to 24 bits up exactly when
  6574. /// its highest dropped bit is set, and the result is that integer (at
  6575. /// most 2^24, so its conversion is exact on any host) scaled by a power
  6576. /// of two; `Q` itself when it fits, the quotient's further bits then
  6577. /// lying below half an ulp. That holds for every code of every width but
  6578. /// 11 and 12 (checked for all codes of widths 2 to 16), which take
  6579. /// [`Self::exact_norm`]. The host's conversion of a larger integer is
  6580. /// not relied on: WARP rounds those above 2^31 otherwise.
  6581. fn norm_quotient(&mut self, a: V, w: u32) -> V {
  6582. if matches!(w, 11 | 12) {
  6583. return self.exact_norm(a, w);
  6584. }
  6585. let c = self.cur;
  6586. let d = (1u64 << w) - 1;
  6587. let (kk, r) = ((1u64 << 32) / d, (1u64 << 32) % d);
  6588. let k = |l: &mut Self, v: u64| l.s.m.i32(v as u32);
  6589. let (one, kv) = (k(self, 1), k(self, kk));
  6590. let mut q = self.s.m.bin(c, Bin::Mul, a, kv);
  6591. if r != 1 {
  6592. let (rv, dv) = (k(self, r), k(self, d));
  6593. let t = self.s.m.bin(c, Bin::Mul, a, rv);
  6594. let more = self.s.m.bin(c, Bin::UDiv, t, dv);
  6595. q = self.s.m.bin(c, Bin::Add, q, more);
  6596. }
  6597. // The bits to drop (1 to 8) from the exponent of `q >> 8`, which
  6598. // converts exactly (fewer than 25 bits); none when `q` fits.
  6599. let k8 = k(self, 8);
  6600. let top = self.s.m.bin(c, Bin::LShr, q, k8);
  6601. let top = self.s.m.cast(c, Cast::UiToFp, top, self.s.t.f32);
  6602. let top = self.as_int(top);
  6603. let k23 = k(self, 23);
  6604. let e = self.s.m.bin(c, Bin::LShr, top, k23);
  6605. let bias = k(self, 127 + 15);
  6606. let shift = self.s.m.bin(c, Bin::Sub, e, bias);
  6607. let (zero, b24) = (k(self, 0), k(self, 1 << 24));
  6608. let fits = self.s.m.cmp(c, pred::IULT, q, b24);
  6609. let shift = self.s.m.select(c, fits, zero, shift);
  6610. // Rounded up when the highest dropped bit is set: `a / d` is never
  6611. // exact, so a dropped half is more than half, never a tie.
  6612. let up = self.s.m.bin(c, Bin::Shl, q, one);
  6613. let up = self.s.m.bin(c, Bin::LShr, up, shift);
  6614. let up = self.s.m.bin(c, Bin::And, up, one);
  6615. let m = self.s.m.bin(c, Bin::LShr, q, shift);
  6616. let m = self.s.m.bin(c, Bin::Add, m, up);
  6617. // At most 2^24: exact as a float, and so its scale by 2^(shift - 32).
  6618. let f = self.s.m.cast(c, Cast::UiToFp, m, self.s.t.f32);
  6619. let b95 = k(self, 127 - 32);
  6620. let scale = self.s.m.bin(c, Bin::Add, shift, b95);
  6621. let scale = self.s.m.bin(c, Bin::Shl, scale, k23);
  6622. let scale = self.as_float(scale);
  6623. let f = self.s.m.bin(c, Bin::Mul, f, scale);
  6624. self.as_int(f)
  6625. }
  6626. /// [`Self::norm_quotient`] in integers only, for any width up to 16: `Q`
  6627. /// as there, 8 more bits when that leaves fewer than 25 (codes of wide
  6628. /// formats near 0), then rounded to 24 bits to nearest even with the
  6629. /// remainder as sticky bit, and assembled as float bits.
  6630. fn exact_norm(&mut self, a: V, w: u32) -> V {
  6631. let c = self.cur;
  6632. let d = (1u64 << w) - 1;
  6633. let (kk, r) = ((1u64 << 32) / d, (1u64 << 32) % d);
  6634. let k = |l: &mut Self, v: u64| l.s.m.i32(v as u32);
  6635. let (one, zero, dv, k8) = (k(self, 1), k(self, 0), k(self, d), k(self, 8));
  6636. let kv = k(self, kk);
  6637. let mut q = self.s.m.bin(c, Bin::Mul, a, kv);
  6638. let mut rem = a;
  6639. if r != 1 {
  6640. let rv = k(self, r);
  6641. let t = self.s.m.bin(c, Bin::Mul, a, rv);
  6642. let more = self.s.m.bin(c, Bin::UDiv, t, dv);
  6643. q = self.s.m.bin(c, Bin::Add, q, more);
  6644. rem = self.s.m.bin(c, Bin::URem, t, dv);
  6645. }
  6646. // The exponent's bias less the 32 (or 40) fraction bits of `q`; the
  6647. // shift below is added.
  6648. let mut bias = k(self, 127 + 23 - 32);
  6649. if kk < 1 << 24 {
  6650. // Fewer than 25 bits for the smallest codes: 8 more.
  6651. let t = self.s.m.bin(c, Bin::Shl, rem, k8);
  6652. let more = self.s.m.bin(c, Bin::UDiv, t, dv);
  6653. let rest = self.s.m.bin(c, Bin::URem, t, dv);
  6654. let wide = self.s.m.bin(c, Bin::Shl, q, k8);
  6655. let wide = self.s.m.bin(c, Bin::Or, wide, more);
  6656. let limit = k(self, 1 << 24);
  6657. let small = self.s.m.cmp(c, pred::IULT, q, limit);
  6658. q = self.s.m.select(c, small, wide, q);
  6659. rem = self.s.m.select(c, small, rest, rem);
  6660. let b40 = k(self, 127 + 23 - 40);
  6661. bias = self.s.m.select(c, small, b40, bias);
  6662. }
  6663. // Bits to drop: the bit length less 24, 1 to 8.
  6664. let mut shift = one;
  6665. for bit in 25..32 {
  6666. let at = k(self, 1 << bit);
  6667. let ge = self.s.m.cmp(c, pred::IUGE, q, at);
  6668. let add = self.s.m.select(c, ge, one, zero);
  6669. shift = self.s.m.bin(c, Bin::Add, shift, add);
  6670. }
  6671. let mant = self.s.m.bin(c, Bin::LShr, q, shift);
  6672. let below = self.s.m.bin(c, Bin::Sub, shift, one);
  6673. let half = self.s.m.bin(c, Bin::LShr, q, below);
  6674. let half = self.s.m.bin(c, Bin::And, half, one);
  6675. let low = self.s.m.bin(c, Bin::Shl, one, below);
  6676. let low = self.s.m.bin(c, Bin::Sub, low, one);
  6677. let low = self.s.m.bin(c, Bin::And, q, low);
  6678. let rest = self.s.m.bin(c, Bin::Or, low, rem);
  6679. let sticky = self.s.m.cmp(c, pred::NE, rest, zero);
  6680. let odd = self.s.m.bin(c, Bin::And, mant, one);
  6681. let tie = self.s.m.select(c, sticky, one, odd);
  6682. let up = self.s.m.bin(c, Bin::And, half, tie);
  6683. let mant = self.s.m.bin(c, Bin::Add, mant, up);
  6684. // Rounding up to 2^24 moves to the next exponent.
  6685. let k24 = k(self, 24);
  6686. let carry = self.s.m.bin(c, Bin::LShr, mant, k24);
  6687. let mant = self.s.m.bin(c, Bin::LShr, mant, carry);
  6688. let e = self.s.m.bin(c, Bin::Add, bias, shift);
  6689. let e = self.s.m.bin(c, Bin::Add, e, carry);
  6690. let k23 = k(self, 23);
  6691. let e = self.s.m.bin(c, Bin::Shl, e, k23);
  6692. let fraction = k(self, 0x7F_FFFF);
  6693. let m = self.s.m.bin(c, Bin::And, mant, fraction);
  6694. let bits = self.s.m.bin(c, Bin::Or, e, m);
  6695. let is_zero = self.s.m.cmp(c, pred::EQ, a, zero);
  6696. self.s.m.select(c, is_zero, zero, bits)
  6697. }
  6698. /// Channels of buffer format `format`, as [`Self::format_load`] gives
  6699. /// them, as d16 data: 16 bits each, two per dword, low half first (an
  6700. /// odd last high half 0). Integer formats keep their low 16 bits; the
  6701. /// others become f16.
  6702. fn d16_channels(&mut self, format: u8, channels: Vec<V>) -> Result<Vec<V>, Why> {
  6703. let (_, numeric) = buffer_format(format).ok_or("a buffer format")?;
  6704. let c = self.cur;
  6705. let mut halves = Vec::new();
  6706. for x in channels {
  6707. halves.push(if matches!(numeric, Numeric::Uint | Numeric::Sint) {
  6708. let m = self.s.m.i32(0xFFFF);
  6709. self.s.m.bin(c, Bin::And, x, m)
  6710. } else {
  6711. let (f, i32t) = (self.as_float(x), self.s.t.i32);
  6712. self.s
  6713. .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f])
  6714. });
  6715. }
  6716. let mut out = Vec::new();
  6717. for pair in halves.chunks(2) {
  6718. out.push(match *pair {
  6719. [lo, hi] => {
  6720. let k16 = self.s.m.i32(16);
  6721. let hi = self.s.m.bin(c, Bin::Shl, hi, k16);
  6722. self.s.m.bin(c, Bin::Or, lo, hi)
  6723. }
  6724. [lo] => lo,
  6725. _ => unreachable!("chunks of one or two"),
  6726. });
  6727. }
  6728. Ok(out)
  6729. }
  6730. /// The byte offset a buffer descriptor built around a root descriptor adds
  6731. /// (constant and computed parts); none for other descriptors.
  6732. fn built_offset(&mut self, src: &Source) -> Result<(u32, Option<V>), Why> {
  6733. match src {
  6734. Source::Built { address, .. } => {
  6735. let mut x = match address.dynamic {
  6736. Some(v) => Some(self.i32_of(v)?),
  6737. None => None,
  6738. };
  6739. if let Some(bias) = self.root_bias(address.param) {
  6740. x = Some(match x {
  6741. Some(d) => self.s.m.bin(self.cur, Bin::Add, d, bias),
  6742. None => bias,
  6743. });
  6744. }
  6745. Ok((address.offset, x))
  6746. }
  6747. _ => Ok((0, None)),
  6748. }
  6749. }
  6750. /// For a root view the host binds as a raw view that may begin before
  6751. /// the title's address (`shader.rs` `USER_VIEW_BIAS`): the bytes to add
  6752. /// to offsets through it. Every root UAV (root SRVs keep the views they
  6753. /// have).
  6754. fn root_bias(&mut self, param: usize) -> Option<V> {
  6755. use super::shader::USER_VIEW_BIAS;
  6756. let rp = *self.x.native.layout.get(param)?;
  6757. // (Title memory by address where the user-data table is spilled:
  6758. // [`Lower::root_memory`].)
  6759. if rp.root != RootType::Descriptor || crate::spill::is_spilled(self.x.native) {
  6760. return None;
  6761. }
  6762. let kind = self
  6763. .x
  6764. .native
  6765. .used
  6766. .iter()
  6767. .find(|u| u.user_data == rp.user_data)
  6768. .map(|u| u.kind);
  6769. (kind == Some(ResourceType::Uav)).then(|| self.host_word(RootType::Other(USER_VIEW_BIAS), rp.slot, 0))
  6770. }
  6771. /// The used-resource entry a descriptor loaded from a table falls in.
  6772. fn used_kind(&self, src: &Source) -> Option<&'a UsedResource> {
  6773. if let Source::Phi { args, .. } | Source::Select { args, .. } | Source::Lanes { args, .. } =
  6774. src
  6775. {
  6776. return self.used_kind(args.first()?);
  6777. }
  6778. if let Source::LanePhi { args, .. } = src {
  6779. return args.iter().flatten().find_map(|a| self.used_kind(a));
  6780. }
  6781. if let Source::Built { address, .. } = src {
  6782. let rp = self.x.native.layout.get(address.param)?;
  6783. return self
  6784. .x
  6785. .native
  6786. .used
  6787. .iter()
  6788. .find(|u| u.root == RootType::Descriptor && u.user_data == rp.user_data);
  6789. }
  6790. let (Source::Loaded { load, first } | Source::Fetched { load, first }) = src else {
  6791. return None;
  6792. };
  6793. let a = self.scalar.get(load)?;
  6794. let rp = self.x.native.layout.get(a.param)?;
  6795. if rp.root != RootType::Table {
  6796. return None;
  6797. }
  6798. let dword = (a.offset / 4) + u32::from(*first);
  6799. self.x
  6800. .native
  6801. .used
  6802. .iter()
  6803. .filter(|u| {
  6804. u.root == RootType::Table
  6805. && u.user_data == rp.user_data
  6806. && u.table_offset_dwords <= dword
  6807. })
  6808. .max_by_key(|u| u.table_offset_dwords)
  6809. }
  6810. /// A handle for the descriptor `src` read at `site`.
  6811. fn handle(
  6812. &mut self,
  6813. site: Site,
  6814. src: &Source,
  6815. sampler: bool,
  6816. props: (u32, u32),
  6817. ) -> Result<V, Why> {
  6818. match src {
  6819. Source::Loaded { load, first } => {
  6820. let key = (self.cur, *load, *first, sampler, props);
  6821. if let Some(&h) = self.handles.get(&key) {
  6822. return Ok(h);
  6823. }
  6824. let index = self.heap_index(*load, *first, sampler)?;
  6825. let (index, bounded) = self.raw_twin(src, index, sampler, props);
  6826. // A waterfall loop's load at the first lane's offset reads
  6827. // each lane's own entry (see `resource::Waterfall`).
  6828. let per_lane = self.x.res.waterfall.loads.contains(load);
  6829. let h = self
  6830. .s
  6831. .heap_handle_at(self.cur, index, sampler, per_lane, props, bounded);
  6832. self.handles.insert(key, h);
  6833. Ok(h)
  6834. }
  6835. Source::Constant(words) if sampler => {
  6836. let n = self.register_sampler(words, props.0 & 0x8000 != 0)?;
  6837. Ok(self.s.sampler_handle(self.cur, n))
  6838. }
  6839. Source::Constant(_) => Err("a constant resource descriptor"),
  6840. Source::Built { .. } if self.root_copy.is_some() => self.root_copy.ok_or("no copy"),
  6841. Source::Built { address, .. } => {
  6842. let rp = *self
  6843. .x
  6844. .native
  6845. .layout
  6846. .get(address.param)
  6847. .ok_or("a descriptor built around a table in the code")?;
  6848. let kind = self
  6849. .x
  6850. .native
  6851. .used
  6852. .iter()
  6853. .find(|u| u.user_data == rp.user_data)
  6854. .map(|u| u.kind);
  6855. match (rp.root, kind, props.0) {
  6856. (RootType::Descriptor, Some(ResourceType::Cbv) | None, 13) => {
  6857. Ok(self.s.root_cbv_handle(rp.slot))
  6858. }
  6859. (RootType::Descriptor, Some(ResourceType::Srv), 11) => {
  6860. Ok(self.s.root_srv_handle(rp.slot))
  6861. }
  6862. // A root UAV: a raw buffer whether the access reads
  6863. // (11) or writes (11 with the UAV bit). Indexed
  6864. // accesses reach here as raw ones at index times the
  6865. // entry's stride (`buffer`).
  6866. (RootType::Descriptor, Some(ResourceType::Uav), 11 | 0x100b) => {
  6867. Ok(self.s.root_uav_handle(rp.slot))
  6868. }
  6869. (RootType::Descriptor, Some(ResourceType::Srv), 0x100b) => {
  6870. Err("a write through a root SRV")
  6871. }
  6872. _ => Err("a typed root view"),
  6873. }
  6874. }
  6875. Source::Phi { block, args } => {
  6876. let _ = site;
  6877. let phi = self.descriptor_phi(*block, args, sampler, 8)?;
  6878. let (index, bounded) = self.raw_twin(src, phi, sampler, props);
  6879. Ok(self.s.heap_handle_at(self.cur, index, sampler, false, props, bounded))
  6880. }
  6881. Source::Select { scc, args } => {
  6882. // The heap index of each choice, picked by SCC (uniform).
  6883. let [
  6884. Source::Loaded { load: a, first: fa },
  6885. Source::Loaded { load: b, first: fb },
  6886. ] = args[..]
  6887. else {
  6888. return Err("a descriptor chosen by a condition");
  6889. };
  6890. let cond = match self.get(*scc)? {
  6891. Val::Bit(x) => x,
  6892. _ => return Err("SCC without a value"),
  6893. };
  6894. let set = self.heap_index(a, fa, sampler)?;
  6895. let clear = self.heap_index(b, fb, sampler)?;
  6896. let index = self.s.m.select(self.cur, cond, set, clear);
  6897. let (index, bounded) = self.raw_twin(src, index, sampler, props);
  6898. Ok(self.s.heap_handle_at(self.cur, index, sampler, false, props, bounded))
  6899. }
  6900. Source::Fetched { .. } | Source::Lanes { .. } | Source::LanePhi { .. } => {
  6901. // A descriptor each lane has its own of (a waterfall loop
  6902. // reads it from the first active lane): each lane's heap
  6903. // index, non-uniform.
  6904. let index = self.lane_heap_index(src, sampler)?;
  6905. let (index, bounded) = self.raw_twin(src, index, sampler, props);
  6906. Ok(self.s.heap_handle_at(self.cur, index, sampler, true, props, bounded))
  6907. }
  6908. }
  6909. }
  6910. /// The heap index to read descriptor `src` at, `index` being the title's:
  6911. /// for a buffer read as raw bytes, through a table or picked from the
  6912. /// heap itself (or picked and read as a constant buffer), the host's raw
  6913. /// twin of that slot ([`super::shader::raw_views`]), whose reads end where
  6914. /// the view does. Everything else (textures, typed buffers, tables'
  6915. /// constant buffers) stays in place. And whether it is a twin's (inside
  6916. /// the host's heap).
  6917. ///
  6918. /// Tables too: a view that does not begin on 16 bytes cannot be raw, and
  6919. /// a pixel program of the main pass (3711fdad456538a1, stopped at in the
  6920. /// device losses of runs n03 and n04) reads a structured one of 8 byte
  6921. /// elements at 8 as raw bytes per lane.
  6922. fn raw_twin(&mut self, src: &Source, index: V, sampler: bool, props: (u32, u32)) -> (V, bool) {
  6923. // Raw and constant buffers (DXIL resource kinds 11 and 13).
  6924. const RAW: u32 = 11;
  6925. const CONSTANT: u32 = 13;
  6926. let first = super::shader::raw_views();
  6927. let picked = |leaf: &&Source| {
  6928. let (Source::Loaded { load, .. } | Source::Fetched { load, .. }) = leaf else {
  6929. return false;
  6930. };
  6931. self.scalar
  6932. .get(load)
  6933. .and_then(|a| self.x.native.layout.get(a.param))
  6934. .is_some_and(|p| {
  6935. p.root == RootType::ResourceHeap || (p.root == RootType::Table && props.0 & 0xFF == RAW)
  6936. })
  6937. };
  6938. if first == 0 || sampler || !matches!(props.0 & 0xFF, RAW | CONSTANT) || !src.leaves().iter().all(picked) {
  6939. return (index, false);
  6940. }
  6941. let c = self.cur;
  6942. let (last, first) = (self.s.m.i32(first - 1), self.s.m.i32(first));
  6943. let i32t = self.s.t.i32;
  6944. // (As `dx.op.binary` UMin, see `heap_handle`.)
  6945. let index = self.s.op(c, "binary.i32", Attr::ReadNone, i32t, 40, &[index, last]);
  6946. self.s.m.tag(index, Tag::Clamp);
  6947. (self.s.m.bin(c, Bin::Or, index, first), true)
  6948. }
  6949. /// The heap index a descriptor phi picks. Each predecessor computes its
  6950. /// heap index at its end and the join picks one with a phi; a
  6951. /// predecessor whose descriptor is itself chosen by control flow (a
  6952. /// phi of an earlier join, which dominates it) gives that join's phi,
  6953. /// at most `depth` joins deep.
  6954. fn descriptor_phi(
  6955. &mut self,
  6956. block: usize,
  6957. args: &[Source],
  6958. sampler: bool,
  6959. depth: u32,
  6960. ) -> Result<V, Why> {
  6961. const WHY: Why = "a descriptor chosen by control flow";
  6962. let p = self.x.p;
  6963. let mut incoming = Vec::new();
  6964. for (&q, arg) in p.blocks[block].preds.iter().zip(args) {
  6965. if self.block[q].is_none() {
  6966. continue;
  6967. }
  6968. let tail = self.tail[q].ok_or(WHY)?;
  6969. let at = self.edges.get(&(q, block)).copied().unwrap_or(tail);
  6970. let index = match arg {
  6971. Source::Loaded { load, first } => {
  6972. let here = std::mem::replace(&mut self.cur, at);
  6973. let index = self.heap_index(*load, *first, sampler);
  6974. self.cur = here;
  6975. index?
  6976. }
  6977. Source::Phi { block: inner, args: inner_args } if depth > 0 => {
  6978. self.descriptor_phi(*inner, inner_args, sampler, depth - 1)?
  6979. }
  6980. _ => return Err(WHY),
  6981. };
  6982. incoming.push((index, at));
  6983. }
  6984. let join = self.block[block].ok_or(WHY)?;
  6985. let phi = self.s.m.phi(join, self.s.t.i32);
  6986. self.s.m.set_phi(phi, incoming);
  6987. Ok(phi)
  6988. }
  6989. /// Registers an immediate sampler constant and returns its slot index: a
  6990. /// constant used with and without comparison takes one slot for each.
  6991. fn register_sampler(&mut self, words: &[u32], cmp: bool) -> Result<u32, Why> {
  6992. let words: [u32; 4] = words
  6993. .get(..4)
  6994. .and_then(|w| w.try_into().ok())
  6995. .ok_or("a sampler constant")?;
  6996. let slot = self
  6997. .samplers
  6998. .iter()
  6999. .enumerate()
  7000. .position(|(n, w)| *w == words && (self.s.cmp_samplers >> n & 1 != 0) == cmp);
  7001. let n = match slot {
  7002. Some(n) => n,
  7003. None => {
  7004. let n = self.samplers.len();
  7005. if n >= u64::BITS as usize {
  7006. return Err("more than 64 immediate sampler slots");
  7007. }
  7008. self.samplers.push(words);
  7009. self.s.cmp_samplers |= u64::from(cmp) << n;
  7010. n
  7011. }
  7012. };
  7013. Ok(n as u32)
  7014. }
  7015. /// Resolves a control-flow phi of immediate sampler constants into either a
  7016. /// single static sampler register (`One`) or a uniform `i32` phi index over
  7017. /// `regs` (`Many`) for branch dispatch at the sample site.
  7018. fn sampler_phi_choice(
  7019. &mut self,
  7020. block: usize,
  7021. args: &[Source],
  7022. cmp: bool,
  7023. depth: u32,
  7024. ) -> Result<(Option<V>, Vec<u32>), Why> {
  7025. const WHY: Why = "a descriptor chosen by control flow";
  7026. let mut distinct: Vec<[u32; 4]> = Vec::new();
  7027. self.collect_constant_samplers(block, args, depth, &mut distinct)?;
  7028. if distinct.is_empty() {
  7029. return Err(WHY);
  7030. }
  7031. let mut regs = Vec::with_capacity(distinct.len());
  7032. for w in &distinct {
  7033. regs.push(self.register_sampler(w, cmp)?);
  7034. }
  7035. if regs.len() == 1 {
  7036. return Ok((None, regs));
  7037. }
  7038. let idx = self.sampler_index_phi(block, args, 0, &distinct, depth)?;
  7039. Ok((Some(idx), regs))
  7040. }
  7041. fn collect_constant_samplers(
  7042. &self,
  7043. block: usize,
  7044. args: &[Source],
  7045. depth: u32,
  7046. distinct: &mut Vec<[u32; 4]>,
  7047. ) -> Result<(), Why> {
  7048. const WHY: Why = "a descriptor chosen by control flow";
  7049. let p = self.x.p;
  7050. for (&q, arg) in p.blocks[block].preds.iter().zip(args) {
  7051. if self.block[q].is_none() {
  7052. continue;
  7053. }
  7054. match arg {
  7055. Source::Constant(w) if w.len() >= 4 => {
  7056. let k: [u32; 4] = w[..4].try_into().unwrap();
  7057. if !distinct.contains(&k) {
  7058. distinct.push(k);
  7059. }
  7060. }
  7061. Source::Phi {
  7062. block: inner,
  7063. args: inner_args,
  7064. } if depth > 0 => {
  7065. self.collect_constant_samplers(*inner, inner_args, depth - 1, distinct)?;
  7066. }
  7067. _ => return Err(WHY),
  7068. }
  7069. }
  7070. Ok(())
  7071. }
  7072. fn sampler_index_phi(
  7073. &mut self,
  7074. block: usize,
  7075. args: &[Source],
  7076. lower: u32,
  7077. distinct: &[[u32; 4]],
  7078. depth: u32,
  7079. ) -> Result<V, Why> {
  7080. const WHY: Why = "a descriptor chosen by control flow";
  7081. let p = self.x.p;
  7082. let mut incoming = Vec::new();
  7083. for (&q, arg) in p.blocks[block].preds.iter().zip(args) {
  7084. if self.block[q].is_none() {
  7085. continue;
  7086. }
  7087. let tail = self.tail[q].ok_or(WHY)?;
  7088. let at = self.edges.get(&(q, block)).copied().unwrap_or(tail);
  7089. let idx = match arg {
  7090. Source::Constant(w) if w.len() >= 4 => {
  7091. let k: [u32; 4] = w[..4].try_into().unwrap();
  7092. let pos = distinct.iter().position(|d| *d == k).ok_or(WHY)? as u32;
  7093. self.s.m.i32(lower + pos)
  7094. }
  7095. Source::Phi {
  7096. block: inner,
  7097. args: inner_args,
  7098. } if depth > 0 => {
  7099. self.sampler_index_phi(*inner, inner_args, lower, distinct, depth - 1)?
  7100. }
  7101. _ => return Err(WHY),
  7102. };
  7103. incoming.push((idx, at));
  7104. }
  7105. let join = self.block[block].ok_or(WHY)?;
  7106. let phi = self.s.m.phi(join, self.s.t.i32);
  7107. self.s.m.set_phi(phi, incoming);
  7108. Ok(phi)
  7109. }
  7110. /// The bytes per element of the buffer view `src` names, if the program
  7111. /// picks it from the view heap at an index it computes (root type
  7112. /// `ResourceHeap`): read from the host's table by heap slot in the
  7113. /// current block.
  7114. fn slot_stride(&mut self, src: &Source) -> Result<Option<V>, Why> {
  7115. let word = self.slot_word(src)?;
  7116. Ok(word.map(|word| {
  7117. let bits = self.s.m.i32(super::shader::VIEW_STRIDE_BITS);
  7118. self.s.m.bin(self.cur, Bin::And, word, bits)
  7119. }))
  7120. }
  7121. /// Whether the typed buffer view `src` names is one of an integer format,
  7122. /// and whether a signed one, as [`Self::slot_stride`] (`None`: a view the
  7123. /// program does not pick from the heap).
  7124. fn integer_view(&mut self, src: &Source) -> Result<Option<(V, V)>, Why> {
  7125. let Some(word) = self.slot_word(src)? else {
  7126. return Ok(None);
  7127. };
  7128. let c = self.cur;
  7129. let zero = self.s.m.i32(0);
  7130. let [int, signed] = [super::shader::VIEW_INTEGER, super::shader::VIEW_SIGNED].map(|bit| {
  7131. let bit = self.s.m.i32(bit);
  7132. let x = self.s.m.bin(c, Bin::And, word, bit);
  7133. self.s.m.cmp(c, pred::NE, x, zero)
  7134. });
  7135. Ok(Some((int, signed)))
  7136. }
  7137. /// The host's word for the buffer view `src` names: its stride and
  7138. /// format kind ([`super::shader::SLOT_STRIDES`]).
  7139. fn slot_word(&mut self, src: &Source) -> Result<Option<V>, Why> {
  7140. let Source::Loaded { load, first } = src else {
  7141. return Ok(None);
  7142. };
  7143. let heap = self
  7144. .scalar
  7145. .get(load)
  7146. .and_then(|a| self.x.native.layout.get(a.param))
  7147. .is_some_and(|p| p.root == RootType::ResourceHeap);
  7148. if !heap {
  7149. return Ok(None);
  7150. }
  7151. let key = (self.cur, *load, *first);
  7152. if let Some(&v) = self.strides.get(&key) {
  7153. return Ok(Some(v));
  7154. }
  7155. let c = self.cur;
  7156. let slot = self.heap_index(*load, *first, false)?;
  7157. // Inside the table whatever the index (lanes that do not run
  7158. // compute one too): a root view has no bounds of its own.
  7159. let last = self.s.m.i32(super::shader::SLOT_STRIDES_COUNT - 1);
  7160. let i32t = self.s.t.i32;
  7161. let slot = self.s.op(c, "binary.i32", Attr::ReadNone, i32t, 40, &[slot, last]);
  7162. self.s.m.tag(slot, Tag::Clamp);
  7163. let two = self.s.m.i32(2);
  7164. let byte = self.s.m.bin(c, Bin::Shl, slot, two);
  7165. let h = self.s.root_srv_handle(super::shader::SLOT_STRIDES);
  7166. let iu = self.s.m.undef(self.s.t.i32);
  7167. let mask = self.s.m.i8(1);
  7168. let align = self.s.m.i32(4);
  7169. let r = self.s.op(
  7170. c,
  7171. "rawBufferLoad.f32",
  7172. Attr::ReadOnly,
  7173. self.s.t.res_ret,
  7174. 139,
  7175. &[h, byte, iu, mask, align],
  7176. );
  7177. let f = self.s.m.extract(c, r, 0);
  7178. let v = self.as_int(f);
  7179. self.strides.insert(key, v);
  7180. Ok(Some(v))
  7181. }
  7182. /// The heap index of a descriptor that may differ between lanes,
  7183. /// computed in the current block (or, chosen by control flow, at the
  7184. /// join).
  7185. fn lane_heap_index(&mut self, src: &Source, sampler: bool) -> Result<V, Why> {
  7186. match src {
  7187. Source::Loaded { load, first } => self.heap_index(*load, *first, sampler),
  7188. Source::Fetched { load, first } => self.fetched_index(*load, *first, sampler),
  7189. Source::Lanes { mask, args } | Source::Select { scc: mask, args } => {
  7190. let [a, b] = &args[..] else {
  7191. return Err("a descriptor chosen per lane");
  7192. };
  7193. let cond = if matches!(src, Source::Lanes { .. }) {
  7194. let &m = self
  7195. .x
  7196. .st
  7197. .masks
  7198. .get(mask)
  7199. .ok_or("a descriptor chosen per lane by an untracked mask")?;
  7200. self.boolean(m, self.cur)?
  7201. } else {
  7202. match self.get(*mask)? {
  7203. Val::Bit(x) => x,
  7204. _ => return Err("SCC without a value"),
  7205. }
  7206. };
  7207. let set = self.lane_heap_index(a, sampler)?;
  7208. let clear = self.lane_heap_index(b, sampler)?;
  7209. Ok(self.s.m.select(self.cur, cond, set, clear))
  7210. }
  7211. Source::LanePhi { block, args } => {
  7212. // Each predecessor computes its heap index at its end (what
  7213. // it reads is there: the dwords are, on that edge); the join
  7214. // picks the one of the edge the lane came by. An edge no
  7215. // lane reading it takes gives index 0.
  7216. let join =
  7217. self.block[*block].ok_or("a per-lane descriptor chosen by control flow")?;
  7218. let mut incoming = Vec::new();
  7219. for (&q, arg) in self.x.p.blocks[*block].preds.iter().zip(args) {
  7220. if self.block[q].is_none() {
  7221. continue;
  7222. }
  7223. let tail =
  7224. self.tail[q].ok_or("a per-lane descriptor joined from a later block")?;
  7225. let at = self.edges.get(&(q, *block)).copied().unwrap_or(tail);
  7226. let index = match arg {
  7227. Some(arg) => {
  7228. let here = std::mem::replace(&mut self.cur, at);
  7229. let index = self.lane_heap_index(arg, sampler);
  7230. self.cur = here;
  7231. index?
  7232. }
  7233. None => self.s.m.i32(0),
  7234. };
  7235. incoming.push((index, at));
  7236. }
  7237. let phi = self.s.m.phi(join, self.s.t.i32);
  7238. self.s.m.set_phi(phi, incoming);
  7239. Ok(phi)
  7240. }
  7241. _ => Err("a per-lane descriptor from neither a heap load nor a choice of them"),
  7242. }
  7243. }
  7244. /// The heap index of the descriptor at dword `first` of what the global
  7245. /// load at `load` reads, in each lane: its address (base plus offsets)
  7246. /// over the descriptor size.
  7247. fn fetched_index(&mut self, load: Site, first: u8, sampler: bool) -> Result<V, Why> {
  7248. const WHY: Why = "a per-lane descriptor load";
  7249. let a = *self
  7250. .scalar
  7251. .get(&load)
  7252. .ok_or("an untracked descriptor load")?;
  7253. match self.x.native.layout.get(a.param).map(|p| p.root) {
  7254. Some(RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap) => {}
  7255. _ => return Err("a descriptor outside the heaps"),
  7256. }
  7257. let li: &Inst = &self.x.p.blocks[load.0].insts[load.1];
  7258. let Fields::Flat {
  7259. addr: Some(Operand::Vector { reg, .. }),
  7260. saddr,
  7261. offset,
  7262. ..
  7263. } = li.fields
  7264. else {
  7265. return Err(WHY);
  7266. };
  7267. let c = self.cur;
  7268. // The low dword of the address: SGPR base plus VGPR offset, or the
  7269. // VGPR pair's low half (heap addresses fit in 32 bits).
  7270. let mut at = self.i32_of(li.read(Reg::V(reg)).ok_or(WHY)?)?;
  7271. if let Some(Operand::Scalar { code, .. }) = saddr
  7272. && code != NULL
  7273. {
  7274. let base = self.i32_of(li.read(Reg::S(code)).ok_or(WHY)?)?;
  7275. at = self.s.m.bin(c, Bin::Add, base, at);
  7276. }
  7277. let k = self
  7278. .s
  7279. .m
  7280. .i32((offset as i32 as u32).wrapping_add(4 * u32::from(first)));
  7281. at = self.s.m.bin(c, Bin::Add, at, k);
  7282. let shift = self.s.m.i32(if sampler { 4 } else { 5 });
  7283. Ok(self.s.m.bin(c, Bin::LShr, at, shift))
  7284. }
  7285. /// The heap index of the descriptor at dword `first` of what the scalar
  7286. /// load at `load` reads, computed in the current block.
  7287. fn heap_index(&mut self, load: Site, first: u8, sampler: bool) -> Result<V, Why> {
  7288. let a = *self
  7289. .scalar
  7290. .get(&load)
  7291. .ok_or("an untracked descriptor load")?;
  7292. match self.x.native.layout.get(a.param).map(|p| p.root) {
  7293. Some(RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap) => {}
  7294. _ => return Err("a descriptor outside the heaps"),
  7295. }
  7296. let li: &Inst = &self.x.p.blocks[load.0].insts[load.1];
  7297. let Fields::Smem {
  7298. base,
  7299. offset,
  7300. soffset,
  7301. ..
  7302. } = &li.fields
  7303. else {
  7304. return Err("a descriptor load");
  7305. };
  7306. let Operand::Scalar { code, .. } = *base else {
  7307. return Err("a descriptor load");
  7308. };
  7309. let c = self.cur;
  7310. let base = li.read(Reg::S(code)).ok_or("a descriptor load")?;
  7311. let mut addr = self.i32_of(base)?;
  7312. let k = self
  7313. .s
  7314. .m
  7315. .i32((*offset as u32).wrapping_add(4 * u32::from(first)));
  7316. addr = self.s.m.bin(c, Bin::Add, addr, k);
  7317. if !matches!(soffset, Operand::Scalar { code: NULL, .. }) {
  7318. let so = self.operand(li, soffset)?;
  7319. addr = self.s.m.bin(c, Bin::Add, addr, so);
  7320. }
  7321. let shift = self.s.m.i32(if sampler { 4 } else { 5 });
  7322. Ok(self.s.m.bin(c, Bin::LShr, addr, shift))
  7323. }
  7324. fn valu(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  7325. let Fields::Valu(v) = &inst.fields else {
  7326. unreachable!()
  7327. };
  7328. let name = inst.name();
  7329. if self.x.res.waterfall.compares.contains(&(b, i)) {
  7330. // The first lane's dwords of a waterfall loop are each lane's
  7331. // own (see `resource::Waterfall`).
  7332. self.lane(inst, Some(true));
  7333. return Ok(());
  7334. }
  7335. // One lane of a VGPR a whole-wave section left.
  7336. if name == "v_readlane_b32"
  7337. && let Some(&(_, w)) = inst.writes.first()
  7338. && let Some(sh) = self.sections.get(&b).and_then(|s| {
  7339. s.iter().filter(|s| s.1.end < i).find_map(|s| s.1.reads.get(&w).copied())
  7340. })
  7341. {
  7342. let x = self.shape(sh, false)?;
  7343. self.vals.insert(w, Val::I32(x));
  7344. return Ok(());
  7345. }
  7346. if let Some(rest) = name.strip_prefix("v_cmp_").or(name.strip_prefix("v_cmpx_")) {
  7347. let r = if v.dpp.is_some() {
  7348. Err("a compare with DPP")
  7349. } else {
  7350. self.compare(inst, rest)
  7351. };
  7352. if let Err(why) = r {
  7353. for &(_, w) in &inst.writes {
  7354. self.lane_fail.insert(w, why);
  7355. }
  7356. }
  7357. return r;
  7358. }
  7359. let mut guard = self.guard(b, i)?;
  7360. if let Some(d) = v.dpp {
  7361. let (x, enable) = self.dpp(inst, d)?;
  7362. guard = match (guard, enable) {
  7363. (Some(g), Some(e)) => Some(self.s.m.bin(self.cur, Bin::And, g, e)),
  7364. (g, e) => g.or(e),
  7365. };
  7366. self.src0 = Some(x);
  7367. }
  7368. let r = self.valu_op(inst, guard);
  7369. self.src0 = None;
  7370. r
  7371. }
  7372. /// DPP: src0 as read from another lane, and which lanes write their
  7373. /// result (none: all).
  7374. fn dpp(&mut self, inst: &Inst, dpp: Dpp) -> Result<(V, Option<V>), Why> {
  7375. let Fields::Valu(v) = &inst.fields else {
  7376. unreachable!()
  7377. };
  7378. let Some(&Operand::Vector { reg, .. }) = v.src.first() else {
  7379. return Err("a DPP operand");
  7380. };
  7381. let x = self.i32_of(inst.read(Reg::V(reg)).ok_or("a DPP operand")?)?;
  7382. // Quad permutations and DPP8 stay in groups the pixel layout shares.
  7383. let quad = matches!(dpp, Dpp::Row { ctrl: 0..=0xFF, .. });
  7384. let mesh_quad = self.s.mesh.is_some() && quad;
  7385. if !mesh_quad {
  7386. self.cross_lane(quad)?;
  7387. }
  7388. let c = self.cur;
  7389. let lane = self.lane_index();
  7390. let k = |l: &mut Self, n: u32| l.s.m.i32(n);
  7391. let (sixteen_mask, low) = (k(self, !15), k(self, 15));
  7392. let row = self.s.m.bin(c, Bin::And, lane, sixteen_mask);
  7393. let pos = self.s.m.bin(c, Bin::And, lane, low);
  7394. // Source lane, and whether it lies in the row.
  7395. let (src, inside, masks, zero) = match dpp {
  7396. Dpp::Lanes { sel, .. } => {
  7397. let (seven, not7, three) = (k(self, 7), k(self, !7), k(self, 3));
  7398. let p = self.s.m.bin(c, Bin::And, lane, seven);
  7399. let sh = self.s.m.bin(c, Bin::Mul, p, three);
  7400. let sel = k(self, sel);
  7401. let pick = self.s.m.bin(c, Bin::LShr, sel, sh);
  7402. let pick = self.s.m.bin(c, Bin::And, pick, seven);
  7403. let base = self.s.m.bin(c, Bin::And, lane, not7);
  7404. (self.s.m.bin(c, Bin::Or, base, pick), None, None, false)
  7405. }
  7406. Dpp::Row {
  7407. ctrl,
  7408. row_mask,
  7409. bank_mask,
  7410. bound_ctrl,
  7411. ..
  7412. } => {
  7413. let n = u32::from(ctrl & 15);
  7414. let (src, inside) = match ctrl {
  7415. 0..=0xFF => {
  7416. let (three, one, not3) = (k(self, 3), k(self, 1), k(self, !3));
  7417. let p = self.s.m.bin(c, Bin::And, lane, three);
  7418. let sh = self.s.m.bin(c, Bin::Shl, p, one);
  7419. let perm = k(self, u32::from(ctrl));
  7420. let pick = self.s.m.bin(c, Bin::LShr, perm, sh);
  7421. let pick = self.s.m.bin(c, Bin::And, pick, three);
  7422. let base = self.s.m.bin(c, Bin::And, lane, not3);
  7423. (self.s.m.bin(c, Bin::Or, base, pick), None)
  7424. }
  7425. 0x101..=0x10F | 0x111..=0x11F => {
  7426. let nn = k(self, n);
  7427. let left = ctrl < 0x110;
  7428. let (op, p) = if left {
  7429. (Bin::Add, pred::IULT)
  7430. } else {
  7431. (Bin::Sub, pred::IUGE)
  7432. };
  7433. let s = self.s.m.bin(c, op, lane, nn);
  7434. // Left: pos + n < 16; right: pos >= n.
  7435. let bound = if left { k(self, 16 - n) } else { nn };
  7436. (s, Some(self.s.m.cmp(c, p, pos, bound)))
  7437. }
  7438. 0x121..=0x12F => {
  7439. let nn = k(self, n);
  7440. let t = self.s.m.bin(c, Bin::Sub, pos, nn);
  7441. let t = self.s.m.bin(c, Bin::And, t, low);
  7442. (self.s.m.bin(c, Bin::Or, row, t), None)
  7443. }
  7444. 0x140 | 0x141 => {
  7445. let m = k(self, if ctrl == 0x140 { 15 } else { 7 });
  7446. let t = self.s.m.bin(c, Bin::Xor, lane, m);
  7447. (t, None)
  7448. }
  7449. 0x150..=0x15F => {
  7450. let nn = k(self, n);
  7451. (self.s.m.bin(c, Bin::Or, row, nn), None)
  7452. }
  7453. 0x160..=0x16F => {
  7454. let nn = k(self, n);
  7455. (self.s.m.bin(c, Bin::Xor, lane, nn), None)
  7456. }
  7457. _ => return Err("a DPP lane pattern"),
  7458. };
  7459. let masks = (row_mask != 0xF || bank_mask != 0xF).then_some((row_mask, bank_mask));
  7460. (src, inside, masks, bound_ctrl)
  7461. }
  7462. };
  7463. let mut r = if mesh_quad {
  7464. self.quad_pick(x, src)
  7465. } else if let Dpp::Row { ctrl, .. } = dpp
  7466. && self.helpers_read(quad)
  7467. {
  7468. self.quad_read(x, [0, 1, 2, 3].map(|i| (ctrl >> (2 * i) & 3) as u8))
  7469. } else {
  7470. self.read_lane(x, src)
  7471. };
  7472. let mut enable = None;
  7473. if let Some(inside) = inside {
  7474. if zero {
  7475. let z = k(self, 0);
  7476. r = self.s.m.select(c, inside, r, z);
  7477. } else {
  7478. enable = Some(inside);
  7479. }
  7480. }
  7481. if let Some((rows, banks)) = masks {
  7482. // Row (16 lanes) and bank (4 lanes of a row) write masks.
  7483. let (four, two, three) = (k(self, 4), k(self, 2), k(self, 3));
  7484. let ri = self.s.m.bin(c, Bin::LShr, lane, four);
  7485. let ri = self.s.m.bin(c, Bin::And, ri, three);
  7486. let bi = self.s.m.bin(c, Bin::LShr, lane, two);
  7487. let bi = self.s.m.bin(c, Bin::And, bi, three);
  7488. let (rm, bm) = (k(self, u32::from(rows)), k(self, u32::from(banks)));
  7489. let rb = self.s.m.bin(c, Bin::LShr, rm, ri);
  7490. let bb = self.s.m.bin(c, Bin::LShr, bm, bi);
  7491. let both = self.s.m.bin(c, Bin::And, rb, bb);
  7492. let (one, z) = (k(self, 1), k(self, 0));
  7493. let both = self.s.m.bin(c, Bin::And, both, one);
  7494. let on = self.s.m.cmp(c, pred::NE, both, z);
  7495. enable = Some(match enable {
  7496. Some(e) => self.s.m.bin(c, Bin::And, e, on),
  7497. None => on,
  7498. });
  7499. }
  7500. Ok((r, enable))
  7501. }
  7502. fn valu_op(&mut self, inst: &Inst, guard: Option<V>) -> Result<(), Why> {
  7503. let Fields::Valu(v) = &inst.fields else {
  7504. unreachable!()
  7505. };
  7506. let name = inst.name();
  7507. let c = self.cur;
  7508. let f = |l: &mut Self, k| l.fsrc(inst, k);
  7509. let s = |l: &mut Self, k| l.src(inst, k);
  7510. let float = |l: &mut Self, r: V| l.write_f(inst, r, guard);
  7511. let int = |l: &mut Self, r: V| l.write_i(inst, r, guard);
  7512. if let Some(r) = self.valu16(inst, name, guard) {
  7513. return r;
  7514. }
  7515. if let Some(op) = name.strip_prefix("v_pk_") {
  7516. return self.packed16(inst, op, guard);
  7517. }
  7518. match name {
  7519. "v_mad_u64_u32" => {
  7520. // a * b + c, c and the result 64 bits wide; the carry out
  7521. // of the sum is this lane's bit of the mask it names.
  7522. let (a, b) = (s(self, 0)?, s(self, 1)?);
  7523. let x = self.src64(inst, 2)?;
  7524. let i64t = self.s.m.int(64);
  7525. self.s.flags |= flags::INT64;
  7526. let a = self.s.m.cast(c, Cast::ZExt, a, i64t);
  7527. let b = self.s.m.cast(c, Cast::ZExt, b, i64t);
  7528. let product = self.s.m.bin(c, Bin::Mul, a, b);
  7529. let r = self.s.m.bin(c, Bin::Add, product, x);
  7530. let carry = self.s.m.cmp(c, pred::IULT, r, x);
  7531. let Some(Operand::Vector { reg, .. }) = v.dst else {
  7532. return Err("a 64-bit result");
  7533. };
  7534. let (lo, hi) = self.split64(r);
  7535. self.write(inst, Reg::V(reg), lo, guard);
  7536. self.write(inst, Reg::V(reg + 1), hi, guard);
  7537. if let Some(Operand::Scalar { code, .. }) = v.carry
  7538. && let Some(w) = inst.write(Reg::S(code))
  7539. {
  7540. self.lane_bits.insert(w, carry);
  7541. }
  7542. for &(_, w) in &inst.writes {
  7543. self.vals
  7544. .entry(w)
  7545. .or_insert(Val::Missing("a lane mask read as data"));
  7546. }
  7547. Ok(())
  7548. }
  7549. "v_lshlrev_b64" | "v_lshrrev_b64" | "v_ashrrev_i64" => {
  7550. let n = s(self, 0)?;
  7551. let x = self.src64(inst, 1)?;
  7552. let i64t = self.s.m.int(64);
  7553. let k63 = self.s.m.i32(63);
  7554. let n = self.s.m.bin(c, Bin::And, n, k63);
  7555. let n = self.s.m.cast(c, Cast::ZExt, n, i64t);
  7556. let op = match name {
  7557. "v_lshlrev_b64" => Bin::Shl,
  7558. "v_lshrrev_b64" => Bin::LShr,
  7559. _ => Bin::AShr,
  7560. };
  7561. let r = self.s.m.bin(c, op, x, n);
  7562. let Some(Operand::Vector { reg, .. }) = v.dst else {
  7563. return Err("a 64-bit result");
  7564. };
  7565. let (lo, hi) = self.split64(r);
  7566. self.write(inst, Reg::V(reg), lo, guard);
  7567. self.write(inst, Reg::V(reg + 1), hi, guard);
  7568. Ok(())
  7569. }
  7570. "v_cubeid_f32" | "v_cubesc_f32" | "v_cubetc_f32" | "v_cubema_f32" => {
  7571. // Cube-map face coordinates (AMD's ISA): the major axis is z
  7572. // when |z| >= |x| and |z| >= |y|, else y when |y| >= |x|,
  7573. // else x.
  7574. let (x, y, z) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  7575. let (ax, ay, az) = (self.unary(6, x), self.unary(6, y), self.unary(6, z));
  7576. let zx = self.s.m.cmp(c, pred::OGE, az, ax);
  7577. let zy = self.s.m.cmp(c, pred::OGE, az, ay);
  7578. let zmaj = self.s.m.bin(c, Bin::And, zx, zy);
  7579. let ymaj = self.s.m.cmp(c, pred::OGE, ay, ax);
  7580. let zero = self.s.m.f32(0);
  7581. let neg = |l: &mut Self, v: V| l.s.m.cmp(c, pred::OLT, v, zero);
  7582. let minus = |l: &mut Self, v: V| {
  7583. let z = l.s.m.f32(0x8000_0000);
  7584. l.s.m.bin(c, Bin::Sub, z, v)
  7585. };
  7586. let pick = |l: &mut Self, zv: V, yv: V, xv: V| {
  7587. let t = l.s.m.select(c, ymaj, yv, xv);
  7588. l.s.m.select(c, zmaj, zv, t)
  7589. };
  7590. let r = match name {
  7591. "v_cubeid_f32" => {
  7592. let k = |l: &mut Self, v: f32| l.s.m.f32(v.to_bits());
  7593. let (nz, ny, nx) = (neg(self, z), neg(self, y), neg(self, x));
  7594. let (f5, f4, f3, f2, f1, f0) = (
  7595. k(self, 5.0),
  7596. k(self, 4.0),
  7597. k(self, 3.0),
  7598. k(self, 2.0),
  7599. k(self, 1.0),
  7600. k(self, 0.0),
  7601. );
  7602. let zf = self.s.m.select(c, nz, f5, f4);
  7603. let yf = self.s.m.select(c, ny, f3, f2);
  7604. let xf = self.s.m.select(c, nx, f1, f0);
  7605. pick(self, zf, yf, xf)
  7606. }
  7607. "v_cubesc_f32" => {
  7608. let (nz, nx) = (neg(self, z), neg(self, x));
  7609. let (mx, mz) = (minus(self, x), minus(self, z));
  7610. let zf = self.s.m.select(c, nz, mx, x);
  7611. let xf = self.s.m.select(c, nx, z, mz);
  7612. pick(self, zf, x, xf)
  7613. }
  7614. "v_cubetc_f32" => {
  7615. let ny = neg(self, y);
  7616. let (my, mz) = (minus(self, y), minus(self, z));
  7617. let yf = self.s.m.select(c, ny, mz, z);
  7618. pick(self, my, yf, my)
  7619. }
  7620. _ => {
  7621. let t = pick(self, z, y, x);
  7622. let two = self.s.m.f32(2.0f32.to_bits());
  7623. self.s.m.bin(c, Bin::Mul, t, two)
  7624. }
  7625. };
  7626. float(self, r)
  7627. }
  7628. "v_movrels_b32" | "v_movreld_b32" | "v_movrelsd_b32" => {
  7629. // M0 indexes the source (movrels), the destination (movreld)
  7630. // or both, from the encoded register up to the program's
  7631. // VGPR count (the registers the instruction reads or writes).
  7632. let m0 = self.i32_of(inst.read(Reg::S(crate::ir::M0)).ok_or("M0")?)?;
  7633. let (
  7634. Some(&Operand::Vector { reg: sreg, .. }),
  7635. Some(Operand::Vector { reg: dreg, .. }),
  7636. ) = (v.src.first(), v.dst)
  7637. else {
  7638. return Err("an M0-relative move");
  7639. };
  7640. let indexed_src = name != "v_movreld_b32";
  7641. let value = if indexed_src {
  7642. let mut r = self.s.m.i32(0);
  7643. for k in 0..=255u8.saturating_sub(sreg) {
  7644. let Some(x) = inst.read(Reg::V(sreg + k)) else {
  7645. break;
  7646. };
  7647. let x = self.i32_of(x)?;
  7648. let kk = self.s.m.i32(u32::from(k));
  7649. let is = self.s.m.cmp(c, pred::EQ, m0, kk);
  7650. r = self.s.m.select(c, is, x, r);
  7651. }
  7652. r
  7653. } else {
  7654. s(self, 0)?
  7655. };
  7656. if name == "v_movrels_b32" {
  7657. return int(self, value);
  7658. }
  7659. for k in 0..=255u8.saturating_sub(dreg) {
  7660. let Some(_) = inst.write(Reg::V(dreg + k)) else {
  7661. break;
  7662. };
  7663. let old = match inst.read(Reg::V(dreg + k)) {
  7664. Some(o) => self.i32_of(o)?,
  7665. None => self.s.m.i32(0),
  7666. };
  7667. let kk = self.s.m.i32(u32::from(k));
  7668. let is = self.s.m.cmp(c, pred::EQ, m0, kk);
  7669. let x = self.s.m.select(c, is, value, old);
  7670. self.write_placed(inst, Reg::V(dreg + k), x, guard);
  7671. }
  7672. Ok(())
  7673. }
  7674. "v_swap_b32" => {
  7675. let (
  7676. Some(&Operand::Vector { reg: sreg, .. }),
  7677. Some(Operand::Vector { reg: dreg, .. }),
  7678. ) = (v.src.first(), v.dst)
  7679. else {
  7680. return Err("v_swap_b32");
  7681. };
  7682. let a = self.i32_of(inst.read(Reg::V(dreg)).ok_or("v_swap_b32")?)?;
  7683. let b = self.i32_of(inst.read(Reg::V(sreg)).ok_or("v_swap_b32")?)?;
  7684. self.write_placed(inst, Reg::V(dreg), b, guard);
  7685. if dreg != sreg {
  7686. self.write_placed(inst, Reg::V(sreg), a, guard);
  7687. }
  7688. Ok(())
  7689. }
  7690. "v_ffbh_u32" | "v_ffbh_i32" => {
  7691. // Counted from the top bit, -1 when none (DXIL's too).
  7692. let a = s(self, 0)?;
  7693. let op = if name == "v_ffbh_u32" { 33 } else { 34 };
  7694. let r = self
  7695. .s
  7696. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]);
  7697. int(self, r)
  7698. }
  7699. "v_dot4c_i32_i8" => {
  7700. // D += the dot product of four signed bytes, wrapping: DXIL's
  7701. // Dot4AddI8Packed.
  7702. let (a, bb) = (s(self, 0)?, s(self, 1)?);
  7703. let Some(Operand::Vector { reg, .. }) = v.dst else {
  7704. return Err("an accumulator");
  7705. };
  7706. let acc = self.i32_of(inst.read(Reg::V(reg)).ok_or("an accumulator")?)?;
  7707. let i32_ty = self.s.t.i32;
  7708. let r = self.s.op(
  7709. c,
  7710. "dot4AddPacked.i32",
  7711. Attr::ReadNone,
  7712. i32_ty,
  7713. 163,
  7714. &[acc, a, bb],
  7715. );
  7716. int(self, r)
  7717. }
  7718. "v_dot4_i32_i8" => {
  7719. // VOP3P: op_sel picks the half each multiplicand's low half
  7720. // reads, op_sel_hi its high half's; the accumulator is read
  7721. // whole (as AMD's compilers fold constants into it).
  7722. if v.clamp || v.neg_hi != 0 {
  7723. return Err("a saturating or negated dot product");
  7724. }
  7725. let mut xs = Vec::new();
  7726. for k in 0..2 {
  7727. let x = s(self, k)?;
  7728. let (lo, hi) = (v.opsel >> k & 1 != 0, v.opsel_hi >> k & 1 != 0);
  7729. if (lo, hi) == (false, true) {
  7730. xs.push(x);
  7731. continue;
  7732. }
  7733. let (k16, low) = (self.s.m.i32(16), self.s.m.i32(0xFFFF));
  7734. let top = self.s.m.bin(c, Bin::LShr, x, k16);
  7735. let bottom = self.s.m.bin(c, Bin::And, x, low);
  7736. let hi = self
  7737. .s
  7738. .m
  7739. .bin(c, Bin::Shl, if hi { top } else { bottom }, k16);
  7740. xs.push(self.s.m.bin(c, Bin::Or, if lo { top } else { bottom }, hi));
  7741. }
  7742. let acc = s(self, 2)?;
  7743. let i32_ty = self.s.t.i32;
  7744. let r = self.s.op(
  7745. c,
  7746. "dot4AddPacked.i32",
  7747. Attr::ReadNone,
  7748. i32_ty,
  7749. 163,
  7750. &[acc, xs[0], xs[1]],
  7751. );
  7752. int(self, r)
  7753. }
  7754. "v_mov_b32" => {
  7755. if v.abs != 0 || v.neg != 0 || v.clamp || v.omod != 0 {
  7756. let a = f(self, 0)?;
  7757. return float(self, a);
  7758. }
  7759. let a = s(self, 0)?;
  7760. int(self, a)
  7761. }
  7762. "v_add_f32" | "v_sub_f32" | "v_subrev_f32" | "v_mul_f32" | "v_mul_legacy_f32"
  7763. | "v_max_f32" | "v_min_f32" => {
  7764. let (a, bb) = (f(self, 0)?, f(self, 1)?);
  7765. let r = match name {
  7766. "v_add_f32" => self.s.m.bin(c, Bin::Add, a, bb),
  7767. "v_sub_f32" => self.s.m.bin(c, Bin::Sub, a, bb),
  7768. "v_subrev_f32" => self.s.m.bin(c, Bin::Sub, bb, a),
  7769. "v_mul_f32" => self.s.m.bin(c, Bin::Mul, a, bb),
  7770. "v_mul_legacy_f32" => self.legacy_mul(a, bb),
  7771. "v_max_f32" => self.max_min(true, a, bb),
  7772. _ => self.max_min(false, a, bb),
  7773. };
  7774. float(self, r)
  7775. }
  7776. "v_fma_f32" | "v_fmaak_f32" | "v_fmamk_f32" => {
  7777. // shortcut: DXIL has no fused f32 multiply-add; FMad lets the driver fuse.
  7778. let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  7779. let r = self.fmad(a, bb, cc);
  7780. float(self, r)
  7781. }
  7782. "v_div_scale_f32" => {
  7783. // RDNA2 ISA: src0 = value to scale, src1 = denominator, src2 = numerator.
  7784. let (a, den, num) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  7785. let (ai, ni, di) = (self.as_int(a), self.as_int(num), self.as_int(den));
  7786. let (k23, k255, kabs) = (
  7787. self.s.m.i32(23),
  7788. self.s.m.i32(0xFF),
  7789. self.s.m.i32(0x7FFF_FFFF),
  7790. );
  7791. let (zero, k23_exp, k232_exp, k96) = (
  7792. self.s.m.i32(0),
  7793. self.s.m.i32(23),
  7794. self.s.m.i32(232),
  7795. self.s.m.i32(96),
  7796. );
  7797. let exp_of = |l: &mut Self, x: V| {
  7798. let s = l.s.m.bin(c, Bin::LShr, x, k23);
  7799. l.s.m.bin(c, Bin::And, s, k255)
  7800. };
  7801. let (e1, e2) = (exp_of(self, ni), exp_of(self, di));
  7802. let n_abs = self.s.m.bin(c, Bin::And, ni, kabs);
  7803. let d_abs = self.s.m.bin(c, Bin::And, di, kabs);
  7804. let z1 = self.s.m.cmp(c, pred::EQ, n_abs, zero);
  7805. let z2 = self.s.m.cmp(c, pred::EQ, d_abs, zero);
  7806. let any_zero = self.s.m.bin(c, Bin::Or, z1, z2);
  7807. let special = {
  7808. let s1 = self.s.m.cmp(c, pred::EQ, e1, k255);
  7809. let s2 = self.s.m.cmp(c, pred::EQ, e2, k255);
  7810. let a12 = self.s.m.bin(c, Bin::Or, s1, s2);
  7811. self.s.m.bin(c, Bin::Or, a12, any_zero)
  7812. };
  7813. let is_den = self.s.m.cmp(c, pred::EQ, ai, di);
  7814. let diff = self.s.m.bin(c, Bin::Sub, e2, e1);
  7815. let den_tiny = self.s.m.cmp(c, pred::IULE, e2, k23_exp);
  7816. let den_huge = self.s.m.cmp(c, pred::IUGE, e2, k232_exp);
  7817. let num_tiny_exp = self.s.m.cmp(c, pred::IULE, e1, k23_exp);
  7818. let num_huge = self.s.m.cmp(c, pred::IUGE, e1, k232_exp);
  7819. let num_gap = self.s.m.cmp(c, pred::SGE, diff, k96);
  7820. let not_den_huge = {
  7821. let t = self.s.m.bool(true);
  7822. self.s.m.bin(c, Bin::Xor, den_huge, t)
  7823. };
  7824. let num_gap = self.s.m.bin(c, Bin::And, num_gap, not_den_huge);
  7825. let num_tiny = self.s.m.bin(c, Bin::Or, num_tiny_exp, num_gap);
  7826. let up_raw = self.s.m.select(c, is_den, den_tiny, num_tiny);
  7827. let dn_raw = self.s.m.select(c, is_den, den_huge, num_huge);
  7828. let not_special = {
  7829. let t = self.s.m.bool(true);
  7830. self.s.m.bin(c, Bin::Xor, special, t)
  7831. };
  7832. let up = self.s.m.bin(c, Bin::And, up_raw, not_special);
  7833. let dn = self.s.m.bin(c, Bin::And, dn_raw, not_special);
  7834. let uncancelled = {
  7835. let x_tiny = self.s.m.bin(c, Bin::Xor, den_tiny, num_tiny);
  7836. let x_huge = self.s.m.bin(c, Bin::Xor, den_huge, num_huge);
  7837. self.s.m.bin(c, Bin::Or, x_tiny, x_huge)
  7838. };
  7839. let flag_raw = self.s.m.select(c, is_den, uncancelled, up_raw);
  7840. let flag = self.s.m.bin(c, Bin::And, flag_raw, not_special);
  7841. let k_up = self.s.m.f32(0x5F80_0000);
  7842. let k_dn = self.s.m.f32(0x1F80_0000);
  7843. let a_up = self.s.m.bin(c, Bin::Mul, a, k_up);
  7844. let a_dn = self.s.m.bin(c, Bin::Mul, a, k_dn);
  7845. let r = self.s.m.select(c, dn, a_dn, a);
  7846. let r = self.s.m.select(c, up, a_up, r);
  7847. let qnan = self.s.m.f32(0x7FC0_0000);
  7848. let r = self.s.m.select(c, any_zero, qnan, r);
  7849. float(self, r)?;
  7850. if let Some(Operand::Scalar { code, .. }) = v.carry
  7851. && let Some(w) = inst.write(Reg::S(code))
  7852. {
  7853. self.lane_bits.insert(w, flag);
  7854. }
  7855. for &(_, w) in &inst.writes {
  7856. self.vals
  7857. .entry(w)
  7858. .or_insert(Val::Missing("a lane mask read as data"));
  7859. }
  7860. Ok(())
  7861. }
  7862. "v_div_fmas_f32" => {
  7863. let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  7864. let m = inst
  7865. .read(Reg::S(crate::ir::VCC))
  7866. .and_then(|v| self.x.st.masks.get(&v).copied())
  7867. .ok_or("v_div_fmas_f32 without VCC")?;
  7868. let vcc = self.boolean(m, c)?;
  7869. let tmp = self.fmad(a, bb, cc);
  7870. let ci = self.as_int(cc);
  7871. let (k23, k255, k128) = (self.s.m.i32(23), self.s.m.i32(0xFF), self.s.m.i32(128));
  7872. let sh = self.s.m.bin(c, Bin::LShr, ci, k23);
  7873. let exp = self.s.m.bin(c, Bin::And, sh, k255);
  7874. let exp_ge = self.s.m.cmp(c, pred::IUGE, exp, k128);
  7875. let (k_up, k_dn) = (self.s.m.f32(0x5F80_0000), self.s.m.f32(0x1F80_0000));
  7876. let scale = self.s.m.select(c, exp_ge, k_up, k_dn);
  7877. let scaled = self.s.m.bin(c, Bin::Mul, tmp, scale);
  7878. let r = self.s.m.select(c, vcc, scaled, tmp);
  7879. float(self, r)
  7880. }
  7881. "v_div_fixup_f32" => {
  7882. let (q, den, num) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  7883. let (qi, di, ni) = (self.as_int(q), self.as_int(den), self.as_int(num));
  7884. let (ksign, kabs, kinf) = (
  7885. self.s.m.i32(0x8000_0000),
  7886. self.s.m.i32(0x7FFF_FFFF),
  7887. self.s.m.i32(0x7F80_0000),
  7888. );
  7889. let (kqnan_bit, kneg_qnan, zero) = (
  7890. self.s.m.i32(0x0040_0000),
  7891. self.s.m.i32(0xFFC0_0000),
  7892. self.s.m.i32(0),
  7893. );
  7894. let sign = {
  7895. let x = self.s.m.bin(c, Bin::Xor, ni, di);
  7896. self.s.m.bin(c, Bin::And, x, ksign)
  7897. };
  7898. let q_abs = self.s.m.bin(c, Bin::And, qi, kabs);
  7899. let d_abs = self.s.m.bin(c, Bin::And, di, kabs);
  7900. let n_abs = self.s.m.bin(c, Bin::And, ni, kabs);
  7901. let q_nan = self.s.m.cmp(c, pred::IUGT, q_abs, kinf);
  7902. let d_nan = self.s.m.cmp(c, pred::IUGT, d_abs, kinf);
  7903. let n_nan = self.s.m.cmp(c, pred::IUGT, n_abs, kinf);
  7904. let d_inf = self.s.m.cmp(c, pred::EQ, d_abs, kinf);
  7905. let n_inf = self.s.m.cmp(c, pred::EQ, n_abs, kinf);
  7906. let d_zero = self.s.m.cmp(c, pred::EQ, d_abs, zero);
  7907. let n_zero = self.s.m.cmp(c, pred::EQ, n_abs, zero);
  7908. let both_inf = self.s.m.bin(c, Bin::And, n_inf, d_inf);
  7909. let both_zero = self.s.m.bin(c, Bin::And, n_zero, d_zero);
  7910. let invalid = self.s.m.bin(c, Bin::Or, both_inf, both_zero);
  7911. let make_inf = {
  7912. let t = self.s.m.bin(c, Bin::Or, n_inf, d_zero);
  7913. self.s.m.bin(c, Bin::Or, t, q_nan)
  7914. };
  7915. let make_zero = self.s.m.bin(c, Bin::Or, d_inf, n_zero);
  7916. let signed_q = self.s.m.bin(c, Bin::Or, sign, q_abs);
  7917. let signed_inf = self.s.m.bin(c, Bin::Or, sign, kinf);
  7918. let n_qnan = self.s.m.bin(c, Bin::Or, ni, kqnan_bit);
  7919. let d_qnan = self.s.m.bin(c, Bin::Or, di, kqnan_bit);
  7920. let r = self.s.m.select(c, make_zero, sign, signed_q);
  7921. let r = self.s.m.select(c, make_inf, signed_inf, r);
  7922. let r = self.s.m.select(c, invalid, kneg_qnan, r);
  7923. let r = self.s.m.select(c, d_nan, d_qnan, r);
  7924. let r = self.s.m.select(c, n_nan, n_qnan, r);
  7925. let rf = self.as_float(r);
  7926. float(self, rf)
  7927. }
  7928. "v_fmac_f32" | "v_mac_f32" | "v_mac_legacy_f32" => {
  7929. let (a, bb) = (f(self, 0)?, f(self, 1)?);
  7930. let Some(Operand::Vector { reg, .. }) = v.dst else {
  7931. return Err("an accumulator");
  7932. };
  7933. let acc = inst.read(Reg::V(reg)).ok_or("an accumulator")?;
  7934. let acc = match self.floats.get(&acc) {
  7935. Some(&x) => x,
  7936. None => {
  7937. let x = self.i32_of(acc)?;
  7938. self.as_float(x)
  7939. }
  7940. };
  7941. let r = match name {
  7942. "v_fmac_f32" => self.fmad(a, bb, acc),
  7943. "v_mac_f32" => {
  7944. let m = self.s.m.bin(c, Bin::Mul, a, bb);
  7945. self.s.m.bin(c, Bin::Add, m, acc)
  7946. }
  7947. _ => {
  7948. let m = self.legacy_mul(a, bb);
  7949. self.s.m.bin(c, Bin::Add, m, acc)
  7950. }
  7951. };
  7952. float(self, r)
  7953. }
  7954. "v_mad_f32" | "v_madak_f32" | "v_madmk_f32" | "v_mad_legacy_f32" => {
  7955. let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  7956. let m = if name == "v_mad_legacy_f32" {
  7957. self.legacy_mul(a, bb)
  7958. } else {
  7959. self.s.m.bin(c, Bin::Mul, a, bb)
  7960. };
  7961. let r = self.s.m.bin(c, Bin::Add, m, cc);
  7962. float(self, r)
  7963. }
  7964. "v_max3_f32" | "v_min3_f32" | "v_med3_f32" => {
  7965. let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  7966. let r = match name {
  7967. "v_max3_f32" => {
  7968. let t = self.max_min(true, a, bb);
  7969. self.max_min(true, t, cc)
  7970. }
  7971. "v_min3_f32" => {
  7972. let t = self.max_min(false, a, bb);
  7973. self.max_min(false, t, cc)
  7974. }
  7975. _ => self.med3(a, bb, cc),
  7976. };
  7977. float(self, r)
  7978. }
  7979. "v_rcp_f32" | "v_rcp_iflag_f32" => {
  7980. // shortcut: the hardware reciprocal is approximate (1 ULP); this divides.
  7981. let a = f(self, 0)?;
  7982. let one = self.s.m.f32(1.0f32.to_bits());
  7983. let r = self.s.m.bin(c, Bin::SDiv, one, a);
  7984. float(self, r)
  7985. }
  7986. "v_rsq_f32" | "v_sqrt_f32" | "v_log_f32" | "v_exp_f32" | "v_fract_f32"
  7987. | "v_trunc_f32" | "v_floor_f32" | "v_ceil_f32" | "v_rndne_f32" | "v_sin_f32"
  7988. | "v_cos_f32" => {
  7989. let a = f(self, 0)?;
  7990. let op = match name {
  7991. "v_rsq_f32" => 25,
  7992. "v_sqrt_f32" => 24,
  7993. "v_log_f32" => 23,
  7994. "v_exp_f32" => 21,
  7995. "v_fract_f32" => 22,
  7996. "v_trunc_f32" => 29,
  7997. "v_floor_f32" => 27,
  7998. "v_ceil_f32" => 28,
  7999. "v_rndne_f32" => 26,
  8000. "v_sin_f32" => 13,
  8001. _ => 12,
  8002. };
  8003. let r = match op {
  8004. 12 | 13 => self.trig_turns(a, op == 12),
  8005. 22 => self.fract(a, 1.0, f32::from_bits(0x3F7F_FFFF)),
  8006. _ => self.unary(op, a),
  8007. };
  8008. float(self, r)
  8009. }
  8010. "v_cvt_i32_f32" | "v_cvt_u32_f32" | "v_cvt_flr_i32_f32" | "v_cvt_rpi_i32_f32" => {
  8011. let mut a = f(self, 0)?;
  8012. if name == "v_cvt_rpi_i32_f32" {
  8013. let h = self.s.m.f32(0.5f32.to_bits());
  8014. a = self.s.m.bin(c, Bin::Add, a, h);
  8015. }
  8016. if name != "v_cvt_i32_f32" && name != "v_cvt_u32_f32" {
  8017. a = self.unary(27, a);
  8018. }
  8019. // D3D's conversions saturate and give 0 for NaN, as the
  8020. // hardware does (checked on the RX 6700 XT and WARP).
  8021. let op = if name == "v_cvt_u32_f32" {
  8022. Cast::FpToUi
  8023. } else {
  8024. Cast::FpToSi
  8025. };
  8026. let r = self.s.m.cast(c, op, a, self.s.t.i32);
  8027. int(self, r)
  8028. }
  8029. "v_cvt_f32_f64" => {
  8030. let (lo, hi) = self.f64_pair(inst, 0)?;
  8031. let bits = self.f64_to_f32_bits(lo, hi);
  8032. let r = self.as_float(bits);
  8033. float(self, r)
  8034. }
  8035. "v_cvt_f32_i32" | "v_cvt_f32_u32" | "v_cvt_f32_ubyte0" | "v_cvt_f32_ubyte1"
  8036. | "v_cvt_f32_ubyte2" | "v_cvt_f32_ubyte3" => {
  8037. let mut a = s(self, 0)?;
  8038. if let Some(n) = name.strip_prefix("v_cvt_f32_ubyte") {
  8039. let sh = self.s.m.i32(8 * u32::from(n.as_bytes()[0] - b'0'));
  8040. let ff = self.s.m.i32(0xff);
  8041. a = self.s.m.bin(c, Bin::LShr, a, sh);
  8042. a = self.s.m.bin(c, Bin::And, a, ff);
  8043. }
  8044. let op = if name == "v_cvt_f32_i32" {
  8045. Cast::SiToFp
  8046. } else {
  8047. Cast::UiToFp
  8048. };
  8049. let r = self.s.m.cast(c, op, a, self.s.t.f32);
  8050. float(self, r)
  8051. }
  8052. "v_cvt_off_f32_i4" => {
  8053. // The low nibble as a signed 4-bit integer, over 16.
  8054. let a = s(self, 0)?;
  8055. let k28 = self.s.m.i32(28);
  8056. let a = self.s.m.bin(c, Bin::Shl, a, k28);
  8057. let a = self.s.m.bin(c, Bin::AShr, a, k28);
  8058. let f = self.s.m.cast(c, Cast::SiToFp, a, self.s.t.f32);
  8059. let k = self.s.m.f32(0.0625f32.to_bits());
  8060. let r = self.s.m.bin(c, Bin::Mul, f, k);
  8061. float(self, r)
  8062. }
  8063. "v_fma_mix_f32" | "v_fma_mixlo_f16" | "v_fma_mixhi_f16" => {
  8064. // Each source is f32, or with op_sel_hi the low (op_sel: high)
  8065. // f16 half; neg_hi is the absolute value here.
  8066. let mut xs = Vec::new();
  8067. for i in 0..3 {
  8068. let op = v.src.get(i).ok_or("a missing operand")?;
  8069. let mut x = if v.opsel_hi >> i & 1 != 0 {
  8070. let x = self.f16_operand(inst, op)?;
  8071. let h = if v.opsel >> i & 1 != 0 {
  8072. let k16 = self.s.m.i32(16);
  8073. self.s.m.bin(c, Bin::LShr, x, k16)
  8074. } else {
  8075. x
  8076. };
  8077. self.s
  8078. .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[h])
  8079. } else {
  8080. let x = self.operand(inst, op)?;
  8081. self.as_float(x)
  8082. };
  8083. if v.neg_hi >> i & 1 != 0 {
  8084. x = self.unary(6, x);
  8085. }
  8086. if v.neg >> i & 1 != 0 {
  8087. let z = self.s.m.f32(0x8000_0000);
  8088. x = self.s.m.bin(c, Bin::Sub, z, x);
  8089. }
  8090. xs.push(x);
  8091. }
  8092. let mut r = self.fmad(xs[0], xs[1], xs[2]);
  8093. if name == "v_fma_mix_f32" {
  8094. return float(self, r);
  8095. }
  8096. if v.clamp {
  8097. r = self.unary(7, r);
  8098. }
  8099. // The f16 result goes to one half; the other half stays.
  8100. let Some(Operand::Vector { reg, .. }) = v.dst else {
  8101. return Err("a mixed-precision result");
  8102. };
  8103. let old = match inst.read(Reg::V(reg)) {
  8104. Some(o) => self.i32_of(o)?,
  8105. None => self.s.m.i32(0),
  8106. };
  8107. let h = self
  8108. .s
  8109. .op(c, "legacyF32ToF16", Attr::ReadNone, self.s.t.i32, 130, &[r]);
  8110. let (keep, h) = if name == "v_fma_mixhi_f16" {
  8111. let k16 = self.s.m.i32(16);
  8112. (0xFFFF, self.s.m.bin(c, Bin::Shl, h, k16))
  8113. } else {
  8114. (0xFFFF_0000, h)
  8115. };
  8116. let keep = self.s.m.i32(keep);
  8117. let old = self.s.m.bin(c, Bin::And, old, keep);
  8118. let x = self.s.m.bin(c, Bin::Or, old, h);
  8119. self.write(inst, Reg::V(reg), x, guard);
  8120. Ok(())
  8121. }
  8122. "v_cvt_pkrtz_f16_f32" => {
  8123. let (a, bb) = (f(self, 0)?, f(self, 1)?);
  8124. let lo = self.f16_toward_zero(a);
  8125. let hi = self.f16_toward_zero(bb);
  8126. let sh = self.s.m.i32(16);
  8127. let hi = self.s.m.bin(c, Bin::Shl, hi, sh);
  8128. let r = self.s.m.bin(c, Bin::Or, lo, hi);
  8129. int(self, r)
  8130. }
  8131. "v_cvt_f16_f32" if v.opsel == 0 => {
  8132. // Rounded to nearest even (the MODE default) into the low half.
  8133. let a = f(self, 0)?;
  8134. let r = self
  8135. .s
  8136. .op(c, "legacyF32ToF16", Attr::ReadNone, self.s.t.i32, 130, &[a]);
  8137. let Some(Operand::Vector { reg, .. }) = v.dst else {
  8138. return Err("a 16-bit result outside a VGPR");
  8139. };
  8140. let r = self.low_half(inst, reg, r);
  8141. int(self, r)
  8142. }
  8143. "v_pack_b32_f16" => {
  8144. // Two f16 sources (op_sel: their high halves; abs and neg on
  8145. // the sign bit) into the low and high half.
  8146. let mut halves = Vec::new();
  8147. for k in 0..2 {
  8148. let op = v.src.get(k).ok_or("a missing operand")?;
  8149. let mut x = self.f16_operand(inst, op)?;
  8150. if v.opsel >> k & 1 != 0 {
  8151. let k16 = self.s.m.i32(16);
  8152. x = self.s.m.bin(c, Bin::LShr, x, k16);
  8153. }
  8154. let mask = if v.abs >> k & 1 != 0 { 0x7FFF } else { 0xFFFF };
  8155. let mask = self.s.m.i32(mask);
  8156. x = self.s.m.bin(c, Bin::And, x, mask);
  8157. if v.neg >> k & 1 != 0 {
  8158. let sign = self.s.m.i32(0x8000);
  8159. x = self.s.m.bin(c, Bin::Xor, x, sign);
  8160. }
  8161. halves.push(x);
  8162. }
  8163. let k16 = self.s.m.i32(16);
  8164. let hi = self.s.m.bin(c, Bin::Shl, halves[1], k16);
  8165. let r = self.s.m.bin(c, Bin::Or, halves[0], hi);
  8166. int(self, r)
  8167. }
  8168. "v_cvt_f32_f16" if v.opsel == 0 => {
  8169. let a = s(self, 0)?;
  8170. let r = self
  8171. .s
  8172. .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[a]);
  8173. float(self, r)
  8174. }
  8175. "v_cndmask_b32" => {
  8176. let mask = match v.src.get(2) {
  8177. Some(&Operand::Scalar { code, .. }) => inst.read(Reg::S(code)),
  8178. _ => None,
  8179. };
  8180. const UNTRACKED: Why = "a select on an untracked mask";
  8181. let cond = match mask.and_then(|m| self.x.st.masks.get(&m).copied()) {
  8182. Some(m) => self.boolean(m, c)?,
  8183. // A mask the code holds as a number (a constant bit
  8184. // pattern: every other lane, every other pair...):
  8185. // this lane's bit of it. Exact where host lanes are
  8186. // the console's.
  8187. None if self.mask_data == MaskData::Console => {
  8188. // Each host wave taken as a wave of its own has no
  8189. // console lane numbers to pick the bits by.
  8190. if self.local {
  8191. return Err("a constant lane mask in a half-wave");
  8192. }
  8193. let m = mask.ok_or(UNTRACKED)?;
  8194. let lo = self.i32_of(m).map_err(|_| UNTRACKED)?;
  8195. // wave64: the register after it holds lanes 32-63.
  8196. let high = match v.src.get(2) {
  8197. Some(&Operand::Scalar { code, .. }) if self.x.native.wave64 => {
  8198. Some(inst.read(Reg::S(code + 1)).ok_or(UNTRACKED)?)
  8199. }
  8200. _ => None,
  8201. };
  8202. let hi = match high {
  8203. Some(h) => Some(self.i32_of(h).map_err(|_| UNTRACKED)?),
  8204. None => None,
  8205. };
  8206. self.cross_lane(false)?;
  8207. self.lane_bit(c, lo, hi)
  8208. }
  8209. None => return Err(UNTRACKED),
  8210. };
  8211. if v.abs != 0 || v.neg != 0 {
  8212. let (a, bb) = (f(self, 0)?, f(self, 1)?);
  8213. let r = self.s.m.select(c, cond, bb, a);
  8214. return float(self, r);
  8215. }
  8216. let (a, bb) = (s(self, 0)?, s(self, 1)?);
  8217. let r = self.s.m.select(c, cond, bb, a);
  8218. int(self, r)
  8219. }
  8220. "v_add_co_u32" | "v_sub_co_u32" | "v_subrev_co_u32" | "v_add_co_ci_u32"
  8221. | "v_sub_co_ci_u32" | "v_subrev_co_ci_u32" => {
  8222. // The carry (borrow) out is a lane mask: this lane's bit.
  8223. let (mut a, mut bb) = (s(self, 0)?, s(self, 1)?);
  8224. if name.contains("subrev") {
  8225. std::mem::swap(&mut a, &mut bb);
  8226. }
  8227. let cin = if name.ends_with("_ci_u32") {
  8228. let m = match v.src.get(2) {
  8229. Some(&Operand::Scalar { code, .. }) => inst.read(Reg::S(code)),
  8230. _ => None,
  8231. };
  8232. let m = m
  8233. .and_then(|m| self.x.st.masks.get(&m).copied())
  8234. .ok_or("a carry-in from an untracked mask")?;
  8235. Some(self.boolean(m, c)?)
  8236. } else {
  8237. None
  8238. };
  8239. let (r, carry) = self.add_sub_carry(c, name.starts_with("v_add"), a, bb, cin);
  8240. int(self, r)?;
  8241. if let Some(Operand::Scalar { code, .. }) = v.carry
  8242. && let Some(w) = inst.write(Reg::S(code))
  8243. {
  8244. self.lane_bits.insert(w, carry);
  8245. }
  8246. for &(_, w) in &inst.writes {
  8247. self.vals
  8248. .entry(w)
  8249. .or_insert(Val::Missing("a lane mask read as data"));
  8250. }
  8251. Ok(())
  8252. }
  8253. "v_permlane16_b32" | "v_permlanex16_b32" => {
  8254. // RDNA2 ISA 12.12: each nibble of {src2, src1} selects a lane
  8255. // in this row of 16, or the other row of the same 32-lane half.
  8256. // OP_SEL[0:1] are fetch-inactive and bound-control, not half selects.
  8257. if v.abs != 0 || v.neg != 0 || v.opsel & !3 != 0 {
  8258. return Err("permlane input modifiers");
  8259. }
  8260. self.cross_lane(false)?;
  8261. let fetch_inactive = v.opsel & 1 != 0;
  8262. if fetch_inactive
  8263. && !all_lane_blocks(self.x.st).is_some_and(|all| all[self.cur_ir])
  8264. {
  8265. // DXIL cannot read the last VGPR value of a host invocation
  8266. // that has left through a lane branch. A guard keeps it here.
  8267. return Err("a permlane fetch from lanes outside the host branch");
  8268. }
  8269. let (x, lo, hi) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  8270. let lane = self.lane_index();
  8271. let (k7, k8, k15, k16, k31, k32, k4, one, zero) = (
  8272. self.s.m.i32(7),
  8273. self.s.m.i32(8),
  8274. self.s.m.i32(15),
  8275. self.s.m.i32(16),
  8276. self.s.m.i32(31),
  8277. self.s.m.i32(32),
  8278. self.s.m.i32(4),
  8279. self.s.m.i32(1),
  8280. self.s.m.i32(0),
  8281. );
  8282. let pos = self.s.m.bin(c, Bin::And, lane, k15);
  8283. let lower = self.s.m.cmp(c, pred::IULT, pos, k8);
  8284. let packed = self.s.m.select(c, lower, lo, hi);
  8285. let shift = self.s.m.bin(c, Bin::And, pos, k7);
  8286. let shift = self.s.m.bin(c, Bin::Mul, shift, k4);
  8287. let pick = self.s.m.bin(c, Bin::LShr, packed, shift);
  8288. let pick = self.s.m.bin(c, Bin::And, pick, k15);
  8289. let not15 = self.s.m.i32(!15);
  8290. let mut row = self.s.m.bin(c, Bin::And, lane, not15);
  8291. if name == "v_permlanex16_b32" {
  8292. row = self.s.m.bin(c, Bin::Xor, row, k16);
  8293. }
  8294. let src = self.s.m.bin(c, Bin::Or, row, pick);
  8295. let r = if fetch_inactive {
  8296. self.read_lane(x, src)
  8297. } else {
  8298. // Ballot the console EXEC guard as well as the host's active
  8299. // invocations. Never shuffle from an inactive host lane.
  8300. let enabled = guard.unwrap_or_else(|| self.s.m.bool(true));
  8301. let i32t = self.s.t.i32;
  8302. let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]);
  8303. let mask = self.s.op(
  8304. c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[enabled],
  8305. );
  8306. let lo = self.s.m.extract(c, mask, 0);
  8307. let hi = self.s.m.extract(c, mask, 1);
  8308. let lower = self.s.m.cmp(c, pred::IULT, src, k32);
  8309. let word = self.s.m.select(c, lower, lo, hi);
  8310. let bit = self.s.m.bin(c, Bin::And, src, k31);
  8311. let bit = self.s.m.bin(c, Bin::LShr, word, bit);
  8312. let bit = self.s.m.bin(c, Bin::And, bit, one);
  8313. let active = self.s.m.cmp(c, pred::NE, bit, zero);
  8314. let safe = self.s.m.select(c, active, src, lane);
  8315. let read = self.read_lane(x, safe);
  8316. let fallback = if v.opsel & 2 != 0 {
  8317. zero
  8318. } else {
  8319. let Some(Operand::Vector { reg, .. }) = v.dst else {
  8320. return Err("a permlane result outside a VGPR");
  8321. };
  8322. self.i32_of(inst.read(Reg::V(reg)).ok_or("a permlane old value")?)?
  8323. };
  8324. self.s.m.select(c, active, read, fallback)
  8325. };
  8326. int(self, r)
  8327. }
  8328. "v_readlane_b32" => {
  8329. let (a, lane) = (s(self, 0)?, s(self, 1)?);
  8330. // A computed lane in a pixel or vertex program is a host lane
  8331. // (from a mask or `v_mbcnt`); a constant one is the console's.
  8332. if self.mask_data == MaskData::Host && !matches!(lane, V::Const(_)) {
  8333. self.s.flags |= flags::WAVE_OPS;
  8334. } else {
  8335. self.cross_lane(false)?;
  8336. }
  8337. if let Some(slot) = self.exchange.as_ref().map(|e| e.0) {
  8338. if self.local && self.local_any {
  8339. // this host wave's lane of that number (lanes 32..63 are 0..31 here)
  8340. let k31 = self.s.m.i32(31);
  8341. let here = self.s.m.bin(self.cur, Bin::And, lane, k31);
  8342. let r = self.read_lane(a, here);
  8343. return int(self, r);
  8344. }
  8345. if self.local {
  8346. return Err("a lane read in a half-wave");
  8347. }
  8348. if self.exchange.as_ref().is_some_and(|e| e.1) {
  8349. // a group of 32 or fewer: the lane is in this host wave
  8350. let r = self.read_lane(a, lane);
  8351. return int(self, r);
  8352. }
  8353. // the lane that holds it may be in the other host wave: it gives it through LDS
  8354. if !self.all_lanes(self.cur_ir) {
  8355. need(self.cur_ir);
  8356. return Err("a lane read where not every lane runs");
  8357. }
  8358. let cl = self.console_lane();
  8359. let is = self.s.m.cmp(self.cur, pred::EQ, cl, lane);
  8360. let k = self.exchange_pair(slot);
  8361. let at = self.begin_guarded(Some(is));
  8362. let lds = self.s.lds();
  8363. let ptr = self.s.m.element(self.cur, lds, k);
  8364. self.s.m.store(self.cur, ptr, a);
  8365. self.end_guarded(at, &[]);
  8366. let c2 = self.cur;
  8367. self.group_sync(c2);
  8368. let ptr = self.s.m.element(c2, lds, k);
  8369. let r = self.s.m.load(c2, ptr);
  8370. self.group_sync(c2);
  8371. return int(self, r);
  8372. }
  8373. let r = self.read_lane(a, lane);
  8374. int(self, r)
  8375. }
  8376. "v_writelane_b32" => {
  8377. // The lane given takes the scalar; the others keep their value.
  8378. let (a, lane) = (s(self, 0)?, s(self, 1)?);
  8379. let Some(Operand::Vector { reg, .. }) = v.dst else {
  8380. return Err("a lane write");
  8381. };
  8382. let old = match inst.read(Reg::V(reg)) {
  8383. Some(o) => self.i32_of(o)?,
  8384. None => self.s.m.i32(0),
  8385. };
  8386. self.cross_lane(false)?;
  8387. if self.local && !self.local_any {
  8388. return Err("a lane write in a half-wave");
  8389. }
  8390. let me = self.console_lane();
  8391. let is = self.s.m.cmp(c, pred::EQ, me, lane);
  8392. let r = self.s.m.select(c, is, a, old);
  8393. int(self, r)
  8394. }
  8395. "v_readfirstlane_b32"
  8396. if inst
  8397. .writes
  8398. .first()
  8399. .is_some_and(|w| self.x.res.waterfall.reads.contains(&w.1)) =>
  8400. {
  8401. // A waterfall loop's read of a descriptor dword: the lane's own.
  8402. let a = s(self, 0)?;
  8403. int(self, a)
  8404. }
  8405. "v_readfirstlane_b32"
  8406. if matches!(v.src.first(), Some(&Operand::Vector { reg, .. })
  8407. if inst.read(Reg::V(reg)).is_some_and(|x| self.own_bits.alike.contains(&x))) =>
  8408. {
  8409. // The bits a loop over a wave OR has still to visit (`own_bits`): every lane of
  8410. // the host wave holds the same, so the first lane's is the lane's own.
  8411. let a = s(self, 0)?;
  8412. int(self, a)
  8413. }
  8414. "v_readfirstlane_b32" => {
  8415. let a = s(self, 0)?;
  8416. let (mine, any) = self.first_lane(a, guard);
  8417. // two host waves that exchange: the console's first lane may be in the other
  8418. // one, unless every lane holds the same value
  8419. let alike = match v.src.first() {
  8420. Some(&Operand::Vector { reg, .. }) => {
  8421. inst.read(Reg::V(reg)).is_some_and(|x| self.uniform.contains(&x))
  8422. }
  8423. _ => true,
  8424. };
  8425. let halves = self.exchange.as_ref().is_some_and(|e| !e.1) && !self.local;
  8426. let r = if halves && !alike {
  8427. if !self.all_lanes(self.cur_ir) {
  8428. // shortcut: `VICTORY_FIRSTLANE_OWN=1` takes the host wave's own
  8429. // first lane, exact when the value is the same in every lane of
  8430. // the console wave (the ray-tracing builder's scans read a sum of
  8431. // scalars this way, inside a loop whose exit is per console wave).
  8432. static OWN: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  8433. if *OWN.get_or_init(|| std::env::var_os("VICTORY_FIRSTLANE_OWN").is_some_and(|v| v == "1")) {
  8434. return int(self, mine);
  8435. }
  8436. need(self.cur_ir);
  8437. return Err("a first-lane read where not every lane runs");
  8438. }
  8439. let c = self.cur;
  8440. if guard.is_none() && super::shader_opt() & super::bitcode::opt::FIRST != 0 {
  8441. // Every lane is in EXEC: the console's first lane is
  8442. // lane 0, which the lower half of every console wave
  8443. // has. No half needs to ask the other whether it has
  8444. // a lane (an exchange of the constant 1: two group
  8445. // barriers), and the lower half's value is the answer.
  8446. let (lo, _) = self.exchange_halves(c, mine);
  8447. lo
  8448. } else {
  8449. let i32t = self.s.t.i32;
  8450. let has = self.s.m.cast(c, Cast::ZExt, any, i32t);
  8451. let (lo_has, hi_has) = self.exchange_halves(c, has);
  8452. let (lo, hi) = self.exchange_halves(c, mine);
  8453. let z = self.s.m.i32(0);
  8454. let in_lo = self.s.m.cmp(c, pred::NE, lo_has, z);
  8455. let in_hi = self.s.m.cmp(c, pred::NE, hi_has, z);
  8456. // neither half has a lane in EXEC: the console reads lane 0
  8457. let hi = self.s.m.select(c, in_hi, hi, lo);
  8458. self.s.m.select(c, in_lo, lo, hi)
  8459. }
  8460. } else {
  8461. mine
  8462. };
  8463. int(self, r)
  8464. }
  8465. _ => {
  8466. let r = self.integer(inst, name)?;
  8467. int(self, r)
  8468. }
  8469. }
  8470. }
  8471. /// A 64-bit source (a register pair; inline constants sign-extend).
  8472. fn src64(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  8473. let Fields::Valu(v) = &inst.fields else {
  8474. unreachable!()
  8475. };
  8476. if v.abs >> k & 1 != 0 || v.neg >> k & 1 != 0 || v.sdwa.is_some() || v.dpp.is_some() {
  8477. return Err("64-bit operand modifiers");
  8478. }
  8479. let c = self.cur;
  8480. let i64t = self.s.m.int(64);
  8481. self.s.flags |= flags::INT64;
  8482. let op = *v.src.get(k).ok_or("a missing operand")?;
  8483. let pair = |l: &mut Self, r: Reg, r1: Reg| -> Result<V, Why> {
  8484. let lo = l.i32_of(inst.read(r).ok_or("an unread operand")?)?;
  8485. let hi = l.i32_of(inst.read(r1).ok_or("an unread operand")?)?;
  8486. Ok(l.join64(lo, hi))
  8487. };
  8488. match op {
  8489. Operand::Vector { reg, .. } => pair(self, Reg::V(reg), Reg::V(reg + 1)),
  8490. Operand::Scalar { code, .. } if code != NULL => {
  8491. pair(self, Reg::S(code), Reg::S(code + 1))
  8492. }
  8493. Operand::Const(k @ 128..=208) => {
  8494. let x = crate::resource::inline(k).ok_or("a special operand")?;
  8495. Ok(self.s.m.int_const(i64t, i64::from(x as i32)))
  8496. }
  8497. // A signed 64-bit operand sign-extends its 32-bit literal, as
  8498. // the hardware does (LLVM's AMDGPU operand rules).
  8499. Operand::Literal(x) if inst.name().ends_with("_i64") => {
  8500. Ok(self.s.m.int_const(i64t, i64::from(x as i32)))
  8501. }
  8502. _ => {
  8503. // Literals (of unsigned and bit operands) and the null
  8504. // register: zero-extended.
  8505. let x = self.operand(inst, &op)?;
  8506. Ok(self.s.m.cast(c, Cast::ZExt, x, i64t))
  8507. }
  8508. }
  8509. }
  8510. /// Reads an IEEE-754 binary64 operand as `(lo, hi)` 32-bit words, applying
  8511. /// `abs` and `neg` input modifiers on operand `k`.
  8512. fn f64_pair(&mut self, inst: &Inst, k: usize) -> Result<(V, V), Why> {
  8513. let Fields::Valu(v) = &inst.fields else {
  8514. unreachable!()
  8515. };
  8516. if v.sdwa.is_some() || v.dpp.is_some() {
  8517. return Err("64-bit operand modifiers");
  8518. }
  8519. let op = *v.src.get(k).ok_or("a missing operand")?;
  8520. let pair = |l: &mut Self, r: Reg, r1: Reg| -> Result<(V, V), Why> {
  8521. let lo = l.i32_of(inst.read(r).ok_or("an unread operand")?)?;
  8522. let hi = l.i32_of(inst.read(r1).ok_or("an unread operand")?)?;
  8523. Ok((lo, hi))
  8524. };
  8525. let (lo, mut hi) = match op {
  8526. Operand::Vector { reg, .. } => pair(self, Reg::V(reg), Reg::V(reg + 1))?,
  8527. Operand::Scalar { code, .. } if code != NULL => {
  8528. pair(self, Reg::S(code), Reg::S(code + 1))?
  8529. }
  8530. Operand::Const(128) => (self.s.m.i32(0), self.s.m.i32(0)),
  8531. Operand::Const(c @ 240..=248) => {
  8532. const INLINE_F64: [f64; 9] = [
  8533. 0.5,
  8534. -0.5,
  8535. 1.0,
  8536. -1.0,
  8537. 2.0,
  8538. -2.0,
  8539. 4.0,
  8540. -4.0,
  8541. 1.0 / std::f64::consts::TAU,
  8542. ];
  8543. let bits = INLINE_F64[(c - 240) as usize].to_bits();
  8544. (self.s.m.i32(bits as u32), self.s.m.i32((bits >> 32) as u32))
  8545. }
  8546. // GFX10 places a 32-bit literal in the high 32 bits of a 64-bit float operand.
  8547. Operand::Literal(x) => (self.s.m.i32(0), self.s.m.i32(x)),
  8548. _ => return Err("a 64-bit float operand"),
  8549. };
  8550. let c = self.cur;
  8551. if v.abs >> k & 1 != 0 {
  8552. let mask = self.s.m.i32(0x7FFF_FFFF);
  8553. hi = self.s.m.bin(c, Bin::And, hi, mask);
  8554. }
  8555. if v.neg >> k & 1 != 0 {
  8556. let sign = self.s.m.i32(0x8000_0000);
  8557. hi = self.s.m.bin(c, Bin::Xor, hi, sign);
  8558. }
  8559. Ok((lo, hi))
  8560. }
  8561. /// Converts IEEE-754 binary64 `(lo, hi)` to binary32 bits with round-to-nearest-even,
  8562. /// without requiring host `DOUBLES` (`f64`) support.
  8563. fn f64_to_f32_bits(&mut self, lo: V, hi: V) -> V {
  8564. let c = self.cur;
  8565. let k0 = self.s.m.i32(0);
  8566. let k1 = self.s.m.i32(1);
  8567. let sign_mask = self.s.m.i32(0x8000_0000);
  8568. let sign = self.s.m.bin(c, Bin::And, hi, sign_mask);
  8569. let k20 = self.s.m.i32(20);
  8570. let k7ff = self.s.m.i32(0x7FF);
  8571. let exp64 = self.s.m.bin(c, Bin::LShr, hi, k20);
  8572. let exp64 = self.s.m.bin(c, Bin::And, exp64, k7ff);
  8573. let frac_mask = self.s.m.i32(0x000F_FFFF);
  8574. let frac_hi = self.s.m.bin(c, Bin::And, hi, frac_mask);
  8575. let frac_any = self.s.m.bin(c, Bin::Or, frac_hi, lo);
  8576. let frac_nz = self.s.m.cmp(c, pred::NE, frac_any, k0);
  8577. let k3 = self.s.m.i32(3);
  8578. let k29 = self.s.m.i32(29);
  8579. let m23_hi = self.s.m.bin(c, Bin::Shl, frac_hi, k3);
  8580. let m23_lo = self.s.m.bin(c, Bin::LShr, lo, k29);
  8581. let m23 = self.s.m.bin(c, Bin::Or, m23_hi, m23_lo);
  8582. let rem_mask = self.s.m.i32(0x1FFF_FFFF);
  8583. let rem = self.s.m.bin(c, Bin::And, lo, rem_mask);
  8584. let half_rem = self.s.m.i32(0x1000_0000);
  8585. let gt_half = self.s.m.cmp(c, pred::IUGT, rem, half_rem);
  8586. let eq_half = self.s.m.cmp(c, pred::EQ, rem, half_rem);
  8587. let m23_odd_bit = self.s.m.bin(c, Bin::And, m23, k1);
  8588. let m23_odd = self.s.m.cmp(c, pred::NE, m23_odd_bit, k0);
  8589. let tie_up = self.s.m.bin(c, Bin::And, eq_half, m23_odd);
  8590. let norm_round = self.s.m.bin(c, Bin::Or, gt_half, tie_up);
  8591. let norm_inc = self.s.m.select(c, norm_round, k1, k0);
  8592. // Normal range: exp64 in [897, 1150] -> exp32 in [1, 254].
  8593. let k896 = self.s.m.i32(896);
  8594. let k23 = self.s.m.i32(23);
  8595. let exp32 = self.s.m.bin(c, Bin::Sub, exp64, k896);
  8596. let exp32_sh = self.s.m.bin(c, Bin::Shl, exp32, k23);
  8597. let norm_body = self.s.m.bin(c, Bin::Add, exp32_sh, m23);
  8598. let norm_body = self.s.m.bin(c, Bin::Add, norm_body, norm_inc);
  8599. let norm_res = self.s.m.bin(c, Bin::Or, sign, norm_body);
  8600. // Subnormal range: exp64 in [874, 896] -> shift in [1, 23].
  8601. let k897 = self.s.m.i32(897);
  8602. let k32 = self.s.m.i32(32);
  8603. let k31 = self.s.m.i32(31);
  8604. let imp = self.s.m.i32(0x0080_0000);
  8605. let sig24 = self.s.m.bin(c, Bin::Or, imp, m23);
  8606. let raw_shift = self.s.m.bin(c, Bin::Sub, k897, exp64);
  8607. // Clamp shift to [1, 23] so shifts never produce poison outside the subnormal branch.
  8608. let lt1 = self.s.m.cmp(c, pred::IULT, raw_shift, k1);
  8609. let shift = self.s.m.select(c, lt1, k1, raw_shift);
  8610. let gt23 = self.s.m.cmp(c, pred::IUGT, shift, k23);
  8611. let shift = self.s.m.select(c, gt23, k23, shift);
  8612. let sub_m = self.s.m.bin(c, Bin::LShr, sig24, shift);
  8613. let inv_shift = self.s.m.bin(c, Bin::Sub, k32, shift);
  8614. let lost = self.s.m.bin(c, Bin::Shl, sig24, inv_shift);
  8615. let round_bit = self.s.m.bin(c, Bin::LShr, lost, k31);
  8616. let round_on = self.s.m.cmp(c, pred::NE, round_bit, k0);
  8617. let low31 = self.s.m.i32(0x7FFF_FFFF);
  8618. let lost_lo = self.s.m.bin(c, Bin::And, lost, low31);
  8619. let sticky = self.s.m.bin(c, Bin::Or, lost_lo, rem);
  8620. let sticky_on = self.s.m.cmp(c, pred::NE, sticky, k0);
  8621. let sub_odd_bit = self.s.m.bin(c, Bin::And, sub_m, k1);
  8622. let sub_odd = self.s.m.cmp(c, pred::NE, sub_odd_bit, k0);
  8623. let sub_tie = self.s.m.bin(c, Bin::Or, sticky_on, sub_odd);
  8624. let sub_round = self.s.m.bin(c, Bin::And, round_on, sub_tie);
  8625. let sub_inc = self.s.m.select(c, sub_round, k1, k0);
  8626. let sub_body = self.s.m.bin(c, Bin::Add, sub_m, sub_inc);
  8627. let sub_res = self.s.m.bin(c, Bin::Or, sign, sub_body);
  8628. // Underflow range: exp64 < 874. Only exp64 == 873 with non-zero fraction rounds up to min subnormal (1).
  8629. let k873 = self.s.m.i32(873);
  8630. let eq873 = self.s.m.cmp(c, pred::EQ, exp64, k873);
  8631. let round_min = self.s.m.bin(c, Bin::And, eq873, frac_nz);
  8632. let min_bit = self.s.m.select(c, round_min, k1, k0);
  8633. let under_res = self.s.m.bin(c, Bin::Or, sign, min_bit);
  8634. // Overflow / Inf / NaN: exp64 >= 1151.
  8635. let is_exp_all = self.s.m.cmp(c, pred::EQ, exp64, k7ff);
  8636. let is_nan = self.s.m.bin(c, Bin::And, is_exp_all, frac_nz);
  8637. let inf_bits = self.s.m.i32(0x7F80_0000);
  8638. let qnan_bits = self.s.m.i32(0x7FC0_0000);
  8639. let nan_body = self.s.m.bin(c, Bin::Or, qnan_bits, m23);
  8640. let over_body = self.s.m.select(c, is_nan, nan_body, inf_bits);
  8641. let over_res = self.s.m.bin(c, Bin::Or, sign, over_body);
  8642. // Select final result by exponent range.
  8643. let k874 = self.s.m.i32(874);
  8644. let k1151 = self.s.m.i32(1151);
  8645. let is_under = self.s.m.cmp(c, pred::IULT, exp64, k874);
  8646. let is_sub = self.s.m.cmp(c, pred::IULT, exp64, k897);
  8647. let is_over = self.s.m.cmp(c, pred::IUGE, exp64, k1151);
  8648. let r = self.s.m.select(c, is_over, over_res, norm_res);
  8649. let r = self.s.m.select(c, is_sub, sub_res, r);
  8650. self.s.m.select(c, is_under, under_res, r)
  8651. }
  8652. fn join64(&mut self, lo: V, hi: V) -> V {
  8653. let c = self.cur;
  8654. let ty = self.s.m.int(64);
  8655. let lo = self.s.m.cast(c, Cast::ZExt, lo, ty);
  8656. let hi = self.s.m.cast(c, Cast::ZExt, hi, ty);
  8657. let shift = self.s.m.int_const(ty, 32);
  8658. let hi = self.s.m.bin(c, Bin::Shl, hi, shift);
  8659. self.s.m.bin(c, Bin::Or, lo, hi)
  8660. }
  8661. /// The bits of the float nearest the double whose dwords are `lo` and
  8662. /// `hi`, on 32-bit integers: round to nearest even, infinities and NaN
  8663. /// kept (a NaN stays quiet), a result below the smallest normal float
  8664. /// signed zero (flushed, as the console's default float mode does).
  8665. // The flush-to-zero form of v_cvt_f32_f64: kept beside the IEEE form in use until the console's
  8666. // float mode for this instruction is checked.
  8667. #[allow(dead_code)]
  8668. fn f64_bits_to_f32_bits(&mut self, lo: V, hi: V) -> V {
  8669. let c = self.cur;
  8670. let k = |l: &mut Self, x: u32| l.s.m.i32(x);
  8671. let (k20, k29, k3, k23) = (k(self, 20), k(self, 29), k(self, 3), k(self, 23));
  8672. let sign_mask = k(self, 0x8000_0000);
  8673. let sign = self.s.m.bin(c, Bin::And, hi, sign_mask);
  8674. let e = self.s.m.bin(c, Bin::LShr, hi, k20);
  8675. let e_mask = k(self, 0x7ff);
  8676. let e = self.s.m.bin(c, Bin::And, e, e_mask);
  8677. // The top 23 bits of the 52-bit mantissa, and the 29 below them.
  8678. let m_mask = k(self, 0x000f_ffff);
  8679. let mh = self.s.m.bin(c, Bin::And, hi, m_mask);
  8680. let mh = self.s.m.bin(c, Bin::Shl, mh, k3);
  8681. let ml = self.s.m.bin(c, Bin::LShr, lo, k29);
  8682. let m = self.s.m.bin(c, Bin::Or, mh, ml);
  8683. let rest_mask = k(self, 0x1fff_ffff);
  8684. let rest = self.s.m.bin(c, Bin::And, lo, rest_mask);
  8685. // Round to nearest even: up past half, or at half when odd.
  8686. let half = k(self, 0x1000_0000);
  8687. let one = k(self, 1);
  8688. let above = self.s.m.cmp(c, pred::IUGT, rest, half);
  8689. let at = self.s.m.cmp(c, pred::EQ, rest, half);
  8690. let odd = self.s.m.bin(c, Bin::And, m, one);
  8691. let zero = k(self, 0);
  8692. let odd = self.s.m.cmp(c, pred::NE, odd, zero);
  8693. let tie = self.s.m.bin(c, Bin::And, at, odd);
  8694. let up = self.s.m.bin(c, Bin::Or, above, tie);
  8695. let up = self.s.m.select(c, up, one, zero);
  8696. // Rebias the exponent (1023 → 127); a carry out of the mantissa
  8697. // steps the exponent, up to infinity.
  8698. let bias = k(self, 1023 - 127);
  8699. let e32 = self.s.m.bin(c, Bin::Sub, e, bias);
  8700. let ex = self.s.m.bin(c, Bin::Shl, e32, k23);
  8701. let normal = self.s.m.bin(c, Bin::Add, ex, m);
  8702. let normal = self.s.m.bin(c, Bin::Add, normal, up);
  8703. let normal = self.s.m.bin(c, Bin::Or, normal, sign);
  8704. // Exponents out of the float's range (signed, after rebiasing).
  8705. let inf = k(self, 0x7f80_0000);
  8706. let inf = self.s.m.bin(c, Bin::Or, inf, sign);
  8707. let k255 = k(self, 255);
  8708. let big = self.s.m.cmp(c, pred::SGE, e32, k255);
  8709. let small = self.s.m.cmp(c, pred::SLE, e32, zero);
  8710. let r = self.s.m.select(c, big, inf, normal);
  8711. let r = self.s.m.select(c, small, sign, r);
  8712. // Infinity and NaN (a NaN with any mantissa bit set stays a NaN).
  8713. let all = k(self, 0x7ff);
  8714. let special = self.s.m.cmp(c, pred::EQ, e, all);
  8715. let any = self.s.m.bin(c, Bin::Or, mh, ml);
  8716. let any = self.s.m.bin(c, Bin::Or, any, rest);
  8717. let nan = self.s.m.cmp(c, pred::NE, any, zero);
  8718. let quiet = k(self, 0x0040_0000);
  8719. let quiet = self.s.m.select(c, nan, quiet, zero);
  8720. let special_bits = self.s.m.bin(c, Bin::Or, inf, quiet);
  8721. self.s.m.select(c, special, special_bits, r)
  8722. }
  8723. /// The low and high dwords of an i64.
  8724. fn split64(&mut self, x: V) -> (V, V) {
  8725. let c = self.cur;
  8726. let i64t = self.s.m.int(64);
  8727. let k32 = self.s.m.int_const(i64t, 32);
  8728. let lo = self.s.m.cast(c, Cast::Trunc, x, self.s.t.i32);
  8729. let hi = self.s.m.bin(c, Bin::LShr, x, k32);
  8730. let hi = self.s.m.cast(c, Cast::Trunc, hi, self.s.t.i32);
  8731. (lo, hi)
  8732. }
  8733. /// Source `k` of a 16-bit operation in the low 16 bits (the rest 0):
  8734. /// op_sel (or an SDWA word select) picks the high half; inline float
  8735. /// constants are f16 values here.
  8736. fn half_src(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  8737. let Fields::Valu(v) = &inst.fields else {
  8738. unreachable!()
  8739. };
  8740. let op = *v.src.get(k).ok_or("a missing operand")?;
  8741. let mut high = v.opsel >> k & 1 != 0;
  8742. if let Some(sd) = v.sdwa {
  8743. match sd.src_sel.get(k).copied().unwrap_or(6) {
  8744. 4 => {}
  8745. 5 => high = true,
  8746. 6 => {}
  8747. _ => return Err("a byte select on a 16-bit operation"),
  8748. }
  8749. }
  8750. let x = match self.src0 {
  8751. Some(x) if k == 0 => x,
  8752. _ => self.f16_operand(inst, &op)?,
  8753. };
  8754. let c = self.cur;
  8755. let x = if high {
  8756. let k16 = self.s.m.i32(16);
  8757. self.s.m.bin(c, Bin::LShr, x, k16)
  8758. } else {
  8759. x
  8760. };
  8761. let m = self.s.m.i32(0xFFFF);
  8762. Ok(self.s.m.bin(c, Bin::And, x, m))
  8763. }
  8764. /// An f16 source as an f32 (exact), with its abs/neg modifiers.
  8765. fn half_fsrc(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  8766. let Fields::Valu(v) = &inst.fields else {
  8767. unreachable!()
  8768. };
  8769. let h = self.half_src(inst, k)?;
  8770. let f32t = self.s.t.f32;
  8771. let mut f = self
  8772. .s
  8773. .op(self.cur, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]);
  8774. if v.abs >> k & 1 != 0 {
  8775. f = self.unary(6, f);
  8776. }
  8777. if v.neg >> k & 1 != 0 {
  8778. let z = self.s.m.f32(0x8000_0000);
  8779. f = self.s.m.bin(self.cur, Bin::Sub, z, f);
  8780. }
  8781. Ok(f)
  8782. }
  8783. /// Writes a 16-bit result (low bits of `x`) into the destination's low
  8784. /// half, or its high half with op_sel bit 3 (or an SDWA WORD_1 select);
  8785. /// the other half is kept (GFX10).
  8786. fn write_half(&mut self, inst: &Inst, x: V, guard: Option<V>) -> Result<(), Why> {
  8787. let Fields::Valu(v) = &inst.fields else {
  8788. unreachable!()
  8789. };
  8790. let Some(Operand::Vector { reg, .. }) = v.dst else {
  8791. return Err("a 16-bit result outside a VGPR");
  8792. };
  8793. let mut high = v.opsel >> 3 & 1 != 0;
  8794. // SDWA: the word written, the other one kept (preserve) or zero
  8795. // (pad; a sign extension above the high word adds nothing).
  8796. let mut keep = true;
  8797. if let Some(sd) = v.sdwa {
  8798. match (sd.dst_sel, sd.dst_unused) {
  8799. (4, 2) => {}
  8800. (5, 2) => high = true,
  8801. (4 | 6, _) => keep = false,
  8802. (5, _) => (high, keep) = (true, false),
  8803. _ => return Err("an SDWA destination of a 16-bit operation"),
  8804. }
  8805. }
  8806. let c = self.cur;
  8807. let old = match inst.read(Reg::V(reg)).map(|o| self.i32_of(o)) {
  8808. Some(Ok(o)) if keep => o,
  8809. _ => self.s.m.i32(0),
  8810. };
  8811. let (k16, low) = (self.s.m.i32(16), self.s.m.i32(0xFFFF));
  8812. let x = self.s.m.bin(c, Bin::And, x, low);
  8813. let r = if high {
  8814. let o = self.s.m.bin(c, Bin::And, old, low);
  8815. let x = self.s.m.bin(c, Bin::Shl, x, k16);
  8816. self.s.m.bin(c, Bin::Or, o, x)
  8817. } else {
  8818. let keep = self.s.m.i32(0xFFFF_0000);
  8819. let o = self.s.m.bin(c, Bin::And, old, keep);
  8820. self.s.m.bin(c, Bin::Or, o, x)
  8821. };
  8822. self.write_placed(inst, Reg::V(reg), r, guard);
  8823. Ok(())
  8824. }
  8825. /// 16-bit operations, computed in f32 or i32: f16 sums, differences and
  8826. /// products are exact there and round once to f16 (f32 has the 2 x 11 +
  8827. /// 2 bits that make double rounding harmless); `None` if `name` is none.
  8828. fn valu16(&mut self, inst: &Inst, name: &str, guard: Option<V>) -> Option<Result<(), Why>> {
  8829. const FLOAT2: &[&str] = &[
  8830. "v_add_f16",
  8831. "v_sub_f16",
  8832. "v_subrev_f16",
  8833. "v_mul_f16",
  8834. "v_max_f16",
  8835. "v_min_f16",
  8836. ];
  8837. const FLOAT3: &[&str] = &[
  8838. "v_fma_f16",
  8839. "v_mad_f16",
  8840. "v_fmac_f16",
  8841. "v_mac_f16",
  8842. "v_max3_f16",
  8843. "v_min3_f16",
  8844. "v_med3_f16",
  8845. ];
  8846. const FLOAT1: &[&str] = &[
  8847. "v_rcp_f16",
  8848. "v_sqrt_f16",
  8849. "v_rsq_f16",
  8850. "v_log_f16",
  8851. "v_exp_f16",
  8852. "v_fract_f16",
  8853. "v_trunc_f16",
  8854. "v_floor_f16",
  8855. "v_ceil_f16",
  8856. "v_rndne_f16",
  8857. "v_sin_f16",
  8858. "v_cos_f16",
  8859. "v_cvt_f16_u16",
  8860. "v_cvt_f16_i16",
  8861. ];
  8862. const INT: &[&str] = &[
  8863. "v_add_nc_u16",
  8864. "v_sub_nc_u16",
  8865. "v_subrev_nc_u16",
  8866. "v_mul_lo_u16",
  8867. "v_lshlrev_b16",
  8868. "v_lshrrev_b16",
  8869. "v_ashrrev_i16",
  8870. "v_max_u16",
  8871. "v_max_i16",
  8872. "v_min_u16",
  8873. "v_min_i16",
  8874. "v_cvt_u16_f16",
  8875. "v_cvt_i16_f16",
  8876. "v_cvt_norm_i16_f16",
  8877. "v_cvt_norm_u16_f16",
  8878. ];
  8879. let all = [FLOAT1, FLOAT2, FLOAT3, INT];
  8880. if !all.iter().any(|l| l.contains(&name))
  8881. && !matches!(name, "v_cvt_f16_f32" | "v_cvt_f32_f16")
  8882. {
  8883. return None;
  8884. }
  8885. Some(self.valu16_op(inst, name, guard, FLOAT1, FLOAT2, FLOAT3))
  8886. }
  8887. #[allow(clippy::too_many_arguments)]
  8888. fn valu16_op(
  8889. &mut self,
  8890. inst: &Inst,
  8891. name: &str,
  8892. guard: Option<V>,
  8893. float1: &[&str],
  8894. float2: &[&str],
  8895. float3: &[&str],
  8896. ) -> Result<(), Why> {
  8897. let Fields::Valu(v) = &inst.fields else {
  8898. unreachable!()
  8899. };
  8900. let c = self.cur;
  8901. let i32t = self.s.t.i32;
  8902. let f32t = self.s.t.f32;
  8903. if name == "v_cvt_f32_f16" {
  8904. let f = self.half_fsrc(inst, 0)?;
  8905. return self.write_f(inst, f, guard);
  8906. }
  8907. let float_result = |l: &mut Self, mut f: V| -> Result<(), Why> {
  8908. match v.omod {
  8909. 0 => {}
  8910. k => {
  8911. let factor = [1.0f32, 2.0, 4.0, 0.5][usize::from(k)];
  8912. let k = l.s.m.f32(factor.to_bits());
  8913. f = l.s.m.bin(l.cur, Bin::Mul, f, k);
  8914. }
  8915. }
  8916. if v.clamp {
  8917. f = l.unary(7, f);
  8918. }
  8919. // The console rounds to nearest; the host's conversion may round toward zero
  8920. // (NVIDIA's does), one step of the last place lower where the two differ.
  8921. // shortcut: the host's conversion unless `VICTORY_F16_NEAREST=1`
  8922. // ([`f16_nearest_on`]), which costs a dozen instructions per result.
  8923. let h = if f16_nearest_on() {
  8924. l.f16_nearest(f)
  8925. } else {
  8926. l.s.op(l.cur, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f])
  8927. };
  8928. l.write_half(inst, h, guard)
  8929. };
  8930. if name == "v_cvt_f16_f32" {
  8931. let f = self.fsrc(inst, 0)?;
  8932. return float_result(self, f);
  8933. }
  8934. if float2.contains(&name) {
  8935. let (a, b) = (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?);
  8936. let r = match name {
  8937. "v_add_f16" => self.s.m.bin(c, Bin::Add, a, b),
  8938. "v_sub_f16" => self.s.m.bin(c, Bin::Sub, a, b),
  8939. "v_subrev_f16" => self.s.m.bin(c, Bin::Sub, b, a),
  8940. "v_mul_f16" => self.s.m.bin(c, Bin::Mul, a, b),
  8941. "v_max_f16" => self.max_min(true, a, b),
  8942. _ => self.max_min(false, a, b),
  8943. };
  8944. return float_result(self, r);
  8945. }
  8946. if float3.contains(&name) {
  8947. let (a, b) = (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?);
  8948. let acc = if matches!(name, "v_fmac_f16" | "v_mac_f16") {
  8949. // The accumulator is the destination's half that is written.
  8950. let Some(Operand::Vector { reg, .. }) = v.dst else {
  8951. return Err("an accumulator");
  8952. };
  8953. let x = self.i32_of(inst.read(Reg::V(reg)).ok_or("an accumulator")?)?;
  8954. let x = if v.opsel >> 3 & 1 != 0 {
  8955. let k16 = self.s.m.i32(16);
  8956. self.s.m.bin(c, Bin::LShr, x, k16)
  8957. } else {
  8958. x
  8959. };
  8960. let m = self.s.m.i32(0xFFFF);
  8961. let x = self.s.m.bin(c, Bin::And, x, m);
  8962. self.s
  8963. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x])
  8964. } else {
  8965. self.half_fsrc(inst, 2)?
  8966. };
  8967. let r = match name {
  8968. // shortcut: fused f16 multiply-adds as FMad in f32 (the
  8969. // product is exact; the sum rounds twice).
  8970. "v_fma_f16" | "v_fmac_f16" | "v_mad_f16" | "v_mac_f16" => self.fmad(a, b, acc),
  8971. "v_max3_f16" => {
  8972. let t = self.max_min(true, a, b);
  8973. self.max_min(true, t, acc)
  8974. }
  8975. "v_min3_f16" => {
  8976. let t = self.max_min(false, a, b);
  8977. self.max_min(false, t, acc)
  8978. }
  8979. _ => self.med3(a, b, acc),
  8980. };
  8981. return float_result(self, r);
  8982. }
  8983. if float1.contains(&name) {
  8984. let r = match name {
  8985. "v_cvt_f16_u16" | "v_cvt_f16_i16" => {
  8986. let mut x = self.half_src(inst, 0)?;
  8987. let op = if name == "v_cvt_f16_i16" {
  8988. let k16 = self.s.m.i32(16);
  8989. let t = self.s.m.bin(c, Bin::Shl, x, k16);
  8990. x = self.s.m.bin(c, Bin::AShr, t, k16);
  8991. Cast::SiToFp
  8992. } else {
  8993. Cast::UiToFp
  8994. };
  8995. self.s.m.cast(c, op, x, f32t)
  8996. }
  8997. "v_rcp_f16" => {
  8998. let a = self.half_fsrc(inst, 0)?;
  8999. let one = self.s.m.f32(1.0f32.to_bits());
  9000. self.s.m.bin(c, Bin::SDiv, one, a)
  9001. }
  9002. _ => {
  9003. let a = self.half_fsrc(inst, 0)?;
  9004. let op = match name {
  9005. "v_sqrt_f16" => 24,
  9006. "v_rsq_f16" => 25,
  9007. "v_log_f16" => 23,
  9008. "v_exp_f16" => 21,
  9009. "v_fract_f16" => 22,
  9010. "v_trunc_f16" => 29,
  9011. "v_floor_f16" => 27,
  9012. "v_ceil_f16" => 28,
  9013. "v_rndne_f16" => 26,
  9014. "v_sin_f16" => 13,
  9015. _ => 12,
  9016. };
  9017. match op {
  9018. 12 | 13 => self.trig_turns(a, op == 12),
  9019. // Any f16 in (-2^-11, 0) has fract >= 1 - 2^-12; clamp to 0x3bff (1 - 2^-11).
  9020. 22 => self.fract(a, 1.0 - 1.0 / 4096.0, 1.0 - 1.0 / 2048.0),
  9021. _ => self.unary(op, a),
  9022. }
  9023. }
  9024. };
  9025. return float_result(self, r);
  9026. }
  9027. if matches!(name, "v_cvt_u16_f16" | "v_cvt_i16_f16") {
  9028. if v.clamp || v.omod != 0 {
  9029. return Err("modifiers on a 16-bit integer operation");
  9030. }
  9031. // Toward zero, saturating at the 16-bit range (infinities
  9032. // included); NaN gives 0. Clamped in f32 first, where every
  9033. // f16 is exact, so the conversion never leaves i32's range
  9034. // (upstream PR #384's arithmetic; the source's abs and neg
  9035. // modifiers are applied by `half_fsrc`, as before).
  9036. let a = self.half_fsrc(inst, 0)?;
  9037. let (lo, hi) = if name == "v_cvt_u16_f16" {
  9038. (0.0f32, 65535.0f32)
  9039. } else {
  9040. (-32768.0, 32767.0)
  9041. };
  9042. let (lo, hi) = (self.s.m.f32(lo.to_bits()), self.s.m.f32(hi.to_bits()));
  9043. let t = self.binary(35, a, lo);
  9044. let t = self.binary(36, t, hi);
  9045. let r = self.s.m.cast(c, Cast::FpToSi, t, i32t);
  9046. let nan = self.s.m.cmp(c, pred::UNO, a, a);
  9047. let z = self.s.m.i32(0);
  9048. let r = self.s.m.select(c, nan, z, r);
  9049. return self.write_half(inst, r, guard);
  9050. }
  9051. if matches!(name, "v_cvt_norm_i16_f16" | "v_cvt_norm_u16_f16") {
  9052. if v.clamp || v.omod != 0 {
  9053. return Err("modifiers on a 16-bit integer operation");
  9054. }
  9055. let r = self.cvt_norm16(inst, name == "v_cvt_norm_i16_f16")?;
  9056. return self.write_half(inst, r, guard);
  9057. }
  9058. // 16-bit integers: computed on the low halves, the low 16 bits kept.
  9059. if v.clamp || v.omod != 0 || v.abs != 0 || v.neg != 0 {
  9060. return Err("modifiers on a 16-bit integer operation");
  9061. }
  9062. let r = {
  9063. let (mut a, mut b) = (self.half_src(inst, 0)?, self.half_src(inst, 1)?);
  9064. let k16 = self.s.m.i32(16);
  9065. let sext = |l: &mut Self, x: V| {
  9066. let t = l.s.m.bin(c, Bin::Shl, x, k16);
  9067. l.s.m.bin(c, Bin::AShr, t, k16)
  9068. };
  9069. if name.ends_with("_i16") {
  9070. a = sext(self, a);
  9071. b = sext(self, b);
  9072. }
  9073. let k15 = self.s.m.i32(15);
  9074. match name {
  9075. "v_add_nc_u16" => self.s.m.bin(c, Bin::Add, a, b),
  9076. "v_sub_nc_u16" => self.s.m.bin(c, Bin::Sub, a, b),
  9077. "v_subrev_nc_u16" => self.s.m.bin(c, Bin::Sub, b, a),
  9078. "v_mul_lo_u16" => self.s.m.bin(c, Bin::Mul, a, b),
  9079. "v_lshlrev_b16" | "v_lshrrev_b16" | "v_ashrrev_i16" => {
  9080. // src0 is the shift (4 bits), src1 the value.
  9081. let sh = self.s.m.bin(c, Bin::And, a, k15);
  9082. let x = if name == "v_ashrrev_i16" {
  9083. sext(self, b)
  9084. } else {
  9085. b
  9086. };
  9087. let op = match name {
  9088. "v_lshlrev_b16" => Bin::Shl,
  9089. "v_lshrrev_b16" => Bin::LShr,
  9090. _ => Bin::AShr,
  9091. };
  9092. self.s.m.bin(c, op, x, sh)
  9093. }
  9094. _ => {
  9095. let p = match name {
  9096. "v_max_u16" => pred::IUGT,
  9097. "v_min_u16" => pred::IULT,
  9098. "v_max_i16" => pred::SGT,
  9099. _ => pred::SLT,
  9100. };
  9101. let t = self.s.m.cmp(c, p, a, b);
  9102. self.s.m.select(c, t, a, b)
  9103. }
  9104. }
  9105. };
  9106. self.write_half(inst, r, guard)
  9107. }
  9108. /// `v_cvt_norm_i16_f16` / `v_cvt_norm_u16_f16`: the f16 source (with its
  9109. /// abs/neg modifiers) clamped to [-1, 1] or [0, 1], times 32767 or 65535,
  9110. /// rounded to nearest even once from the exact product; NaN gives 0.
  9111. /// Worked on the f16's bits in integers, because in f32 the product
  9112. /// (up to 26 significant bits) would round before the rounding to an
  9113. /// integer.
  9114. fn cvt_norm16(&mut self, inst: &Inst, signed: bool) -> Result<V, Why> {
  9115. let Fields::Valu(v) = &inst.fields else {
  9116. unreachable!()
  9117. };
  9118. let c = self.cur;
  9119. let k = |l: &mut Self, x: u32| l.s.m.i32(x);
  9120. let mut h = self.half_src(inst, 0)?;
  9121. if v.abs & 1 != 0 {
  9122. let m = k(self, 0x7FFF);
  9123. h = self.s.m.bin(c, Bin::And, h, m);
  9124. }
  9125. if v.neg & 1 != 0 {
  9126. let m = k(self, 0x8000);
  9127. h = self.s.m.bin(c, Bin::Xor, h, m);
  9128. }
  9129. let scale = if signed { 0x7FFF } else { 0xFFFF };
  9130. let (k0, k1, k10) = (k(self, 0), k(self, 1), k(self, 10));
  9131. let mag_mask = k(self, 0x7FFF);
  9132. let mag = self.s.m.bin(c, Bin::And, h, mag_mask);
  9133. let k15 = k(self, 15);
  9134. let neg = self.s.m.bin(c, Bin::LShr, h, k15);
  9135. let neg = self.s.m.cmp(c, pred::NE, neg, k0);
  9136. // |x| < 1: x = m * 2^-s with m < 2^11 and 11 <= s <= 24.
  9137. let exp = self.s.m.bin(c, Bin::LShr, mag, k10);
  9138. let man_mask = k(self, 0x3FF);
  9139. let man = self.s.m.bin(c, Bin::And, mag, man_mask);
  9140. let implicit = k(self, 0x400);
  9141. let normal = self.s.m.bin(c, Bin::Or, man, implicit);
  9142. let sub = self.s.m.cmp(c, pred::EQ, exp, k0);
  9143. let m = self.s.m.select(c, sub, man, normal);
  9144. let k25 = k(self, 25);
  9145. let s_norm = self.s.m.bin(c, Bin::Sub, k25, exp);
  9146. let k24 = k(self, 24);
  9147. let sh = self.s.m.select(c, sub, k24, s_norm);
  9148. let ks = k(self, scale);
  9149. let p = self.s.m.bin(c, Bin::Mul, m, ks);
  9150. let q = self.s.m.bin(c, Bin::LShr, p, sh);
  9151. let one_s = self.s.m.bin(c, Bin::Shl, k1, sh);
  9152. let low_mask = self.s.m.bin(c, Bin::Sub, one_s, k1);
  9153. let rem = self.s.m.bin(c, Bin::And, p, low_mask);
  9154. let half = self.s.m.bin(c, Bin::LShr, one_s, k1);
  9155. let above = self.s.m.cmp(c, pred::IUGT, rem, half);
  9156. let tie = self.s.m.cmp(c, pred::EQ, rem, half);
  9157. let odd = self.s.m.bin(c, Bin::And, q, k1);
  9158. let odd = self.s.m.cmp(c, pred::NE, odd, k0);
  9159. let tie_up = self.s.m.bin(c, Bin::And, tie, odd);
  9160. let up = self.s.m.bin(c, Bin::Or, above, tie_up);
  9161. let r = self.s.m.select(c, up, k1, k0);
  9162. let r = self.s.m.bin(c, Bin::Add, q, r);
  9163. // |x| >= 1 (and infinity) saturates; NaN gives 0.
  9164. let one_h = k(self, 0x3C00);
  9165. let big = self.s.m.cmp(c, pred::IUGE, mag, one_h);
  9166. let r = self.s.m.select(c, big, ks, r);
  9167. let inf = k(self, 0x7C00);
  9168. let nan = self.s.m.cmp(c, pred::IUGT, mag, inf);
  9169. let r = self.s.m.select(c, nan, k0, r);
  9170. let r = if signed {
  9171. let n = self.s.m.bin(c, Bin::Sub, k0, r);
  9172. self.s.m.select(c, neg, n, r)
  9173. } else {
  9174. self.s.m.select(c, neg, k0, r)
  9175. };
  9176. let m16 = k(self, 0xFFFF);
  9177. Ok(self.s.m.bin(c, Bin::And, r, m16))
  9178. }
  9179. /// Half `high` of source `k` of a packed (VOP3P) operation, in the low
  9180. /// 16 bits: op_sel picks the half the low result reads, op_sel_hi the
  9181. /// half the high result reads. Packed integer instructions see the f32
  9182. /// bits of an inline float constant.
  9183. fn packed_src(&mut self, inst: &Inst, k: usize, high: bool, float: bool) -> Result<V, Why> {
  9184. let Fields::Valu(v) = &inst.fields else {
  9185. unreachable!()
  9186. };
  9187. let op = *v.src.get(k).ok_or("a missing operand")?;
  9188. let sel = if high { v.opsel_hi } else { v.opsel } >> k & 1 != 0;
  9189. let x = if float {
  9190. self.f16_operand(inst, &op)?
  9191. } else {
  9192. self.operand(inst, &op)?
  9193. };
  9194. let c = self.cur;
  9195. let x = if sel {
  9196. let k16 = self.s.m.i32(16);
  9197. self.s.m.bin(c, Bin::LShr, x, k16)
  9198. } else {
  9199. x
  9200. };
  9201. let m = self.s.m.i32(0xFFFF);
  9202. Ok(self.s.m.bin(c, Bin::And, x, m))
  9203. }
  9204. /// Half `high` of source `k` of `v_pk_fmac_f16`, in the low 16 bits: a
  9205. /// VOP2 operation (no op_sel) whose third source is its destination.
  9206. fn fmac_half(&mut self, inst: &Inst, k: usize, high: bool) -> Result<V, Why> {
  9207. let Fields::Valu(v) = &inst.fields else {
  9208. unreachable!()
  9209. };
  9210. let op = if k == 2 { v.dst } else { v.src.get(k).copied() };
  9211. let op = op.ok_or("a missing operand")?;
  9212. if matches!(op, Operand::Const(_) | Operand::Literal(_)) {
  9213. // shortcut: no constant operand seen; its high half is not known.
  9214. return Err("a constant operand of v_pk_fmac_f16");
  9215. }
  9216. let x = self.operand(inst, &op)?;
  9217. let c = self.cur;
  9218. let x = if high {
  9219. let k16 = self.s.m.i32(16);
  9220. self.s.m.bin(c, Bin::LShr, x, k16)
  9221. } else {
  9222. x
  9223. };
  9224. let m = self.s.m.i32(0xFFFF);
  9225. Ok(self.s.m.bin(c, Bin::And, x, m))
  9226. }
  9227. /// Packed 16-bit operations (`v_pk_*`): each half computed as the
  9228. /// 16-bit operation does, f16 through f32 as in [`Self::valu16`].
  9229. fn packed16(&mut self, inst: &Inst, op: &str, guard: Option<V>) -> Result<(), Why> {
  9230. let Fields::Valu(v) = &inst.fields else {
  9231. unreachable!()
  9232. };
  9233. let float = op.ends_with("_f16");
  9234. let n = match op {
  9235. "fma_f16" | "fmac_f16" | "mad_u16" | "mad_i16" => 3,
  9236. "add_f16" | "mul_f16" | "min_f16" | "max_f16" | "add_u16" | "sub_u16" | "add_i16"
  9237. | "sub_i16" | "mul_lo_u16" | "lshlrev_b16" | "lshrrev_b16" | "ashrrev_i16"
  9238. | "max_u16" | "min_u16" | "max_i16" | "min_i16" => 2,
  9239. _ => return Err("a packed 16-bit operation"),
  9240. };
  9241. if v.omod != 0 || !float && (v.clamp || v.neg != 0 || v.neg_hi != 0) {
  9242. return Err("modifiers on a packed integer operation");
  9243. }
  9244. let c = self.cur;
  9245. let (i32t, f32t) = (self.s.t.i32, self.s.t.f32);
  9246. let mut halves = Vec::new();
  9247. for high in [false, true] {
  9248. let mut xs = Vec::new();
  9249. for k in 0..n {
  9250. let h = if op == "fmac_f16" {
  9251. self.fmac_half(inst, k, high)?
  9252. } else {
  9253. self.packed_src(inst, k, high, float)?
  9254. };
  9255. if float {
  9256. let mut f = self
  9257. .s
  9258. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]);
  9259. let neg = if high { v.neg_hi } else { v.neg };
  9260. if neg >> k & 1 != 0 {
  9261. let z = self.s.m.f32(0x8000_0000);
  9262. f = self.s.m.bin(c, Bin::Sub, z, f);
  9263. }
  9264. xs.push(f);
  9265. } else {
  9266. xs.push(h);
  9267. }
  9268. }
  9269. let r = if float {
  9270. let mut f = match op {
  9271. "add_f16" => self.s.m.bin(c, Bin::Add, xs[0], xs[1]),
  9272. "mul_f16" => self.s.m.bin(c, Bin::Mul, xs[0], xs[1]),
  9273. "min_f16" => self.max_min(false, xs[0], xs[1]),
  9274. "max_f16" => self.max_min(true, xs[0], xs[1]),
  9275. // shortcut: FMad in f32, as v_fma_f16.
  9276. _ => self.fmad(xs[0], xs[1], xs[2]),
  9277. };
  9278. if v.clamp {
  9279. f = self.unary(7, f);
  9280. }
  9281. self.s
  9282. .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f])
  9283. } else {
  9284. let k16 = self.s.m.i32(16);
  9285. let sext = |l: &mut Self, x: V| {
  9286. let t = l.s.m.bin(c, Bin::Shl, x, k16);
  9287. l.s.m.bin(c, Bin::AShr, t, k16)
  9288. };
  9289. if op.ends_with("_i16") {
  9290. for x in &mut xs {
  9291. *x = sext(self, *x);
  9292. }
  9293. }
  9294. let k15 = self.s.m.i32(15);
  9295. match op {
  9296. "add_u16" | "add_i16" => self.s.m.bin(c, Bin::Add, xs[0], xs[1]),
  9297. "sub_u16" | "sub_i16" => self.s.m.bin(c, Bin::Sub, xs[0], xs[1]),
  9298. "mul_lo_u16" => self.s.m.bin(c, Bin::Mul, xs[0], xs[1]),
  9299. "mad_u16" | "mad_i16" => {
  9300. let m = self.s.m.bin(c, Bin::Mul, xs[0], xs[1]);
  9301. self.s.m.bin(c, Bin::Add, m, xs[2])
  9302. }
  9303. "lshlrev_b16" | "lshrrev_b16" | "ashrrev_i16" => {
  9304. let sh = self.s.m.bin(c, Bin::And, xs[0], k15);
  9305. let o = match op {
  9306. "lshlrev_b16" => Bin::Shl,
  9307. "lshrrev_b16" => Bin::LShr,
  9308. _ => Bin::AShr,
  9309. };
  9310. let x = if op == "ashrrev_i16" {
  9311. sext(self, xs[1])
  9312. } else {
  9313. xs[1]
  9314. };
  9315. self.s.m.bin(c, o, x, sh)
  9316. }
  9317. _ => {
  9318. let p = match op {
  9319. "max_u16" => pred::IUGT,
  9320. "min_u16" => pred::IULT,
  9321. "max_i16" => pred::SGT,
  9322. _ => pred::SLT,
  9323. };
  9324. let t = self.s.m.cmp(c, p, xs[0], xs[1]);
  9325. self.s.m.select(c, t, xs[0], xs[1])
  9326. }
  9327. }
  9328. };
  9329. let m = self.s.m.i32(0xFFFF);
  9330. halves.push(self.s.m.bin(c, Bin::And, r, m));
  9331. }
  9332. let k16 = self.s.m.i32(16);
  9333. let hi = self.s.m.bin(c, Bin::Shl, halves[1], k16);
  9334. let r = self.s.m.bin(c, Bin::Or, halves[0], hi);
  9335. let Some(Operand::Vector { reg, .. }) = v.dst else {
  9336. return Err("a packed result outside a VGPR");
  9337. };
  9338. self.write(inst, Reg::V(reg), r, guard);
  9339. Ok(())
  9340. }
  9341. fn integer(&mut self, inst: &Inst, name: &'static str) -> Result<V, Why> {
  9342. let c = self.cur;
  9343. let s = |l: &mut Self, k| l.src(inst, k);
  9344. let k = |l: &mut Self, x: u32| l.s.m.i32(x);
  9345. let m31 = |l: &mut Self, x: V| {
  9346. let k31 = l.s.m.i32(31);
  9347. l.s.m.bin(c, Bin::And, x, k31)
  9348. };
  9349. Ok(match name {
  9350. "v_and_b32" | "v_or_b32" | "v_xor_b32" | "v_add_nc_u32" | "v_sub_nc_u32"
  9351. | "v_subrev_nc_u32" | "v_mul_lo_u32" => {
  9352. let (a, b) = (s(self, 0)?, s(self, 1)?);
  9353. let (op, a, b) = match name {
  9354. "v_and_b32" => (Bin::And, a, b),
  9355. "v_or_b32" => (Bin::Or, a, b),
  9356. "v_xor_b32" => (Bin::Xor, a, b),
  9357. "v_add_nc_u32" => (Bin::Add, a, b),
  9358. "v_sub_nc_u32" => (Bin::Sub, a, b),
  9359. "v_subrev_nc_u32" => (Bin::Sub, b, a),
  9360. _ => (Bin::Mul, a, b),
  9361. };
  9362. self.s.m.bin(c, op, a, b)
  9363. }
  9364. "v_xnor_b32" => {
  9365. let (a, b) = (s(self, 0)?, s(self, 1)?);
  9366. let x = self.s.m.bin(c, Bin::Xor, a, b);
  9367. let ones = k(self, u32::MAX);
  9368. self.s.m.bin(c, Bin::Xor, x, ones)
  9369. }
  9370. "v_not_b32" => {
  9371. let a = s(self, 0)?;
  9372. let ones = k(self, u32::MAX);
  9373. self.s.m.bin(c, Bin::Xor, a, ones)
  9374. }
  9375. "v_lshlrev_b32" | "v_lshrrev_b32" | "v_ashrrev_i32" => {
  9376. let (sh, a) = (s(self, 0)?, s(self, 1)?);
  9377. let sh = m31(self, sh);
  9378. let op = match name {
  9379. "v_lshlrev_b32" => Bin::Shl,
  9380. "v_lshrrev_b32" => Bin::LShr,
  9381. _ => Bin::AShr,
  9382. };
  9383. self.s.m.bin(c, op, a, sh)
  9384. }
  9385. "v_lshl_add_u32" | "v_lshl_or_b32" | "v_add_lshl_u32" | "v_and_or_b32"
  9386. | "v_or3_b32" | "v_xad_u32" | "v_add3_u32" | "v_xor3_b32" => {
  9387. let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  9388. match name {
  9389. "v_lshl_add_u32" | "v_lshl_or_b32" => {
  9390. let b = m31(self, b);
  9391. let t = self.s.m.bin(c, Bin::Shl, a, b);
  9392. let op = if name == "v_lshl_add_u32" {
  9393. Bin::Add
  9394. } else {
  9395. Bin::Or
  9396. };
  9397. self.s.m.bin(c, op, t, d)
  9398. }
  9399. "v_add_lshl_u32" => {
  9400. let t = self.s.m.bin(c, Bin::Add, a, b);
  9401. let d = m31(self, d);
  9402. self.s.m.bin(c, Bin::Shl, t, d)
  9403. }
  9404. _ => {
  9405. let (o1, o2) = match name {
  9406. "v_and_or_b32" => (Bin::And, Bin::Or),
  9407. "v_or3_b32" => (Bin::Or, Bin::Or),
  9408. "v_xad_u32" => (Bin::Xor, Bin::Add),
  9409. "v_add3_u32" => (Bin::Add, Bin::Add),
  9410. _ => (Bin::Xor, Bin::Xor),
  9411. };
  9412. let t = self.s.m.bin(c, o1, a, b);
  9413. self.s.m.bin(c, o2, t, d)
  9414. }
  9415. }
  9416. }
  9417. "v_mul_u32_u24" | "v_mul_i32_i24" => {
  9418. let (a, b) = (s(self, 0)?, s(self, 1)?);
  9419. let (sh, op) = (
  9420. k(self, 8),
  9421. if name == "v_mul_i32_i24" {
  9422. Bin::AShr
  9423. } else {
  9424. Bin::LShr
  9425. },
  9426. );
  9427. let a = self.s.m.bin(c, Bin::Shl, a, sh);
  9428. let a = self.s.m.bin(c, op, a, sh);
  9429. let b = self.s.m.bin(c, Bin::Shl, b, sh);
  9430. let b = self.s.m.bin(c, op, b, sh);
  9431. self.s.m.bin(c, Bin::Mul, a, b)
  9432. }
  9433. "v_mul_hi_u32_u24" | "v_mul_hi_i32_i24" => {
  9434. // The high dword of the same 48-bit product: the low 24 bits
  9435. // of each operand, zero- or sign-extended, multiplied.
  9436. let (a, b) = (s(self, 0)?, s(self, 1)?);
  9437. let signed = name == "v_mul_hi_i32_i24";
  9438. let (sh, op) = (k(self, 8), if signed { Bin::AShr } else { Bin::LShr });
  9439. let a = self.s.m.bin(c, Bin::Shl, a, sh);
  9440. let a = self.s.m.bin(c, op, a, sh);
  9441. let b = self.s.m.bin(c, Bin::Shl, b, sh);
  9442. let b = self.s.m.bin(c, op, b, sh);
  9443. self.mul_hi(a, b, signed)
  9444. }
  9445. "v_bfe_u32" | "v_bfe_i32" => {
  9446. let (a, off, w) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  9447. let w = m31(self, w);
  9448. self.bfe(a, off, w, name == "v_bfe_i32")
  9449. }
  9450. "v_bfi_b32" => {
  9451. let (m, a, b) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  9452. let ones = k(self, u32::MAX);
  9453. let nm = self.s.m.bin(c, Bin::Xor, m, ones);
  9454. let x = self.s.m.bin(c, Bin::And, m, a);
  9455. let y = self.s.m.bin(c, Bin::And, nm, b);
  9456. self.s.m.bin(c, Bin::Or, x, y)
  9457. }
  9458. "v_max_i32" | "v_min_i32" | "v_max_u32" | "v_min_u32" => {
  9459. let (a, b) = (s(self, 0)?, s(self, 1)?);
  9460. let p = match name {
  9461. "v_max_i32" => pred::SGT,
  9462. "v_min_i32" => pred::SLT,
  9463. "v_max_u32" => pred::IUGT,
  9464. _ => pred::IULT,
  9465. };
  9466. let t = self.s.m.cmp(c, p, a, b);
  9467. self.s.m.select(c, t, a, b)
  9468. }
  9469. "v_mul_hi_u32" | "v_mul_hi_i32" => {
  9470. let (a, b) = (s(self, 0)?, s(self, 1)?);
  9471. self.mul_hi(a, b, name == "v_mul_hi_i32")
  9472. }
  9473. "v_alignbit_b32" | "v_alignbyte_b32" => {
  9474. // The low dword of {a, b} >> shift.
  9475. let (a, b, sh) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  9476. let sh = if name == "v_alignbyte_b32" {
  9477. let three = k(self, 3);
  9478. let t = self.s.m.bin(c, Bin::And, sh, three);
  9479. let k3 = k(self, 3);
  9480. self.s.m.bin(c, Bin::Shl, t, k3)
  9481. } else {
  9482. m31(self, sh)
  9483. };
  9484. let k32 = k(self, 32);
  9485. let lo = self.s.m.bin(c, Bin::LShr, b, sh);
  9486. let left = self.s.m.bin(c, Bin::Sub, k32, sh);
  9487. let left = m31(self, left);
  9488. let hi = self.s.m.bin(c, Bin::Shl, a, left);
  9489. let zero = k(self, 0);
  9490. let none = self.s.m.cmp(c, pred::EQ, sh, zero);
  9491. let hi = self.s.m.select(c, none, zero, hi);
  9492. self.s.m.bin(c, Bin::Or, lo, hi)
  9493. }
  9494. "v_bfrev_b32" => {
  9495. let a = s(self, 0)?;
  9496. self.s
  9497. .op(c, "unary.i32", Attr::ReadNone, self.s.t.i32, 30, &[a])
  9498. }
  9499. "v_bcnt_u32_b32" => {
  9500. let (a, b) = (s(self, 0)?, s(self, 1)?);
  9501. let n = self
  9502. .s
  9503. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 31, &[a]);
  9504. self.s.m.bin(c, Bin::Add, n, b)
  9505. }
  9506. "v_mad_u32_u24" | "v_mad_i32_i24" => {
  9507. let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  9508. let (sh, op) = (
  9509. k(self, 8),
  9510. if name == "v_mad_i32_i24" {
  9511. Bin::AShr
  9512. } else {
  9513. Bin::LShr
  9514. },
  9515. );
  9516. let a = self.s.m.bin(c, Bin::Shl, a, sh);
  9517. let a = self.s.m.bin(c, op, a, sh);
  9518. let b = self.s.m.bin(c, Bin::Shl, b, sh);
  9519. let b = self.s.m.bin(c, op, b, sh);
  9520. let m = self.s.m.bin(c, Bin::Mul, a, b);
  9521. self.s.m.bin(c, Bin::Add, m, d)
  9522. }
  9523. "v_sad_u8" | "v_sad_hi_u8" | "v_sad_u16" | "v_sad_u32" | "v_msad_u8" => {
  9524. // src2 plus the sum of the unsigned differences |a - b| of
  9525. // the operands' bytes, halves or whole dwords, wrapping at 32
  9526. // bits. v_sad_hi_u8 adds the sum shifted to the high half;
  9527. // v_msad_u8 leaves out a byte whose mask byte (src1) is 0.
  9528. let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  9529. let (width, parts) = match name {
  9530. "v_sad_u16" => (16, 2),
  9531. "v_sad_u32" => (32, 1),
  9532. _ => (8, 4),
  9533. };
  9534. let zero = k(self, 0);
  9535. let mut sum = zero;
  9536. for i in 0..parts {
  9537. let (mut x, mut y) = (a, b);
  9538. if width < 32 {
  9539. let (sh, mask) = (k(self, width * i), k(self, (1 << width) - 1));
  9540. x = self.s.m.bin(c, Bin::LShr, x, sh);
  9541. x = self.s.m.bin(c, Bin::And, x, mask);
  9542. y = self.s.m.bin(c, Bin::LShr, y, sh);
  9543. y = self.s.m.bin(c, Bin::And, y, mask);
  9544. }
  9545. let above = self.s.m.cmp(c, pred::IUGT, x, y);
  9546. let hi = self.s.m.select(c, above, x, y);
  9547. let lo = self.s.m.select(c, above, y, x);
  9548. let mut diff = self.s.m.bin(c, Bin::Sub, hi, lo);
  9549. if name == "v_msad_u8" {
  9550. let masked = self.s.m.cmp(c, pred::NE, y, zero);
  9551. diff = self.s.m.select(c, masked, diff, zero);
  9552. }
  9553. sum = self.s.m.bin(c, Bin::Add, sum, diff);
  9554. }
  9555. if name == "v_sad_hi_u8" {
  9556. let k16 = k(self, 16);
  9557. sum = self.s.m.bin(c, Bin::Shl, sum, k16);
  9558. }
  9559. self.s.m.bin(c, Bin::Add, sum, d)
  9560. }
  9561. "v_min3_i32" | "v_max3_i32" | "v_min3_u32" | "v_max3_u32" | "v_med3_i32"
  9562. | "v_med3_u32" => {
  9563. let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  9564. let signed = name.ends_with("i32");
  9565. let (lt, gt) = if signed {
  9566. (pred::SLT, pred::SGT)
  9567. } else {
  9568. (pred::IULT, pred::IUGT)
  9569. };
  9570. let pick = |l: &mut Self, p, x, y| {
  9571. let t = l.s.m.cmp(c, p, x, y);
  9572. l.s.m.select(c, t, x, y)
  9573. };
  9574. match &name[2..6] {
  9575. "min3" => {
  9576. let t = pick(self, lt, a, b);
  9577. pick(self, lt, t, d)
  9578. }
  9579. "max3" => {
  9580. let t = pick(self, gt, a, b);
  9581. pick(self, gt, t, d)
  9582. }
  9583. _ => {
  9584. let lo = pick(self, lt, a, b);
  9585. let hi = pick(self, gt, a, b);
  9586. let t = pick(self, lt, hi, d);
  9587. pick(self, gt, lo, t)
  9588. }
  9589. }
  9590. }
  9591. "v_perm_b32" => {
  9592. // Byte i of the result is byte S of {src0, src1} (src1 the
  9593. // low dword) for selector byte S below 8; 8-11 repeat the
  9594. // sign of bytes 1 and 3 of src1, then of src0; 12 is 0x00,
  9595. // higher 0xFF.
  9596. let Fields::Valu(v) = &inst.fields else {
  9597. unreachable!()
  9598. };
  9599. let sel = match v.src.get(2) {
  9600. Some(&Operand::Literal(x)) => x,
  9601. Some(&Operand::Const(k)) => crate::resource::inline(k).ok_or(name)?,
  9602. _ => {
  9603. // A computed selector: each byte picked at run time.
  9604. let (a, b, sv) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  9605. let mut r = k(self, 0);
  9606. for i in 0..4u32 {
  9607. let (sh, ff) = (k(self, 8 * i), k(self, 0xFF));
  9608. let sel = self.s.m.bin(c, Bin::LShr, sv, sh);
  9609. let sel = self.s.m.bin(c, Bin::And, sel, ff);
  9610. // Select a dword and a byte within it.
  9611. // Later selects handle codes 8 and above.
  9612. let four = k(self, 4);
  9613. let zero = k(self, 0);
  9614. let high = self.s.m.bin(c, Bin::And, sel, four);
  9615. let high = self.s.m.cmp(c, pred::NE, high, zero);
  9616. let word = self.s.m.select(c, high, a, b);
  9617. let three = k(self, 3);
  9618. let index = self.s.m.bin(c, Bin::And, sel, three);
  9619. let bits = self.s.m.bin(c, Bin::Shl, index, three);
  9620. let x = self.s.m.bin(c, Bin::LShr, word, bits);
  9621. let mut byte = self.s.m.bin(c, Bin::And, x, ff);
  9622. // 8-11: the sign of bytes 1, 3 of src1, then of src0.
  9623. for (n, src, bit) in [(8, b, 15), (9, b, 31), (10, a, 15), (11, a, 31)]
  9624. {
  9625. let left = k(self, 31 - bit);
  9626. let t = self.s.m.bin(c, Bin::Shl, src, left);
  9627. let k31 = k(self, 31);
  9628. let t = self.s.m.bin(c, Bin::AShr, t, k31);
  9629. let t = self.s.m.bin(c, Bin::And, t, ff);
  9630. let kn = k(self, n);
  9631. let is = self.s.m.cmp(c, pred::EQ, sel, kn);
  9632. byte = self.s.m.select(c, is, t, byte);
  9633. }
  9634. let (k12, z) = (k(self, 12), k(self, 0));
  9635. let is12 = self.s.m.cmp(c, pred::EQ, sel, k12);
  9636. byte = self.s.m.select(c, is12, z, byte);
  9637. let above = self.s.m.cmp(c, pred::IUGT, sel, k12);
  9638. byte = self.s.m.select(c, above, ff, byte);
  9639. let at = k(self, 8 * i);
  9640. let byte = self.s.m.bin(c, Bin::Shl, byte, at);
  9641. r = self.s.m.bin(c, Bin::Or, r, byte);
  9642. }
  9643. return Ok(r);
  9644. }
  9645. };
  9646. let (a, b) = (s(self, 0)?, s(self, 1)?);
  9647. let mut r = k(self, 0);
  9648. for i in 0..4 {
  9649. let pick = sel >> (8 * i) & 0xFF;
  9650. let byte = match pick {
  9651. 0..=7 => {
  9652. let (src, n) = if pick < 4 { (b, pick) } else { (a, pick - 4) };
  9653. let sh = k(self, 8 * n);
  9654. let t = self.s.m.bin(c, Bin::LShr, src, sh);
  9655. let ff = k(self, 0xFF);
  9656. self.s.m.bin(c, Bin::And, t, ff)
  9657. }
  9658. 8..=11 => {
  9659. let src = if pick < 10 { b } else { a };
  9660. let bit = if pick % 2 == 0 { 15 } else { 31 };
  9661. let left = k(self, 31 - bit);
  9662. let t = self.s.m.bin(c, Bin::Shl, src, left);
  9663. let k31 = k(self, 31);
  9664. let t = self.s.m.bin(c, Bin::AShr, t, k31);
  9665. let ff = k(self, 0xFF);
  9666. self.s.m.bin(c, Bin::And, t, ff)
  9667. }
  9668. 12 => continue,
  9669. _ => k(self, 0xFF),
  9670. };
  9671. let at = k(self, 8 * i);
  9672. let byte = self.s.m.bin(c, Bin::Shl, byte, at);
  9673. r = self.s.m.bin(c, Bin::Or, r, byte);
  9674. }
  9675. r
  9676. }
  9677. "v_bfm_b32" => {
  9678. // ((1 << src0[4:0]) - 1) << src1[4:0]
  9679. let (a, b) = (s(self, 0)?, s(self, 1)?);
  9680. let one = k(self, 1);
  9681. let (a, b) = (m31(self, a), m31(self, b));
  9682. let m = self.s.m.bin(c, Bin::Shl, one, a);
  9683. let m = self.s.m.bin(c, Bin::Sub, m, one);
  9684. self.s.m.bin(c, Bin::Shl, m, b)
  9685. }
  9686. "v_cvt_pk_u8_f32" => {
  9687. // src0 rounded to nearest even and saturated to a byte, into
  9688. // byte src1[1:0] of src2.
  9689. let f = self.fsrc(inst, 0)?;
  9690. let (b, d) = (s(self, 1)?, s(self, 2)?);
  9691. let f = self.unary(26, f);
  9692. let (zero, max) = (self.s.m.f32(0), self.s.m.f32(255.0f32.to_bits()));
  9693. let f = self.binary(35, f, zero);
  9694. let f = self.binary(36, f, max);
  9695. let x = self.s.m.cast(c, Cast::FpToUi, f, self.s.t.i32);
  9696. let (three, k3) = (k(self, 3), k(self, 3));
  9697. let sh = self.s.m.bin(c, Bin::And, b, three);
  9698. let sh = self.s.m.bin(c, Bin::Shl, sh, k3);
  9699. let x = self.s.m.bin(c, Bin::Shl, x, sh);
  9700. let ff = k(self, 0xFF);
  9701. let hole = self.s.m.bin(c, Bin::Shl, ff, sh);
  9702. let ones = k(self, u32::MAX);
  9703. let hole = self.s.m.bin(c, Bin::Xor, hole, ones);
  9704. let d = self.s.m.bin(c, Bin::And, d, hole);
  9705. self.s.m.bin(c, Bin::Or, d, x)
  9706. }
  9707. "v_ffbl_b32" => {
  9708. // -1 for zero, as DXIL's first-bit-low.
  9709. let a = s(self, 0)?;
  9710. self.s
  9711. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 32, &[a])
  9712. }
  9713. "v_mbcnt_lo_u32_b32" | "v_mbcnt_hi_u32_b32" => {
  9714. // Bits of the mask's low (high) half below this lane, plus src1:
  9715. // with an all-ones mask, the lane index.
  9716. let (a, b) = (s(self, 0)?, s(self, 1)?);
  9717. // Mesh lanes are the console's by construction; pixel and
  9718. // vertex lanes are the host's, as their masks are.
  9719. if self.mask_data == MaskData::Host {
  9720. // Host lanes: the mask must be one (a ballot) or all lanes.
  9721. let Fields::Valu(v) = &inst.fields else {
  9722. unreachable!()
  9723. };
  9724. let host = match v.src.first() {
  9725. Some(&Operand::Const(193)) => true,
  9726. Some(&Operand::Scalar { code, .. }) => {
  9727. inst.read(Reg::S(code)).is_some_and(|m| {
  9728. self.x.st.masks.contains_key(&m) || self.x.st.highs.contains_key(&m)
  9729. })
  9730. }
  9731. _ => false,
  9732. };
  9733. if !host {
  9734. return Err("v_mbcnt of a mask that is no ballot (console lane layout)");
  9735. }
  9736. self.s.flags |= flags::WAVE_OPS;
  9737. } else if self.s.mesh.is_none() {
  9738. self.cross_lane(false)?;
  9739. }
  9740. let lane = self.console_lane();
  9741. let below = if name == "v_mbcnt_lo_u32_b32" {
  9742. lane
  9743. } else {
  9744. let (k32, z) = (k(self, 32), k(self, 0));
  9745. let t = self.s.m.bin(c, Bin::Sub, lane, k32);
  9746. let low = self.s.m.cmp(c, pred::IULT, lane, k32);
  9747. self.s.m.select(c, low, z, t)
  9748. };
  9749. // (1 << below) - 1, all ones from 32 on.
  9750. let (one, k32, ones) = (k(self, 1), k(self, 32), k(self, u32::MAX));
  9751. let sh = m31(self, below);
  9752. let m = self.s.m.bin(c, Bin::Shl, one, sh);
  9753. let m = self.s.m.bin(c, Bin::Sub, m, one);
  9754. let full = self.s.m.cmp(c, pred::IUGE, below, k32);
  9755. let m = self.s.m.select(c, full, ones, m);
  9756. let x = self.s.m.bin(c, Bin::And, a, m);
  9757. let n = self
  9758. .s
  9759. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 31, &[x]);
  9760. self.s.m.bin(c, Bin::Add, n, b)
  9761. }
  9762. _ => return Err(name),
  9763. })
  9764. }
  9765. fn compare(&mut self, inst: &Inst, rest: &str) -> Result<(), Why> {
  9766. let (op, ty) = rest.rsplit_once('_').ok_or("a compare")?;
  9767. let c = self.cur;
  9768. let r = match ty {
  9769. "f32" | "f16" if op == "class" => {
  9770. // Bit k of src1 tests class k: signalling NaN, quiet NaN,
  9771. // -inf, -normal, -denormal, -0, +0, +denormal, +normal, +inf.
  9772. let f16 = ty == "f16";
  9773. let x = if f16 {
  9774. let Fields::Valu(v) = &inst.fields else {
  9775. unreachable!()
  9776. };
  9777. let mut h = self.half_src(inst, 0)?;
  9778. if v.abs & 1 != 0 {
  9779. let m = self.s.m.i32(0x7FFF);
  9780. h = self.s.m.bin(c, Bin::And, h, m);
  9781. }
  9782. if v.neg & 1 != 0 {
  9783. let s = self.s.m.i32(0x8000);
  9784. h = self.s.m.bin(c, Bin::Xor, h, s);
  9785. }
  9786. h
  9787. } else {
  9788. let x = self.fsrc(inst, 0)?;
  9789. self.as_int(x)
  9790. };
  9791. let mask = self.src(inst, 1)?;
  9792. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  9793. let (exp_sh, sign_sh, exp_mask, mant_mask, quiet_bit) = if f16 {
  9794. (10, 15, 0x1F, 0x03FF, 0x0200)
  9795. } else {
  9796. (23, 31, 0xFF, 0x7F_FFFF, 0x40_0000)
  9797. };
  9798. let (k_exp, k_sign, k_emax, mant, quiet) = (
  9799. k(self, exp_sh),
  9800. k(self, sign_sh),
  9801. k(self, exp_mask),
  9802. k(self, mant_mask),
  9803. k(self, quiet_bit),
  9804. );
  9805. let e = self.s.m.bin(c, Bin::LShr, x, k_exp);
  9806. let e = self.s.m.bin(c, Bin::And, e, k_emax);
  9807. let m = self.s.m.bin(c, Bin::And, x, mant);
  9808. let neg = self.s.m.bin(c, Bin::LShr, x, k_sign);
  9809. let zero = k(self, 0);
  9810. let (e0, emax) = (
  9811. self.s.m.cmp(c, pred::EQ, e, zero),
  9812. self.s.m.cmp(c, pred::EQ, e, k_emax),
  9813. );
  9814. let m0 = self.s.m.cmp(c, pred::EQ, m, zero);
  9815. let q = self.s.m.bin(c, Bin::And, x, quiet);
  9816. let q = self.s.m.cmp(c, pred::NE, q, zero);
  9817. // Positive classes 6-9; negative ones are 11 minus those.
  9818. let (normal, inf, zero_c, denorm) =
  9819. (k(self, 8), k(self, 9), k(self, 6), k(self, 7));
  9820. let t = self.s.m.select(c, m0, zero_c, denorm);
  9821. let t = self.s.m.select(c, e0, t, normal);
  9822. let t = self.s.m.select(c, emax, inf, t);
  9823. let eleven = k(self, 11);
  9824. let mirrored = self.s.m.bin(c, Bin::Sub, eleven, t);
  9825. let is_neg = self.s.m.cmp(c, pred::NE, neg, zero);
  9826. let t = self.s.m.select(c, is_neg, mirrored, t);
  9827. let (one, snan) = (k(self, 1), k(self, 0));
  9828. let nan_class = self.s.m.select(c, q, one, snan);
  9829. let yes = self.s.m.bool(true);
  9830. let nan = self.s.m.bin(c, Bin::Xor, m0, yes);
  9831. let nan = self.s.m.bin(c, Bin::And, nan, emax);
  9832. let t = self.s.m.select(c, nan, nan_class, t);
  9833. let bit = self.s.m.bin(c, Bin::LShr, mask, t);
  9834. let bit = self.s.m.bin(c, Bin::And, bit, one);
  9835. self.s.m.cmp(c, pred::NE, bit, zero)
  9836. }
  9837. "f32" | "f16" => {
  9838. let (a, b) = if ty == "f16" {
  9839. (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?)
  9840. } else {
  9841. (self.fsrc(inst, 0)?, self.fsrc(inst, 1)?)
  9842. };
  9843. if op == "lg" {
  9844. // Ordered and not equal, false for a NaN, as `olt | ogt`.
  9845. // `fcmp one` means the same, but the AMD D3D12 driver
  9846. // runs it as unordered (true for a NaN) where NVIDIA
  9847. // and WARP do not; olt and ogt agree on all three.
  9848. let lt = self.s.m.cmp(c, pred::OLT, a, b);
  9849. let gt = self.s.m.cmp(c, pred::OGT, a, b);
  9850. self.s.m.bin(c, Bin::Or, lt, gt)
  9851. } else {
  9852. let p = match op {
  9853. "f" => pred::FALSE,
  9854. "lt" => pred::OLT,
  9855. "eq" => pred::OEQ,
  9856. "le" => pred::OLE,
  9857. "gt" => pred::OGT,
  9858. "ge" => pred::OGE,
  9859. "o" => pred::ORD,
  9860. "u" => pred::UNO,
  9861. "nge" => pred::ULT,
  9862. "nlg" => pred::UEQ,
  9863. "ngt" => pred::ULE,
  9864. "nle" => pred::UGT,
  9865. "neq" => pred::UNE,
  9866. "nlt" => pred::UGE,
  9867. "tru" => pred::TRUE,
  9868. _ => return Err(inst.name()),
  9869. };
  9870. self.s.m.cmp(c, p, a, b)
  9871. }
  9872. }
  9873. "u64" | "i64" => {
  9874. let (a, b) = (self.src64(inst, 0)?, self.src64(inst, 1)?);
  9875. let signed = ty == "i64";
  9876. let p = match op {
  9877. "eq" => pred::EQ,
  9878. "ne" | "lg" => pred::NE,
  9879. "lt" if signed => pred::SLT,
  9880. "le" if signed => pred::SLE,
  9881. "gt" if signed => pred::SGT,
  9882. "ge" if signed => pred::SGE,
  9883. "lt" => pred::IULT,
  9884. "le" => pred::IULE,
  9885. "gt" => pred::IUGT,
  9886. "ge" => pred::IUGE,
  9887. _ => return Err("a 64-bit compare"),
  9888. };
  9889. self.s.m.cmp(c, p, a, b)
  9890. }
  9891. "u32" | "i32" | "u16" | "i16" => {
  9892. let (a, b) = if ty.ends_with("16") {
  9893. let (mut a, mut b) = (self.half_src(inst, 0)?, self.half_src(inst, 1)?);
  9894. if ty == "i16" {
  9895. let k16 = self.s.m.i32(16);
  9896. for x in [&mut a, &mut b] {
  9897. let t = self.s.m.bin(c, Bin::Shl, *x, k16);
  9898. *x = self.s.m.bin(c, Bin::AShr, t, k16);
  9899. }
  9900. }
  9901. (a, b)
  9902. } else {
  9903. (self.src(inst, 0)?, self.src(inst, 1)?)
  9904. };
  9905. let signed = ty == "i32" || ty == "i16";
  9906. let p = match op {
  9907. "eq" => pred::EQ,
  9908. "ne" | "lg" => pred::NE,
  9909. "lt" if signed => pred::SLT,
  9910. "le" if signed => pred::SLE,
  9911. "gt" if signed => pred::SGT,
  9912. "ge" if signed => pred::SGE,
  9913. "lt" => pred::IULT,
  9914. "le" => pred::IULE,
  9915. "gt" => pred::IUGT,
  9916. "ge" => pred::IUGE,
  9917. "f" | "t" => {
  9918. self.lane(inst, Some(op == "t"));
  9919. return Ok(());
  9920. }
  9921. _ => return Err("an integer compare"),
  9922. };
  9923. self.s.m.cmp(c, p, a, b)
  9924. }
  9925. _ => return Err(inst.name()),
  9926. };
  9927. self.lane_bits_for(inst, r);
  9928. Ok(())
  9929. }
  9930. fn lane(&mut self, inst: &Inst, value: Option<bool>) {
  9931. let b = self.s.m.bool(value == Some(true));
  9932. self.lane_bits_for(inst, b);
  9933. }
  9934. fn lane_bits_for(&mut self, inst: &Inst, r: V) {
  9935. let Fields::Valu(v) = &inst.fields else {
  9936. return;
  9937. };
  9938. let code = if inst.name().starts_with("v_cmpx") {
  9939. Some(EXEC)
  9940. } else {
  9941. match v.dst {
  9942. Some(Operand::Scalar { code, .. }) => Some(code),
  9943. _ => None,
  9944. }
  9945. };
  9946. if let Some(lo) = code.and_then(|c| inst.write(Reg::S(c))) {
  9947. self.lane_bits.insert(lo, r);
  9948. }
  9949. for &(_, w) in &inst.writes {
  9950. self.vals
  9951. .entry(w)
  9952. .or_insert(Val::Missing("a lane mask read as data"));
  9953. }
  9954. }
  9955. fn interp(&mut self, inst: &Inst, site: Site) -> Result<(), Why> {
  9956. let Some(&interp) = self.interps.get(&site) else {
  9957. // The first half of a pair: its second half interpolates the
  9958. // attribute itself, so nothing needs this half's partial sum.
  9959. // But an f16 second half that writes the high half of the
  9960. // register this one wrote keeps the low half as it was (the
  9961. // console compiler reuses the register; the low half is not
  9962. // read), so the register needs a value: 0.
  9963. let name = inst.name();
  9964. if name == "v_interp_p1_f32" || name == "v_interp_p1ll_f16" {
  9965. let dst = match &inst.fields {
  9966. Fields::Vintrp { dst, .. } => Some(*dst),
  9967. Fields::Valu(v) => v.dst,
  9968. _ => None,
  9969. };
  9970. if let Some(Operand::Vector { reg, .. }) = dst {
  9971. let zero = self.s.m.i32(0);
  9972. self.write(inst, Reg::V(reg), zero, None);
  9973. return Ok(());
  9974. }
  9975. }
  9976. return Err(FIRST_HALF);
  9977. };
  9978. let name = inst.name();
  9979. let (dst, src) = match &inst.fields {
  9980. Fields::Vintrp { dst, src, .. } => (*dst, Some(*src)),
  9981. Fields::Valu(v) => {
  9982. if v.abs != 0 || v.neg != 0 {
  9983. return Err("interpolation operand modifiers");
  9984. }
  9985. (v.dst.ok_or("an interpolation")?, v.src.get(1).copied())
  9986. }
  9987. _ => unreachable!(),
  9988. };
  9989. let Operand::Vector { reg, .. } = dst else {
  9990. return Err("an interpolation");
  9991. };
  9992. // A float operand of the instruction.
  9993. let float = |l: &mut Self, op: Option<Operand>| -> Result<V, Why> {
  9994. let x = l.operand(inst, &op.ok_or("an interpolation operand")?)?;
  9995. Ok(l.as_float(x))
  9996. };
  9997. // What the result adds to the evaluated channel (a second half's
  9998. // first half, when the halves evaluate on their own).
  9999. let mut add = None;
  10000. let (attribute, eval) = match *interp {
  10001. Interp::Interpolated {
  10002. attribute,
  10003. barycentric,
  10004. ..
  10005. } => {
  10006. let mode = interp_mode(barycentric).ok_or("pull-model interpolation")?;
  10007. let eval = if self.per_vertex(attribute.row) {
  10008. // The element is read per vertex elsewhere, so it is
  10009. // constant: weigh its vertices with SV_Barycentrics.
  10010. let mut ij = [None; 2];
  10011. for (index, w) in ij.iter_mut().enumerate() {
  10012. let x = match self.barycentric(barycentric, index as u8) {
  10013. Val::I32(x) => x,
  10014. Val::Missing(w) => return Err(w),
  10015. Val::Bit(_) => unreachable!(),
  10016. };
  10017. *w = Some(self.as_float(x));
  10018. }
  10019. Eval::Weights {
  10020. p0: true,
  10021. i: ij[0],
  10022. j: ij[1],
  10023. }
  10024. } else {
  10025. Eval::Mode(mode)
  10026. };
  10027. (attribute, eval)
  10028. }
  10029. // P0, the provoking vertex: a flat (nointerpolation) input.
  10030. Interp::Vertex {
  10031. attribute,
  10032. vertex: 2,
  10033. } => (attribute, Eval::Mode(1)),
  10034. // P10 and P20: what the first and second halves weigh, P1 - P0
  10035. // and P2 - P0, which is what the hardware holds for an
  10036. // attribute the program also interpolates.
  10037. Interp::Vertex { attribute, vertex } if self.interpolated(attribute.row) => {
  10038. let one = Some(self.s.m.f32(1f32.to_bits()));
  10039. let (i, j) = if vertex == 0 {
  10040. (one, None)
  10041. } else {
  10042. (None, one)
  10043. };
  10044. (attribute, Eval::Weights { p0: false, i, j })
  10045. }
  10046. Interp::Vertex { .. } => return Err("a non-provoking vertex value"),
  10047. // A half of an interpolation with computed i or j: P0 + i P10,
  10048. // or the old dst (f16: the third operand) + j P20.
  10049. Interp::Weighted { attribute } if name.starts_with("v_interp_p1") => {
  10050. let i = Some(float(self, src)?);
  10051. (
  10052. attribute,
  10053. Eval::Weights {
  10054. p0: true,
  10055. i,
  10056. j: None,
  10057. },
  10058. )
  10059. }
  10060. Interp::Weighted { attribute } => {
  10061. let old = match &inst.fields {
  10062. Fields::Valu(v) => v.src.get(2).copied(),
  10063. _ => Some(dst),
  10064. };
  10065. add = Some(float(self, old)?);
  10066. let j = Some(float(self, src)?);
  10067. (
  10068. attribute,
  10069. Eval::Weights {
  10070. p0: false,
  10071. i: None,
  10072. j,
  10073. },
  10074. )
  10075. }
  10076. };
  10077. let packing = match &self.x.native.io {
  10078. StageIo::Ps { inputs, .. } => inputs
  10079. .iter()
  10080. .find(|i| i.row == attribute.row && i.fp16)
  10081. .map(|i| {
  10082. let packs = if i.pack2 {
  10083. input_packs(&self.x.native.io, &self.s.inputs)
  10084. } else {
  10085. Vec::new()
  10086. };
  10087. (i.pack2, packs)
  10088. }),
  10089. _ => None,
  10090. };
  10091. let f16 = name.ends_with("_f16");
  10092. // The evaluated channel plus `add`, as a float.
  10093. let total = |l: &mut Self, row: u8, ch: u8| -> Result<V, Why> {
  10094. let x = l.eval_channel(row, ch, eval)?;
  10095. let x = l.as_float(x);
  10096. Ok(match add {
  10097. Some(a) => l.s.m.bin(l.cur, Bin::Add, a, x),
  10098. None => x,
  10099. })
  10100. };
  10101. let x = match packing {
  10102. None if f16 || attribute.high => return Err("a 16-bit read of a 32-bit input"),
  10103. None => {
  10104. let x = total(self, attribute.row, attribute.channel)?;
  10105. self.as_int(x)
  10106. }
  10107. Some((pack2, packs)) => {
  10108. // 16-bit values: one in the low half of each dword, or two
  10109. // per dword (`packed_half`); the host's are 32-bit floats.
  10110. let half = |l: &mut Self, h: u8| -> Result<Option<V>, Why> {
  10111. let src = if pack2 {
  10112. packed_half(&l.s.inputs, &packs, attribute.row, h)
  10113. } else {
  10114. h.is_multiple_of(2).then_some((attribute.row, h / 2))
  10115. };
  10116. match src {
  10117. Some((row, ch)) => total(l, row, ch).map(Some),
  10118. None => Ok(None),
  10119. }
  10120. };
  10121. let to_f16 = |l: &mut Self, f: V| {
  10122. let i32t = l.s.t.i32;
  10123. l.s.op(l.cur, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f])
  10124. };
  10125. let h = 2 * attribute.channel + u8::from(attribute.high);
  10126. let c = self.cur;
  10127. if name == "v_interp_p1ll_f16" {
  10128. // An f32 result from 16-bit vertex values.
  10129. let f = half(self, h)?.ok_or("a packed input half no element holds")?;
  10130. self.as_int(f)
  10131. } else if f16 {
  10132. let mut f = half(self, h)?.ok_or("a packed input half no element holds")?;
  10133. if let Fields::Valu(v) = &inst.fields {
  10134. // omod, then clamp, before the one rounding to 16 bits; op_sel[3]
  10135. // picks the destination half (VIctory e29391f: the low half was
  10136. // always written, the high one's value never arrived).
  10137. let (omod, clamp) = (v.omod, v.clamp);
  10138. if omod != 0 {
  10139. let factor = [1.0f32, 2.0, 4.0, 0.5][usize::from(omod)];
  10140. let k = self.s.m.f32(factor.to_bits());
  10141. f = self.s.m.bin(c, Bin::Mul, f, k);
  10142. }
  10143. if clamp {
  10144. f = self.unary(7, f);
  10145. }
  10146. let lo = to_f16(self, f);
  10147. return self.write_half(inst, lo, None);
  10148. }
  10149. let lo = to_f16(self, f);
  10150. self.low_half(inst, reg, lo)
  10151. } else if matches!(eval, Eval::Mode(1)) {
  10152. // The whole dword of a flat input: both halves.
  10153. let h = 2 * attribute.channel;
  10154. let z = self.s.m.i32(0);
  10155. let lo = match half(self, h)? {
  10156. Some(f) => to_f16(self, f),
  10157. None => z,
  10158. };
  10159. let hi = match half(self, h + 1)? {
  10160. Some(f) => to_f16(self, f),
  10161. None => z,
  10162. };
  10163. let k16 = self.s.m.i32(16);
  10164. let hi = self.s.m.bin(c, Bin::Shl, hi, k16);
  10165. self.s.m.bin(c, Bin::Or, lo, hi)
  10166. } else {
  10167. return Err("32-bit interpolation of a 16-bit input");
  10168. }
  10169. }
  10170. };
  10171. // A pixel interpolates in every lane; guards only hide inactive ones.
  10172. self.write(inst, Reg::V(reg), x, None);
  10173. Ok(())
  10174. }
  10175. /// Whether the program reads attribute row `row` per vertex (an
  10176. /// interpolation with computed barycentrics, or P10 or P20): then its
  10177. /// element is declared constant and read with `attributeAtVertex`.
  10178. fn per_vertex(&self, row: u8) -> bool {
  10179. self.x.io.interps.iter().any(|(_, i)| match *i {
  10180. Interp::Weighted { attribute } => attribute.row == row,
  10181. Interp::Vertex { attribute, vertex } => {
  10182. attribute.row == row && vertex != 2 && self.interpolated(row)
  10183. }
  10184. Interp::Interpolated { .. } => false,
  10185. })
  10186. }
  10187. /// Whether the program interpolates attribute row `row` (so the
  10188. /// hardware holds P1 - P0 and P2 - P0 for it).
  10189. fn interpolated(&self, row: u8) -> bool {
  10190. self.x.io.interps.iter().any(|(_, i)| match *i {
  10191. Interp::Interpolated { attribute, .. } | Interp::Weighted { attribute } => {
  10192. attribute.row == row
  10193. }
  10194. Interp::Vertex { .. } => false,
  10195. })
  10196. }
  10197. /// Channel `ch` of input row `row` evaluated as `eval` says, as raw bits.
  10198. fn eval_channel(&mut self, row: u8, ch: u8, eval: Eval) -> Result<V, Why> {
  10199. let (id, col) = self
  10200. .find_input(row, ch)
  10201. .ok_or("an input the signature lacks")?;
  10202. let mode = match eval {
  10203. Eval::Mode(mode) => mode,
  10204. Eval::Weights { .. } => 1,
  10205. };
  10206. let e = &mut self.s.inputs[id];
  10207. if e.interp != mode && e.usage != 0 {
  10208. return Err("one input interpolated two ways");
  10209. }
  10210. e.interp = mode;
  10211. let Eval::Weights { p0, i, j } = eval else {
  10212. return match self.load_any_input(id, col) {
  10213. Val::I32(x) => Ok(x),
  10214. _ => Err("an input"),
  10215. };
  10216. };
  10217. let v0 = self.vertex_input(id, col, 0);
  10218. let c = self.cur;
  10219. let mut acc = p0.then_some(v0);
  10220. for (k, w) in [(1, i), (2, j)] {
  10221. let Some(w) = w else { continue };
  10222. let vk = self.vertex_input(id, col, k);
  10223. let d = self.s.m.bin(c, Bin::Sub, vk, v0);
  10224. acc = Some(match acc {
  10225. Some(a) => self.fmad(w, d, a),
  10226. None => self.s.m.bin(c, Bin::Mul, w, d),
  10227. });
  10228. }
  10229. let acc = acc.ok_or("an interpolation")?;
  10230. Ok(self.as_int(acc))
  10231. }
  10232. /// Vertex `k` (0 the provoking vertex, as `barycentric` orders them)
  10233. /// of a constant input element's channel, as a float.
  10234. fn vertex_input(&mut self, id: usize, col: u8, k: u8) -> V {
  10235. let e = &mut self.s.inputs[id];
  10236. e.usage |= 1 << col;
  10237. let int = e.comp != 9;
  10238. let (ty, suffix) = if int {
  10239. (self.s.t.i32, ".i32")
  10240. } else {
  10241. (self.s.t.f32, ".f32")
  10242. };
  10243. self.s.flags |= flags::BARYCENTRICS;
  10244. let entry = self.s.entry;
  10245. let args = [
  10246. self.s.m.i32(id as u32),
  10247. self.s.m.i32(0),
  10248. self.s.m.i8(col),
  10249. self.s.m.i8(k),
  10250. ];
  10251. let v = self.s.op(
  10252. entry,
  10253. &format!("attributeAtVertex{suffix}"),
  10254. Attr::ReadNone,
  10255. ty,
  10256. 137,
  10257. &args,
  10258. );
  10259. if int {
  10260. self.s.m.cast(entry, Cast::Bitcast, v, self.s.t.f32)
  10261. } else {
  10262. v
  10263. }
  10264. }
  10265. /// `x` (an f16 in the low bits) as the low half of VGPR `reg`: 16-bit
  10266. /// results keep the register's high half (GFX10).
  10267. fn low_half(&mut self, inst: &Inst, reg: u8, x: V) -> V {
  10268. let c = self.cur;
  10269. let old = match inst.read(Reg::V(reg)).map(|o| self.i32_of(o)) {
  10270. Some(Ok(o)) => o,
  10271. _ => self.s.m.i32(0),
  10272. };
  10273. let (high, low) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF));
  10274. let old = self.s.m.bin(c, Bin::And, old, high);
  10275. let x = self.s.m.bin(c, Bin::And, x, low);
  10276. self.s.m.bin(c, Bin::Or, old, x)
  10277. }
  10278. fn image(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  10279. let Fields::Image {
  10280. data,
  10281. addr,
  10282. dmask,
  10283. dim,
  10284. unorm,
  10285. a16,
  10286. d16,
  10287. tfe,
  10288. lwe,
  10289. ..
  10290. } = &inst.fields
  10291. else {
  10292. unreachable!()
  10293. };
  10294. if *tfe || *lwe {
  10295. return Err("an image access with tfe or lwe");
  10296. }
  10297. let name = inst.name();
  10298. // A load or sample with no channel enabled returns the first.
  10299. let dmask = if *dmask == 0 { &1 } else { dmask };
  10300. let site = (b, i);
  10301. let guard = self.guard(b, i)?;
  10302. let c = self.cur;
  10303. let (kind, coords) = match dim {
  10304. 0 => (1, 1),
  10305. 1 => (2, 2),
  10306. 2 => (4, 3),
  10307. // Sampled (face coordinates and face, see `cube_direction`) or
  10308. // sized only.
  10309. 3 if name.starts_with("image_sample")
  10310. || name.starts_with("image_gather")
  10311. || name == "image_get_resinfo" =>
  10312. {
  10313. (5, 3)
  10314. }
  10315. 4 => (6, 2),
  10316. 5 => (7, 3),
  10317. _ => return Err("an image dimension (cube loads or MSAA)"),
  10318. };
  10319. // Address VGPRs in order.
  10320. let mut regs = Vec::new();
  10321. for a in addr {
  10322. if let Operand::Vector { reg, dwords } = *a {
  10323. regs.extend((0..dwords).map(|k| reg + k));
  10324. }
  10325. }
  10326. // Full 32-bit address VGPR at `reg_idx` (offset, bias, z-compare).
  10327. let addr_u32 = |l: &mut Self, reg_idx: usize| -> Result<V, Why> {
  10328. let r = *regs.get(reg_idx).ok_or("an image address")?;
  10329. let v = inst.read(Reg::V(r)).ok_or("an image address")?;
  10330. l.i32_of(v)
  10331. };
  10332. // With a16, two 16-bit components per VGPR starting at `base_reg`, low half first.
  10333. let addr_packed = |l: &mut Self, base_reg: usize, k: usize| -> Result<V, Why> {
  10334. let x = addr_u32(l, base_reg + if *a16 { k / 2 } else { k })?;
  10335. if !*a16 {
  10336. return Ok(x);
  10337. }
  10338. let c = l.cur;
  10339. let (sh, mask) = (l.s.m.i32(16 * (k as u32 % 2)), l.s.m.i32(0xFFFF));
  10340. let x = l.s.m.bin(c, Bin::LShr, x, sh);
  10341. Ok(l.s.m.bin(c, Bin::And, x, mask))
  10342. };
  10343. let addr_val = |l: &mut Self, k: usize| -> Result<V, Why> { addr_packed(l, 0, k) };
  10344. let src = self
  10345. .descriptors
  10346. .get(&(site, false))
  10347. .copied()
  10348. .ok_or("an untracked image")?;
  10349. let store = name.starts_with("image_store");
  10350. let uav = store
  10351. || self
  10352. .used_kind(src)
  10353. .is_some_and(|u| u.kind == ResourceType::Uav);
  10354. // A UAV inside an ordered section is a rasterizer ordered view.
  10355. let ordered = uav && self.ordered.contains(&site);
  10356. if ordered {
  10357. self.s.flags |= flags::ROVS;
  10358. }
  10359. let rov = if ordered { 0x2000 } else { 0 };
  10360. let props = (kind | if uav { 0x1000 } else { 0 } | rov, 0x409);
  10361. if let Some(op) = name.strip_prefix("image_atomic_") {
  10362. // GLC returns the old value. DXIL implements subtraction by adding
  10363. // the two's complement of the operand at the same width.
  10364. let code = match op {
  10365. "add" | "sub" => 0,
  10366. "and" => 1,
  10367. "or" => 2,
  10368. "xor" => 3,
  10369. "smin" => 4,
  10370. "smax" => 5,
  10371. "umin" => 6,
  10372. "umax" => 7,
  10373. "swap" => 8,
  10374. "cmpswap" => u32::MAX,
  10375. _ => return Err(name),
  10376. };
  10377. let Fields::Image { cache, .. } = &inst.fields else {
  10378. unreachable!()
  10379. };
  10380. // 16-bit coordinates (a16) are read as `addr_val` reads them.
  10381. if *d16 {
  10382. return Err("a 16-bit image atomic");
  10383. }
  10384. // Compare-exchange consumes a replacement followed by a comparand.
  10385. let compare = code == u32::MAX;
  10386. let wide = match (compare, *dmask) {
  10387. (false, 1) | (true, 3) => false,
  10388. (false, 3) | (true, 15) => true,
  10389. _ => return Err("an image atomic data mask"),
  10390. };
  10391. let iu = self.s.m.undef(self.s.t.i32);
  10392. let mut cs = vec![iu; 3];
  10393. for (k, slot) in cs.iter_mut().enumerate().take(coords) {
  10394. *slot = addr_val(self, k)?;
  10395. }
  10396. let Operand::Vector { reg, .. } = *data else {
  10397. return Err("image atomic data");
  10398. };
  10399. let width = if wide { 2 } else { 1 };
  10400. let vals = self.vgprs(inst, data, if compare { 2 * width } else { width })?;
  10401. let (ty, component) = if wide {
  10402. self.s.flags |= flags::INT64 | flags::ATOMIC_TYPED64 | flags::ATOMIC_HEAP64;
  10403. (self.s.m.int(64), 0x107) // one uint64_t in an R32G32_UINT view
  10404. } else {
  10405. (self.s.t.i32, 0x105)
  10406. };
  10407. let original = if wide {
  10408. self.join64(vals[0], vals[1])
  10409. } else {
  10410. vals[0]
  10411. };
  10412. let value = if op == "sub" {
  10413. let zero = self.s.m.int_const(ty, 0);
  10414. self.s.m.bin(c, Bin::Sub, zero, original)
  10415. } else {
  10416. original
  10417. };
  10418. let h = self.handle(site, src, false, (kind | 0x1000 | rov, component))?;
  10419. let mut args = vec![h];
  10420. let (intrinsic, opcode) = if compare {
  10421. let comparand = if wide {
  10422. self.join64(vals[2], vals[3])
  10423. } else {
  10424. vals[1]
  10425. };
  10426. args.extend(cs);
  10427. args.extend([comparand, value]);
  10428. let intrinsic = if wide {
  10429. "atomicCompareExchange.i64"
  10430. } else {
  10431. "atomicCompareExchange.i32"
  10432. };
  10433. (intrinsic, 79)
  10434. } else {
  10435. args.push(self.s.m.i32(code));
  10436. args.extend(cs);
  10437. args.push(value);
  10438. (
  10439. if wide {
  10440. "atomicBinOp.i64"
  10441. } else {
  10442. "atomicBinOp.i32"
  10443. },
  10444. 78,
  10445. )
  10446. };
  10447. let at = self.begin_guarded(guard);
  10448. let r = self
  10449. .s
  10450. .op(self.cur, intrinsic, Attr::NoUnwind, ty, opcode, &args);
  10451. if cache.glc {
  10452. let old = self.end_guarded(at, &[(r, original)])[0];
  10453. if wide {
  10454. let (lo, hi) = self.split64(old);
  10455. self.write(inst, Reg::V(reg), lo, None);
  10456. self.write(inst, Reg::V(reg + 1), hi, None);
  10457. } else {
  10458. self.write(inst, Reg::V(reg), old, None);
  10459. }
  10460. } else {
  10461. self.end_guarded(at, &[]);
  10462. }
  10463. return Ok(());
  10464. }
  10465. if store {
  10466. if name != "image_store" {
  10467. return Err("an image store to a mip level");
  10468. }
  10469. // shortcut: stores are taken to write all four channels of a
  10470. // float format (the console converts by the view's format).
  10471. // One channel goes into a view the program also counts in.
  10472. let counter = *dmask == 1 && self.is_counter(src);
  10473. if *dmask != 0xF && !counter {
  10474. return Err("an image store of some channels");
  10475. }
  10476. let iu = self.s.m.undef(self.s.t.i32);
  10477. let mut cs = vec![iu; 3];
  10478. for (k, slot) in cs.iter_mut().enumerate().take(coords) {
  10479. *slot = addr_val(self, k)?;
  10480. }
  10481. let Operand::Vector { reg, .. } = *data else {
  10482. return Err("image store data");
  10483. };
  10484. if counter {
  10485. let v = inst.read(Reg::V(reg)).ok_or("image store data")?;
  10486. let x = self.i32_of(v)?;
  10487. // A 16-bit integer, extended by the view's sign: the same
  10488. // number either way only if it is known to be small.
  10489. if *d16 && !self.s.m.int_k(x).is_some_and(|(_, k)| k < 0x8000) {
  10490. return Err("a 16-bit image store of one channel");
  10491. }
  10492. let h = self.handle(site, src, false, (kind | 0x1000 | rov, 0x105))?;
  10493. let at = self.begin_guarded(guard);
  10494. // All four channels are written (the validator wants them
  10495. // all): the view has the first alone.
  10496. let mut args = vec![h];
  10497. args.extend(cs);
  10498. args.extend([x; 4]);
  10499. args.push(self.s.m.i8(0xF));
  10500. let void = self.s.t.void;
  10501. self.s.op(
  10502. self.cur,
  10503. "textureStore.i32",
  10504. Attr::NoUnwind,
  10505. void,
  10506. 67,
  10507. &args,
  10508. );
  10509. self.end_guarded(at, &[]);
  10510. return Ok(());
  10511. }
  10512. let mut vals = Vec::new();
  10513. for k in 0..4u8 {
  10514. // d16: two f16 channels per VGPR, low half first.
  10515. let r = if *d16 { k / 2 } else { k };
  10516. let v = inst.read(Reg::V(reg + r)).ok_or("image store data")?;
  10517. vals.push(if *d16 {
  10518. let mut x = self.i32_of(v)?;
  10519. if k % 2 == 1 {
  10520. let k16 = self.s.m.i32(16);
  10521. x = self.s.m.bin(self.cur, Bin::LShr, x, k16);
  10522. }
  10523. let f32t = self.s.t.f32;
  10524. self.s
  10525. .op(self.cur, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x])
  10526. } else {
  10527. self.float_of(v)?
  10528. });
  10529. }
  10530. let h = self.handle(site, src, false, props)?;
  10531. let at = self.begin_guarded(guard);
  10532. let mut args = vec![h];
  10533. args.extend(cs);
  10534. args.extend(vals);
  10535. args.push(self.s.m.i8(0xF));
  10536. let void = self.s.t.void;
  10537. self.s.op(
  10538. self.cur,
  10539. "textureStore.f32",
  10540. Attr::NoUnwind,
  10541. void,
  10542. 67,
  10543. &args,
  10544. );
  10545. self.end_guarded(at, &[]);
  10546. return Ok(());
  10547. }
  10548. let has_cl = name.ends_with("_cl");
  10549. let (op, sample) = match name {
  10550. "image_sample" | "image_sample_o" | "image_sample_cl" => (60, true),
  10551. "image_sample_lz" | "image_sample_l" | "image_sample_lz_o" => (62, true),
  10552. "image_sample_b" | "image_sample_b_cl" => (61, true),
  10553. "image_sample_c_lz" => (65, true),
  10554. "image_sample_d" | "image_sample_d_cl" => (63, true),
  10555. "image_get_lod" if self.s.pixel => (81, true),
  10556. // Implicit derivatives: pixel shaders only.
  10557. "image_sample_c" if self.s.pixel => (64, true),
  10558. "image_sample_c_cl" if self.s.pixel => (64, true),
  10559. "image_gather4" | "image_gather4_lz" | "image_gather4_lz_o" | "image_gather4_l" | "image_gather4_l_o" => (73, true),
  10560. "image_load" | "image_load_mip" => (66, false),
  10561. "image_get_resinfo" => (72, false),
  10562. _ => return Err(name),
  10563. };
  10564. if op == 72 {
  10565. // Width, height, depth or layers, levels (per dmask) of the level
  10566. // in the first address: DXIL's dimensions; a channel DXIL leaves
  10567. // out reads 1 (UAVs: one level).
  10568. let h = self.handle(site, src, false, props)?;
  10569. let mip = if uav {
  10570. self.s.m.undef(self.s.t.i32)
  10571. } else {
  10572. addr_val(self, 0)?
  10573. };
  10574. let i32t = self.s.t.i32;
  10575. let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
  10576. let d = self
  10577. .s
  10578. .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]);
  10579. let one = self.s.m.i32(1);
  10580. let present = match kind {
  10581. 1 => [true, false, false, true],
  10582. 2 | 5 | 6 => [true, true, false, true],
  10583. _ => [true, true, true, true],
  10584. };
  10585. let Operand::Vector { reg, .. } = *data else {
  10586. return Err("an image result");
  10587. };
  10588. for (k, ch) in (0..4u32).filter(|ch| dmask >> ch & 1 != 0).enumerate() {
  10589. let x = if ch == 3 && uav || !present[ch as usize] {
  10590. one
  10591. } else {
  10592. self.s.m.extract(c, d, ch)
  10593. };
  10594. self.write(inst, Reg::V(reg + k as u8), x, guard);
  10595. }
  10596. return Ok(());
  10597. }
  10598. if uav && op != 66 {
  10599. return Err("sampling a UAV");
  10600. }
  10601. let h = self.handle(site, src, false, props)?;
  10602. let fu = self.s.m.undef(self.s.t.f32);
  10603. let iu = self.s.m.undef(self.s.t.i32);
  10604. // A gather at a named level, done as four texel reads (below).
  10605. let mut gathered: Option<[V; 4]> = None;
  10606. let r = if sample {
  10607. let ss = self
  10608. .descriptors
  10609. .get(&(site, true))
  10610. .copied()
  10611. .ok_or("an untracked sampler")?;
  10612. // Comparison: the reference value is the first address after
  10613. // the bias, and the sampler is a comparison sampler.
  10614. let cmp = matches!(op, 64 | 65);
  10615. if cmp && (*a16 || dmask.count_ones() != 1) {
  10616. return Err("a comparison sample of 16-bit coordinates or several channels");
  10617. }
  10618. let mut sampler_choice: Option<(V, Vec<u32>)> = None;
  10619. let sh = match ss {
  10620. Source::Phi { block, args } => {
  10621. match self.sampler_phi_choice(*block, args, cmp, 8) {
  10622. Ok((None, regs)) => self.s.sampler_handle(self.cur, regs[0]),
  10623. Ok((Some(idx), regs)) => {
  10624. let first = self.s.sampler_handle(self.cur, regs[0]);
  10625. sampler_choice = Some((idx, regs));
  10626. first
  10627. }
  10628. Err(_) => {
  10629. self.handle(site, ss, true, (14 | if cmp { 0x8000 } else { 0 }, 0))?
  10630. }
  10631. }
  10632. }
  10633. _ => self.handle(site, ss, true, (14 | if cmp { 0x8000 } else { 0 }, 0))?,
  10634. };
  10635. // Texel offsets (`_o`) come first: x in bits 0-5, y in 8-13,
  10636. // signed (programmable offsets: gathers only).
  10637. let offset_word = name.ends_with("_o");
  10638. let first = usize::from(offset_word)
  10639. + usize::from(name.starts_with("image_sample_b"))
  10640. + usize::from(cmp);
  10641. // Coordinates the size divides (not the array slice); explicit
  10642. // gradients (x then y) come before the coordinates.
  10643. let spatial = coords - usize::from(kind == 6 || kind == 7);
  10644. // A cube's gradients are the two of its face coordinates.
  10645. let grads = if kind == 5 { 2 } else { spatial };
  10646. let deriv_regs = if op == 63 {
  10647. if *a16 {
  10648. grads.div_ceil(2)
  10649. } else {
  10650. grads
  10651. }
  10652. } else {
  10653. 0
  10654. };
  10655. let coord_base = first + 2 * deriv_regs;
  10656. let mut cs = vec![fu; 4];
  10657. // With a16, sampling coordinates, gradients, LOD and clamp are f16.
  10658. let to_float = |l: &mut Self, x: V| {
  10659. if *a16 {
  10660. let f = l.s.t.f32;
  10661. l.s.op(l.cur, "legacyF16ToF32", Attr::ReadNone, f, 131, &[x])
  10662. } else {
  10663. l.as_float(x)
  10664. }
  10665. };
  10666. if kind == 5 && (*unorm || op == 81) {
  10667. return Err("a cube sample with texel coordinates or a level query");
  10668. }
  10669. for (k, slot) in cs.iter_mut().enumerate().take(coords) {
  10670. let x = addr_packed(self, coord_base, k)?;
  10671. *slot = to_float(self, x);
  10672. }
  10673. if kind == 5 {
  10674. let dir = self.cube_direction(cs[0], cs[1], cs[2]);
  10675. cs[..3].copy_from_slice(&dir);
  10676. }
  10677. if *unorm {
  10678. // Texel coordinates: divided by the size of level 0.
  10679. let i32t = self.s.t.i32;
  10680. let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
  10681. let z = self.s.m.i32(0);
  10682. let d = self
  10683. .s
  10684. .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, z]);
  10685. for (k, slot) in cs.iter_mut().enumerate().take(spatial) {
  10686. let n = self.s.m.extract(c, d, k as u32);
  10687. let n = self.s.m.cast(c, Cast::UiToFp, n, self.s.t.f32);
  10688. *slot = self.s.m.bin(c, Bin::SDiv, *slot, n);
  10689. }
  10690. }
  10691. if op == 81 {
  10692. // The clamped then the unclamped level of detail.
  10693. let Operand::Vector { reg, .. } = *data else {
  10694. return Err("an image result");
  10695. };
  10696. let f32t = self.s.t.f32;
  10697. for (k, ch) in (0..2u32).filter(|ch| dmask >> ch & 1 != 0).enumerate() {
  10698. let clamped = self.s.m.bool(ch == 0);
  10699. let lod = self.s.op(
  10700. c,
  10701. "calculateLOD.f32",
  10702. Attr::ReadOnly,
  10703. f32t,
  10704. 81,
  10705. &[h, sh, cs[0], cs[1], cs[2], clamped],
  10706. );
  10707. let x = self.as_int(lod);
  10708. self.write(inst, Reg::V(reg + k as u8), x, guard);
  10709. }
  10710. return Ok(());
  10711. }
  10712. let offsets = if kind == 5 {
  10713. 0
  10714. } else {
  10715. (coords - usize::from(kind == 6 || kind == 7)).min(3)
  10716. };
  10717. let zero = self.s.m.i32(0);
  10718. let mut os = vec![iu; 3];
  10719. for o in os.iter_mut().take(offsets) {
  10720. *o = zero;
  10721. }
  10722. if offset_word && offsets > 0 {
  10723. let w = addr_val(self, 0)?;
  10724. for (k, at) in [(0, 26), (1, 18)].into_iter().take(offsets.min(2)) {
  10725. // Bits at..at+5 sign-extended: shift up, then down.
  10726. let left = self.s.m.i32(at);
  10727. let t = self.s.m.bin(c, Bin::Shl, w, left);
  10728. let k26 = self.s.m.i32(26);
  10729. os[k] = self.s.m.bin(c, Bin::AShr, t, k26);
  10730. }
  10731. }
  10732. let mut args = vec![h, sh];
  10733. args.extend(&cs);
  10734. let clamp = if has_cl {
  10735. let x = addr_packed(self, coord_base, coords)?;
  10736. to_float(self, x)
  10737. } else {
  10738. fu
  10739. };
  10740. let call_sample = |l: &mut Self,
  10741. intrinsic: &str,
  10742. opcode: u32,
  10743. args: &[V],
  10744. gathered: &mut Option<[V; 4]>|
  10745. -> V {
  10746. let Some((idx, ref regs)) = sampler_choice else {
  10747. return l
  10748. .s
  10749. .op(c, intrinsic, Attr::ReadOnly, l.s.t.res_ret, opcode, args);
  10750. };
  10751. let merge = l.s.m.new_block();
  10752. let mut cur_test = c;
  10753. let mut per_ch: [Vec<(V, usize)>; 4] = Default::default();
  10754. let mut last_r = args[0];
  10755. for (i, &reg) in regs.iter().enumerate() {
  10756. let arm = if i + 1 == regs.len() {
  10757. cur_test
  10758. } else {
  10759. let arm = l.s.m.new_block();
  10760. let next = l.s.m.new_block();
  10761. let k = l.s.m.i32(i as u32);
  10762. let cond = l.s.m.cmp(cur_test, pred::EQ, idx, k);
  10763. l.s.m.terminate(cur_test, Term::CondBr(cond, arm, next));
  10764. cur_test = next;
  10765. arm
  10766. };
  10767. let mut arm_args = args.to_vec();
  10768. arm_args[1] = l.s.sampler_handle(arm, reg);
  10769. let r_i = l.s.op(
  10770. arm,
  10771. intrinsic,
  10772. Attr::ReadOnly,
  10773. l.s.t.res_ret,
  10774. opcode,
  10775. &arm_args,
  10776. );
  10777. for (ch, slot) in per_ch.iter_mut().enumerate() {
  10778. let v = l.s.m.extract(arm, r_i, ch as u32);
  10779. slot.push((v, arm));
  10780. }
  10781. l.s.m.terminate(arm, Term::Br(merge));
  10782. last_r = r_i;
  10783. }
  10784. let mut phis = [fu; 4];
  10785. for (ch, incoming) in per_ch.into_iter().enumerate() {
  10786. let phi = l.s.m.phi(merge, l.s.t.f32);
  10787. l.s.m.set_phi(phi, incoming);
  10788. phis[ch] = phi;
  10789. }
  10790. *gathered = Some(phis);
  10791. l.cur = merge;
  10792. last_r
  10793. };
  10794. match op {
  10795. // Outside a pixel shader there are no screen derivatives:
  10796. // the validator refuses `sample` there ("features
  10797. // incompatible with the shader stage": 730 compute programs,
  10798. // among them the G-buffer resolves and the sky), and what a
  10799. // driver does with it is its own affair.
  10800. // shortcut: such a sample reads level 0 (a bias: that
  10801. // level). The console takes derivatives from neighbouring
  10802. // lanes there; compute them from the lanes if a resolve
  10803. // shows the wrong mip.
  10804. 60 if !self.s.pixel => {
  10805. args.extend(&os);
  10806. args.push(self.s.m.f32(0));
  10807. call_sample(self, "sampleLevel.f32", 62, &args, &mut gathered)
  10808. }
  10809. 60 => {
  10810. if offset_word {
  10811. // DXIL wants immediate offsets in -8..=7 here; the
  10812. // console's are 6-bit and may be computed. A
  10813. // constant word in range becomes immediates
  10814. // (upstream PR #634); anything else keeps the
  10815. // offsets computed above (upstream refuses those).
  10816. let w = addr_val(self, 0)?;
  10817. if let Some(w) = self.s.m.int_value(w) {
  10818. let w = w as u32;
  10819. let field = |k: usize| {
  10820. let x = (w >> (8 * k) & 0x3F) as i32;
  10821. if x >= 32 { x - 64 } else { x }
  10822. };
  10823. let n = offsets.min(2);
  10824. if (0..n).all(|k| (-8..=7).contains(&field(k))) {
  10825. for (k, o) in os.iter_mut().enumerate().take(n) {
  10826. *o = self.s.m.i32(field(k) as u32);
  10827. }
  10828. }
  10829. }
  10830. }
  10831. args.extend(&os);
  10832. args.push(clamp);
  10833. call_sample(self, "sample.f32", 60, &args, &mut gathered)
  10834. }
  10835. 61 => {
  10836. // With a16 the bias is an f16 in the low half of its
  10837. // word (the word is whole, the value is not).
  10838. let bias = addr_u32(self, usize::from(offset_word))?;
  10839. let bias = if *a16 {
  10840. let low = self.s.m.i32(0xFFFF);
  10841. let bias = self.s.m.bin(c, Bin::And, bias, low);
  10842. to_float(self, bias)
  10843. } else {
  10844. self.as_float(bias)
  10845. };
  10846. args.extend(&os);
  10847. if self.s.pixel {
  10848. args.extend([bias, clamp]);
  10849. call_sample(self, "sampleBias.f32", 61, &args, &mut gathered)
  10850. } else {
  10851. // As above: the bias is the level.
  10852. args.push(bias);
  10853. call_sample(self, "sampleLevel.f32", 62, &args, &mut gathered)
  10854. }
  10855. }
  10856. 63 if kind == 5 => {
  10857. // A cube with explicit gradients: the host wants them
  10858. // as changes of the direction, the console gives the
  10859. // changes of the face coordinates (the face is one
  10860. // unit wide). The level they select is taken from the
  10861. // longer of the two, in texels, and sampled directly.
  10862. // shortcut: no anisotropic filtering for these samples
  10863. // (the longer axis alone decides the level).
  10864. let mut len = [fu; 2];
  10865. for (axis, slot) in len.iter_mut().enumerate() {
  10866. let mut sum = self.s.m.f32(0);
  10867. for k in 0..2 {
  10868. let x = addr_packed(self, first + axis * deriv_regs, k)?;
  10869. let x = to_float(self, x);
  10870. let sq = self.s.m.bin(c, Bin::Mul, x, x);
  10871. sum = self.s.m.bin(c, Bin::Add, sum, sq);
  10872. }
  10873. *slot = self.unary(24, sum); // square root
  10874. }
  10875. let longer = self.binary(35, len[0], len[1]); // maximum
  10876. let i32t = self.s.t.i32;
  10877. let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
  10878. let z = self.s.m.i32(0);
  10879. let d = self
  10880. .s
  10881. .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, z]);
  10882. let width = self.s.m.extract(c, d, 0);
  10883. let width = self.s.m.cast(c, Cast::UiToFp, width, self.s.t.f32);
  10884. let texels = self.s.m.bin(c, Bin::Mul, longer, width);
  10885. // DXIL's logarithm is the one to base 2 (it was taken for
  10886. // the natural one: every level came out 1.44 times too
  10887. // high; DexNom/VIctory 921d8d3b). A length of 0 gives
  10888. // minus infinity, which the sampler clamps to level 0.
  10889. // SampleLevel takes no clamp: the instruction's least
  10890. // level is applied here.
  10891. let lod = self.unary(23, texels);
  10892. let lod = if has_cl { self.binary(35, lod, clamp) } else { lod };
  10893. args.extend(&os);
  10894. args.push(lod);
  10895. call_sample(self, "sampleLevel.f32", 62, &args, &mut gathered)
  10896. }
  10897. 63 => {
  10898. let mut g = vec![fu; 6];
  10899. for k in 0..spatial {
  10900. let x = addr_packed(self, first, k)?;
  10901. g[k] = to_float(self, x);
  10902. let y = addr_packed(self, first + deriv_regs, k)?;
  10903. g[3 + k] = to_float(self, y);
  10904. }
  10905. args.extend(&os);
  10906. args.extend(g);
  10907. args.push(clamp);
  10908. call_sample(self, "sampleGrad.f32", 63, &args, &mut gathered)
  10909. }
  10910. 64 | 65 => {
  10911. let reference = addr_u32(self, first - 1)?;
  10912. let reference = self.as_float(reference);
  10913. args.extend(&os);
  10914. args.push(reference);
  10915. let name = if op == 64 {
  10916. args.push(clamp);
  10917. "sampleCmp.f32"
  10918. } else {
  10919. "sampleCmpLevelZero.f32"
  10920. };
  10921. call_sample(self, name, op, &args, &mut gathered)
  10922. }
  10923. 62 => {
  10924. let lod = if name == "image_sample_l" {
  10925. let x = addr_packed(self, coord_base, coords)?;
  10926. to_float(self, x)
  10927. } else {
  10928. self.s.m.f32(0)
  10929. };
  10930. args.extend(&os);
  10931. args.push(lod);
  10932. call_sample(self, "sampleLevel.f32", 62, &args, &mut gathered)
  10933. }
  10934. _ => {
  10935. if name == "image_gather4" {
  10936. return Err("a gather with implicit level");
  10937. }
  10938. if dmask.count_ones() != 1 {
  10939. return Err("a gather of several channels");
  10940. }
  10941. if matches!(name, "image_gather4_l" | "image_gather4_l_o")
  10942. && coords == 2
  10943. && spatial == 2
  10944. {
  10945. // The host's gather has no level: it read level 0
  10946. // where the title names one (the depth pyramid its
  10947. // occlusion tests read: most of the world was
  10948. // culled against the wrong depths). The four texels
  10949. // are read at the level instead, in the gather's
  10950. // order: (u0,v1) (u1,v1) (u1,v0) (u0,v0).
  10951. // With an offset too (`image_gather4_l_o`): the
  10952. // offset is in texels of that level.
  10953. // The title's meshlet culling takes a 4x4 block of
  10954. // the pyramid as one gather and three offset ones
  10955. // ((2,0), (0,2), (2,2)); the three read level 0,
  10956. // two texels beside the first one's place, so a
  10957. // meshlet three or four texels wide was tested
  10958. // against a quarter of what it covers.
  10959. // shortcut: the level is rounded to a whole one and
  10960. // coordinates past the edge are clamped, whatever
  10961. // the sampler says.
  10962. let lod = addr_packed(self, coord_base, coords)?;
  10963. let lod = to_float(self, lod);
  10964. let (i32t, f32t) = (self.s.t.i32, self.s.t.f32);
  10965. let zero = self.s.m.f32(0);
  10966. let lod = self.binary(35, lod, zero); // maximum
  10967. let lod = self.unary(26, lod); // round to nearest
  10968. let mip = self.s.m.cast(c, Cast::FpToUi, lod, i32t);
  10969. let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
  10970. let d = self
  10971. .s
  10972. .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]);
  10973. let half = self.s.m.f32(0.5f32.to_bits());
  10974. let one = self.s.m.f32(1.0f32.to_bits());
  10975. let (mut lo, mut hi) = ([iu; 2], [iu; 2]);
  10976. for k in 0..2 {
  10977. let n = self.s.m.extract(c, d, k as u32);
  10978. let n = self.s.m.cast(c, Cast::UiToFp, n, f32t);
  10979. let last = self.s.m.bin(c, Bin::Sub, n, one);
  10980. let t = self.s.m.bin(c, Bin::Mul, cs[k], n);
  10981. let t = self.s.m.bin(c, Bin::Sub, t, half);
  10982. let first = self.unary(27, t); // round down
  10983. // The offset word's field (0 without one).
  10984. let by = self.s.m.cast(c, Cast::SiToFp, os[k], f32t);
  10985. let first = self.s.m.bin(c, Bin::Add, first, by);
  10986. let next = self.s.m.bin(c, Bin::Add, first, one);
  10987. for (slot, x) in [(&mut lo[k], first), (&mut hi[k], next)] {
  10988. let x = self.binary(35, x, zero); // maximum
  10989. let x = self.binary(36, x, last); // minimum
  10990. *slot = self.s.m.cast(c, Cast::FpToSi, x, i32t);
  10991. }
  10992. }
  10993. let ch = dmask.trailing_zeros();
  10994. let mut g = [fu; 4];
  10995. let mut read = None;
  10996. let texels = [(lo[0], hi[1]), (hi[0], hi[1]), (hi[0], lo[1]), (lo[0], lo[1])];
  10997. for (slot, (x, y)) in g.iter_mut().zip(texels) {
  10998. let r = self.s.op(
  10999. c,
  11000. "textureLoad.f32",
  11001. Attr::ReadOnly,
  11002. self.s.t.res_ret,
  11003. 66,
  11004. &[h, mip, x, y, iu, iu, iu, iu],
  11005. );
  11006. *slot = self.s.m.extract(c, r, ch);
  11007. read = Some(r);
  11008. }
  11009. gathered = Some(g);
  11010. read.expect("four reads")
  11011. } else {
  11012. args.extend(&os[..2]);
  11013. args.push(self.s.m.i32(dmask.trailing_zeros()));
  11014. call_sample(self, "textureGather.f32", 73, &args, &mut gathered)
  11015. }
  11016. }
  11017. }
  11018. } else {
  11019. let mut cs = vec![iu; 3];
  11020. for (k, slot) in cs.iter_mut().enumerate().take(coords) {
  11021. *slot = addr_val(self, k)?;
  11022. }
  11023. let mip = if name == "image_load_mip" {
  11024. addr_val(self, coords)?
  11025. } else if uav {
  11026. // Our declarations have four channels.
  11027. self.s.flags |= flags::TYPED_UAV_LOADS;
  11028. iu
  11029. } else {
  11030. self.s.m.i32(0)
  11031. };
  11032. let mut args = vec![h, mip];
  11033. args.extend(&cs);
  11034. args.extend([iu, iu, iu]);
  11035. self.s.op(
  11036. c,
  11037. "textureLoad.f32",
  11038. Attr::ReadOnly,
  11039. self.s.t.res_ret,
  11040. 66,
  11041. &args,
  11042. )
  11043. };
  11044. let Operand::Vector { reg, .. } = *data else {
  11045. return Err("an image result");
  11046. };
  11047. let channels: Vec<u32> = if op == 73 {
  11048. vec![0, 1, 2, 3]
  11049. } else {
  11050. (0..4).filter(|ch| dmask >> ch & 1 != 0).collect()
  11051. };
  11052. let mut xs = Vec::new();
  11053. for ch in channels {
  11054. let x = match gathered {
  11055. Some(g) => g[ch as usize],
  11056. None => self.s.m.extract(c, r, ch),
  11057. };
  11058. xs.push(if *d16 {
  11059. // shortcut: d16 results are taken as floats (rounded to
  11060. // nearest even); integer formats would keep 16 bits.
  11061. let i32t = self.s.t.i32;
  11062. self.s
  11063. .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[x])
  11064. } else {
  11065. self.as_int(x)
  11066. });
  11067. }
  11068. if *d16 {
  11069. // Two channels per VGPR, low half first (an odd last high half 0).
  11070. let k16 = self.s.m.i32(16);
  11071. xs = xs
  11072. .chunks(2)
  11073. .map(|p| match *p {
  11074. [lo, hi] => {
  11075. let hi = self.s.m.bin(c, Bin::Shl, hi, k16);
  11076. self.s.m.bin(c, Bin::Or, lo, hi)
  11077. }
  11078. _ => p[0],
  11079. })
  11080. .collect();
  11081. }
  11082. for (k, x) in xs.into_iter().enumerate() {
  11083. self.write(inst, Reg::V(reg + k as u8), x, guard);
  11084. }
  11085. Ok(())
  11086. }
  11087. /// The direction a cube sample's face coordinates stand for: the
  11088. /// console takes s and t in [1, 2] (`v_cubesc`/`v_cubetc` over
  11089. /// `|v_cubema|`, plus 1.5) and the face id (`v_cubeid`), which the
  11090. /// host's cube sampling turns back into the same texel.
  11091. // shortcut: the view is taken as a cube, not a cube array (whose face
  11092. // operand adds 8 × the slice).
  11093. fn cube_direction(&mut self, s: V, t: V, face: V) -> [V; 3] {
  11094. let c = self.cur;
  11095. let k = |l: &mut Self, v: f32| l.s.m.f32(v.to_bits());
  11096. let (two, three) = (k(self, 2.0), k(self, 3.0));
  11097. let u = self.s.m.bin(c, Bin::Mul, s, two);
  11098. let u = self.s.m.bin(c, Bin::Sub, u, three);
  11099. let v = self.s.m.bin(c, Bin::Mul, t, two);
  11100. let v = self.s.m.bin(c, Bin::Sub, v, three);
  11101. let z = self.s.m.f32(0x8000_0000);
  11102. let (nu, nv) = (
  11103. self.s.m.bin(c, Bin::Sub, z, u),
  11104. self.s.m.bin(c, Bin::Sub, z, v),
  11105. );
  11106. let (one, mone) = (k(self, 1.0), k(self, -1.0));
  11107. let f = self.s.m.cast(c, Cast::FpToUi, face, self.s.t.i32);
  11108. // Per face +x, -x, +y, -y, +z, -z.
  11109. let table = [
  11110. [one, mone, u, u, u, nu],
  11111. [nv, nv, one, mone, nv, nv],
  11112. [nu, u, v, nv, one, mone],
  11113. ];
  11114. table.map(|row| {
  11115. let mut r = row[0];
  11116. for (n, &x) in row.iter().enumerate().skip(1) {
  11117. let kn = self.s.m.i32(n as u32);
  11118. let is = self.s.m.cmp(c, pred::EQ, f, kn);
  11119. r = self.s.m.select(c, is, x, r);
  11120. }
  11121. r
  11122. })
  11123. }
  11124. fn buffer(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  11125. self.root_copy = None;
  11126. let Fields::Buffer {
  11127. data,
  11128. addr,
  11129. soffset,
  11130. offset,
  11131. offen,
  11132. idxen,
  11133. format,
  11134. lds,
  11135. tfe,
  11136. ..
  11137. } = &inst.fields
  11138. else {
  11139. unreachable!()
  11140. };
  11141. let name = inst.name();
  11142. if name == "buffer_gl0_inv" || name == "buffer_gl1_inv" {
  11143. // The host has no console buffer cache to invalidate.
  11144. return Ok(());
  11145. }
  11146. if *lds || *tfe {
  11147. return Err("a buffer access to LDS or with tfe");
  11148. }
  11149. if format.is_some() && !name.starts_with("tbuffer_load_format_") {
  11150. return Err(name);
  11151. }
  11152. let site = (b, i);
  11153. let guard = self.guard(b, i)?;
  11154. let c = self.cur;
  11155. let store = name.starts_with("buffer_store_");
  11156. // DXIL atomic operations: add, and, or, xor, signed and unsigned
  11157. // min and max, exchange; compare-exchange apart.
  11158. let atomic = match name.strip_prefix("buffer_atomic_") {
  11159. None => None,
  11160. Some("add") => Some(0),
  11161. Some("and") => Some(1),
  11162. Some("or") => Some(2),
  11163. Some("xor") => Some(3),
  11164. Some("smin") => Some(4),
  11165. Some("smax") => Some(5),
  11166. Some("umin") => Some(6),
  11167. Some("umax") => Some(7),
  11168. Some("swap") => Some(8),
  11169. Some("cmpswap") => Some(u32::MAX),
  11170. Some(_) => return Err(name),
  11171. };
  11172. // Byte and 16-bit accesses: bits, and whether a load sign-extends.
  11173. let narrow = match name {
  11174. "buffer_load_ubyte" | "buffer_store_byte" => Some((8, false)),
  11175. "buffer_load_sbyte" => Some((8, true)),
  11176. "buffer_load_ushort" | "buffer_store_short" => Some((16, false)),
  11177. "buffer_load_sshort" => Some((16, true)),
  11178. _ => None,
  11179. };
  11180. // d16: two 16-bit channels per VGPR, low half first (buffer and
  11181. // tbuffer formats alike).
  11182. let d16 = name.contains("_format_d16_");
  11183. let plain = name.replace("_format_d16_", "_format_");
  11184. let (typed, count) = match plain
  11185. .strip_prefix("buffer_load_")
  11186. .or(plain.strip_prefix("buffer_store_"))
  11187. .or(plain.strip_prefix("tbuffer_load_"))
  11188. {
  11189. _ if atomic.is_some() || narrow.is_some() => (false, 1),
  11190. Some("dword") => (false, 1),
  11191. Some("dwordx2") => (false, 2),
  11192. Some("dwordx3") => (false, 3),
  11193. Some("dwordx4") => (false, 4),
  11194. Some("format_x") => (true, 1),
  11195. Some("format_xy") => (true, 2),
  11196. Some("format_xyz") => (true, 3),
  11197. Some("format_xyzw") => (true, 4),
  11198. _ => return Err(name),
  11199. };
  11200. let Operand::Vector { reg: areg, .. } = *addr else {
  11201. return Err("a buffer address");
  11202. };
  11203. let vaddr = |l: &mut Self, k: u8| -> Result<V, Why> {
  11204. let v = inst.read(Reg::V(areg + k)).ok_or("a buffer address")?;
  11205. l.i32_of(v)
  11206. };
  11207. let index = if *idxen { Some(vaddr(self, 0)?) } else { None };
  11208. let mut off = self.s.m.i32(u32::from(*offset));
  11209. if *offen {
  11210. let o = vaddr(self, u8::from(*idxen))?;
  11211. off = self.s.m.bin(c, Bin::Add, off, o);
  11212. }
  11213. if !matches!(
  11214. soffset,
  11215. Operand::Scalar { code: NULL, .. } | Operand::Const(128)
  11216. ) {
  11217. let so = self.operand(inst, soffset)?;
  11218. off = self.s.m.bin(c, Bin::Add, off, so);
  11219. }
  11220. let src = self
  11221. .descriptors
  11222. .get(&(site, false))
  11223. .copied()
  11224. .ok_or("an untracked buffer")?;
  11225. let used = self.used_kind(src);
  11226. let (base, extra) = self.built_offset(src)?;
  11227. if base != 0 {
  11228. let b = self.s.m.i32(base);
  11229. off = self.s.m.bin(c, Bin::Add, off, b);
  11230. }
  11231. if let Some(x) = extra {
  11232. off = self.s.m.bin(c, Bin::Add, off, x);
  11233. }
  11234. // A buffer the program picks from the view heap by an index it
  11235. // computes: no used-resource entry gives its stride, the host's
  11236. // table by heap slot does; the access becomes a raw one at the
  11237. // element's byte. (Also tells the host this shader reads such
  11238. // buffers.)
  11239. let mut index = index;
  11240. if let Some(stride) = self.slot_stride(src)?
  11241. && let Some(element) = index
  11242. && !typed
  11243. && used.is_none()
  11244. {
  11245. let at = self.s.m.bin(c, Bin::Mul, element, stride);
  11246. off = self.s.m.bin(c, Bin::Add, at, off);
  11247. index = None;
  11248. }
  11249. // A structured buffer by its used-resource entry's stride: raw
  11250. // bytes too. The host makes its buffer views raw (a raw read
  11251. // through a structured view gives zeros on NVIDIA), and one kind
  11252. // of view can then serve every shader that reads the buffer.
  11253. if let (Some(element), Some(u)) = (index, used)
  11254. && !typed
  11255. && u.kind != ResourceType::Cbv
  11256. && u.stride >= 4
  11257. && u.stride.is_multiple_of(4)
  11258. {
  11259. let k = self.s.m.i32(u.stride);
  11260. let at = self.s.m.bin(c, Bin::Mul, element, k);
  11261. off = self.s.m.bin(c, Bin::Add, at, off);
  11262. index = None;
  11263. }
  11264. if used.is_some_and(|u| u.kind == ResourceType::Cbv) && !typed {
  11265. // A constant buffer read per lane (a dynamically indexed array).
  11266. // shortcut: the console's CBV descriptor is taken to have a 16-byte
  11267. // stride, as the vector loads of whole rows suggest.
  11268. let h = self.handle(site, src, false, (13, 0x1_0000))?;
  11269. let byte = match index {
  11270. Some(i) => {
  11271. let sixteen = self.s.m.i32(16);
  11272. let rows = self.s.m.bin(c, Bin::Mul, i, sixteen);
  11273. self.s.m.bin(c, Bin::Add, rows, off)
  11274. }
  11275. None => off,
  11276. };
  11277. let Some(Operand::Vector { reg, .. }) = *data else {
  11278. return Err("a buffer result");
  11279. };
  11280. for k in 0..count {
  11281. let four = self.s.m.i32(4 * k);
  11282. let a = self.s.m.bin(c, Bin::Add, byte, four);
  11283. let x = self.cbuffer_dword(h, a);
  11284. self.write(inst, Reg::V(reg + k as u8), x, guard);
  11285. }
  11286. return Ok(());
  11287. }
  11288. if self.root_address(src).is_some() {
  11289. // Title memory by address: the byte in the host copy from here on.
  11290. if let Some(element) = index {
  11291. if used.is_none_or(|u| u.stride != 1) {
  11292. return Err("an indexed access through a root view by address");
  11293. }
  11294. off = self.s.m.bin(c, Bin::Add, element, off);
  11295. index = None;
  11296. }
  11297. if let Some((_, byte)) = self.root_memory(src, off, guard, store || atomic.is_some()) {
  11298. off = byte;
  11299. }
  11300. }
  11301. let c = self.cur;
  11302. let uav = store || atomic.is_some() || used.is_some_and(|u| u.kind == ResourceType::Uav);
  11303. let mut u = if uav { 0x1000 } else { 0 };
  11304. if uav && !typed && self.entry(src).is_some_and(|e| self.coherent.contains(&e)) {
  11305. u |= 0x4000;
  11306. }
  11307. let iu = self.s.m.undef(self.s.t.i32);
  11308. if let Some((bits, signed)) = narrow {
  11309. // Below a dword: raw buffers are read and written in dwords on
  11310. // 4 bytes, so the dword that holds the value is read and
  11311. // shifted, or changed with two atomic operations that touch
  11312. // only the value's own bits (other lanes may write the rest of
  11313. // the dword at the same time). A 16-bit value at a dword's
  11314. // last byte continues in the next dword.
  11315. let byte = match index {
  11316. None => off,
  11317. Some(index) if used.is_some_and(|u| u.stride == 1) => {
  11318. self.s.m.bin(c, Bin::Add, index, off)
  11319. }
  11320. Some(_) => return Err("a byte or 16-bit buffer access by index"),
  11321. };
  11322. let h = self.handle(site, src, false, (11 | u, 0))?;
  11323. let k3 = self.s.m.i32(3);
  11324. let within = self.s.m.bin(c, Bin::And, byte, k3);
  11325. let aligned = self.s.m.bin(c, Bin::Sub, byte, within);
  11326. let shift = self.s.m.bin(c, Bin::Shl, within, k3);
  11327. let four = self.s.m.i32(4);
  11328. let next = self.s.m.bin(c, Bin::Add, aligned, four);
  11329. let ones = self.s.m.i32(if bits == 8 { 0xff } else { 0xffff });
  11330. let zero = self.s.m.i32(0);
  11331. let k8 = self.s.m.i32(8);
  11332. let straddles = self.s.m.cmp(c, pred::EQ, within, k3);
  11333. if !store {
  11334. let mask = self.s.m.i8(1);
  11335. let align = self.s.m.i32(4);
  11336. let dword = |l: &mut Self, at: V| {
  11337. let r = l.s.op(
  11338. c,
  11339. "rawBufferLoad.f32",
  11340. Attr::ReadOnly,
  11341. l.s.t.res_ret,
  11342. 139,
  11343. &[h, at, iu, mask, align],
  11344. );
  11345. let f = l.s.m.extract(c, r, 0);
  11346. l.as_int(f)
  11347. };
  11348. let low = dword(self, aligned);
  11349. let mut x = self.s.m.bin(c, Bin::LShr, low, shift);
  11350. if bits == 16 {
  11351. let high = dword(self, next);
  11352. let high = self.s.m.bin(c, Bin::Shl, high, k8);
  11353. let high = self.s.m.select(c, straddles, high, zero);
  11354. x = self.s.m.bin(c, Bin::Or, x, high);
  11355. }
  11356. x = self.s.m.bin(c, Bin::And, x, ones);
  11357. if signed {
  11358. let up = self.s.m.i32(32 - bits);
  11359. x = self.s.m.bin(c, Bin::Shl, x, up);
  11360. x = self.s.m.bin(c, Bin::AShr, x, up);
  11361. }
  11362. let Some(Operand::Vector { reg, .. }) = *data else {
  11363. return Err("a buffer result");
  11364. };
  11365. self.write(inst, Reg::V(reg), x, guard);
  11366. return Ok(());
  11367. }
  11368. let d = data.as_ref().ok_or("buffer store data")?;
  11369. let v = self.vgprs(inst, d, 1)?[0];
  11370. let v = self.s.m.bin(c, Bin::And, v, ones);
  11371. let all = self.s.m.i32(u32::MAX);
  11372. let clear = self.s.m.bin(c, Bin::Shl, ones, shift);
  11373. let keep = self.s.m.bin(c, Bin::Xor, clear, all);
  11374. let set = self.s.m.bin(c, Bin::Shl, v, shift);
  11375. let keep_next = self.s.m.i32(0xffff_ff00);
  11376. let set_next = self.s.m.bin(c, Bin::LShr, v, k8);
  11377. let (and, or) = (self.s.m.i32(1), self.s.m.i32(2));
  11378. let i32t = self.s.t.i32;
  11379. let at = self.begin_guarded(guard);
  11380. for (op, x) in [(and, keep), (or, set)] {
  11381. let args = [h, op, aligned, iu, iu, x];
  11382. self.s
  11383. .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args);
  11384. }
  11385. if bits == 16 {
  11386. let second = self.begin_guarded(Some(straddles));
  11387. for (op, x) in [(and, keep_next), (or, set_next)] {
  11388. let args = [h, op, next, iu, iu, x];
  11389. self.s
  11390. .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args);
  11391. }
  11392. self.end_guarded(second, &[]);
  11393. }
  11394. self.end_guarded(at, &[]);
  11395. return Ok(());
  11396. }
  11397. if let Some(op) = atomic {
  11398. let d = data.as_ref().ok_or("buffer atomic data")?;
  11399. let vals = self.vgprs(inst, d, if op == u32::MAX { 2 } else { 1 })?;
  11400. let (h, coords) = match index {
  11401. // A raw buffer (stride 1) read by index: the index is the byte.
  11402. Some(index) if used.is_some_and(|u| u.stride == 1) => {
  11403. let byte = self.s.m.bin(c, Bin::Add, index, off);
  11404. (self.handle(site, src, false, (11 | u, 0))?, [byte, iu, iu])
  11405. }
  11406. Some(index) => {
  11407. let stride = used.map_or(0, |u| u.stride);
  11408. if stride < 4 || !stride.is_multiple_of(4) {
  11409. return Err("a structured buffer of unknown stride");
  11410. }
  11411. let h = self.handle(site, src, false, (12 | u, stride))?;
  11412. (h, [index, off, iu])
  11413. }
  11414. None => (self.handle(site, src, false, (11 | u, 0))?, [off, iu, iu]),
  11415. };
  11416. let Operand::Vector { reg, .. } = *d else {
  11417. return Err("buffer atomic data");
  11418. };
  11419. let returns = matches!(inst.fields, Fields::Buffer { cache, .. } if cache.glc);
  11420. let old = match inst.read(Reg::V(reg)) {
  11421. Some(v) if returns => self.i32_of(v)?,
  11422. _ => self.s.m.i32(0),
  11423. };
  11424. let at = self.begin_guarded(guard);
  11425. let i32t = self.s.t.i32;
  11426. let r = if op == u32::MAX {
  11427. // cmpswap: data is (new, compare).
  11428. let mut args = vec![h];
  11429. args.extend(coords);
  11430. args.extend([vals[1], vals[0]]);
  11431. self.s.op(
  11432. self.cur,
  11433. "atomicCompareExchange.i32",
  11434. Attr::NoUnwind,
  11435. i32t,
  11436. 79,
  11437. &args,
  11438. )
  11439. } else {
  11440. let mut args = vec![h, self.s.m.i32(op)];
  11441. args.extend(coords);
  11442. args.push(vals[0]);
  11443. self.s
  11444. .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args)
  11445. };
  11446. let r = self.end_guarded(at, &[(r, old)])[0];
  11447. if returns {
  11448. self.write(inst, Reg::V(reg), r, None);
  11449. }
  11450. return Ok(());
  11451. }
  11452. if store {
  11453. let regs = if d16 { count.div_ceil(2) } else { count };
  11454. let mut vals =
  11455. self.vgprs(inst, data.as_ref().ok_or("buffer store data")?, regs as u8)?;
  11456. if d16 {
  11457. // d16 data is taken as f16, widened for the 32-bit float
  11458. // store; through a view of an integer format it is a 16-bit
  11459. // integer, zero- or sign-extended (VIctory 4243a96a: the face
  11460. // network keeps its halves in UINT views; its output was
  11461. // noise). shortcut: that is known of the views a program
  11462. // picks from the heap, not of those in its tables; and the
  11463. // handle stays a float one, whose bits the drivers pass.
  11464. let integer = if typed { self.integer_view(src)? } else { None };
  11465. let mut wide = Vec::new();
  11466. for k in 0..count {
  11467. let mut x = vals[(k / 2) as usize];
  11468. if k % 2 == 1 {
  11469. let k16 = self.s.m.i32(16);
  11470. x = self.s.m.bin(c, Bin::LShr, x, k16);
  11471. }
  11472. let f32t = self.s.t.f32;
  11473. let f = self
  11474. .s
  11475. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]);
  11476. let mut w = self.as_int(f);
  11477. if let Some((int, signed)) = integer {
  11478. let (k16, low) = (self.s.m.i32(16), self.s.m.i32(0xFFFF));
  11479. let zero_ext = self.s.m.bin(c, Bin::And, x, low);
  11480. let up = self.s.m.bin(c, Bin::Shl, x, k16);
  11481. let sign_ext = self.s.m.bin(c, Bin::AShr, up, k16);
  11482. let n = self.s.m.select(c, signed, sign_ext, zero_ext);
  11483. w = self.s.m.select(c, int, n, w);
  11484. }
  11485. wide.push(w);
  11486. }
  11487. vals = wide;
  11488. }
  11489. let mut args = Vec::new();
  11490. let (op, name) = if typed {
  11491. // shortcut: typed stores are taken to write all four channels
  11492. // of a float format.
  11493. if count != 4 || *offen || *offset != 0 {
  11494. return Err("a typed buffer store of some channels or at an offset");
  11495. }
  11496. args.push(self.handle(site, src, false, (10 | u, 0x409))?);
  11497. args.extend([index.unwrap_or(self.s.m.i32(0)), iu]);
  11498. for x in vals {
  11499. args.push(self.as_float(x));
  11500. }
  11501. (69, "bufferStore.f32")
  11502. } else {
  11503. match index {
  11504. // A raw buffer (stride 1) written by index: the index is the byte.
  11505. Some(index) if used.is_some_and(|u| u.stride == 1) => {
  11506. let byte = self.s.m.bin(c, Bin::Add, index, off);
  11507. args.push(self.handle(site, src, false, (11 | u, 0))?);
  11508. args.extend([byte, iu]);
  11509. }
  11510. Some(index) => {
  11511. let stride = used.map_or(0, |u| u.stride);
  11512. if stride < 4 || !stride.is_multiple_of(4) {
  11513. return Err("a structured buffer of unknown stride");
  11514. }
  11515. args.push(self.handle(site, src, false, (12 | u, stride))?);
  11516. args.extend([index, off]);
  11517. }
  11518. None => {
  11519. args.push(self.handle(site, src, false, (11 | u, 0))?);
  11520. args.extend([off, iu]);
  11521. }
  11522. }
  11523. args.extend(&vals);
  11524. args.resize(3 + 4, iu);
  11525. (140, "rawBufferStore.i32")
  11526. };
  11527. args.push(self.s.m.i8(if typed { 0xF } else { (1u8 << count) - 1 }));
  11528. if !typed {
  11529. args.push(self.s.m.i32(4));
  11530. }
  11531. let at = self.begin_guarded(guard);
  11532. let void = self.s.t.void;
  11533. self.s.op(self.cur, name, Attr::NoUnwind, void, op, &args);
  11534. self.end_guarded(at, &[]);
  11535. return Ok(());
  11536. }
  11537. if let Some(f) = *format {
  11538. if index.is_some() {
  11539. return Err("a typed-format load by index");
  11540. }
  11541. let h = self.handle(site, src, false, (11 | u, 0))?;
  11542. let Some(Operand::Vector { reg, .. }) = *data else {
  11543. return Err("a buffer result");
  11544. };
  11545. let mut xs = self.format_load(h, off, f, count)?;
  11546. if d16 {
  11547. xs = self.d16_channels(f, xs)?;
  11548. }
  11549. for (k, x) in xs.into_iter().enumerate() {
  11550. self.write(inst, Reg::V(reg + k as u8), x, guard);
  11551. }
  11552. return Ok(());
  11553. }
  11554. let r = if typed {
  11555. if *offen || matches!(off, V::Inst(_)) || *offset != 0 {
  11556. return Err("a typed buffer load at an offset");
  11557. }
  11558. if uav {
  11559. self.s.flags |= flags::TYPED_UAV_LOADS;
  11560. }
  11561. let h = self.handle(site, src, false, (10 | u, 0x409))?;
  11562. let index = index.unwrap_or(self.s.m.i32(0));
  11563. self.s.op(
  11564. c,
  11565. "bufferLoad.f32",
  11566. Attr::ReadOnly,
  11567. self.s.t.res_ret,
  11568. 68,
  11569. &[h, index, iu],
  11570. )
  11571. } else {
  11572. let mask = self.s.m.i8((1u8 << count) - 1);
  11573. let align = self.s.m.i32(4);
  11574. match index {
  11575. // A raw buffer (stride 1) read by index: the index is the byte.
  11576. Some(index) if used.is_some_and(|u| u.stride == 1) => {
  11577. let byte = self.s.m.bin(c, Bin::Add, index, off);
  11578. let h = self.handle(site, src, false, (11 | u, 0))?;
  11579. self.s.op(
  11580. c,
  11581. "rawBufferLoad.f32",
  11582. Attr::ReadOnly,
  11583. self.s.t.res_ret,
  11584. 139,
  11585. &[h, byte, iu, mask, align],
  11586. )
  11587. }
  11588. Some(index) => {
  11589. let stride = used.map_or(0, |u| u.stride);
  11590. if stride < 4 || !stride.is_multiple_of(4) {
  11591. return Err("a structured buffer of unknown stride");
  11592. }
  11593. let h = self.handle(site, src, false, (12 | u, stride))?;
  11594. self.s.op(
  11595. c,
  11596. "rawBufferLoad.f32",
  11597. Attr::ReadOnly,
  11598. self.s.t.res_ret,
  11599. 139,
  11600. &[h, index, off, mask, align],
  11601. )
  11602. }
  11603. None => {
  11604. let h = self.handle(site, src, false, (11 | u, 0))?;
  11605. self.s.op(
  11606. c,
  11607. "rawBufferLoad.f32",
  11608. Attr::ReadOnly,
  11609. self.s.t.res_ret,
  11610. 139,
  11611. &[h, off, iu, mask, align],
  11612. )
  11613. }
  11614. }
  11615. };
  11616. let Some(Operand::Vector { reg, .. }) = *data else {
  11617. return Err("a buffer result");
  11618. };
  11619. if d16 {
  11620. // Two f16 channels per VGPR (an odd last high half 0); the low
  11621. // 16 bits of an integer view's (see the stores above).
  11622. let integer = if typed { self.integer_view(src)? } else { None };
  11623. let k16 = self.s.m.i32(16);
  11624. let i32t = self.s.t.i32;
  11625. for k in 0..count.div_ceil(2) {
  11626. let mut x = None;
  11627. for ch in (2 * k..(2 * k + 2).min(count)).rev() {
  11628. let f = self.s.m.extract(c, r, ch);
  11629. let mut h = self
  11630. .s
  11631. .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]);
  11632. if let Some((int, _)) = integer {
  11633. let bits = self.as_int(f);
  11634. let low = self.s.m.i32(0xFFFF);
  11635. let low = self.s.m.bin(c, Bin::And, bits, low);
  11636. h = self.s.m.select(c, int, low, h);
  11637. }
  11638. x = Some(match x {
  11639. Some(hi) => {
  11640. let hi = self.s.m.bin(c, Bin::Shl, hi, k16);
  11641. self.s.m.bin(c, Bin::Or, h, hi)
  11642. }
  11643. None => h,
  11644. });
  11645. }
  11646. self.write(inst, Reg::V(reg + k as u8), x.expect("a channel"), guard);
  11647. }
  11648. return Ok(());
  11649. }
  11650. for k in 0..count {
  11651. let x = self.s.m.extract(c, r, k);
  11652. let x = self.as_int(x);
  11653. self.write(inst, Reg::V(reg + k as u8), x, guard);
  11654. }
  11655. Ok(())
  11656. }
  11657. fn export(&mut self, b: usize, i: usize) -> Result<(), Why> {
  11658. let e = *self
  11659. .exports
  11660. .get(&(b, i))
  11661. .ok_or("an export I/O raising did not see")?;
  11662. if e.compressed {
  11663. return Err("a compressed export");
  11664. }
  11665. let guard = self.guard(b, i)?;
  11666. let mesh = self.s.mesh.is_some();
  11667. let c = self.cur;
  11668. if let Some(g) = guard
  11669. && !mesh
  11670. {
  11671. if !(e.done && self.s.pixel) {
  11672. return Err("a conditional export");
  11673. }
  11674. let t = self.s.m.bool(true);
  11675. let kill = self.s.m.bin(c, Bin::Xor, g, t);
  11676. self.s
  11677. .op(c, "discard", Attr::NoUnwind, self.s.t.void, 82, &[kill]);
  11678. }
  11679. if mesh && e.target == Target::Primitive {
  11680. return self.emit_indices(e, guard);
  11681. }
  11682. let param_row = |usage: Usage, row: u8| match usage {
  11683. // The 2020 compiler leaves a mesh program's first entry zeroed
  11684. // (usage "position"): its row is the one no other entry names.
  11685. Usage::Other(0) if mesh => self.unnamed_row(),
  11686. _ => Some(row),
  11687. };
  11688. // (output element, channel) per exported channel; per-primitive
  11689. // outputs are elements of `prims`.
  11690. let mut stores = Vec::new();
  11691. let primitive = matches!(e.target, Target::PrimitiveParam { .. });
  11692. let outputs = if primitive {
  11693. &self.s.prims
  11694. } else {
  11695. &self.s.outputs
  11696. };
  11697. let by_kind = |kind: u8| outputs.iter().position(|o| o.kind == kind);
  11698. // 16-bit vertex outputs: the halves each dword carries, as (output
  11699. // element, channel, high half) per channel.
  11700. let halves = match e.target {
  11701. Target::Param { usage, row } => {
  11702. param_row(usage, row).and_then(|r| self.half_outputs.get(&r).map(|&h| (r, h)))
  11703. }
  11704. _ => None,
  11705. };
  11706. if let Some((row, (pack2, _))) = halves {
  11707. let packs: Vec<(u8, Option<u8>)> = self
  11708. .half_outputs
  11709. .iter()
  11710. .filter(|(_, h)| h.0)
  11711. .map(|(&r, h)| (r, h.1))
  11712. .collect();
  11713. for ch in 0..4u8 {
  11714. let Some(value) = e.values[usize::from(ch)] else {
  11715. continue;
  11716. };
  11717. for high in [false, true] {
  11718. let h = 2 * ch + u8::from(high);
  11719. let src = if pack2 {
  11720. packed_half(outputs, &packs, row, h)
  11721. } else {
  11722. (!high).then_some((row, ch))
  11723. };
  11724. let found = src.and_then(|(r, c)| {
  11725. outputs.iter().position(|o| {
  11726. o.row == Some(u32::from(r)) && c >= o.col && c < o.col + o.cols
  11727. })
  11728. });
  11729. if let Some(id) = found {
  11730. let col = src.expect("found").1 - outputs[id].col;
  11731. stores.push((id, col, value, Some(high)));
  11732. }
  11733. }
  11734. }
  11735. }
  11736. for ch in 0..4u8 {
  11737. let Some(value) = e.values[usize::from(ch)] else {
  11738. continue;
  11739. };
  11740. if halves.is_some() {
  11741. break;
  11742. }
  11743. let found = match e.target {
  11744. Target::Color(n) => outputs
  11745. .iter()
  11746. .position(|o| o.kind == 16 && o.row == Some(u32::from(n)))
  11747. .map(|id| (id, ch)),
  11748. Target::Position(0) => by_kind(3).map(|id| (id, ch)),
  11749. Target::Depth => match ch {
  11750. 0 => by_kind(17)
  11751. .or(by_kind(18))
  11752. .or(by_kind(19))
  11753. .map(|id| (id, 0)),
  11754. 1 => by_kind(20).map(|id| (id, 0)),
  11755. 2 => by_kind(14).map(|id| (id, 0)),
  11756. _ => None,
  11757. },
  11758. Target::Param { usage, row } | Target::PrimitiveParam { usage, row } => {
  11759. let row = param_row(usage, row);
  11760. outputs
  11761. .iter()
  11762. .position(|o| {
  11763. row.is_some_and(|r| o.row == Some(u32::from(r)))
  11764. && ch >= o.col
  11765. && ch < o.col + o.cols
  11766. })
  11767. .map(|id| (id, ch - outputs[id].col))
  11768. }
  11769. Target::Null | Target::Unread => None,
  11770. Target::Position(n @ 1..=2) => {
  11771. // shortcut: without the misc vector (point size, render
  11772. // target or viewport index) pos1 and pos2 carry the clip
  11773. // then cull distances, in semantic order.
  11774. if outputs.iter().any(|o| matches!(o.kind, 4 | 5)) {
  11775. return Err("render-target or viewport index exports");
  11776. }
  11777. let mut dists: Vec<usize> = (0..outputs.len())
  11778. .filter(|&i| matches!(outputs[i].kind, 6 | 7))
  11779. .collect();
  11780. dists.sort_by_key(|&i| (outputs[i].kind, outputs[i].index));
  11781. let flat: Vec<(usize, u8)> = dists
  11782. .iter()
  11783. .flat_map(|&i| (0..outputs[i].cols).map(move |c| (i, c)))
  11784. .collect();
  11785. // Channels past the distances the signature declares are
  11786. // ones the clipper does not enable (`PA_CL_VS_OUT_CNTL`).
  11787. let k = usize::from(n - 1) * 4 + usize::from(ch);
  11788. flat.get(k).copied()
  11789. }
  11790. Target::Position(_) => return Err("clip, cull or point-size exports"),
  11791. Target::Primitive => return Err("a primitive export"),
  11792. };
  11793. if let Some((id, col)) = found {
  11794. stores.push((id, col, value, None));
  11795. }
  11796. }
  11797. fn elements<'l>(l: &'l mut Lower, primitive: bool) -> &'l mut Vec<SigElement> {
  11798. if primitive {
  11799. &mut l.s.prims
  11800. } else {
  11801. &mut l.s.outputs
  11802. }
  11803. }
  11804. if stores
  11805. .iter()
  11806. .any(|s| s.3.is_none() && elements(self, primitive)[s.0].half)
  11807. {
  11808. return Err("a 16-bit output the stage data does not mark");
  11809. }
  11810. // A mesh lane writes its own vertex or primitive, where it exports.
  11811. let at = if mesh {
  11812. let flat = self.mesh_thread();
  11813. let limit = if let Some(m) = self.s.mesh {
  11814. if primitive {
  11815. m.max_primitives
  11816. } else {
  11817. m.max_vertices
  11818. }
  11819. } else {
  11820. 0
  11821. };
  11822. let threads = self.s.threads.map(|t| t[0]).unwrap_or(u32::MAX);
  11823. let mesh_guard = if limit > 0 && threads > limit {
  11824. let lim = self.s.m.i32(limit);
  11825. let in_bounds = self.s.m.cmp(self.cur, pred::IULT, flat, lim);
  11826. match guard {
  11827. Some(g) => Some(self.s.m.bin(self.cur, Bin::And, g, in_bounds)),
  11828. None => Some(in_bounds),
  11829. }
  11830. } else {
  11831. guard
  11832. };
  11833. self.begin_guarded(mesh_guard)
  11834. } else {
  11835. None
  11836. };
  11837. let (name, opcode) = match (mesh, primitive) {
  11838. (false, _) => ("storeOutput", 5),
  11839. (true, false) => ("storeVertexOutput", 171),
  11840. (true, true) => ("storePrimitiveOutput", 172),
  11841. };
  11842. for (id, col, value, half) in stores {
  11843. let mut x = self.i32_of(value)?;
  11844. if let Some(high) = half {
  11845. // An f16 half, declared a 32-bit float on the host.
  11846. let c = self.cur;
  11847. if high {
  11848. let k16 = self.s.m.i32(16);
  11849. x = self.s.m.bin(c, Bin::LShr, x, k16);
  11850. }
  11851. let f32t = self.s.t.f32;
  11852. let f = self
  11853. .s
  11854. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]);
  11855. x = self.as_int(f);
  11856. }
  11857. let el = &mut elements(self, primitive)[id];
  11858. el.usage |= 1 << col;
  11859. let (suffix, x) = match el.comp {
  11860. 9 if half.is_some() => (".f32", self.as_float(x)),
  11861. 9 => {
  11862. let f = match self.floats.get(&value) {
  11863. Some(&f) => f,
  11864. None => self.as_float(x),
  11865. };
  11866. (".f32", f)
  11867. }
  11868. _ => (".i32", x),
  11869. };
  11870. let mut args = vec![
  11871. self.s.m.i32(id as u32),
  11872. self.s.m.i32(0),
  11873. self.s.m.i8(col),
  11874. x,
  11875. ];
  11876. if mesh {
  11877. args.push(self.mesh_thread());
  11878. }
  11879. let void = self.s.t.void;
  11880. self.s.op(
  11881. self.cur,
  11882. &format!("{name}{suffix}"),
  11883. Attr::NoUnwind,
  11884. void,
  11885. opcode,
  11886. &args,
  11887. );
  11888. }
  11889. self.end_guarded(at, &[]);
  11890. Ok(())
  11891. }
  11892. /// Mesh: `exp prim` as the lane's primitive. Each corner takes ten
  11893. /// bits: a 9-bit vertex index and, above it, its edge flag (bits 9, 19
  11894. /// and 29), which only the console's edge-flag rasterisation reads and
  11895. /// which is no part of the index. Bit 31 culls it (all indices 0: no
  11896. /// area).
  11897. fn emit_indices(&mut self, e: &Export, guard: Option<V>) -> Result<(), Why> {
  11898. let v = e.values[0].ok_or("a primitive export without its indices")?;
  11899. let x = self.i32_of(v)?;
  11900. let flat = self.mesh_thread();
  11901. let guard = if let Some(mesh) = self.s.mesh {
  11902. let threads = self.s.threads.map(|t| t[0]).unwrap_or(u32::MAX);
  11903. if threads > mesh.max_primitives {
  11904. let p = self.s.m.i32(mesh.max_primitives);
  11905. let in_bounds = self.s.m.cmp(self.cur, pred::IULT, flat, p);
  11906. match guard {
  11907. Some(g) => Some(self.s.m.bin(self.cur, Bin::And, g, in_bounds)),
  11908. None => Some(in_bounds),
  11909. }
  11910. } else {
  11911. guard
  11912. }
  11913. } else {
  11914. guard
  11915. };
  11916. let at = self.begin_guarded(guard);
  11917. let c = self.cur;
  11918. let z = self.s.m.i32(0);
  11919. let mut culled = self.s.m.cmp(c, pred::SLT, x, z);
  11920. // A primitive that names a vertex past the declared count, or one
  11921. // no lane writes (lane n writes vertex n alone), is culled too: the
  11922. // host would read a vertex nothing set, at any position.
  11923. let written = self.s.mesh.map(|m| {
  11924. m.max_vertices
  11925. .min(self.s.threads.map_or(u32::MAX, |t| t[0]))
  11926. });
  11927. let mut indices = [z; 3];
  11928. for (k, slot) in indices.iter_mut().enumerate() {
  11929. let (shift, mask) = (self.s.m.i32(10 * k as u32), self.s.m.i32(0x1FF));
  11930. let i = self.s.m.bin(c, Bin::LShr, x, shift);
  11931. let i = self.s.m.bin(c, Bin::And, i, mask);
  11932. if let Some(n) = written {
  11933. let n = self.s.m.i32(n);
  11934. let past = self.s.m.cmp(c, pred::IUGE, i, n);
  11935. culled = self.s.m.bin(c, Bin::Or, culled, past);
  11936. }
  11937. *slot = i;
  11938. }
  11939. let mut args = vec![flat];
  11940. for i in indices {
  11941. args.push(self.s.m.select(c, culled, z, i));
  11942. }
  11943. let void = self.s.t.void;
  11944. self.s
  11945. .op(c, "emitIndices", Attr::NoUnwind, void, 169, &args);
  11946. self.end_guarded(at, &[]);
  11947. Ok(())
  11948. }
  11949. /// The per-vertex arbitrary row no mesh output entry names but one
  11950. /// (the 2020 compiler's zeroed entry).
  11951. fn unnamed_row(&self) -> Option<u8> {
  11952. let StageIo::Ms(ms) = &self.x.native.io else {
  11953. return None;
  11954. };
  11955. let named = |r: u32| {
  11956. ms.outputs
  11957. .iter()
  11958. .any(|o| o.param & 0x80 == 0 && o.usage != Usage::Other(0) && u32::from(o.row) == r)
  11959. };
  11960. let free: std::collections::BTreeSet<u32> = self
  11961. .s
  11962. .outputs
  11963. .iter()
  11964. .filter(|o| o.kind == 0)
  11965. .filter_map(|o| o.row)
  11966. .filter(|&r| !named(r))
  11967. .collect();
  11968. match free.into_iter().collect::<Vec<_>>()[..] {
  11969. [r] => u8::try_from(r).ok(),
  11970. _ => None,
  11971. }
  11972. }
  11973. fn exit(&mut self, b: usize) -> Result<(), Stop> {
  11974. let offset = self.x.p.blocks[b]
  11975. .insts
  11976. .last()
  11977. .map_or(self.x.p.blocks[b].offset, |i| i.machine.offset);
  11978. let term = match self.x.st.exits[b] {
  11979. LaneExit::Jump(t) if self.counters.contains_key(&t) && self.rpo[t] <= self.rpo[b] => {
  11980. let ok = self.count_iteration(t, pred::IULT);
  11981. let abort = self.abort_block();
  11982. Term::CondBr(ok, self.block[t].expect("reachable"), abort)
  11983. }
  11984. LaneExit::Jump(t) => {
  11985. self.enter_loop(b, t, self.cur);
  11986. Term::Br(self.block[t].expect("reachable"))
  11987. }
  11988. LaneExit::Branch {
  11989. when,
  11990. taken,
  11991. not_taken,
  11992. } => {
  11993. // A negated condition branches the other way round.
  11994. let (cond, taken, not_taken) = match self.x.st.bools.node(when) {
  11995. _ if self.x.st.wide.contains(&b) => {
  11996. let c = self.wave_wide(b, when).map_err(|w| unsupported(offset, w))?;
  11997. (c, taken, not_taken)
  11998. }
  11999. Some((atom, Bool::TRUE, Bool::FALSE)) => {
  12000. let a = self
  12001. .atom(atom, self.cur)
  12002. .map_err(|w| unsupported(offset, w))?;
  12003. (a, not_taken, taken)
  12004. }
  12005. _ => {
  12006. let c = self
  12007. .boolean(when, self.cur)
  12008. .map_err(|w| unsupported(offset, w))?;
  12009. (c, taken, not_taken)
  12010. }
  12011. };
  12012. // A back edge is taken only below the iteration limit.
  12013. let back =
  12014. |l: &Self, to: usize| l.counters.contains_key(&to) && l.rpo[to] <= l.rpo[b];
  12015. // (No `xor` of a compare: a loop exit testing one hung the
  12016. // AMD driver.)
  12017. let cond = if back(self, taken) {
  12018. let ok = self.count_iteration(taken, pred::IULT);
  12019. self.s.m.bin(self.cur, Bin::And, cond, ok)
  12020. } else if back(self, not_taken) {
  12021. let stop = self.count_iteration(not_taken, pred::IUGE);
  12022. self.s.m.bin(self.cur, Bin::Or, cond, stop)
  12023. } else {
  12024. cond
  12025. };
  12026. // Critical edges get a block of their own, so loops have
  12027. // dedicated exits and preheaders as DXC emits them.
  12028. let (t, f) = (self.edge(b, taken), self.edge(b, not_taken));
  12029. for (to, via) in [(taken, t), (not_taken, f)] {
  12030. if !back(self, to) {
  12031. // From an edge block, or from here.
  12032. let from = if Some(via) == self.block[to] {
  12033. self.cur
  12034. } else {
  12035. via
  12036. };
  12037. self.enter_loop(b, to, from);
  12038. }
  12039. }
  12040. Term::CondBr(cond, t, f)
  12041. }
  12042. LaneExit::End => {
  12043. if self.s.pixel && !self.exported[b] && !self.has_done_export(b) {
  12044. // A lane leaving without its final export was killed.
  12045. let t = self.s.m.bool(true);
  12046. self.s
  12047. .op(self.cur, "discard", Attr::NoUnwind, self.s.t.void, 82, &[t]);
  12048. }
  12049. Term::Ret
  12050. }
  12051. LaneExit::Indirect => return Err(unsupported(offset, "an indirect jump")),
  12052. };
  12053. let _ = Exit::End;
  12054. self.s.m.terminate(self.cur, term);
  12055. Ok(())
  12056. }
  12057. /// A forward edge into loop header `to` (from DXIL block `via`) starts
  12058. /// its count at 0.
  12059. fn enter_loop(&mut self, _from: usize, to: usize, via: usize) {
  12060. if let Some((_, incoming)) = self.counters.get_mut(&to) {
  12061. let z = self.s.m.i32(0);
  12062. incoming.push((z, via));
  12063. }
  12064. }
  12065. /// A back edge to header `to` (a back edge keeps its block, no
  12066. /// critical-edge block): the count goes up; the result compares it with
  12067. /// [`LOOP_LIMIT`] by `p` (below: go on; at or above: stop).
  12068. fn count_iteration(&mut self, to: usize, p: u8) -> V {
  12069. let c = self.cur;
  12070. let (phi, _) = self.counters[&to];
  12071. let one = self.s.m.i32(1);
  12072. let next = self.s.m.bin(c, Bin::Add, phi, one);
  12073. self.s.m.tag(phi, Tag::Counter);
  12074. self.s.m.tag(next, Tag::Counter);
  12075. // Per stage unless the switch names one: a loop that never meets its
  12076. // exit (a count read from a buffer the host has not got yet, say)
  12077. // runs to the limit in every lane. A million iterations a pixel
  12078. // hung the GPU for seconds a draw until Windows reset it
  12079. // (PS_Textured_Eight, 2026-11-24, run 12).
  12080. // shortcut: a pixel loop past 128 iterations, a vertex or mesh loop
  12081. // past 256 or a compute loop past 4,096 is cut short. (They were
  12082. // 1,024, 4,096 and 65,536: the opening cutscene then lost the card
  12083. // 14-25 frames in, in a minimap or shadow mesh draw; with every
  12084. // loop cut at 64 it ran 90 frames. Raise them again once shaders
  12085. // stop reading data that is not there yet.)
  12086. let limit = match super::loop_limit() {
  12087. LOOP_LIMIT if self.s.pixel => 1 << 7,
  12088. LOOP_LIMIT if self.s.mesh.is_some() || self.s.threads.is_none() => 1 << 8,
  12089. LOOP_LIMIT => 1 << 12,
  12090. named => named,
  12091. };
  12092. let limit = self.s.m.i32(limit);
  12093. self.counters
  12094. .get_mut(&to)
  12095. .expect("header")
  12096. .1
  12097. .push((next, c));
  12098. let over = self.s.m.cmp(c, p, next, limit);
  12099. self.s.m.tag(over, Tag::Counter);
  12100. over
  12101. }
  12102. /// The block a lane stopped by [`LOOP_LIMIT`] leaves through.
  12103. fn abort_block(&mut self) -> usize {
  12104. if let Some(a) = self.abort {
  12105. return a;
  12106. }
  12107. let a = self.s.m.new_block();
  12108. if self.s.pixel {
  12109. let t = self.s.m.bool(true);
  12110. self.s
  12111. .op(a, "discard", Attr::NoUnwind, self.s.t.void, 82, &[t]);
  12112. }
  12113. self.s.m.terminate(a, Term::Ret);
  12114. self.abort = Some(a);
  12115. a
  12116. }
  12117. /// The DXIL block a branch from IR block `from` to `to` goes to.
  12118. fn edge(&mut self, from: usize, to: usize) -> usize {
  12119. let target = self.block[to].expect("reachable");
  12120. let preds = self.x.p.blocks[to]
  12121. .preds
  12122. .iter()
  12123. .filter(|&&q| self.block[q].is_some())
  12124. .count();
  12125. // Back edges stay as they are: the exiting block is the latch.
  12126. if preds < 2 || self.rpo[to] <= self.rpo[from] {
  12127. return target;
  12128. }
  12129. let e = self.s.m.new_block();
  12130. self.s.m.terminate(e, Term::Br(target));
  12131. self.edges.insert((from, to), e);
  12132. e
  12133. }
  12134. fn fill_phis(&mut self) -> Result<(), Stop> {
  12135. let p = self.x.p;
  12136. // Lane-mask joins first (what an edge brings may ask for more joins,
  12137. // of masks and of numbers): each edge's mask as the structure
  12138. // tracked it, a constant or a scalar-built one included.
  12139. let st = self.x.st;
  12140. while let Some((v, b, i)) = self.pending_masks.pop() {
  12141. let phi = &p.blocks[b].phis[i];
  12142. let offset = p.blocks[b].offset;
  12143. let args = st
  12144. .phi_masks
  12145. .get(&phi.value)
  12146. .ok_or_else(|| unsupported(offset, "a lane-mask join of an untracked mask"))?;
  12147. let mut incoming = Vec::new();
  12148. for (n, &q) in p.blocks[b].preds.iter().enumerate() {
  12149. let Some(qb) = self.tail[q] else { continue };
  12150. let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb);
  12151. let x = self.boolean(args[n], qb).map_err(|w| unsupported(offset, w))?;
  12152. incoming.push((x, qb));
  12153. }
  12154. self.s.m.set_phi(v, incoming);
  12155. }
  12156. // A join that only another join reads is read wherever that one is. Left
  12157. // unmarked, a value without a DXIL form coming into it became zero without a
  12158. // word (the looked-up tint of the material resolve programs, whose size
  12159. // computation had no value, was zero in every lane that way).
  12160. // shortcut: only with `VICTORY_STRICT_JOINS` set (the offline pack
  12161. // listing sets it to count them): 40 programs that translate today
  12162. // stop by name with it (vehicle paint pixel shaders at "the first
  12163. // half of an interpolation", foliage mesh shaders); until those are
  12164. // lowered they keep drawing with that zero.
  12165. static STRICT: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  12166. let strict = *STRICT.get_or_init(|| std::env::var_os("VICTORY_STRICT_JOINS").is_some());
  12167. let mut work: Vec<Value> = if strict {
  12168. self.read_phis.iter().copied().collect()
  12169. } else {
  12170. Vec::new()
  12171. };
  12172. while let Some(v) = work.pop() {
  12173. let Some(&(b, i)) = self.phi_at.get(&v) else {
  12174. continue;
  12175. };
  12176. for &a in &p.blocks[b].phis[i].args {
  12177. if self.phi_at.contains_key(&a) && self.read_phis.insert(a) {
  12178. work.push(a);
  12179. }
  12180. }
  12181. }
  12182. for (v, b, i) in std::mem::take(&mut self.data_phis) {
  12183. let phi = &p.blocks[b].phis[i];
  12184. let bit = phi.reg == Reg::Scc;
  12185. // A join of numbers with dead registers (`dead`): the paths that bring those
  12186. // never read the result, so they bring zero. Not for a join that is itself a
  12187. // lane mask (a ballot gives that one as data).
  12188. let st = self.x.st;
  12189. let numbers = !bit
  12190. && !st.masks.contains_key(&phi.value)
  12191. && !st.highs.contains_key(&phi.value)
  12192. && phi
  12193. .args
  12194. .iter()
  12195. .any(|a| matches!(self.vals.get(a), Some(Val::I32(_))));
  12196. let mut incoming = Vec::new();
  12197. for (n, &q) in p.blocks[b].preds.iter().enumerate() {
  12198. let Some(qb) = self.tail[q] else { continue };
  12199. let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb);
  12200. let arg = phi.args[n];
  12201. if self.read_phis.contains(&phi.value) && !self.vals.contains_key(&arg) {
  12202. let _ = self.lazy_barycentric(arg);
  12203. // A root parameter nothing read before the join (user
  12204. // data is loaded on first use, in the entry block).
  12205. if !self.vals.contains_key(&arg)
  12206. && let Some(&(param, dword)) = self.params.get(&arg)
  12207. {
  12208. let val = self.user(param, dword);
  12209. self.vals.insert(arg, val);
  12210. }
  12211. }
  12212. let x = match (self.vals.get(&arg).copied(), bit) {
  12213. (Some(Val::I32(x)), false) | (Some(Val::Bit(x)), true) => x,
  12214. (Some(Val::Missing(_)) | None, false)
  12215. if numbers && self.dead(arg, &mut Vec::new()) =>
  12216. {
  12217. self.s.m.i32(0)
  12218. }
  12219. // A lane mask joined with numbers (a traversal that keeps its lanes' masks on
  12220. // a stack with its node numbers): the mask comes as the number it is, the
  12221. // ballot of its lanes where it is written.
  12222. (Some(Val::Missing(_)) | None, false)
  12223. if self.read_phis.contains(&phi.value)
  12224. && self.mask_data == MaskData::Console
  12225. && (st.masks.contains_key(&arg) || st.highs.contains_key(&arg)) =>
  12226. {
  12227. match self.mask_dword(arg) {
  12228. Ok(x) => x,
  12229. Err(why) => return Err(Stop::Retry(phi.value, why)),
  12230. }
  12231. }
  12232. // SCC of a mask operation ("some lane is left") joined with a scalar test:
  12233. // the compiler branches around code that sets SCC and tests SCC after it,
  12234. // the skip bringing "no lane" along. As data it is "some lane of the wave
  12235. // has the bit" - right only if the wave took that skip together, as the
  12236. // console does: a lane that skipped alone would bring "some lane" where the
  12237. // console has the skipped code's SCC. So the branch must be one the wave
  12238. // takes together; else its region is named for `emit`'s retry to widen it.
  12239. (Some(Val::Missing(_)) | None, true)
  12240. if self.read_phis.contains(&phi.value)
  12241. && self.mask_data == MaskData::Console
  12242. && st.scc_some.contains_key(&arg) =>
  12243. {
  12244. let per_lane = !st.wide.contains(&q)
  12245. && matches!(st.exits[q], LaneExit::Branch { when, .. }
  12246. if !st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_))));
  12247. if per_lane {
  12248. for &other in p.blocks[b].preds.iter().filter(|&&o| o != q) {
  12249. need(other);
  12250. }
  12251. return Err(Stop::Retry(phi.value, LANE_MASK));
  12252. }
  12253. match self.scc_some(arg) {
  12254. Ok(x) => x,
  12255. Err(why) => return Err(Stop::Retry(phi.value, why)),
  12256. }
  12257. }
  12258. (Some(Val::Bit(_)), false) if self.read_phis.contains(&phi.value) => {
  12259. return Err(Stop::Retry(phi.value, "an SCC joined with SGPR values"));
  12260. }
  12261. (Some(Val::Missing(why)), _) if self.read_phis.contains(&phi.value) => {
  12262. return Err(Stop::Retry(phi.value, why));
  12263. }
  12264. _ if self.read_phis.contains(&phi.value) => {
  12265. return Err(Stop::Retry(phi.value, "a join of mismatched values"));
  12266. }
  12267. _ if bit => self.s.m.bool(false),
  12268. _ => self.s.m.i32(0),
  12269. };
  12270. incoming.push((x, qb));
  12271. }
  12272. self.s.m.set_phi(v, incoming);
  12273. }
  12274. for (phi, incoming) in std::mem::take(&mut self.counters).into_values() {
  12275. self.s.m.set_phi(phi, incoming);
  12276. }
  12277. Ok(())
  12278. }
  12279. }
  12280. /// The DXIL interpolation mode of a kind of barycentrics (none for the
  12281. /// pull model).
  12282. fn interp_mode(kind: Barycentric) -> Option<u8> {
  12283. Some(match kind {
  12284. Barycentric::PerspectiveCenter => 2,
  12285. Barycentric::PerspectiveCentroid => 3,
  12286. Barycentric::PerspectiveSample => 6,
  12287. Barycentric::LinearCenter => 4,
  12288. Barycentric::LinearCentroid => 5,
  12289. Barycentric::LinearSample => 7,
  12290. Barycentric::PerspectivePullModel => return None,
  12291. })
  12292. }
  12293. #[cfg(test)]
  12294. mod tests {
  12295. use super::{Lowered, Numeric, Parts, buffer_format, half_shift, lower};
  12296. use crate::native::{
  12297. ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource,
  12298. };
  12299. use crate::{io, ir, resource, structure};
  12300. const S_ENDPGM: u32 = 0xBF81_0000;
  12301. #[test]
  12302. fn packed_pixel_inputs_find_their_second_row() {
  12303. use super::super::container::SigElement;
  12304. use super::half_input_partners;
  12305. use crate::native::{PsInput, Usage};
  12306. let entry = |row, row2, pack2| PsInput {
  12307. usage: Usage::Generic,
  12308. row,
  12309. mask: 0xF,
  12310. attr: row,
  12311. flat: false,
  12312. fp16: true,
  12313. pack2,
  12314. row2,
  12315. };
  12316. let element = |row| SigElement {
  12317. name: "TEXCOORD".into(),
  12318. index: row,
  12319. kind: 0,
  12320. comp: 9,
  12321. interp: 2,
  12322. row: Some(row),
  12323. col: 0,
  12324. cols: 4,
  12325. usage: 0,
  12326. half: true,
  12327. };
  12328. // Rows 0 and 3 pack and leave their second row out; 5 names its
  12329. // own (6). Unnamed 16-bit rows: 1, 4, 6, 7.
  12330. let io = StageIo::Ps {
  12331. inputs: vec![entry(0, 0, true), entry(3, 3, true), entry(5, 6, true)],
  12332. input_addr: 0,
  12333. db_shader_control: 0,
  12334. patches: vec![],
  12335. };
  12336. let sig: Vec<_> = [0, 1, 3, 4, 5, 6, 7].map(element).into();
  12337. let p = half_input_partners(&io, &sig);
  12338. assert_eq!(p.get(&0), Some(&1));
  12339. assert_eq!(p.get(&3), Some(&4));
  12340. assert_eq!(p.get(&5), None);
  12341. }
  12342. /// The packed pedestrian layouts of the title: an element
  12343. /// behind another one in its register follows in the first parameter
  12344. /// with a dword left, and is not a half of its register's row.
  12345. #[test]
  12346. fn packed_elements_behind_another_take_the_first_free_dword() {
  12347. use super::super::container::SigElement;
  12348. use super::packed_half;
  12349. let element = |index, row, col, cols| SigElement {
  12350. name: "TEXCOORD".into(),
  12351. index,
  12352. kind: 0,
  12353. comp: 9,
  12354. interp: 2,
  12355. row: Some(row),
  12356. col,
  12357. cols,
  12358. usage: 0,
  12359. half: true,
  12360. };
  12361. // MS_VS_PedTransformPreSkinD_Packed 005fe88ec1bdc0c7 and its pixel
  12362. // shader 93667197d3d05e1c: TEXCOORD6 is one value at register 4
  12363. // column 3; parameter 3 (rows 6 and 7) carries it in dword 3.
  12364. let sig = vec![
  12365. element(1, 2, 0, 4),
  12366. element(2, 3, 0, 4),
  12367. element(4, 4, 0, 3),
  12368. element(6, 4, 3, 1),
  12369. element(3, 5, 0, 4),
  12370. element(5, 6, 0, 4),
  12371. element(7, 7, 0, 2),
  12372. element(9, 9, 0, 3),
  12373. element(11, 10, 0, 3),
  12374. element(15, 12, 0, 4),
  12375. ];
  12376. let packs = [
  12377. (2, Some(3)),
  12378. (4, Some(5)),
  12379. (6, Some(7)),
  12380. (9, Some(10)),
  12381. (12, None),
  12382. ];
  12383. let at = |a, h| packed_half(&sig, &packs, a, h);
  12384. // Parameter 2: TEXCOORD4's three values, a zero half, TEXCOORD3.
  12385. assert_eq!(at(4, 2), Some((4, 2)));
  12386. assert_eq!(at(4, 3), None);
  12387. assert_eq!(at(4, 4), Some((5, 0)));
  12388. assert_eq!(at(4, 7), Some((5, 3)));
  12389. // Parameter 3: TEXCOORD5, TEXCOORD7, then TEXCOORD6 alone.
  12390. assert_eq!(at(6, 3), Some((6, 3)));
  12391. assert_eq!(at(6, 5), Some((7, 1)));
  12392. assert_eq!(at(6, 6), Some((4, 3)));
  12393. assert_eq!(at(6, 7), None);
  12394. // Parameters without such an element are as before.
  12395. assert_eq!(at(9, 3), None);
  12396. assert_eq!(at(9, 4), Some((10, 0)));
  12397. assert_eq!(at(12, 3), Some((12, 3)));
  12398. assert_eq!(at(12, 4), None);
  12399. // The common layout (29805d23a495cdf8): TEXCOORD7 is two values at
  12400. // register 1 columns 2-3; parameter 0 is TEXCOORD0, TEXCOORD1,
  12401. // TEXCOORD7.
  12402. let sig = vec![
  12403. element(0, 1, 0, 2),
  12404. element(7, 1, 2, 2),
  12405. element(1, 2, 0, 4),
  12406. element(2, 3, 0, 4),
  12407. element(4, 4, 0, 3),
  12408. ];
  12409. let packs = [(3, Some(4)), (1, Some(2))];
  12410. let at = |a, h| packed_half(&sig, &packs, a, h);
  12411. assert_eq!(at(1, 1), Some((1, 1)));
  12412. assert_eq!(at(1, 2), Some((2, 0)));
  12413. assert_eq!(at(1, 5), Some((2, 3)));
  12414. assert_eq!(at(1, 6), Some((1, 2)));
  12415. assert_eq!(at(1, 7), Some((1, 3)));
  12416. assert_eq!(at(3, 6), Some((4, 2)));
  12417. assert_eq!(at(3, 7), None);
  12418. // A row no element holds gives nothing, as before.
  12419. assert_eq!(packed_half(&sig, &[(8, None)], 8, 0), None);
  12420. }
  12421. /// Whether a synthetic compute program translates with these input registers.
  12422. fn lowers(words: &[u32], rsrc2: u32) -> Result<(), crate::ShaderError> {
  12423. let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
  12424. let native = NativeProgram {
  12425. stage: HwStage::Cs,
  12426. wave64: false,
  12427. vgprs: 256,
  12428. layout: vec![],
  12429. used: vec![],
  12430. io: StageIo::Cs(ComputeIo {
  12431. rsrc2,
  12432. threads: [1, 1, 1],
  12433. }),
  12434. code,
  12435. };
  12436. let p = ir::build(&native.code, false, 256).unwrap();
  12437. let st = structure::structure(&p).unwrap();
  12438. let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
  12439. let io = io::raise(&p, &native).unwrap();
  12440. lower(&Parts {
  12441. native: &native,
  12442. p: &p,
  12443. st: &st,
  12444. io: &io,
  12445. res: &res,
  12446. inputs: vec![],
  12447. outputs: vec![],
  12448. prims: vec![],
  12449. mesh_stride: 0,
  12450. })
  12451. .map(|_| ())
  12452. }
  12453. /// Lowers a compute program with the root parameters `layout` (in user
  12454. /// SGPRs from s0 on) and the used resources `used`.
  12455. fn lower_with(
  12456. words: &[u32],
  12457. layout: Vec<RootParam>,
  12458. used: Vec<UsedResource>,
  12459. ) -> Result<Lowered, crate::ShaderError> {
  12460. lower_wave(words, layout, used, false)
  12461. }
  12462. /// [`lower_with`] in wave64 if `wave64`.
  12463. fn lower_wave(
  12464. words: &[u32],
  12465. layout: Vec<RootParam>,
  12466. used: Vec<UsedResource>,
  12467. wave64: bool,
  12468. ) -> Result<Lowered, crate::ShaderError> {
  12469. let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
  12470. let sgprs: u32 = layout.iter().map(|p| p.sgprs).sum();
  12471. let native = NativeProgram {
  12472. stage: HwStage::Cs,
  12473. wave64,
  12474. vgprs: 256,
  12475. layout,
  12476. used,
  12477. io: StageIo::Cs(ComputeIo {
  12478. // The layout's user SGPRs (at least two), 512 bytes of LDS.
  12479. rsrc2: 1 << 15 | sgprs.max(2) << 1,
  12480. threads: [1, 1, 1],
  12481. }),
  12482. code,
  12483. };
  12484. let p = ir::build(&native.code, wave64, 256).unwrap();
  12485. let st = structure::structure(&p).unwrap();
  12486. let res = resource::track(&p, &native.layout, native.stage, Some(&st))?;
  12487. let io = io::raise(&p, &native).unwrap();
  12488. lower(&Parts {
  12489. native: &native,
  12490. p: &p,
  12491. st: &st,
  12492. io: &io,
  12493. res: &res,
  12494. inputs: vec![],
  12495. outputs: vec![],
  12496. prims: vec![],
  12497. mesh_stride: 0,
  12498. })
  12499. }
  12500. /// Root parameter `slot` in user SGPRs from `user_data` on.
  12501. fn root(root: RootType, user_data: u8, slot: u8) -> RootParam {
  12502. RootParam {
  12503. root,
  12504. table_offset_dwords: 0,
  12505. sgprs: if root == RootType::Descriptor { 2 } else { 1 },
  12506. base_register: 0,
  12507. user_data,
  12508. slot,
  12509. }
  12510. }
  12511. /// Lowers a one-thread compute program that copies four root constants
  12512. /// (s0..s3) into v1..v4, runs `body`, and stores v0 to a raw buffer from a
  12513. /// descriptor table, so the vector instructions in `body` have an effect.
  12514. fn lowers_valu(body: &[u32]) -> Result<(), crate::ShaderError> {
  12515. let mut words = vec![
  12516. 0xBE85_0380, // s_mov_b32 s5, 0
  12517. 0xF408_0202, // s_load_dwordx4 s[8:11], s[4:5], 0
  12518. 0xFA00_0000,
  12519. ];
  12520. // v_mov_b32 v1..v4, s0..s3
  12521. words.extend((0..4u32).map(|i| 0x7E00_0200 | (i + 1) << 17 | i));
  12522. words.extend_from_slice(body);
  12523. words.extend_from_slice(&[
  12524. 0xE070_0000, // buffer_store_dword v0, off, s[8:11], 0
  12525. 0x8002_0000,
  12526. S_ENDPGM,
  12527. ]);
  12528. let constants = RootParam {
  12529. sgprs: 4,
  12530. ..root(RootType::Constants, 0, 0)
  12531. };
  12532. let buffer = UsedResource {
  12533. kind: ResourceType::Uav,
  12534. root: RootType::Table,
  12535. table_offset_dwords: 0,
  12536. lower_bound: 0,
  12537. stride: 0,
  12538. dwords: 4,
  12539. user_data: 4,
  12540. slot: 1,
  12541. };
  12542. lower_with(
  12543. &words,
  12544. vec![constants, root(RootType::Table, 4, 1)],
  12545. vec![buffer],
  12546. )
  12547. .map(|_| ())
  12548. }
  12549. #[test]
  12550. fn the_24_bit_multiplies_lower_both_halves() {
  12551. // VOP2 `op v0, v1, v2`: v_mul_i32_i24 and v_mul_u32_u24 (the low
  12552. // dword) and v_mul_hi_i32_i24 and v_mul_hi_u32_u24 (the high one).
  12553. for op in [0x09u32, 0x0A, 0x0B, 0x0C] {
  12554. let word = op << 25 | 2 << 9 | 0x101;
  12555. lowers_valu(&[word]).unwrap_or_else(|e| panic!("VOP2 {op:#x}: {e}"));
  12556. }
  12557. }
  12558. #[test]
  12559. fn buffer_cache_invalidations_lower_as_no_ops() {
  12560. // MUBUF opcode 0x071/0x072 with no data operand: the title asks the
  12561. // host to invalidate its cached view of a buffer.
  12562. assert!(lowers(&[0xE1C4_0000, 0, S_ENDPGM], 0).is_ok(), "buffer_gl0_inv");
  12563. assert!(lowers(&[0xE1C8_0000, 0, S_ENDPGM], 0).is_ok(), "buffer_gl1_inv");
  12564. }
  12565. #[test]
  12566. fn sums_of_absolute_differences_lower() {
  12567. // VOP3 `op v0, v1, v2, v3`: v_sad_u8, v_sad_hi_u8, v_sad_u16,
  12568. // v_sad_u32 and v_msad_u8.
  12569. for op in [0x15Au32, 0x15B, 0x15C, 0x15D, 0x171] {
  12570. let words = [0xD400_0000 | op << 16, 0x101 | 0x102 << 9 | 0x103 << 18];
  12571. lowers_valu(&words).unwrap_or_else(|e| panic!("VOP3 {op:#x}: {e}"));
  12572. }
  12573. }
  12574. #[test]
  12575. fn a_scalar_carry_chain_reaches_the_select() {
  12576. // The high dword of a 64-bit add or subtract, then a select on the
  12577. // carry (borrow) the high half leaves in SCC, and a branch on it
  12578. // (only code with an effect needs its operands).
  12579. let add = [
  12580. 0xBE80_03C1, // s_mov_b32 s0, -1
  12581. 0xBE81_0380, // s_mov_b32 s1, 0
  12582. 0x8000_8100, // s_add_u32 s0, s0, 1
  12583. 0x8201_8001, // s_addc_u32 s1, s1, 0
  12584. 0x8502_0001, // s_cselect_b32 s2, s1, s0
  12585. 0xBF07_8002, // s_cmp_lg_u32 s2, 0
  12586. 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm
  12587. 0xBE83_0380, // s_mov_b32 s3, 0
  12588. S_ENDPGM,
  12589. ];
  12590. let sub = [
  12591. 0xBE80_0380, // s_mov_b32 s0, 0
  12592. 0xBE81_0380, // s_mov_b32 s1, 0
  12593. 0x8080_8100, // s_sub_u32 s0, s0, 1
  12594. 0x8281_8001, // s_subb_u32 s1, s1, 0
  12595. 0x8502_0001, // s_cselect_b32 s2, s1, s0
  12596. 0xBF07_8002, // s_cmp_lg_u32 s2, 0
  12597. 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm
  12598. 0xBE83_0380, // s_mov_b32 s3, 0
  12599. S_ENDPGM,
  12600. ];
  12601. for words in [add, sub] {
  12602. lowers(&words, 0).unwrap();
  12603. }
  12604. }
  12605. fn perm_features(selector: u32) -> u64 {
  12606. // Synthetic compute shader:
  12607. // v0 is the thread ID and can supply a dynamic selector.
  12608. // Store the result in LDS to keep the permutation live.
  12609. let words = [
  12610. 0x7E02_02FFu32,
  12611. 0x817F_34AB,
  12612. 0x7E04_02FF,
  12613. 0xFE01_56CD,
  12614. 0xD744_0003,
  12615. 257 | (258 << 9) | (selector << 18),
  12616. 0x3408_0082,
  12617. 0xD834_0000,
  12618. 0x0000_0304,
  12619. S_ENDPGM,
  12620. ];
  12621. let code: Vec<u8> = words.iter()
  12622. .flat_map(|w| w.to_le_bytes())
  12623. .collect();
  12624. let native = NativeProgram {
  12625. stage: HwStage::Cs,
  12626. wave64: false,
  12627. vgprs: 256,
  12628. layout: vec![],
  12629. used: vec![],
  12630. io: StageIo::Cs(ComputeIo {
  12631. rsrc2: 1 << 15,
  12632. threads: [64, 1, 1],
  12633. }),
  12634. code,
  12635. };
  12636. let p = ir::build(&native.code, false, 256).unwrap();
  12637. assert!(p.blocks.iter()
  12638. .flat_map(|b| &b.insts)
  12639. .any(|i| i.name() == "v_perm_b32"));
  12640. let st = structure::structure(&p).unwrap();
  12641. let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
  12642. let io = io::raise(&p, &native).unwrap();
  12643. let emitted = lower(&Parts {
  12644. native: &native,
  12645. p: &p,
  12646. st: &st,
  12647. io: &io,
  12648. res: &res,
  12649. inputs: vec![],
  12650. outputs: vec![],
  12651. prims: vec![],
  12652. mesh_stride: 0,
  12653. }).unwrap();
  12654. let container =
  12655. crate::Container::parse(&emitted.dxil).unwrap();
  12656. let features =
  12657. container.part(crate::FourCC::SFI0).unwrap();
  12658. u64::from_le_bytes(features.data.try_into().unwrap())
  12659. }
  12660. #[test]
  12661. fn perm_constant_selector_needs_no_int64() {
  12662. assert_eq!(perm_features(128) & 0x8000, 0);
  12663. }
  12664. #[test]
  12665. fn perm_dynamic_selector_needs_no_int64() {
  12666. assert_eq!(
  12667. perm_features(256) & 0x8000,
  12668. 0,
  12669. "dynamic v_perm_b32 must not require INT64"
  12670. );
  12671. }
  12672. #[test]
  12673. fn a_descriptor_selected_by_scc_picks_its_heap_index() {
  12674. // Two buffer descriptors loaded from the table at s0, one picked by
  12675. // a root constant (s1) with s_cselect_b64 per half, and loaded
  12676. // through by index and stored to LDS so the load is needed.
  12677. let words = [
  12678. 0xBE84_0300, // s_mov_b32 s4, s0
  12679. 0xBE85_0380, // s_mov_b32 s5, 0
  12680. 0xF408_0202,
  12681. 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null
  12682. 0xF408_0302,
  12683. 0xFA00_0010, // s_load_dwordx4 s[12:15], s[4:5], 0x10
  12684. 0xBF06_8001, // s_cmp_eq_u32 s1, 0
  12685. 0x8590_0C08, // s_cselect_b64 s[16:17], s[8:9], s[12:13]
  12686. 0x8592_0E0A, // s_cselect_b64 s[18:19], s[10:11], s[14:15]
  12687. 0xE030_2000,
  12688. 0x8004_0100, // buffer_load_dword v1, v0, s[16:19], 0 idxen
  12689. 0xD834_0000,
  12690. 0x0000_0100, // ds_write_b32 v0, v1
  12691. S_ENDPGM,
  12692. ];
  12693. let layout = || vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)];
  12694. // Both are structured buffers of dwords in the table's range.
  12695. let used = || {
  12696. vec![UsedResource {
  12697. kind: ResourceType::Srv,
  12698. root: RootType::Table,
  12699. table_offset_dwords: 0,
  12700. lower_bound: 0,
  12701. stride: 4,
  12702. dwords: 4,
  12703. user_data: 0,
  12704. slot: 0,
  12705. }]
  12706. };
  12707. lower_with(&words, layout(), used()).unwrap();
  12708. }
  12709. /// Tables of 2D textures at s0 and samplers at s1.
  12710. fn texture_tables() -> (Vec<RootParam>, Vec<UsedResource>) {
  12711. let range = |kind, user_data, slot| UsedResource {
  12712. kind,
  12713. root: RootType::Table,
  12714. table_offset_dwords: 0,
  12715. lower_bound: 0,
  12716. stride: 0,
  12717. dwords: if kind == ResourceType::Sampler { 4 } else { 8 },
  12718. user_data,
  12719. slot,
  12720. };
  12721. (
  12722. vec![root(RootType::Table, 0, 0), root(RootType::Table, 1, 1)],
  12723. vec![
  12724. range(ResourceType::Srv, 0, 0),
  12725. range(ResourceType::Sampler, 1, 1),
  12726. ],
  12727. )
  12728. }
  12729. #[test]
  12730. fn waterfall_loops_over_per_lane_descriptors_sample_with_each_lanes_own() {
  12731. use crate::resource::tests::{
  12732. WATERFALL_FETCHED_WAVE32, WATERFALL_FETCHED_WAVE64, WATERFALL_PICKED_WAVE32,
  12733. };
  12734. for (words, wave64) in [
  12735. (WATERFALL_FETCHED_WAVE32, false),
  12736. (WATERFALL_FETCHED_WAVE64, true),
  12737. (WATERFALL_PICKED_WAVE32, false),
  12738. ] {
  12739. let (layout, used) = texture_tables();
  12740. let l = lower_wave(words, layout, used, wave64).unwrap();
  12741. // The loop's reads of the first lane became each lane's own
  12742. // dwords: no wave operation is left.
  12743. assert_eq!(l.nonuniform_handles, 1);
  12744. assert!(!l.wave_ops);
  12745. }
  12746. }
  12747. /// [`texture_tables`] with a raw buffer UAV at dword 16 of the first.
  12748. pub(crate) fn texture_and_uav_tables() -> (Vec<RootParam>, Vec<UsedResource>) {
  12749. let (layout, mut used) = texture_tables();
  12750. used.push(UsedResource {
  12751. kind: ResourceType::Uav,
  12752. root: RootType::Table,
  12753. table_offset_dwords: 16,
  12754. lower_bound: 0,
  12755. stride: 0,
  12756. dwords: 4,
  12757. user_data: 0,
  12758. slot: 0,
  12759. });
  12760. (layout, used)
  12761. }
  12762. #[test]
  12763. fn waterfall_loops_over_descriptors_joined_per_lane_sample_with_each_lanes_own() {
  12764. use crate::resource::tests::{WATERFALL_JOINED_MIXED_WAVE32, WATERFALL_JOINED_WAVE32};
  12765. for words in [WATERFALL_JOINED_WAVE32, WATERFALL_JOINED_MIXED_WAVE32] {
  12766. let (layout, used) = texture_and_uav_tables();
  12767. let l = lower_wave(words, layout, used, false).unwrap();
  12768. // One image handle, from the join's per-lane heap index.
  12769. assert_eq!(l.nonuniform_handles, 1);
  12770. assert!(!l.wave_ops);
  12771. }
  12772. }
  12773. #[test]
  12774. fn scalar_bit_tests_lower() {
  12775. // Each tests one bit of a constant into SCC and branches on it (only
  12776. // code with an effect needs its operands).
  12777. let tail = [
  12778. 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm
  12779. 0xBE84_0380, // s_mov_b32 s4, 0
  12780. S_ENDPGM,
  12781. ];
  12782. let bit_tests: [&[u32]; 4] = [
  12783. &[0xBE81_0387, 0xBF0C_8301], // s_mov_b32 s1, 7; s_bitcmp0_b32 s1, 3
  12784. &[0xBE81_0387, 0xBF0D_8301], // s_mov_b32 s1, 7; s_bitcmp1_b32 s1, 3
  12785. &[
  12786. 0xBE80_0387, // s_mov_b32 s0, 7
  12787. 0xBE81_0380, // s_mov_b32 s1, 0
  12788. 0xBF0E_8300, // s_bitcmp0_b64 s[0:1], 3
  12789. ],
  12790. &[
  12791. 0xBE80_0387, // s_mov_b32 s0, 7
  12792. 0xBE81_0380, // s_mov_b32 s1, 0
  12793. 0xBF0F_8300, // s_bitcmp1_b64 s[0:1], 3
  12794. ],
  12795. ];
  12796. for head in bit_tests {
  12797. let words: Vec<u32> = head.iter().chain(&tail).copied().collect();
  12798. lowers(&words, 0).unwrap();
  12799. }
  12800. }
  12801. #[test]
  12802. #[ignore = "ours marks joins read through joins only with VICTORY_STRICT_JOINS (40 programs stop otherwise)"]
  12803. fn a_missing_value_stays_missing_through_two_live_joins() {
  12804. let mut words = [
  12805. 0xF490_0180,
  12806. 0, // s_memtime s[6:7]
  12807. 0xBF06_8000, // s_cmp_eq_u32 s0, 0 (s0 = group id X)
  12808. 0xBF85_0001, // skip the first overwrite
  12809. 0xBE86_0380, // s_mov_b32 s6, 0
  12810. 0xBF06_8101, // s_cmp_eq_u32 s1, 1 (s1 = group id Y)
  12811. 0xBF85_0001, // skip the second overwrite
  12812. 0xBE86_0381, // s_mov_b32 s6, 1
  12813. 0xBF07_8006, // s_cmp_lg_u32 s6, 0
  12814. 0xBF85_0001, // use the result to branch
  12815. 0xBE83_0380,
  12816. S_ENDPGM,
  12817. ];
  12818. let group_ids_xy = 3 << 7;
  12819. // Compare to a direct read so future timestamp support works in both cases.
  12820. let refusal = |code: &[u32]| match lowers(code, group_ids_xy) {
  12821. Ok(()) => None,
  12822. Err(crate::ShaderError::Unsupported { what, .. }) => Some(what),
  12823. Err(error) => panic!("{error}"),
  12824. };
  12825. let direct = [&words[..2], &words[8..]].concat();
  12826. assert_eq!(refusal(&words), refusal(&direct));
  12827. words[8] = 0xBF07_8000; // read the group id instead; the timestamp is dead
  12828. lowers(&words, group_ids_xy).expect("dead timestamp");
  12829. }
  12830. #[test]
  12831. fn buffer_formats_by_number() {
  12832. // The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM,
  12833. // 2_10_10_10_UNORM, 16_FLOAT, 32_32_32_32_FLOAT.
  12834. assert_eq!(buffer_format(56), Some((&[8, 8, 8, 8][..], Numeric::Unorm)));
  12835. assert_eq!(buffer_format(24), Some((&[16, 16][..], Numeric::Snorm)));
  12836. assert_eq!(
  12837. buffer_format(50),
  12838. Some((&[10, 10, 10, 2][..], Numeric::Unorm))
  12839. );
  12840. assert_eq!(buffer_format(13), Some((&[16][..], Numeric::Float)));
  12841. assert_eq!(
  12842. buffer_format(77),
  12843. Some((&[32, 32, 32, 32][..], Numeric::Float))
  12844. );
  12845. // Invalid, past the table.
  12846. assert_eq!(buffer_format(0), None);
  12847. assert_eq!(buffer_format(78), None);
  12848. }
  12849. #[test]
  12850. fn packed_buffer_formats_by_number() {
  12851. // LLVM's `UfmtGFX10`: 10_11_11 is 30-36, 11_11_10 37-43,
  12852. // 10_10_10_2 44-49. Channels from the lowest bits: R11G11B10_FLOAT
  12853. // is 10_11_11 (Mesa), 10_10_10_2 has the 2-bit channel first.
  12854. assert_eq!(buffer_format(30), Some((&[11, 11, 10][..], Numeric::Unorm)));
  12855. assert_eq!(buffer_format(36), Some((&[11, 11, 10][..], Numeric::Float)));
  12856. assert_eq!(buffer_format(37), Some((&[10, 11, 11][..], Numeric::Unorm)));
  12857. assert_eq!(buffer_format(43), Some((&[10, 11, 11][..], Numeric::Float)));
  12858. assert_eq!(
  12859. buffer_format(44),
  12860. Some((&[2, 10, 10, 10][..], Numeric::Unorm))
  12861. );
  12862. assert_eq!(
  12863. buffer_format(45),
  12864. Some((&[2, 10, 10, 10][..], Numeric::Snorm))
  12865. );
  12866. assert_eq!(
  12867. buffer_format(46),
  12868. Some((&[2, 10, 10, 10][..], Numeric::Uscaled))
  12869. );
  12870. assert_eq!(
  12871. buffer_format(47),
  12872. Some((&[2, 10, 10, 10][..], Numeric::Sscaled))
  12873. );
  12874. assert_eq!(
  12875. buffer_format(48),
  12876. Some((&[2, 10, 10, 10][..], Numeric::Uint))
  12877. );
  12878. assert_eq!(
  12879. buffer_format(49),
  12880. Some((&[2, 10, 10, 10][..], Numeric::Sint))
  12881. );
  12882. }
  12883. /// A half's value (sign, 5-bit exponent biased 15, 10-bit mantissa), as
  12884. /// `legacyF16ToF32` widens it.
  12885. fn half(h: u32) -> f32 {
  12886. let (s, e, m) = ((h >> 15) & 1, (h >> 10) & 31, h & 1023);
  12887. let v = match e {
  12888. 0 => m as f32 * 2f32.powi(-24),
  12889. 31 if m == 0 => f32::INFINITY,
  12890. 31 => f32::NAN,
  12891. _ => (1024 + m) as f32 * 2f32.powi(e as i32 - 25),
  12892. };
  12893. if s == 1 { -v } else { v }
  12894. }
  12895. #[test]
  12896. fn small_floats_widen_as_halves() {
  12897. // Unsigned 11- and 10-bit floats: a 5-bit exponent biased 15 over a
  12898. // 6- or 5-bit mantissa, no sign; values from the D3D/GL spec.
  12899. let f11 = |x: u32| half(x << half_shift(11));
  12900. let f10 = |x: u32| half(x << half_shift(10));
  12901. assert_eq!(f11(0), 0.0);
  12902. assert_eq!(f11(0x001), 2f32.powi(-20)); // smallest denormal
  12903. assert_eq!(f11(0x03F), 63.0 * 2f32.powi(-20)); // largest denormal
  12904. assert_eq!(f11(0x040), 2f32.powi(-14)); // smallest normal
  12905. assert_eq!(f11(0x3C0), 1.0);
  12906. assert_eq!(f11(0x3E0), 1.5);
  12907. assert_eq!(f11(0x7BF), 65024.0); // largest
  12908. assert_eq!(f11(0x7C0), f32::INFINITY);
  12909. assert!(f11(0x7C1).is_nan());
  12910. assert_eq!(f10(0x001), 2f32.powi(-19));
  12911. assert_eq!(f10(0x020), 2f32.powi(-14));
  12912. assert_eq!(f10(0x1E0), 1.0);
  12913. assert_eq!(f10(0x3DF), 64512.0);
  12914. assert_eq!(f10(0x3E0), f32::INFINITY);
  12915. assert!(f10(0x3FF).is_nan());
  12916. // A 16-bit float is a half already, sign included.
  12917. assert_eq!(half(0xBC00 << half_shift(16)), -1.0);
  12918. }
  12919. }