lower.rs 267 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682
  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, 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, Resources, Role, Site, Source};
  19. use crate::structure::{Atom, Bool, LaneExit, Structured};
  20. type Why = &'static str;
  21. #[derive(Debug, Clone, Copy)]
  22. enum Val {
  23. I32(V),
  24. Bit(V),
  25. Missing(Why),
  26. }
  27. pub(crate) struct Lowered {
  28. pub dxil: Vec<u8>,
  29. /// Bit n: immediate sampler n is used for comparisons.
  30. pub cmp_samplers: u64,
  31. pub root_cbvs: Vec<u8>,
  32. pub root_srvs: Vec<u8>,
  33. pub user_data: Vec<UserData>,
  34. pub samplers: Vec<[u32; 4]>,
  35. }
  36. pub(crate) struct Parts<'a> {
  37. pub native: &'a NativeProgram,
  38. pub p: &'a Program,
  39. pub st: &'a Structured,
  40. pub io: &'a Io,
  41. pub res: &'a Resources,
  42. pub inputs: Vec<SigElement>,
  43. pub outputs: Vec<SigElement>,
  44. pub prims: Vec<SigElement>,
  45. /// Mesh: what the group id arrives multiplied by.
  46. pub mesh_stride: u32,
  47. }
  48. enum Stop {
  49. /// A phi whose incoming value has no DXIL form was read: redo with it missing.
  50. Retry(Value, Why),
  51. Fail(ShaderError),
  52. }
  53. pub(crate) fn lower(parts: &Parts) -> Result<Lowered, ShaderError> {
  54. let mut bad = HashMap::new();
  55. loop {
  56. match Lower::new(parts, &bad).run() {
  57. Ok(l) => return Ok(l),
  58. Err(Stop::Retry(v, why)) => {
  59. if bad.insert(v, why).is_some() {
  60. return Err(ShaderError::Unsupported {
  61. offset: 0,
  62. what: "a phi that does not settle",
  63. });
  64. }
  65. }
  66. Err(Stop::Fail(e)) => return Err(e),
  67. }
  68. }
  69. }
  70. const TWO_PI: f32 = std::f32::consts::TAU;
  71. /// `s_sendmsg` id of a mesh or NGG stage's output allocation request.
  72. const GS_ALLOC_REQ: u16 = 9;
  73. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  74. enum Numeric {
  75. Unorm,
  76. Snorm,
  77. Uscaled,
  78. Sscaled,
  79. Uint,
  80. Sint,
  81. Float,
  82. }
  83. /// A GFX10 buffer format (the unified format of typed buffer loads): the
  84. /// channel widths from the lowest bits up, and how the channels convert.
  85. /// Formats are numbered in families (`8`, `16`, `8_8`, ...: AMD names
  86. /// list channels from the highest bits), each with its numeric formats in
  87. /// the order unorm, snorm, uscaled, sscaled, uint, sint, float.
  88. fn buffer_format(format: u8) -> Option<(&'static [u32], Numeric)> {
  89. use Numeric::*;
  90. const NORM: &[Numeric] = &[Unorm, Snorm, Uscaled, Sscaled, Uint, Sint];
  91. const ALL: &[Numeric] = &[Unorm, Snorm, Uscaled, Sscaled, Uint, Sint, Float];
  92. const WIDE: &[Numeric] = &[Uint, Sint, Float];
  93. // `None`: a family not decoded (packed floats, 10_10_10_2).
  94. const FAMILIES: [(Option<&[u32]>, &[Numeric]); 14] = [
  95. (Some(&[8]), NORM),
  96. (Some(&[16]), ALL),
  97. (Some(&[8, 8]), NORM),
  98. (Some(&[32]), WIDE),
  99. (Some(&[16, 16]), ALL),
  100. (None, ALL), // 10_11_11
  101. (None, ALL), // 11_11_10
  102. (None, NORM), // 10_10_10_2
  103. (Some(&[10, 10, 10, 2]), NORM), // 2_10_10_10
  104. (Some(&[8, 8, 8, 8]), NORM),
  105. (Some(&[32, 32]), WIDE),
  106. (Some(&[16, 16, 16, 16]), ALL),
  107. (Some(&[32, 32, 32]), WIDE),
  108. (Some(&[32, 32, 32, 32]), WIDE),
  109. ];
  110. let mut n = usize::from(format.checked_sub(1)?);
  111. for (bits, numerics) in FAMILIES {
  112. if n < numerics.len() {
  113. return Some((bits?, numerics[n]));
  114. }
  115. n -= numerics.len();
  116. }
  117. None
  118. }
  119. struct Lower<'a> {
  120. s: Shader,
  121. x: &'a Parts<'a>,
  122. bad: &'a HashMap<Value, Why>,
  123. lane_fail: HashMap<Value, Why>,
  124. vals: HashMap<Value, Val>,
  125. floats: HashMap<Value, V>,
  126. /// DXIL block per IR block (unreachable: none).
  127. block: Vec<Option<usize>>,
  128. cur: usize,
  129. bools: HashMap<(usize, Bool), V>,
  130. lane_bits: HashMap<Value, V>,
  131. /// IR phi location by value.
  132. phi_at: HashMap<Value, (usize, usize)>,
  133. mask_phis: HashMap<Value, V>,
  134. pending_masks: Vec<(V, usize, usize)>,
  135. data_phis: Vec<(V, usize, usize)>,
  136. read_phis: HashSet<Value>,
  137. params: HashMap<Value, (usize, u32)>,
  138. user_data: Option<V>,
  139. user_reads: BTreeMap<u32, UserData>,
  140. samplers: Vec<[u32; 4]>,
  141. descriptors: HashMap<(Site, bool), &'a Source>,
  142. scalar: HashMap<Site, Address>,
  143. exports: HashMap<Site, &'a Export>,
  144. interps: HashMap<Site, &'a Interp>,
  145. handles: HashMap<(usize, Site, u8, bool, u32), V>,
  146. /// Blocks splitting the edge from one IR block to another.
  147. edges: HashMap<(usize, usize), usize>,
  148. /// Per IR block: a `done` export is behind every lane entering it.
  149. exported: Vec<bool>,
  150. /// Reverse-postorder index per IR block.
  151. rpo: Vec<usize>,
  152. /// DXIL block each IR block ends in (guarded stores split blocks).
  153. tail: Vec<Option<usize>>,
  154. /// The program writes UAVs: barriers fence them too.
  155. writes_uavs: bool,
  156. /// src0 of the current instruction as DPP fetched it.
  157. src0: Option<V>,
  158. /// Compute code that reads other lanes: thread ids follow the host
  159. /// lanes, so lane n is console lane n.
  160. console_lanes: bool,
  161. /// Mesh: the thread index in the group (made in the entry block).
  162. flat: Option<V>,
  163. /// Mesh: IR blocks whose `s_barrier` is left out.
  164. no_barrier: HashSet<usize>,
  165. /// Vertex and mesh outputs holding 16-bit values: row, whether two per
  166. /// dword, and the row packed after it.
  167. half_outputs: HashMap<u8, (bool, Option<u8>)>,
  168. /// How lane masks become data.
  169. mask_data: MaskData,
  170. /// The instruction being lowered may read lane masks as data.
  171. mask_ok: bool,
  172. /// Ballots of masks read as data, by low dword: (low, high).
  173. ballots: HashMap<Value, (V, V)>,
  174. /// Masks whose ballot is being built: a mask whose lane bit needs its
  175. /// own value as a number (an opaque mask keyed by a dword it shares
  176. /// with another) would otherwise recurse until the stack overflows.
  177. balloting: HashSet<Value>,
  178. /// Block writing each value.
  179. def_block: HashMap<Value, usize>,
  180. /// IR block being lowered.
  181. cur_ir: usize,
  182. /// Whole-wave sections by block and start index.
  183. sections: HashMap<usize, HashMap<usize, super::wave::Section>>,
  184. /// Values written in a section that code outside it reads.
  185. section_out: HashSet<Value>,
  186. /// The program's constant table (the code from the first byte read
  187. /// through `s_getpc_b64` on): global, first byte, dwords.
  188. code_table: Option<(V, u32, u32)>,
  189. /// Loop headers' iteration counters (see [`LOOP_LIMIT`]): the phi by
  190. /// IR block, and its incoming (value, DXIL block) pairs.
  191. counters: HashMap<usize, (V, Vec<(V, usize)>)>,
  192. /// The block a loop stopped by [`LOOP_LIMIT`] leaves the program from.
  193. abort: Option<usize>,
  194. }
  195. /// Iterations after which a loop is left (per entry into it), unless
  196. /// [`super::loop_limit`] says otherwise. The console runs a loop as long as
  197. /// its data says; data the host has not mirrored yet (a null view reads
  198. /// zeros) can make that four billion iterations, which hangs the host GPU
  199. /// until the driver resets it. A lane that reaches the limit leaves the
  200. /// program as killed (a pixel discards).
  201. // shortcut: a genuine loop of more iterations than this is cut short too.
  202. pub(super) const LOOP_LIMIT: u32 = 1 << 20;
  203. /// Lane masks read as numbers (`s_bcnt1`, `s_ff1`, `v_mbcnt`, scalar
  204. /// compares, bit tests) are ballots of the lanes' booleans, taken where the
  205. /// mask is written: structurisation's `active` masks hold only lanes that
  206. /// reach that block, so the ballot misses none.
  207. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  208. enum MaskData {
  209. /// Compute: host lane n is console lane n (the program declares the
  210. /// console's wave size), so ballots are the console's masks bit for bit
  211. /// and any use is exact.
  212. Console,
  213. /// Pixel and vertex programs: ballots over the host's wave, whatever its
  214. /// size. Only uses that mean the same on any wave are allowed: counts,
  215. /// the first lane, the count below a lane, equality (the HLSL wave
  216. /// operations the console compiler expands). Lane numbers stay host
  217. /// lanes throughout (`v_mbcnt`, `v_readlane` at a computed lane).
  218. Host,
  219. /// Mesh programs: their lanes and waves (LDS per console wave) are the
  220. /// console's but no host wave size can be declared.
  221. None,
  222. }
  223. /// What a value holding a lane mask read as a number stops with.
  224. const LANE_MASK: Why = "a lane mask read as data";
  225. /// Instructions that read a lane mask (not EXEC implicitly, not a lane's
  226. /// bit) as a number.
  227. fn reads_mask_as_data(st: &Structured, i: &Inst) -> bool {
  228. let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v);
  229. let ops: Vec<&Operand> = match &i.fields {
  230. // A mask operation (its result a mask) is no data use.
  231. Fields::Sop { .. }
  232. if i.writes
  233. .iter()
  234. .any(|&(r, w)| matches!(r, Reg::S(_)) && is_mask(w)) =>
  235. {
  236. return false;
  237. }
  238. Fields::Sop { src, .. } => src.iter().collect(),
  239. Fields::Valu(v)
  240. if !matches!(i.name(), "v_cndmask_b32") && !i.name().contains("_co_ci_") =>
  241. {
  242. v.src.iter().collect()
  243. }
  244. _ => return false,
  245. };
  246. ops.into_iter().any(|op| match *op {
  247. Operand::Scalar { code, .. } if code != NULL => i.read(Reg::S(code)).is_some_and(is_mask),
  248. _ => false,
  249. })
  250. }
  251. /// Where half `h` (dword h / 2, the high half when odd) of a parameter
  252. /// packing 16-bit rows `a` and `b` two per dword comes from: a row and
  253. /// channel of `elements`, none for padding. Channel c of `a` is half c;
  254. /// `b` starts at the dword after `a`'s last channel.
  255. fn packed_half(elements: &[SigElement], a: u8, b: Option<u8>, h: u8) -> Option<(u8, u8)> {
  256. let extent = |r: u8| {
  257. elements
  258. .iter()
  259. .filter(|e| e.row == Some(u32::from(r)))
  260. .map(|e| e.col + e.cols)
  261. .max()
  262. };
  263. let na = extent(a)?;
  264. let a_halves = na.div_ceil(2) * 2;
  265. if h < a_halves {
  266. return (h < na).then_some((a, h));
  267. }
  268. let b = b?;
  269. let c = h - a_halves;
  270. (c < extent(b)?).then_some((b, c))
  271. }
  272. /// Vertex or mesh outputs of 16-bit values (see [`Lower::half_outputs`]):
  273. /// a packed row's partner is the next 16-bit row of the signature that no
  274. /// output entry names, taken in row order.
  275. fn half_outputs(io: &StageIo, outputs: &[SigElement]) -> HashMap<u8, (bool, Option<u8>)> {
  276. let entries = match io {
  277. StageIo::Vs { outputs, .. } => outputs,
  278. StageIo::Ms(ms) => &ms.outputs,
  279. _ => return HashMap::new(),
  280. };
  281. let per_vertex = || entries.iter().filter(|o| o.param & 0x80 == 0);
  282. let mut free: Vec<u8> = outputs
  283. .iter()
  284. .filter(|e| e.half && e.kind == 0)
  285. .filter_map(|e| u8::try_from(e.row?).ok())
  286. .filter(|&r| !per_vertex().any(|o| o.row == r))
  287. .collect();
  288. free.sort_unstable();
  289. free.dedup();
  290. let mut halves: Vec<_> = per_vertex().filter(|o| o.fp16).collect();
  291. halves.sort_by_key(|o| o.row);
  292. halves
  293. .into_iter()
  294. .map(|o| {
  295. let b = o
  296. .pack2
  297. .then(|| free.iter().position(|&r| r > o.row))
  298. .flatten();
  299. (o.row, (o.pack2, b.map(|i| free.remove(i))))
  300. })
  301. .collect()
  302. }
  303. fn unsupported(offset: usize, what: Why) -> Stop {
  304. Stop::Fail(ShaderError::Unsupported { offset, what })
  305. }
  306. impl<'a> Lower<'a> {
  307. fn new(x: &'a Parts<'a>, bad: &'a HashMap<Value, Why>) -> Self {
  308. let p = x.p;
  309. let mut phi_at = HashMap::new();
  310. for (b, block) in p.blocks.iter().enumerate() {
  311. for (i, phi) in block.phis.iter().enumerate() {
  312. phi_at.insert(phi.value, (b, i));
  313. }
  314. }
  315. let mut s = Shader::new(x.native.stage == HwStage::Ps);
  316. s.inputs = x.inputs.clone();
  317. s.outputs = x.outputs.clone();
  318. let insts = || p.blocks.iter().flat_map(|b| &b.insts);
  319. let writes_uavs = insts().any(|i| {
  320. matches!(i.fields, Fields::Image { .. } | Fields::Buffer { .. })
  321. && (i.name().contains("store") || i.name().contains("atomic"))
  322. });
  323. let mut console_lanes = false;
  324. if let StageIo::Cs(cs) = x.native.io {
  325. s.threads = Some(cs.threads);
  326. s.lds_dwords = cs.lds_bytes() / 4;
  327. // Code reading other lanes needs the console's wave size and
  328. // lane order; so do lane masks read as numbers, and LDS shared
  329. // within one wave, where the console compiler leaves out barriers.
  330. console_lanes = insts().any(|i| {
  331. let n = i.name();
  332. n.starts_with("ds_swizzle")
  333. || n.contains("permute")
  334. || n.starts_with("v_mbcnt")
  335. || matches!(n, "v_readlane_b32" | "v_writelane_b32")
  336. || matches!(&i.fields, Fields::Valu(v) if v.dpp.is_some())
  337. || reads_mask_as_data(x.st, i)
  338. }) || {
  339. // Masks held as numbers or constant lane sets: the lane
  340. // tests its own bit by its console lane.
  341. let whens = x.st.exits.iter().filter_map(|e| match *e {
  342. LaneExit::Branch { when, .. } => Some(when),
  343. _ => None,
  344. });
  345. let mut all: Vec<Bool> =
  346. x.st.guards
  347. .iter()
  348. .flatten()
  349. .flatten()
  350. .copied()
  351. .chain(whens)
  352. .collect();
  353. all.sort_unstable();
  354. all.dedup();
  355. all.into_iter().any(|g| {
  356. x.st.bools
  357. .support(g)
  358. .iter()
  359. .any(|a| matches!(a, Atom::Opaque(_) | Atom::Constant(_)))
  360. })
  361. };
  362. let wave = if x.native.wave64 { 64 } else { 32 };
  363. let one_wave = cs.threads.iter().product::<u32>() <= wave;
  364. if console_lanes || one_wave && s.lds_dwords > 0 {
  365. s.wave_size = Some(wave);
  366. }
  367. }
  368. let mut no_barrier = HashSet::new();
  369. if let StageIo::Ms(ms) = &x.native.io {
  370. s.prims = x.prims.clone();
  371. s.threads = Some([ms.threads, 1, 1]);
  372. s.lds_dwords = ms.lds_bytes.div_ceil(4);
  373. s.mesh = Some(super::shader::Mesh {
  374. max_vertices: ms.max_vertices,
  375. max_primitives: ms.max_primitives,
  376. topology: ms.topology,
  377. });
  378. // Barriers order the lanes' LDS accesses; the console's
  379. // allocation request needs them too, but the host does not. One
  380. // lane sends that request, and what it dominates (the path for
  381. // counts out of range) runs in that lane alone, so its barrier
  382. // would hang the host.
  383. let order = crate::ir::reverse_postorder(&p.blocks);
  384. let mut index = vec![usize::MAX; p.blocks.len()];
  385. for (n, &b) in order.iter().enumerate() {
  386. index[b] = n;
  387. }
  388. let idom = crate::ir::idoms(&p.blocks, &order, &index);
  389. let alloc: Vec<usize> = (0..p.blocks.len())
  390. .filter(|&b| {
  391. p.blocks[b].insts.iter().any(|i| {
  392. i.name() == "s_sendmsg"
  393. && matches!(i.fields, Fields::Sopp { imm } if imm & 0xF == GS_ALLOC_REQ)
  394. })
  395. })
  396. .collect();
  397. for &b in &order {
  398. let mut d = b;
  399. let dominated = loop {
  400. if alloc.contains(&d) {
  401. break true;
  402. }
  403. if idom[d] == d || idom[d] == usize::MAX {
  404. break false;
  405. }
  406. d = idom[d];
  407. };
  408. if ms.lds_bytes == 0 || dominated {
  409. no_barrier.insert(b);
  410. }
  411. }
  412. }
  413. Lower {
  414. s,
  415. x,
  416. bad,
  417. lane_fail: HashMap::new(),
  418. vals: HashMap::new(),
  419. floats: HashMap::new(),
  420. block: vec![None; p.blocks.len()],
  421. cur: 0,
  422. bools: HashMap::new(),
  423. lane_bits: HashMap::new(),
  424. phi_at,
  425. mask_phis: HashMap::new(),
  426. pending_masks: Vec::new(),
  427. data_phis: Vec::new(),
  428. read_phis: HashSet::new(),
  429. params: x.res.params.iter().map(|&(v, p, d)| (v, (p, d))).collect(),
  430. user_data: None,
  431. user_reads: BTreeMap::new(),
  432. samplers: Vec::new(),
  433. descriptors: x
  434. .res
  435. .descriptors
  436. .iter()
  437. .map(|d| ((d.site, d.role == Role::Sampler), &d.source))
  438. .collect(),
  439. scalar: x.res.scalar.iter().copied().collect(),
  440. exports: x.io.exports.iter().map(|e| (e.site, e)).collect(),
  441. interps: x.io.interps.iter().map(|(s, i)| (*s, i)).collect(),
  442. handles: HashMap::new(),
  443. edges: HashMap::new(),
  444. exported: vec![false; p.blocks.len()],
  445. rpo: vec![usize::MAX; p.blocks.len()],
  446. tail: vec![None; p.blocks.len()],
  447. writes_uavs,
  448. src0: None,
  449. console_lanes,
  450. flat: None,
  451. no_barrier,
  452. half_outputs: half_outputs(&x.native.io, &x.outputs),
  453. mask_data: match x.native.stage {
  454. HwStage::Cs => MaskData::Console,
  455. HwStage::Ps | HwStage::Vs => MaskData::Host,
  456. _ => MaskData::None,
  457. },
  458. mask_ok: false,
  459. ballots: HashMap::new(),
  460. balloting: HashSet::new(),
  461. def_block: p
  462. .blocks
  463. .iter()
  464. .enumerate()
  465. .flat_map(|(b, block)| {
  466. block
  467. .insts
  468. .iter()
  469. .flat_map(move |i| i.writes.iter().map(move |w| (w.1, b)))
  470. .chain(block.phis.iter().map(move |phi| (phi.value, b)))
  471. })
  472. .collect(),
  473. cur_ir: 0,
  474. sections: HashMap::new(),
  475. section_out: HashSet::new(),
  476. code_table: None,
  477. counters: HashMap::new(),
  478. abort: None,
  479. }
  480. }
  481. /// The dword of the program's code at byte `byte` (a constant table
  482. /// the compiler appends to the code), as an internal constant array.
  483. // shortcut: an index outside the table reads its last dword (the
  484. // console would read whatever memory follows the code).
  485. fn code_dword(&mut self, byte: V) -> Result<V, Why> {
  486. let (g, base, len) = match self.code_table {
  487. Some(t) => t,
  488. None => {
  489. let first = self
  490. .x
  491. .res
  492. .scalar
  493. .iter()
  494. .map(|s| s.1)
  495. .chain(self.x.res.descriptors.iter().flat_map(|d| {
  496. d.source.leaves().into_iter().filter_map(|l| match l {
  497. Source::Built { address, .. } => Some(*address),
  498. _ => None,
  499. })
  500. }))
  501. .filter(|a| a.param == CODE)
  502. .map(|a| a.offset & !3)
  503. .min()
  504. .ok_or("a code table")?;
  505. let code = &self.x.native.code;
  506. let words: Vec<u32> = code
  507. .get(first as usize..)
  508. .ok_or("a code table past the code")?
  509. .chunks(4)
  510. .map(|c| {
  511. let mut w = [0u8; 4];
  512. w[..c.len()].copy_from_slice(c);
  513. u32::from_le_bytes(w)
  514. })
  515. .collect();
  516. if words.is_empty() {
  517. return Err("a code table past the code");
  518. }
  519. let elems: Vec<V> = words.iter().map(|&w| self.s.m.i32(w)).collect();
  520. let arr = self.s.m.array(words.len() as u32, self.s.t.i32);
  521. let init = self.s.m.aggregate(arr, &elems);
  522. let g = self.s.m.constant_global("code", init);
  523. let t = (g, first, words.len() as u32);
  524. self.code_table = Some(t);
  525. t
  526. }
  527. };
  528. let c = self.cur;
  529. let k = self.s.m.i32(base);
  530. let rel = self.s.m.bin(c, Bin::Sub, byte, k);
  531. let two = self.s.m.i32(2);
  532. let index = self.s.m.bin(c, Bin::LShr, rel, two);
  533. let last = self.s.m.i32(len - 1);
  534. let over = self.s.m.cmp(c, pred::IUGT, index, last);
  535. let index = self.s.m.select(c, over, last, index);
  536. let at = self.s.m.element(c, g, index);
  537. Ok(self.s.m.load(c, at))
  538. }
  539. /// A global memory load (`global_load_*`): from the program's constant
  540. /// table, or from a root SRV at the address the title sets.
  541. fn flat(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  542. let Fields::Flat { dst, .. } = &inst.fields else {
  543. unreachable!()
  544. };
  545. let name = inst.name();
  546. let rest = name
  547. .strip_prefix("global_load_")
  548. .ok_or("a global memory write")?;
  549. let (n, sub) = match rest {
  550. "dword" => (1, None),
  551. "dwordx2" => (2, None),
  552. "dwordx3" => (3, None),
  553. "dwordx4" => (4, None),
  554. "ubyte" => (1, Some((8, false))),
  555. "sbyte" => (1, Some((8, true))),
  556. "ushort" => (1, Some((16, false))),
  557. "sshort" => (1, Some((16, true))),
  558. _ => return Err(name),
  559. };
  560. let a = *self
  561. .scalar
  562. .get(&(b, i))
  563. .ok_or("an untracked global address")?;
  564. let guard = self.guard(b, i)?;
  565. let Some(Operand::Vector { reg, .. }) = *dst else {
  566. return Err("a global load result");
  567. };
  568. let c = self.cur;
  569. let mut off = self.s.m.i32(a.offset);
  570. if let Some(d) = a.dynamic {
  571. let d = self.i32_of(d)?;
  572. off = self.s.m.bin(c, Bin::Add, off, d);
  573. }
  574. let h = if a.param == CODE {
  575. None
  576. } else {
  577. let src = Source::Built {
  578. address: a,
  579. bits: 0,
  580. words: [0, 0],
  581. };
  582. Some(self.handle((b, i), &src, false, (11, 0))?)
  583. };
  584. let dword = |l: &mut Self, byte: V| -> Result<V, Why> {
  585. match h {
  586. None => l.code_dword(byte),
  587. Some(h) => {
  588. let c = l.cur;
  589. let (u, mask, al) = (l.s.m.undef(l.s.t.i32), l.s.m.i8(1), l.s.m.i32(4));
  590. let r = l.s.op(
  591. c,
  592. "rawBufferLoad.f32",
  593. Attr::ReadOnly,
  594. l.s.t.res_ret,
  595. 139,
  596. &[h, byte, u, mask, al],
  597. );
  598. let x = l.s.m.extract(c, r, 0);
  599. Ok(l.as_int(x))
  600. }
  601. }
  602. };
  603. for k in 0..n {
  604. let x = match sub {
  605. None => {
  606. let four = self.s.m.i32(4 * k);
  607. let at = self.s.m.bin(c, Bin::Add, off, four);
  608. dword(self, at)?
  609. }
  610. Some((width, signed)) => {
  611. // shortcut: the field is taken not to cross a dword.
  612. let (not3, three) = (self.s.m.i32(!3), self.s.m.i32(3));
  613. let at = self.s.m.bin(c, Bin::And, off, not3);
  614. let w = dword(self, at)?;
  615. let byte = self.s.m.bin(c, Bin::And, off, three);
  616. let sh = self.s.m.bin(c, Bin::Shl, byte, three);
  617. let x = self.s.m.bin(c, Bin::LShr, w, sh);
  618. let left = self.s.m.i32(32 - width);
  619. let x = self.s.m.bin(c, Bin::Shl, x, left);
  620. self.s
  621. .m
  622. .bin(c, if signed { Bin::AShr } else { Bin::LShr }, x, left)
  623. }
  624. };
  625. self.write(inst, Reg::V(reg + k as u8), x, guard);
  626. }
  627. Ok(())
  628. }
  629. /// Finds the whole-wave sections and the values they leave.
  630. fn find_sections(&mut self) {
  631. let p = self.x.p;
  632. let mut inside: HashMap<Value, (usize, usize, usize)> = HashMap::new();
  633. for b in 0..p.blocks.len() {
  634. let found = super::wave::sections(p, b);
  635. for (&start, sec) in &found {
  636. for i in start + 1..sec.end {
  637. for &(_, w) in &p.blocks[b].insts[i].writes {
  638. inside.insert(w, (b, start, sec.end));
  639. }
  640. }
  641. }
  642. if !found.is_empty() {
  643. self.sections.insert(b, found);
  644. }
  645. }
  646. if inside.is_empty() {
  647. return;
  648. }
  649. for (b, block) in p.blocks.iter().enumerate() {
  650. for phi in &block.phis {
  651. self.section_out
  652. .extend(phi.args.iter().filter(|a| inside.contains_key(a)));
  653. }
  654. for (i, inst) in block.insts.iter().enumerate() {
  655. for &(_, r) in &inst.reads {
  656. if let Some(&(sb, start, end)) = inside.get(&r)
  657. && !(sb == b && i > start && i < end)
  658. {
  659. self.section_out.insert(r);
  660. }
  661. }
  662. }
  663. }
  664. }
  665. /// An instruction inside a whole-wave section: the values that leave
  666. /// the section are made from what the simulation found them to be.
  667. fn section_inst(&mut self, b: usize, i: usize, start: usize) {
  668. const UNKNOWN: Why = "a whole-wave section step the simulation does not follow";
  669. let inst = &self.x.p.blocks[b].insts[i];
  670. for &(_, w) in &inst.writes {
  671. let val = if self.section_out.contains(&w) {
  672. let shape = self.sections[&b][&start].shapes.get(&w).copied();
  673. match shape.ok_or(UNKNOWN).and_then(|sh| self.shape(sh)) {
  674. Ok(x) => Val::I32(x),
  675. Err(why) => Val::Missing(why),
  676. }
  677. } else {
  678. Val::Missing(UNKNOWN)
  679. };
  680. self.vals.insert(w, val);
  681. }
  682. }
  683. /// A value a whole-wave section leaves, as DXIL wave operations over the
  684. /// host's active lanes: the console's result with console lanes; on
  685. /// another wave size, what the HLSL wave operation the console compiler
  686. /// expanded gives on that wave.
  687. fn shape(&mut self, shape: super::wave::Shape) -> Result<V, Why> {
  688. use super::wave::{Op, Shape};
  689. let (op, src, mask, ident, prefix) = match shape {
  690. Shape::K(k) => return Ok(self.s.m.i32(k)),
  691. Shape::Value(v) => return self.i32_of(v),
  692. Shape::Active(op, src, mask, ident) => (op, src, mask, ident, None),
  693. Shape::Masked(src, mask, ident) => {
  694. let c = self.cur;
  695. let &m = self
  696. .x
  697. .st
  698. .masks
  699. .get(&mask)
  700. .ok_or("a wave reduction's untracked mask")?;
  701. let on = self.boolean(m, c)?;
  702. let x = self.i32_of(src)?;
  703. let id = self.s.m.i32(ident);
  704. return Ok(self.s.m.select(c, on, x, id));
  705. }
  706. Shape::Prefix(op, src, mask, ident, inclusive) => {
  707. (op, src, mask, ident, Some(inclusive))
  708. }
  709. };
  710. if self.mask_data == MaskData::None {
  711. return Err("a wave reduction in a mesh shader");
  712. }
  713. let c = self.cur;
  714. let &m = self
  715. .x
  716. .st
  717. .masks
  718. .get(&mask)
  719. .ok_or("a wave reduction's untracked mask")?;
  720. let on = self.boolean(m, c)?;
  721. let x = self.i32_of(src)?;
  722. let id = self.s.m.i32(ident);
  723. let x = self.s.m.select(c, on, x, id);
  724. self.s.flags |= flags::WAVE_OPS;
  725. let float = matches!(op, Op::AddF | Op::MinF | Op::MaxF);
  726. let (i32t, f32t) = (self.s.t.i32, self.s.t.f32);
  727. let arg = if float { self.as_float(x) } else { x };
  728. let ty = if float { f32t } else { i32t };
  729. let sfx = if float { "f32" } else { "i32" };
  730. let r = match (op, prefix) {
  731. (Op::AddU | Op::AddF, Some(inclusive)) => {
  732. let (k0, k1) = (self.s.m.i8(0), self.s.m.i8(1));
  733. let r = self.s.op(
  734. c,
  735. &format!("wavePrefixOp.{sfx}"),
  736. Attr::NoUnwind,
  737. ty,
  738. 121,
  739. &[arg, k0, k1],
  740. );
  741. if inclusive {
  742. self.s.m.bin(c, Bin::Add, r, arg)
  743. } else {
  744. r
  745. }
  746. }
  747. (_, Some(_)) => return Err("a wave prefix of an operation other than a sum"),
  748. (Op::Or | Op::And | Op::Xor, None) => {
  749. let k = self.s.m.i8(match op {
  750. Op::And => 0,
  751. Op::Or => 1,
  752. _ => 2,
  753. });
  754. self.s
  755. .op(c, "waveActiveBit.i32", Attr::NoUnwind, i32t, 120, &[arg, k])
  756. }
  757. (_, None) => {
  758. let (code, unsigned) = match op {
  759. Op::AddU => (0, 1),
  760. Op::AddF => (0, 0),
  761. Op::MinU => (2, 1),
  762. Op::MaxU => (3, 1),
  763. Op::MinI | Op::MinF => (2, 0),
  764. _ => (3, 0),
  765. };
  766. let (k, u) = (self.s.m.i8(code), self.s.m.i8(unsigned));
  767. self.s.op(
  768. c,
  769. &format!("waveActiveOp.{sfx}"),
  770. Attr::NoUnwind,
  771. ty,
  772. 119,
  773. &[arg, k, u],
  774. )
  775. }
  776. };
  777. Ok(if float { self.as_int(r) } else { r })
  778. }
  779. fn run(mut self) -> Result<Lowered, Stop> {
  780. let p = self.x.p;
  781. let order = crate::ir::reverse_postorder(&p.blocks);
  782. for (n, &b) in order.iter().enumerate() {
  783. self.rpo[b] = n;
  784. }
  785. for (n, &b) in order.iter().enumerate() {
  786. self.block[b] = Some(if n == 0 {
  787. self.s.entry
  788. } else {
  789. self.s.m.new_block()
  790. });
  791. }
  792. // Loop headers count iterations (`LOOP_LIMIT`).
  793. for &b in &order {
  794. let header = p.blocks[b]
  795. .preds
  796. .iter()
  797. .any(|&q| self.block[q].is_some() && self.rpo[b] <= self.rpo[q]);
  798. if header {
  799. let blk = self.block[b].expect("reachable");
  800. let phi = self.s.m.phi(blk, self.s.t.i32);
  801. self.counters.insert(b, (phi, Vec::new()));
  802. }
  803. }
  804. self.cur = self.s.entry;
  805. self.find_sections();
  806. self.inputs()?;
  807. if let Some(mesh) = self.s.mesh {
  808. self.mesh_prologue(mesh).map_err(|w| unsupported(0, w))?;
  809. self.block[order[0]] = Some(self.cur);
  810. }
  811. for &b in &order {
  812. self.cur = self.block[b].expect("reachable");
  813. self.cur_ir = b;
  814. let preds: Vec<usize> = p.blocks[b]
  815. .preds
  816. .iter()
  817. .copied()
  818. .filter(|&q| self.block[q].is_some())
  819. .collect();
  820. self.exported[b] = !preds.is_empty() && preds.iter().all(|&q| self.exported_out(q));
  821. for (i, phi) in p.blocks[b].phis.iter().enumerate() {
  822. let val = match phi.reg {
  823. Reg::S(c) if c == EXEC || c == EXEC + 1 => Val::Missing("a lane mask"),
  824. _ if self.bad.contains_key(&phi.value) => Val::Missing(self.bad[&phi.value]),
  825. Reg::Scc => {
  826. let v = self.s.m.phi(self.cur, self.s.t.i1);
  827. self.data_phis.push((v, b, i));
  828. Val::Bit(v)
  829. }
  830. _ => {
  831. let v = self.s.m.phi(self.cur, self.s.t.i32);
  832. self.data_phis.push((v, b, i));
  833. Val::I32(v)
  834. }
  835. };
  836. self.vals.insert(phi.value, val);
  837. }
  838. let mut i = 0;
  839. while i < p.blocks[b].insts.len() {
  840. self.inst(b, i)?;
  841. if let Some(end) = self.sections.get(&b).and_then(|s| s.get(&i)).map(|s| s.end) {
  842. for j in i + 1..end {
  843. self.section_inst(b, j, i);
  844. }
  845. i = end;
  846. continue;
  847. }
  848. i += 1;
  849. }
  850. self.mask_ok = self.mask_data == MaskData::Console;
  851. self.tail[b] = Some(self.cur);
  852. self.exit(b)?;
  853. }
  854. self.fill_phis()?;
  855. let user_data = self.user_reads.values().copied().collect();
  856. self.s.samplers = self.samplers.len() as u32;
  857. let root_cbvs = self.s.root_cbvs.iter().map(|r| r.0).collect();
  858. let root_srvs = self.s.root_srvs.iter().map(|r| r.0).collect();
  859. let cmp_samplers = self.s.cmp_samplers;
  860. Ok(Lowered {
  861. cmp_samplers,
  862. root_cbvs,
  863. root_srvs,
  864. dxil: self.s.finish(),
  865. user_data,
  866. samplers: self.samplers,
  867. })
  868. }
  869. fn exported_out(&self, b: usize) -> bool {
  870. self.exported[b] || self.has_done_export(b)
  871. }
  872. fn has_done_export(&self, b: usize) -> bool {
  873. (0..self.x.p.blocks[b].insts.len())
  874. .any(|i| self.exports.get(&(b, i)).is_some_and(|e| e.done))
  875. }
  876. /// Values of the program's input registers.
  877. fn inputs(&mut self) -> Result<(), Stop> {
  878. let io_inputs: HashMap<Value, Input> = self.x.io.inputs.iter().copied().collect();
  879. for &(reg, v) in &self.x.p.inputs {
  880. let val = match reg {
  881. Reg::S(_) if self.params.contains_key(&v) => continue, // loaded on first use
  882. Reg::S(_) => match io_inputs.get(&v) {
  883. Some(&input) => self.input(input),
  884. None => Val::Missing("a hardware SGPR input"),
  885. },
  886. Reg::Scc => Val::Missing("SCC on entry"),
  887. Reg::V(_) => match io_inputs.get(&v) {
  888. Some(&input) => self.input(input),
  889. // Registers no one set read as zero (the validator
  890. // refuses reads of undef).
  891. None => Val::I32(self.s.m.i32(0)),
  892. },
  893. };
  894. self.vals.insert(v, val);
  895. }
  896. Ok(())
  897. }
  898. fn input(&mut self, input: Input) -> Val {
  899. let (kind, col) = match input {
  900. Input::VertexId => (1, 0),
  901. Input::InstanceId => (2, 0),
  902. Input::Position(c) => (3, c),
  903. Input::Attribute { row, channel } => {
  904. return match self.find_input(row, channel) {
  905. Some((id, col)) => self.load_input(id, col),
  906. None => Val::Missing("a vertex input the signature lacks"),
  907. };
  908. }
  909. Input::Barycentric { .. } => return Val::Missing("barycentrics read directly"),
  910. Input::PrimitiveId => return Val::Missing("the primitive id"),
  911. // The console code tests it against 0 (`v_cmp_ne_u32`), as the
  912. // host's value can be.
  913. Input::FrontFace => (13, 0),
  914. Input::ThreadIdInGroup(c) => return self.thread_id(c),
  915. Input::GroupId(c) => return self.compute_id("groupId.i32", 94, c),
  916. Input::GroupInfo => return Val::Missing("the thread-group info SGPR"),
  917. Input::MeshGroup => {
  918. let Val::I32(g) = self.compute_id("groupId.i32", 94, 0) else {
  919. unreachable!()
  920. };
  921. let n = self.s.m.i32(self.x.mesh_stride);
  922. return Val::I32(self.s.m.bin(self.s.entry, Bin::Mul, g, n));
  923. }
  924. Input::MergedWaveInfo => {
  925. // shortcut: only the wave index (bits 24-27) is set; the
  926. // console's other bits (lane counts) are read by no program.
  927. let f = self.mesh_thread();
  928. let shift = self.s.m.i32(self.wave().trailing_zeros());
  929. let w = self.s.m.bin(self.s.entry, Bin::LShr, f, shift);
  930. let k24 = self.s.m.i32(24);
  931. return Val::I32(self.s.m.bin(self.s.entry, Bin::Shl, w, k24));
  932. }
  933. _ => return Val::Missing("a pixel system input"),
  934. };
  935. let free = self
  936. .s
  937. .inputs
  938. .iter()
  939. .filter_map(|e| e.row)
  940. .map(|r| r + 1)
  941. .max()
  942. .unwrap_or(0);
  943. let id = match self.s.inputs.iter().position(|e| e.kind == kind) {
  944. Some(id) => {
  945. if kind != 3 {
  946. self.s.inputs[id].row.get_or_insert(free);
  947. }
  948. id
  949. }
  950. None if kind >= 3 => return Val::Missing("a pixel system input the signature lacks"),
  951. None => {
  952. // The console signature leaves out vertex and instance ids; PC
  953. // gives them a row after the others.
  954. let row = self
  955. .s
  956. .inputs
  957. .iter()
  958. .filter_map(|e| e.row)
  959. .map(|r| r + 1)
  960. .max()
  961. .unwrap_or(0);
  962. self.s.inputs.push(SigElement {
  963. name: ["", "SV_VertexID", "SV_InstanceID"][kind as usize].into(),
  964. index: 0,
  965. kind,
  966. comp: 5,
  967. interp: 0,
  968. row: Some(row),
  969. col: 0,
  970. cols: 1,
  971. usage: 0,
  972. half: false,
  973. });
  974. self.s.inputs.len() - 1
  975. }
  976. };
  977. self.load_input(id, col)
  978. }
  979. /// A component of a compute thread or group id, read in the entry block.
  980. fn compute_id(&mut self, name: &str, opcode: u32, c: u8) -> Val {
  981. let (entry, c) = (self.s.entry, self.s.m.i32(u32::from(c)));
  982. Val::I32(
  983. self.s
  984. .op(entry, name, Attr::ReadNone, self.s.t.i32, opcode, &[c]),
  985. )
  986. }
  987. fn find_input(&self, row: u8, channel: u8) -> Option<(usize, u8)> {
  988. self.s.inputs.iter().enumerate().find_map(|(id, e)| {
  989. let r = e.row?;
  990. // `then`, not `then_some`: the channel is only past `col` when
  991. // the condition holds.
  992. (r == u32::from(row) && channel >= e.col && channel < e.col + e.cols)
  993. .then(|| (id, channel - e.col))
  994. })
  995. }
  996. fn load_input(&mut self, id: usize, col: u8) -> Val {
  997. if self.s.inputs[id].half {
  998. // shortcut: 16-bit vertex inputs (the fetch routine's) are not
  999. // unpacked; pixel inputs are (`interp`).
  1000. return Val::Missing("a 16-bit input");
  1001. }
  1002. self.load_any_input(id, col)
  1003. }
  1004. /// An input element's channel as declared (16-bit ones as 32-bit floats).
  1005. fn load_any_input(&mut self, id: usize, col: u8) -> Val {
  1006. let e = &mut self.s.inputs[id];
  1007. e.usage |= 1 << col;
  1008. let (int, bit) = (e.comp != 9, e.comp == 1);
  1009. let ty = if bit {
  1010. self.s.t.i1
  1011. } else if int {
  1012. self.s.t.i32
  1013. } else {
  1014. self.s.t.f32
  1015. };
  1016. let suffix = if bit {
  1017. ".i1"
  1018. } else if int {
  1019. ".i32"
  1020. } else {
  1021. ".f32"
  1022. };
  1023. let entry = self.s.entry;
  1024. let args = [
  1025. self.s.m.i32(id as u32),
  1026. self.s.m.i32(0),
  1027. self.s.m.i8(col),
  1028. self.s.m.undef(self.s.t.i32),
  1029. ];
  1030. let v = self.s.op(
  1031. entry,
  1032. &format!("loadInput{suffix}"),
  1033. Attr::ReadNone,
  1034. ty,
  1035. 4,
  1036. &args,
  1037. );
  1038. if bit {
  1039. let z = self.s.m.cast(entry, Cast::ZExt, v, self.s.t.i32);
  1040. Val::I32(z)
  1041. } else if int {
  1042. Val::I32(v)
  1043. } else {
  1044. Val::I32(self.s.m.cast(entry, Cast::Bitcast, v, self.s.t.i32))
  1045. }
  1046. }
  1047. /// The DXIL form of an IR value.
  1048. fn get(&mut self, v: Value) -> Result<Val, Why> {
  1049. if self.phi_at.contains_key(&v) {
  1050. self.read_phis.insert(v);
  1051. }
  1052. let is_mask = self.x.st.masks.contains_key(&v) || self.x.st.highs.contains_key(&v);
  1053. match self.vals.get(&v) {
  1054. Some(&Val::Missing(_)) | None if self.mask_ok && is_mask => {
  1055. return self.mask_dword(v).map(Val::I32);
  1056. }
  1057. Some(&Val::Missing(w)) => return Err(w),
  1058. Some(&val) => return Ok(val),
  1059. None => {}
  1060. }
  1061. if let Some(&(param, dword)) = self.params.get(&v) {
  1062. let val = self.user(param, dword);
  1063. self.vals.insert(v, val);
  1064. return Ok(val);
  1065. }
  1066. Err("a value defined after its use")
  1067. }
  1068. fn i32_of(&mut self, v: Value) -> Result<V, Why> {
  1069. match self.get(v)? {
  1070. Val::I32(x) => Ok(x),
  1071. Val::Bit(x) => Ok(self.s.m.cast(self.cur, Cast::ZExt, x, self.s.t.i32)),
  1072. Val::Missing(w) => Err(w),
  1073. }
  1074. }
  1075. /// A user-data dword: a root parameter's value.
  1076. fn user(&mut self, param: usize, dword: u32) -> Val {
  1077. let rp = self.x.native.layout[param];
  1078. match rp.root {
  1079. RootType::ResourceHeap | RootType::SamplerHeap => return Val::I32(self.s.m.i32(0)),
  1080. RootType::Constants | RootType::Table => {}
  1081. _ => return Val::Missing("a root descriptor"),
  1082. }
  1083. let index = u32::from(rp.user_data) + dword;
  1084. self.user_reads.insert(
  1085. index,
  1086. UserData {
  1087. index,
  1088. slot: rp.slot,
  1089. root: rp.root,
  1090. dword,
  1091. },
  1092. );
  1093. self.s.user_data = self.s.user_data.max(index + 1);
  1094. let h = match self.user_data {
  1095. Some(h) => h,
  1096. None => {
  1097. let h = self.s.user_data_handle();
  1098. self.user_data = Some(h);
  1099. h
  1100. }
  1101. };
  1102. let entry = self.s.entry;
  1103. let row = self.s.m.i32(index / 4);
  1104. let r = self.s.op(
  1105. entry,
  1106. "cbufferLoadLegacy.i32",
  1107. Attr::ReadOnly,
  1108. self.s.t.cbuf_ret,
  1109. 59,
  1110. &[h, row],
  1111. );
  1112. Val::I32(self.s.m.extract(entry, r, index % 4))
  1113. }
  1114. /// A dword of a lane mask as a number: the ballot of the lanes' bits,
  1115. /// taken in the block that writes the mask (see [`MaskData`]).
  1116. fn mask_dword(&mut self, v: Value) -> Result<V, Why> {
  1117. let (lo, high) = match self.x.st.highs.get(&v) {
  1118. Some(&lo) => (lo, true),
  1119. None => (v, false),
  1120. };
  1121. let &m = self.x.st.masks.get(&lo).ok_or(LANE_MASK)?;
  1122. if !self.x.st.active.contains(&lo) {
  1123. return Err("a lane mask holding lanes elsewhere read as data");
  1124. }
  1125. let (x, y) = match self.ballots.get(&lo) {
  1126. Some(&xy) => xy,
  1127. None => {
  1128. let at = match self.def_block.get(&lo) {
  1129. // Program inputs (EXEC on entry).
  1130. None => self.s.entry,
  1131. Some(&b) if b == self.cur_ir => self.cur,
  1132. Some(&b) => self.tail[b].ok_or("a lane mask written after its use")?,
  1133. };
  1134. if !self.balloting.insert(lo) {
  1135. return Err("a lane mask whose lanes depend on its own value");
  1136. }
  1137. let bit = self.boolean(m, at);
  1138. self.balloting.remove(&lo);
  1139. let bit = bit?;
  1140. let i32t = self.s.t.i32;
  1141. let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]);
  1142. let r = self
  1143. .s
  1144. .op(at, "waveActiveBallot", Attr::NoUnwind, four, 116, &[bit]);
  1145. self.s.flags |= flags::WAVE_OPS;
  1146. let xy = (self.s.m.extract(at, r, 0), self.s.m.extract(at, r, 1));
  1147. self.ballots.insert(lo, xy);
  1148. xy
  1149. }
  1150. };
  1151. Ok(if high { y } else { x })
  1152. }
  1153. // ---- operands ----
  1154. fn operand(&mut self, inst: &Inst, op: &Operand) -> Result<V, Why> {
  1155. match *op {
  1156. Operand::Scalar { code: NULL, .. } => Ok(self.s.m.i32(0)),
  1157. Operand::Scalar { code, .. } => {
  1158. let v = inst.read(Reg::S(code)).ok_or("an unread operand")?;
  1159. self.i32_of(v)
  1160. }
  1161. Operand::Vector { reg, .. } => {
  1162. let v = inst.read(Reg::V(reg)).ok_or("an unread operand")?;
  1163. self.i32_of(v)
  1164. }
  1165. Operand::Const(c) => crate::resource::inline(c)
  1166. .map(|x| self.s.m.i32(x))
  1167. .ok_or("a special operand (vccz, execz, scc, lds_direct)"),
  1168. Operand::Literal(x) => Ok(self.s.m.i32(x)),
  1169. Operand::Attr { .. } => Err("an attribute operand"),
  1170. }
  1171. }
  1172. fn as_float(&mut self, x: V) -> V {
  1173. self.s.m.cast(self.cur, Cast::Bitcast, x, self.s.t.f32)
  1174. }
  1175. fn as_int(&mut self, f: V) -> V {
  1176. self.s.m.cast(self.cur, Cast::Bitcast, f, self.s.t.i32)
  1177. }
  1178. /// The SDWA operand selection of source `k`: a byte or word of the
  1179. /// dword, zero- or sign-extended (none: the whole dword).
  1180. fn sdwa_src(inst: &Inst, k: usize) -> Option<(u8, bool)> {
  1181. let Fields::Valu(v) = &inst.fields else {
  1182. return None;
  1183. };
  1184. let s = v.sdwa?;
  1185. let sel = *s.src_sel.get(k)?;
  1186. let sext = s.sext >> k & 1 != 0;
  1187. (sel < 6).then_some((sel, sext))
  1188. }
  1189. /// Bits `sel` (0-3 a byte, 4-5 a word) of `x`, extended.
  1190. fn select_bits(&mut self, x: V, sel: u8, sext: bool) -> V {
  1191. let c = self.cur;
  1192. let (width, at) = if sel < 4 {
  1193. (8, 8 * sel)
  1194. } else {
  1195. (16, 16 * (sel - 4))
  1196. };
  1197. let left = self.s.m.i32(u32::from(32 - width - at));
  1198. let t = self.s.m.bin(c, Bin::Shl, x, left);
  1199. let right = self.s.m.i32(32 - u32::from(width));
  1200. let op = if sext { Bin::AShr } else { Bin::LShr };
  1201. self.s.m.bin(c, op, t, right)
  1202. }
  1203. /// A float source with its abs/neg modifiers.
  1204. fn fsrc(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  1205. let Fields::Valu(v) = &inst.fields else {
  1206. unreachable!()
  1207. };
  1208. let op = *v.src.get(k).ok_or("a missing operand")?;
  1209. let selected = Self::sdwa_src(inst, k);
  1210. let mut f = match op {
  1211. _ if selected.is_some() => {
  1212. let (sel, sext) = selected.expect("checked");
  1213. let x = self.operand(inst, &op)?;
  1214. let x = self.select_bits(x, sel, sext);
  1215. self.as_float(x)
  1216. }
  1217. _ if k == 0 && self.src0.is_some() => {
  1218. let x = self.src0.expect("checked");
  1219. self.as_float(x)
  1220. }
  1221. Operand::Vector { reg, .. } | Operand::Scalar { code: reg, .. }
  1222. if !matches!(op, Operand::Scalar { code: NULL, .. }) =>
  1223. {
  1224. let r = if matches!(op, Operand::Vector { .. }) {
  1225. Reg::V(reg)
  1226. } else {
  1227. Reg::S(reg)
  1228. };
  1229. let val = inst.read(r).ok_or("an unread operand")?;
  1230. match self.floats.get(&val) {
  1231. Some(&f) => f,
  1232. None => {
  1233. let x = self.i32_of(val)?;
  1234. self.as_float(x)
  1235. }
  1236. }
  1237. }
  1238. _ => {
  1239. let x = self.operand(inst, &op)?;
  1240. self.as_float(x)
  1241. }
  1242. };
  1243. if v.abs >> k & 1 != 0 {
  1244. f = self.unary(6, f);
  1245. }
  1246. if v.neg >> k & 1 != 0 {
  1247. let z = self.s.m.f32(0x8000_0000);
  1248. f = self.s.m.bin(self.cur, Bin::Sub, z, f);
  1249. }
  1250. Ok(f)
  1251. }
  1252. fn src(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  1253. let Fields::Valu(v) = &inst.fields else {
  1254. unreachable!()
  1255. };
  1256. let op = *v.src.get(k).ok_or("a missing operand")?;
  1257. if v.abs >> k & 1 != 0 || v.neg >> k & 1 != 0 {
  1258. return Err("integer operand modifiers");
  1259. }
  1260. match self.src0 {
  1261. Some(x) if k == 0 => Ok(x),
  1262. _ => {
  1263. let x = self.operand(inst, &op)?;
  1264. Ok(match Self::sdwa_src(inst, k) {
  1265. Some((sel, sext)) => self.select_bits(x, sel, sext),
  1266. None => x,
  1267. })
  1268. }
  1269. }
  1270. }
  1271. fn unary(&mut self, op: u32, f: V) -> V {
  1272. self.s.op(
  1273. self.cur,
  1274. "unary.f32",
  1275. Attr::ReadNone,
  1276. self.s.t.f32,
  1277. op,
  1278. &[f],
  1279. )
  1280. }
  1281. fn binary(&mut self, op: u32, a: V, b: V) -> V {
  1282. self.s.op(
  1283. self.cur,
  1284. "binary.f32",
  1285. Attr::ReadNone,
  1286. self.s.t.f32,
  1287. op,
  1288. &[a, b],
  1289. )
  1290. }
  1291. fn fmad(&mut self, a: V, b: V, c: V) -> V {
  1292. self.s.op(
  1293. self.cur,
  1294. "tertiary.f32",
  1295. Attr::ReadNone,
  1296. self.s.t.f32,
  1297. 46,
  1298. &[a, b, c],
  1299. )
  1300. }
  1301. /// `f` as an f16 in the low bits, rounded toward zero: the nearest-even
  1302. /// conversion, one step back toward zero where it rounded away (which
  1303. /// also turns an overflow to infinity into the largest finite half).
  1304. fn f16_toward_zero(&mut self, f: V) -> V {
  1305. let c = self.cur;
  1306. let i32t = self.s.t.i32;
  1307. let h = self
  1308. .s
  1309. .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]);
  1310. let back = self
  1311. .s
  1312. .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[h]);
  1313. let (fa, ba) = (self.unary(6, f), self.unary(6, back));
  1314. // Ordered: never for NaN.
  1315. let away = self.s.m.cmp(c, pred::OGT, ba, fa);
  1316. let one = self.s.m.i32(1);
  1317. let stepped = self.s.m.bin(c, Bin::Sub, h, one);
  1318. self.s.m.select(c, away, stepped, h)
  1319. }
  1320. /// `(a >> off[4:0]) & ((1 << width) - 1)`, sign-extended from the field's
  1321. /// top bit when `signed`; widths from 32 on take every bit. A signed
  1322. /// field that runs past bit 31 extends from bit 31, as the hardware
  1323. /// does: the shift is arithmetic then.
  1324. fn bfe(&mut self, a: V, off: V, width: V, signed: bool) -> V {
  1325. let c = self.cur;
  1326. let (k31, k32, zero, one, ones) = (
  1327. self.s.m.i32(31),
  1328. self.s.m.i32(32),
  1329. self.s.m.i32(0),
  1330. self.s.m.i32(1),
  1331. self.s.m.i32(u32::MAX),
  1332. );
  1333. let off = self.s.m.bin(c, Bin::And, off, k31);
  1334. let shift = if signed { Bin::AShr } else { Bin::LShr };
  1335. let shifted = self.s.m.bin(c, shift, a, off);
  1336. let full = self.s.m.cmp(c, pred::IUGE, width, k32);
  1337. let w = self.s.m.bin(c, Bin::And, width, k31);
  1338. let mask = self.s.m.bin(c, Bin::Shl, one, w);
  1339. let mask = self.s.m.bin(c, Bin::Sub, mask, one);
  1340. let mask = self.s.m.select(c, full, ones, mask);
  1341. let r = self.s.m.bin(c, Bin::And, shifted, mask);
  1342. if !signed {
  1343. return r;
  1344. }
  1345. // Sign-extend a field narrower than 32 bits (none for width 0).
  1346. let left = self.s.m.bin(c, Bin::Sub, k32, w);
  1347. let left = self.s.m.bin(c, Bin::And, left, k31);
  1348. let t = self.s.m.bin(c, Bin::Shl, r, left);
  1349. let t = self.s.m.bin(c, Bin::AShr, t, left);
  1350. let is0 = self.s.m.cmp(c, pred::EQ, w, zero);
  1351. let keep = self.s.m.bin(c, Bin::Or, full, is0);
  1352. self.s.m.select(c, keep, r, t)
  1353. }
  1354. /// The median of three. With a NaN among them the hardware gives the
  1355. /// minimum of the three instead (the host's minimum skips NaNs, so that
  1356. /// is the smallest number among them).
  1357. fn med3(&mut self, a: V, b: V, third: V) -> V {
  1358. let c = self.cur;
  1359. let lo = self.binary(36, a, b);
  1360. let hi = self.binary(35, a, b);
  1361. let t = self.binary(36, hi, third);
  1362. let median = self.binary(35, lo, t);
  1363. let least = self.binary(36, lo, third);
  1364. let ab = self.s.m.cmp(c, pred::UNO, a, b);
  1365. let nan3 = self.s.m.cmp(c, pred::UNO, third, third);
  1366. let nan = self.s.m.bin(c, Bin::Or, ab, nan3);
  1367. self.s.m.select(c, nan, least, median)
  1368. }
  1369. /// `a - floor(a)`, which on the hardware never reaches 1.0: where it
  1370. /// would round to it (a tiny negative `a`), the result is `below_one`,
  1371. /// the largest value under 1.0 in the operation's width. Hosts differ
  1372. /// here (some give 1.0). Comparing against a `threshold` distinct from
  1373. /// `below_one` prevents drivers (observed on NVIDIA) from folding
  1374. /// `r > k ? k : r` into `minNum` (`FMNMX`) and swallowing NaN.
  1375. fn fract(&mut self, a: V, threshold: f32, below_one: f32) -> V {
  1376. let c = self.cur;
  1377. let r = self.unary(22, a);
  1378. let limit = self.s.m.f32(threshold.to_bits());
  1379. let k = self.s.m.f32(below_one.to_bits());
  1380. let over = self.s.m.cmp(c, pred::OGE, r, limit);
  1381. self.s.m.select(c, over, k, r)
  1382. }
  1383. /// Sine, or cosine, of an angle in turns, as the hardware takes it. The
  1384. /// whole turns are taken off first (`x - round_even(x)`, exact, within
  1385. /// half a turn), so a large angle keeps its fraction; scaling to radians
  1386. /// first rounds it away. A zero passes unreduced (the sine of -0 is -0).
  1387. /// The sine of a half turn and the cosine of a quarter turn are exactly
  1388. /// +0 on the hardware, where the host's function of the rounded angle
  1389. /// gives about 1e-7. Infinities and NaN give NaN.
  1390. /// shortcut: below 2^-12 turns the hardware scales by a slightly
  1391. /// different constant than 2π (a last-place difference).
  1392. fn trig_turns(&mut self, x: V, cosine: bool) -> V {
  1393. let c = self.cur;
  1394. let zero = self.s.m.f32(0);
  1395. let whole = self.unary(26, x);
  1396. let part = self.s.m.bin(c, Bin::Sub, x, whole);
  1397. let is_zero = self.s.m.cmp(c, pred::OEQ, x, zero);
  1398. let part = self.s.m.select(c, is_zero, x, part);
  1399. let k = self.s.m.f32(TWO_PI.to_bits());
  1400. let angle = self.s.m.bin(c, Bin::Mul, part, k);
  1401. let r = self.unary(if cosine { 12 } else { 13 }, angle);
  1402. let at = if cosine { 0.25f32 } else { 0.5 };
  1403. let at = self.s.m.f32(at.to_bits());
  1404. let size = self.unary(6, part);
  1405. let exact = self.s.m.cmp(c, pred::OEQ, size, at);
  1406. self.s.m.select(c, exact, zero, r)
  1407. }
  1408. /// The high dword of a 32 × 32-bit product.
  1409. fn mul_hi(&mut self, a: V, b: V, signed: bool) -> V {
  1410. let c = self.cur;
  1411. let i64t = self.s.m.int(64);
  1412. let ext = if signed { Cast::SExt } else { Cast::ZExt };
  1413. let a = self.s.m.cast(c, ext, a, i64t);
  1414. let b = self.s.m.cast(c, ext, b, i64t);
  1415. let m = self.s.m.bin(c, Bin::Mul, a, b);
  1416. let k32 = self.s.m.int_const(i64t, 32);
  1417. let hi = self.s.m.bin(c, Bin::LShr, m, k32);
  1418. self.s.flags |= flags::INT64;
  1419. self.s.m.cast(c, Cast::Trunc, hi, self.s.t.i32)
  1420. }
  1421. /// `0 × anything = 0`, as in D3D9.
  1422. fn legacy_mul(&mut self, a: V, b: V) -> V {
  1423. let c = self.cur;
  1424. let m = self.s.m.bin(c, Bin::Mul, a, b);
  1425. let zero = self.s.m.f32(0);
  1426. let az = self.s.m.cmp(c, pred::OEQ, a, zero);
  1427. let bz = self.s.m.cmp(c, pred::OEQ, b, zero);
  1428. let z = self.s.m.bin(c, Bin::Or, az, bz);
  1429. self.s.m.select(c, z, zero, m)
  1430. }
  1431. // ---- lane booleans ----
  1432. fn boolean(&mut self, b: Bool, at: usize) -> Result<V, Why> {
  1433. if b == Bool::TRUE || b == Bool::FALSE {
  1434. return Ok(self.s.m.bool(b == Bool::TRUE));
  1435. }
  1436. if let Some(&v) = self.bools.get(&(at, b)) {
  1437. return Ok(v);
  1438. }
  1439. let (atom, lo, hi) = self.x.st.bools.node(b).expect("not a constant");
  1440. let a = self.atom(atom, at)?;
  1441. let m = &mut self.s.m;
  1442. let v = match (lo, hi) {
  1443. (Bool::FALSE, Bool::TRUE) => a,
  1444. (Bool::TRUE, Bool::FALSE) => {
  1445. let t = m.bool(true);
  1446. m.bin(at, Bin::Xor, a, t)
  1447. }
  1448. (Bool::FALSE, h) => {
  1449. let h = self.boolean(h, at)?;
  1450. self.s.m.bin(at, Bin::And, a, h)
  1451. }
  1452. (l, Bool::TRUE) => {
  1453. let l = self.boolean(l, at)?;
  1454. self.s.m.bin(at, Bin::Or, a, l)
  1455. }
  1456. (l, h) => {
  1457. let l = self.boolean(l, at)?;
  1458. let h = self.boolean(h, at)?;
  1459. self.s.m.select(at, a, h, l)
  1460. }
  1461. };
  1462. self.bools.insert((at, b), v);
  1463. Ok(v)
  1464. }
  1465. fn atom(&mut self, atom: Atom, at: usize) -> Result<V, Why> {
  1466. match atom {
  1467. Atom::Lane(v) => self.lane_bits.get(&v).copied().ok_or_else(|| {
  1468. self.lane_fail
  1469. .get(&v)
  1470. .copied()
  1471. .unwrap_or("a lane mask from a carry")
  1472. }),
  1473. Atom::Uniform(v) => match self.get(v)? {
  1474. Val::Bit(x) => Ok(x),
  1475. Val::I32(x) => {
  1476. let z = self.s.m.i32(0);
  1477. Ok(self.s.m.cmp(at, pred::NE, x, z))
  1478. }
  1479. Val::Missing(w) => Err(w),
  1480. },
  1481. Atom::Phi(id) => {
  1482. if let Some(&v) = self.mask_phis.get(&id) {
  1483. return Ok(v);
  1484. }
  1485. let &(b, i) = self
  1486. .phi_at
  1487. .get(&id)
  1488. .ok_or("a lane-mask join without a phi")?;
  1489. let blk = self.block[b].ok_or("an unreachable join")?;
  1490. let v = self.s.m.phi(blk, self.s.t.i1);
  1491. self.mask_phis.insert(id, v);
  1492. self.pending_masks.push((v, b, i));
  1493. Ok(v)
  1494. }
  1495. // shortcut: "some lane of the quad is set" is taken as true: the
  1496. // lanes it adds only feed derivatives, and exports keep their own
  1497. // masks. Wrong if such a section had a side effect.
  1498. Atom::Quad(_) => Ok(self.s.m.bool(true)),
  1499. // With console lanes, a mask held as a number is the console's:
  1500. // the lane tests its own bit.
  1501. Atom::Opaque(v) if self.console_lanes => {
  1502. let hi = match self.pair_high(v) {
  1503. Some(h) => Some(self.get(h)?),
  1504. None => None,
  1505. };
  1506. let lo = self.get(v)?;
  1507. let word = |w: Val| match w {
  1508. Val::I32(x) => Ok(x),
  1509. _ => Err("an opaque lane mask"),
  1510. };
  1511. let lo = word(lo)?;
  1512. let hi = hi.map(word).transpose()?;
  1513. Ok(self.lane_bit(at, lo, hi))
  1514. }
  1515. Atom::Constant(k) if self.console_lanes => {
  1516. let lo = self.s.m.i32(k as u32);
  1517. let hi = self.s.m.i32((k >> 32) as u32);
  1518. Ok(self.lane_bit(at, lo, Some(hi)))
  1519. }
  1520. Atom::Opaque(_) => Err("an opaque lane mask"),
  1521. Atom::Constant(_) => Err("a constant lane mask"),
  1522. }
  1523. }
  1524. /// This lane's bit of the mask `lo`, `hi` (wave64).
  1525. fn lane_bit(&mut self, at: usize, lo: V, hi: Option<V>) -> V {
  1526. let lane = self.s.op(
  1527. at,
  1528. "waveGetLaneIndex",
  1529. Attr::ReadOnly,
  1530. self.s.t.i32,
  1531. 111,
  1532. &[],
  1533. );
  1534. let (k31, k32, one, z) = (
  1535. self.s.m.i32(31),
  1536. self.s.m.i32(32),
  1537. self.s.m.i32(1),
  1538. self.s.m.i32(0),
  1539. );
  1540. let word = match hi {
  1541. Some(hi) => {
  1542. let low = self.s.m.cmp(at, pred::IULT, lane, k32);
  1543. self.s.m.select(at, low, lo, hi)
  1544. }
  1545. None => lo,
  1546. };
  1547. let sh = self.s.m.bin(at, Bin::And, lane, k31);
  1548. let t = self.s.m.bin(at, Bin::LShr, word, sh);
  1549. let t = self.s.m.bin(at, Bin::And, t, one);
  1550. self.s.m.cmp(at, pred::NE, t, z)
  1551. }
  1552. /// The value of the high dword of the wave64 register pair whose low
  1553. /// dword holds `lo` (none in wave32).
  1554. fn pair_high(&self, lo: Value) -> Option<Value> {
  1555. if !self.x.native.wave64 {
  1556. return None;
  1557. }
  1558. let p = self.x.p;
  1559. let pick = |reg: Reg| match reg {
  1560. Reg::S(c) => Some(Reg::S(c + 1)),
  1561. _ => None,
  1562. };
  1563. if let Some(&(reg, _)) = p.inputs.iter().find(|i| i.1 == lo) {
  1564. let h = pick(reg)?;
  1565. return p.inputs.iter().find(|i| i.0 == h).map(|i| i.1);
  1566. }
  1567. if let Some(&(b, i)) = self.phi_at.get(&lo) {
  1568. let h = pick(p.blocks[b].phis[i].reg)?;
  1569. return p.blocks[b]
  1570. .phis
  1571. .iter()
  1572. .find(|q| q.reg == h)
  1573. .map(|q| q.value);
  1574. }
  1575. let b = *self.def_block.get(&lo)?;
  1576. let inst = p.blocks[b]
  1577. .insts
  1578. .iter()
  1579. .find(|i| i.writes.iter().any(|w| w.1 == lo))?;
  1580. let &(reg, _) = inst.writes.iter().find(|w| w.1 == lo)?;
  1581. inst.write(pick(reg)?)
  1582. }
  1583. fn guard(&mut self, b: usize, i: usize) -> Result<Option<V>, Why> {
  1584. match self.x.st.guards[b][i] {
  1585. None => Ok(None),
  1586. Some(g) => Ok(Some(self.boolean(g, self.cur)?)),
  1587. }
  1588. }
  1589. // ---- results ----
  1590. fn set(&mut self, v: Option<Value>, val: Val) {
  1591. if let Some(v) = v {
  1592. self.vals.insert(v, val);
  1593. }
  1594. }
  1595. /// Writes VGPR `reg` (or the SGPR of a lane read), under `guard`.
  1596. fn write(&mut self, inst: &Inst, reg: Reg, x: V, guard: Option<V>) {
  1597. let x = match (Self::sdwa_dst(inst), reg) {
  1598. (Some((sel, unused)), Reg::V(_)) => self.place_bits(inst, reg, x, sel, unused),
  1599. _ => x,
  1600. };
  1601. self.write_placed(inst, reg, x, guard);
  1602. }
  1603. /// [`Self::write`] of a dword already placed (SDWA applied).
  1604. fn write_placed(&mut self, inst: &Inst, reg: Reg, x: V, guard: Option<V>) {
  1605. let Some(new) = inst.write(reg) else { return };
  1606. let x = match (guard, reg) {
  1607. (Some(g), Reg::V(_)) => {
  1608. let old = match inst.read(reg).map(|o| self.i32_of(o)) {
  1609. Some(Ok(o)) => o,
  1610. // The validator refuses reads of undef.
  1611. _ => self.s.m.i32(0),
  1612. };
  1613. self.s.m.select(self.cur, g, x, old)
  1614. }
  1615. _ => x,
  1616. };
  1617. self.vals.insert(new, Val::I32(x));
  1618. }
  1619. /// The SDWA destination selection: a byte or word, and what the other
  1620. /// bits get (0 zeros, 1 the sign above the field, 2 the old bits).
  1621. fn sdwa_dst(inst: &Inst) -> Option<(u8, u8)> {
  1622. let Fields::Valu(v) = &inst.fields else {
  1623. return None;
  1624. };
  1625. let s = v.sdwa?;
  1626. (s.dst_sel < 6).then_some((s.dst_sel, s.dst_unused))
  1627. }
  1628. /// The low byte or word of `x` placed at `sel` in VGPR `reg`.
  1629. fn place_bits(&mut self, inst: &Inst, reg: Reg, x: V, sel: u8, unused: u8) -> V {
  1630. let c = self.cur;
  1631. let (width, at) = if sel < 4 {
  1632. (8u32, 8 * u32::from(sel))
  1633. } else {
  1634. (16, 16 * u32::from(sel - 4))
  1635. };
  1636. let left = self.s.m.i32(32 - width);
  1637. let t = self.s.m.bin(c, Bin::Shl, x, left);
  1638. let right = self.s.m.i32(32 - width - at);
  1639. if unused == 1 {
  1640. // Bits below the field shift in as zeros.
  1641. return self.s.m.bin(c, Bin::AShr, t, right);
  1642. }
  1643. let field = self.s.m.bin(c, Bin::LShr, t, right);
  1644. if unused != 2 {
  1645. return field;
  1646. }
  1647. let old = match inst.read(reg).map(|o| self.i32_of(o)) {
  1648. Some(Ok(o)) => o,
  1649. _ => self.s.m.i32(0),
  1650. };
  1651. let keep = self.s.m.i32(!((((1u64 << width) - 1) as u32) << at));
  1652. let old = self.s.m.bin(c, Bin::And, old, keep);
  1653. self.s.m.bin(c, Bin::Or, old, field)
  1654. }
  1655. fn write_f(&mut self, inst: &Inst, f: V, guard: Option<V>) -> Result<(), Why> {
  1656. let Fields::Valu(v) = &inst.fields else {
  1657. unreachable!()
  1658. };
  1659. let mut f = f;
  1660. match v.omod {
  1661. 0 => {}
  1662. k => {
  1663. let factor = [1.0f32, 2.0, 4.0, 0.5][usize::from(k)];
  1664. let c = self.s.m.f32(factor.to_bits());
  1665. f = self.s.m.bin(self.cur, Bin::Mul, f, c);
  1666. }
  1667. }
  1668. if v.clamp {
  1669. f = self.unary(7, f);
  1670. }
  1671. let Some(Operand::Vector { reg, .. }) = v.dst else {
  1672. return Err("a float result outside a VGPR");
  1673. };
  1674. let x = self.as_int(f);
  1675. self.write(inst, Reg::V(reg), x, guard);
  1676. if guard.is_none()
  1677. && Self::sdwa_dst(inst).is_none()
  1678. && let Some(new) = inst.write(Reg::V(reg))
  1679. {
  1680. self.floats.insert(new, f);
  1681. }
  1682. Ok(())
  1683. }
  1684. fn write_i(&mut self, inst: &Inst, x: V, guard: Option<V>) -> Result<(), Why> {
  1685. let Fields::Valu(v) = &inst.fields else {
  1686. unreachable!()
  1687. };
  1688. if v.clamp || v.omod != 0 {
  1689. return Err("integer output modifiers");
  1690. }
  1691. match v.dst {
  1692. Some(Operand::Vector { reg, .. }) => self.write(inst, Reg::V(reg), x, guard),
  1693. Some(Operand::Scalar { code, .. }) => self.write(inst, Reg::S(code), x, None),
  1694. _ => return Err("a result without a register"),
  1695. }
  1696. Ok(())
  1697. }
  1698. /// Starts code only the lanes where `guard` holds run (a store under a
  1699. /// lane guard): returns where it started and the join block.
  1700. fn begin_guarded(&mut self, guard: Option<V>) -> Option<(usize, usize)> {
  1701. let g = guard?;
  1702. let (then, join) = (self.s.m.new_block(), self.s.m.new_block());
  1703. self.s.m.terminate(self.cur, Term::CondBr(g, then, join));
  1704. let head = self.cur;
  1705. self.cur = then;
  1706. Some((head, join))
  1707. }
  1708. /// Ends guarded code; each (value inside, value outside) becomes a phi.
  1709. fn end_guarded(&mut self, at: Option<(usize, usize)>, values: &[(V, V)]) -> Vec<V> {
  1710. let Some((head, join)) = at else {
  1711. return values.iter().map(|v| v.0).collect();
  1712. };
  1713. let then = self.cur;
  1714. self.s.m.terminate(then, Term::Br(join));
  1715. self.cur = join;
  1716. values
  1717. .iter()
  1718. .map(|&(inside, outside)| {
  1719. let ty = self.s.m.type_of(inside);
  1720. let phi = self.s.m.phi(join, ty);
  1721. self.s.m.set_phi(phi, vec![(inside, then), (outside, head)]);
  1722. phi
  1723. })
  1724. .collect()
  1725. }
  1726. /// Code that depends on the lane layout: wave operations, and in compute
  1727. /// the console's wave size (lanes are thread ids in group order there).
  1728. /// Pixel lanes match only within a quad.
  1729. fn cross_lane(&mut self, quad: bool) -> Result<(), Why> {
  1730. if self.s.mesh.is_some() {
  1731. // shortcut: no wave size for mesh shaders in SM 6.6, so host
  1732. // lanes cannot follow the console's; emulate through group-shared
  1733. // memory if mesh programs turn out to need these.
  1734. return Err("a cross-lane operation in a mesh shader");
  1735. }
  1736. if self.s.threads.is_none() && !(quad && self.s.pixel) {
  1737. return Err("a cross-lane operation outside compute");
  1738. }
  1739. debug_assert!(self.s.threads.is_none() || self.console_lanes);
  1740. self.s.flags |= flags::WAVE_OPS;
  1741. Ok(())
  1742. }
  1743. /// Component `c` of the thread id in the group. With console lanes, the
  1744. /// thread is relabelled so that its host lane is its console lane: the
  1745. /// flat id is the wave's first lane's, rounded down to the wave size,
  1746. /// plus the lane index. (A bijection while each host wave holds a
  1747. /// wave-aligned run of flat ids, as the console's waves do.)
  1748. fn thread_id(&mut self, c: u8) -> Val {
  1749. if !self.console_lanes {
  1750. return self.compute_id("threadIdInGroup.i32", 95, c);
  1751. }
  1752. let [x, y, _] = self.s.threads.expect("compute");
  1753. let e = self.s.entry;
  1754. let i32t = self.s.t.i32;
  1755. let flat = self.s.op(
  1756. e,
  1757. "flattenedThreadIdInGroup.i32",
  1758. Attr::ReadNone,
  1759. i32t,
  1760. 96,
  1761. &[],
  1762. );
  1763. let first = self.s.op(
  1764. e,
  1765. "waveReadLaneFirst.i32",
  1766. Attr::NoUnwind,
  1767. i32t,
  1768. 118,
  1769. &[flat],
  1770. );
  1771. let wave = self.s.wave_size.expect("set with console lanes");
  1772. let mask = self.s.m.i32(!(wave - 1));
  1773. let base = self.s.m.bin(e, Bin::And, first, mask);
  1774. let lane = self.lane_index();
  1775. let f = self.s.m.bin(e, Bin::Add, base, lane);
  1776. self.s.flags |= flags::WAVE_OPS;
  1777. let (xk, yk, xy) = (self.s.m.i32(x), self.s.m.i32(y), self.s.m.i32(x * y));
  1778. Val::I32(match c {
  1779. 0 => self.s.m.bin(e, Bin::URem, f, xk),
  1780. 1 => {
  1781. let t = self.s.m.bin(e, Bin::UDiv, f, xk);
  1782. self.s.m.bin(e, Bin::URem, t, yk)
  1783. }
  1784. _ => self.s.m.bin(e, Bin::UDiv, f, xy),
  1785. })
  1786. }
  1787. /// Mesh: the counts and the primitives no lane exports. The console's
  1788. /// counts come from one lane's allocation request, which DXIL cannot
  1789. /// express (one call, dominating every output write).
  1790. // shortcut: the counts are the declared maxima and each lane first culls
  1791. // its primitive (all indices 0, zero area), so primitives past the
  1792. // program's count are culled and vertices past it unused; this costs
  1793. // the host the unused vertex and primitive slots. Pass the program's own
  1794. // counts if that shows in frame time.
  1795. fn mesh_prologue(&mut self, mesh: super::shader::Mesh) -> Result<(), Why> {
  1796. let threads = self.s.threads.expect("mesh")[0];
  1797. if mesh.topology != 2 {
  1798. return Err("a mesh shader not drawing triangles");
  1799. }
  1800. if threads > 128 || mesh.max_vertices > 256 || mesh.max_primitives > 256 {
  1801. return Err("a mesh shader beyond the host's limits");
  1802. }
  1803. let e = self.s.entry;
  1804. let void = self.s.t.void;
  1805. let (v, p) = (
  1806. self.s.m.i32(mesh.max_vertices),
  1807. self.s.m.i32(mesh.max_primitives),
  1808. );
  1809. self.s
  1810. .op(e, "setMeshOutputCounts", Attr::NoUnwind, void, 168, &[v, p]);
  1811. let flat = self.mesh_thread();
  1812. let guard = (threads > mesh.max_primitives).then(|| self.s.m.cmp(e, pred::IULT, flat, p));
  1813. let at = self.begin_guarded(guard);
  1814. let z = self.s.m.i32(0);
  1815. self.s.op(
  1816. self.cur,
  1817. "emitIndices",
  1818. Attr::NoUnwind,
  1819. void,
  1820. 169,
  1821. &[flat, z, z, z],
  1822. );
  1823. self.end_guarded(at, &[]);
  1824. Ok(())
  1825. }
  1826. /// Mesh: the thread's index in the group, which is its vertex and
  1827. /// primitive index.
  1828. fn mesh_thread(&mut self) -> V {
  1829. if let Some(f) = self.flat {
  1830. return f;
  1831. }
  1832. let e = self.s.entry;
  1833. let f = self.s.op(
  1834. e,
  1835. "flattenedThreadIdInGroup.i32",
  1836. Attr::ReadNone,
  1837. self.s.t.i32,
  1838. 96,
  1839. &[],
  1840. );
  1841. self.flat = Some(f);
  1842. f
  1843. }
  1844. /// The console wave size.
  1845. fn wave(&self) -> u32 {
  1846. if self.x.native.wave64 { 64 } else { 32 }
  1847. }
  1848. fn lane_index(&mut self) -> V {
  1849. if self.s.mesh.is_some() {
  1850. // The console's lane: mesh code reads no other lanes, so host
  1851. // waves need not match the console's.
  1852. let f = self.mesh_thread();
  1853. let m = self.s.m.i32(self.wave() - 1);
  1854. return self.s.m.bin(self.s.entry, Bin::And, f, m);
  1855. }
  1856. self.s.op(
  1857. self.cur,
  1858. "waveGetLaneIndex",
  1859. Attr::ReadOnly,
  1860. self.s.t.i32,
  1861. 111,
  1862. &[],
  1863. )
  1864. }
  1865. /// `x` of lane `src` (in this lane's quad) through quad reads, whose
  1866. /// lane must be a constant.
  1867. fn quad_pick(&mut self, x: V, src: V) -> V {
  1868. self.s.flags |= flags::WAVE_OPS;
  1869. let c = self.cur;
  1870. let three = self.s.m.i32(3);
  1871. let q = self.s.m.bin(c, Bin::And, src, three);
  1872. let mut r = x;
  1873. for n in 0..4 {
  1874. let kn = self.s.m.i32(n);
  1875. let read = self.s.op(
  1876. c,
  1877. "quadReadLaneAt.i32",
  1878. Attr::NoUnwind,
  1879. self.s.t.i32,
  1880. 122,
  1881. &[x, kn],
  1882. );
  1883. let is = self.s.m.cmp(c, pred::EQ, q, kn);
  1884. r = self.s.m.select(c, is, read, r);
  1885. }
  1886. r
  1887. }
  1888. fn read_lane(&mut self, x: V, lane: V) -> V {
  1889. self.s.op(
  1890. self.cur,
  1891. "waveReadLaneAt.i32",
  1892. Attr::NoUnwind,
  1893. self.s.t.i32,
  1894. 117,
  1895. &[x, lane],
  1896. )
  1897. }
  1898. /// The float value of a register value.
  1899. fn float_of(&mut self, v: Value) -> Result<V, Why> {
  1900. if let Some(&f) = self.floats.get(&v) {
  1901. return Ok(f);
  1902. }
  1903. let x = self.i32_of(v)?;
  1904. Ok(self.as_float(x))
  1905. }
  1906. /// The values of VGPRs `reg..reg + n` as `inst` reads them.
  1907. fn vgprs(&mut self, inst: &Inst, op: &Operand, n: u8) -> Result<Vec<V>, Why> {
  1908. let Operand::Vector { reg, .. } = *op else {
  1909. return Err("a vector operand");
  1910. };
  1911. (0..n)
  1912. .map(|k| {
  1913. let v = inst.read(Reg::V(reg + k)).ok_or("an unread operand")?;
  1914. self.i32_of(v)
  1915. })
  1916. .collect()
  1917. }
  1918. /// LDS (thread-group shared memory) and `ds_swizzle`.
  1919. fn ds(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  1920. let Fields::Ds {
  1921. dst,
  1922. addr,
  1923. data,
  1924. offset0,
  1925. offset1,
  1926. gds,
  1927. } = &inst.fields
  1928. else {
  1929. unreachable!()
  1930. };
  1931. if *gds {
  1932. return Err("GDS");
  1933. }
  1934. let name = inst.name();
  1935. let guard = self.guard(b, i)?;
  1936. let c = self.cur;
  1937. let offset = u32::from(*offset0) | u32::from(*offset1) << 8;
  1938. let dst_reg = match dst {
  1939. Some(Operand::Vector { reg, .. }) => Some(*reg),
  1940. _ => None,
  1941. };
  1942. if name == "ds_swizzle_b32" {
  1943. // Bit 15 set: each lane of a quad picks a lane of it; else lanes
  1944. // of each group of 32 combine their index with and/or/xor masks.
  1945. let quad = offset & 0x8000 != 0
  1946. || offset & 0x1C == 0x1C && offset & 0x380 == 0 && offset >> 10 & 0x1F < 4;
  1947. // Mesh: host quads are threads 4n..4n+3 of a 1D group, as the
  1948. // console's, so quad-local swizzles read through quad operations.
  1949. let mesh_quad = self.s.mesh.is_some() && quad;
  1950. if !mesh_quad {
  1951. self.cross_lane(quad)?;
  1952. }
  1953. // The source sits in the address field.
  1954. let x = self.vgprs(inst, addr.as_ref().ok_or("a swizzle source")?, 1)?[0];
  1955. let lane = self.lane_index();
  1956. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  1957. let src = if offset & 0x8000 != 0 {
  1958. let (three, one) = (k(self, 3), k(self, 1));
  1959. let sel = self.s.m.bin(c, Bin::And, lane, three);
  1960. let sh = self.s.m.bin(c, Bin::Shl, sel, one);
  1961. let pattern = k(self, offset & 0xFF);
  1962. let pick = self.s.m.bin(c, Bin::LShr, pattern, sh);
  1963. let pick = self.s.m.bin(c, Bin::And, pick, three);
  1964. let not3 = k(self, !3);
  1965. let base = self.s.m.bin(c, Bin::And, lane, not3);
  1966. self.s.m.bin(c, Bin::Or, base, pick)
  1967. } else {
  1968. let and = k(self, offset & 0x1F | !0x1F);
  1969. let or = k(self, offset >> 5 & 0x1F);
  1970. let xor = k(self, offset >> 10 & 0x1F);
  1971. let t = self.s.m.bin(c, Bin::And, lane, and);
  1972. let t = self.s.m.bin(c, Bin::Or, t, or);
  1973. self.s.m.bin(c, Bin::Xor, t, xor)
  1974. };
  1975. let r = if mesh_quad {
  1976. self.quad_pick(x, src)
  1977. } else {
  1978. self.read_lane(x, src)
  1979. };
  1980. let reg = dst_reg.ok_or("a swizzle result")?;
  1981. self.write(inst, Reg::V(reg), r, guard);
  1982. return Ok(());
  1983. }
  1984. if self.s.lds_dwords == 0 {
  1985. return Err("LDS the program does not allocate");
  1986. }
  1987. let a = self.vgprs(inst, addr.as_ref().ok_or("an LDS address")?, 1)?[0];
  1988. // shortcut: LDS addresses are taken as dword-aligned and in bounds
  1989. // (out-of-bounds console accesses read 0 and drop writes).
  1990. let dword = |l: &mut Self, bytes: u32| -> V {
  1991. let c = l.cur;
  1992. let o = l.s.m.i32(bytes);
  1993. let at = l.s.m.bin(c, Bin::Add, a, o);
  1994. let two = l.s.m.i32(2);
  1995. let index = l.s.m.bin(c, Bin::LShr, at, two);
  1996. let lds = l.s.lds();
  1997. l.s.m.element(c, lds, index)
  1998. };
  1999. let width = |n: &str| match n.rsplit('_').next() {
  2000. Some("b64") => 2,
  2001. Some("b96") => 3,
  2002. Some("b128") => 4,
  2003. _ => 1,
  2004. };
  2005. // (byte offset, dwords) per element; read2/write2 scale their two
  2006. // offsets by the element size (×64 for st64).
  2007. let pair = |n: &str| -> Vec<(u32, u32)> {
  2008. let w = width(n);
  2009. let scale = 4 * w * if n.contains("st64") { 64 } else { 1 };
  2010. vec![
  2011. (u32::from(*offset0) * scale, w),
  2012. (u32::from(*offset1) * scale, w),
  2013. ]
  2014. };
  2015. if let Some(rest) = name.strip_prefix("ds_read") {
  2016. let elements = if rest.starts_with('2') {
  2017. pair(name)
  2018. } else if matches!(rest, "_b32" | "_b64" | "_b96" | "_b128") {
  2019. vec![(offset, width(name))]
  2020. } else {
  2021. return Err("an LDS read of bytes or halves");
  2022. };
  2023. let reg = dst_reg.ok_or("an LDS read result")?;
  2024. let mut n = 0;
  2025. for (off, w) in elements {
  2026. for k in 0..w {
  2027. let p = dword(self, off + 4 * k);
  2028. let x = self.s.m.load(self.cur, p);
  2029. self.write(inst, Reg::V(reg + n), x, guard);
  2030. n += 1;
  2031. }
  2032. }
  2033. return Ok(());
  2034. }
  2035. if let Some(rest) = name.strip_prefix("ds_write") {
  2036. let elements = if rest.starts_with('2') {
  2037. pair(name)
  2038. } else if matches!(rest, "_b32" | "_b64" | "_b96" | "_b128") {
  2039. vec![(offset, width(name))]
  2040. } else {
  2041. return Err("an LDS write of bytes or halves");
  2042. };
  2043. let mut stores = Vec::new();
  2044. for (e, (off, w)) in elements.into_iter().enumerate() {
  2045. let vals = self.vgprs(inst, data.get(e).ok_or("an LDS write")?, w as u8)?;
  2046. for (k, x) in vals.into_iter().enumerate() {
  2047. stores.push((off + 4 * k as u32, x));
  2048. }
  2049. }
  2050. let at = self.begin_guarded(guard);
  2051. for (off, x) in stores {
  2052. let p = dword(self, off);
  2053. self.s.m.store(self.cur, p, x);
  2054. }
  2055. self.end_guarded(at, &[]);
  2056. return Ok(());
  2057. }
  2058. // Atomics: the old value returns with `_rtn`.
  2059. let op = name
  2060. .strip_prefix("ds_")
  2061. .map(|n| n.replace("_rtn", ""))
  2062. .ok_or("an LDS operation")?;
  2063. use super::bitcode::Rmw;
  2064. let rmw = match op.as_str() {
  2065. "add_u32" => Some(Rmw::Add),
  2066. "sub_u32" => Some(Rmw::Sub),
  2067. "and_b32" => Some(Rmw::And),
  2068. "or_b32" => Some(Rmw::Or),
  2069. "xor_b32" => Some(Rmw::Xor),
  2070. "min_i32" => Some(Rmw::Min),
  2071. "max_i32" => Some(Rmw::Max),
  2072. "min_u32" => Some(Rmw::UMin),
  2073. "max_u32" => Some(Rmw::UMax),
  2074. "wrxchg_b32" => Some(Rmw::Xchg),
  2075. "cmpst_b32" => None,
  2076. _ => return Err("an LDS operation"),
  2077. };
  2078. let v0 = self.vgprs(inst, data.first().ok_or("an LDS atomic")?, 1)?[0];
  2079. let v1 = match data.get(1) {
  2080. Some(d) => Some(self.vgprs(inst, d, 1)?[0]),
  2081. None => None,
  2082. };
  2083. let old_reg = dst_reg.and_then(|r| inst.read(Reg::V(r)).map(|v| (r, v)));
  2084. let outside = match old_reg {
  2085. Some((_, v)) => self.i32_of(v).unwrap_or(self.s.m.i32(0)),
  2086. None => self.s.m.i32(0),
  2087. };
  2088. let p = dword(self, offset);
  2089. let at = self.begin_guarded(guard);
  2090. let r = match rmw {
  2091. Some(op) => self.s.m.atomic(self.cur, op, p, v0),
  2092. // Compare with data0, store data1.
  2093. None => self
  2094. .s
  2095. .m
  2096. .cmpxchg(self.cur, p, v0, v1.ok_or("an LDS compare")?),
  2097. };
  2098. let r = self.end_guarded(at, &[(r, outside)])[0];
  2099. if let Some(reg) = dst_reg {
  2100. self.write(inst, Reg::V(reg), r, None);
  2101. }
  2102. Ok(())
  2103. }
  2104. // ---- instructions ----
  2105. fn inst(&mut self, b: usize, i: usize) -> Result<(), Stop> {
  2106. let inst: &'a Inst = &self.x.p.blocks[b].insts[i];
  2107. let offset = inst.machine.offset;
  2108. let name = inst.name();
  2109. self.mask_ok = match self.mask_data {
  2110. MaskData::Console => true,
  2111. MaskData::Host => {
  2112. name.starts_with("s_bcnt1_i32_")
  2113. || name.starts_with("s_ff1_i32_")
  2114. || name.starts_with("v_mbcnt_")
  2115. || matches!(
  2116. name,
  2117. "s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_u64" | "s_cmp_lg_u64"
  2118. )
  2119. }
  2120. MaskData::None => false,
  2121. };
  2122. let effect = matches!(inst.fields, Fields::Exp { .. })
  2123. || matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_")
  2124. || name.contains("store")
  2125. || name.contains("atomic")
  2126. || name == "s_barrier"
  2127. || matches!(inst.fields, Fields::Ds { .. })
  2128. && !(name.starts_with("ds_read")
  2129. || name.starts_with("ds_swizzle")
  2130. || name.contains("permute"));
  2131. let r = match &inst.fields {
  2132. Fields::Sop { .. } => self.sop(inst),
  2133. Fields::Sopp { .. } if name == "s_barrier" && self.no_barrier.contains(&b) => Ok(()),
  2134. Fields::Sopp { .. } if name == "s_barrier" => {
  2135. // Thread-group sync with a shared-memory fence, and a UAV
  2136. // fence when the program writes UAVs (the waits before an
  2137. // s_barrier make those writes visible on the console).
  2138. let mode = if self.writes_uavs { 1 | 2 | 8 } else { 1 | 8 };
  2139. let mode = self.s.m.i32(mode);
  2140. let void = self.s.t.void;
  2141. self.s
  2142. .op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]);
  2143. Ok(())
  2144. }
  2145. Fields::Sopp { .. } => Ok(()),
  2146. Fields::Smem { .. } => self.smem(inst, (b, i)),
  2147. Fields::Valu(_) if name.starts_with("v_interp_") => self.interp(inst, (b, i)),
  2148. Fields::Valu(_) => self.valu(inst, b, i),
  2149. Fields::Vintrp { .. } => self.interp(inst, (b, i)),
  2150. Fields::Image { .. } => self.image(inst, b, i),
  2151. Fields::Buffer { .. } => self.buffer(inst, b, i),
  2152. Fields::Exp { .. } => self.export(b, i),
  2153. Fields::Ds { .. } => self.ds(inst, b, i),
  2154. Fields::Flat { .. } if name.starts_with("global_") => self.flat(inst, b, i),
  2155. Fields::Flat { .. } => Err("flat memory"),
  2156. };
  2157. match r {
  2158. Ok(()) => Ok(()),
  2159. Err(why) if effect => Err(unsupported(offset, why)),
  2160. Err(why) => {
  2161. for &(_, v) in &inst.writes {
  2162. self.vals.insert(v, Val::Missing(why));
  2163. }
  2164. Ok(())
  2165. }
  2166. }
  2167. }
  2168. fn is_mask(&self, v: Option<Value>) -> bool {
  2169. v.is_some_and(|v| self.x.st.masks.contains_key(&v))
  2170. }
  2171. fn sop(&mut self, inst: &Inst) -> Result<(), Why> {
  2172. let Fields::Sop { dst, src, imm } = &inst.fields else {
  2173. unreachable!()
  2174. };
  2175. let name = inst.name();
  2176. let scc = inst.write(Reg::Scc);
  2177. let dst_code = match dst {
  2178. Some(Operand::Scalar { code, .. }) => Some(*code),
  2179. _ => None,
  2180. };
  2181. let lo = dst_code.and_then(|c| inst.write(Reg::S(c)));
  2182. if inst.write(Reg::S(EXEC)).is_some() || self.is_mask(lo) {
  2183. return Err(LANE_MASK);
  2184. }
  2185. if matches!(
  2186. name,
  2187. "s_setreg_imm32_b32" | "s_setreg_b32" | "s_swappc_b64" | "s_version"
  2188. ) || name.starts_with("s_waitcnt")
  2189. {
  2190. // shortcut: the float MODE register is not modelled; s_swappc_b64 is the
  2191. // vertex fetch call, whose results arrive as inputs.
  2192. return Err("a register the emitter does not model");
  2193. }
  2194. let c = self.cur;
  2195. let src32 = |l: &mut Self, k: usize| -> Result<V, Why> {
  2196. // SOPK arithmetic reads its destination as the first source.
  2197. if k == 0 && matches!(name, "s_addk_i32" | "s_mulk_i32") {
  2198. let d = dst.as_ref().ok_or("a missing operand")?;
  2199. return l.operand(inst, d);
  2200. }
  2201. let op = src.get(k).ok_or("a missing operand")?;
  2202. l.operand(inst, op)
  2203. };
  2204. let sext16 = |l: &mut Self| l.s.m.i32(i32::from(imm.unwrap_or(0) as i16) as u32);
  2205. // Dword `h` of 64-bit source `k` (inline constants sign-extend).
  2206. let half = |l: &mut Self, k: usize, h: u8| -> Result<V, Why> {
  2207. match src.get(k) {
  2208. Some(&Operand::Scalar { code, .. }) if code != NULL => {
  2209. let v = inst.read(Reg::S(code + h)).ok_or("an unread operand")?;
  2210. l.i32_of(v)
  2211. }
  2212. Some(op) if h == 0 => l.operand(inst, op),
  2213. Some(Operand::Const(k)) => {
  2214. let x = crate::resource::inline(*k).ok_or("a special operand")?;
  2215. Ok(l.s.m.i32(if (x as i32) < 0 { u32::MAX } else { 0 }))
  2216. }
  2217. _ => Ok(l.s.m.i32(0)),
  2218. }
  2219. };
  2220. if let Some(op) = name.strip_prefix("s_cmp_").filter(|o| o.ends_with("_u64")) {
  2221. // eq and lg only: both dwords.
  2222. let mut r = None;
  2223. for h in 0..2 {
  2224. let (a, b) = (half(self, 0, h)?, half(self, 1, h)?);
  2225. let e = self.s.m.cmp(c, pred::EQ, a, b);
  2226. r = Some(match r {
  2227. Some(x) => self.s.m.bin(c, Bin::And, x, e),
  2228. None => e,
  2229. });
  2230. }
  2231. let mut r = r.expect("two dwords");
  2232. if op.starts_with("lg") {
  2233. let t = self.s.m.bool(true);
  2234. r = self.s.m.bin(c, Bin::Xor, r, t);
  2235. }
  2236. self.set(scc, Val::Bit(r));
  2237. return Ok(());
  2238. }
  2239. if let Some(op) = name.strip_prefix("s_cmp_").or(name.strip_prefix("s_cmpk_")) {
  2240. let (a, b) = if name.starts_with("s_cmpk_") {
  2241. let b = if op.ends_with("_i32") {
  2242. sext16(self)
  2243. } else {
  2244. self.s.m.i32(u32::from(imm.unwrap_or(0)))
  2245. };
  2246. (src32(self, 0)?, b)
  2247. } else {
  2248. if op.ends_with("64") {
  2249. return Err("a 64-bit scalar compare");
  2250. }
  2251. (src32(self, 0)?, src32(self, 1)?)
  2252. };
  2253. let signed = op.ends_with("_i32");
  2254. let p = match &op[..2] {
  2255. "eq" => pred::EQ,
  2256. "lg" => pred::NE,
  2257. "gt" if signed => pred::SGT,
  2258. "ge" if signed => pred::SGE,
  2259. "lt" if signed => pred::SLT,
  2260. "le" if signed => pred::SLE,
  2261. "gt" => pred::IUGT,
  2262. "ge" => pred::IUGE,
  2263. "lt" => pred::IULT,
  2264. "le" => pred::IULE,
  2265. _ => return Err("a scalar compare"),
  2266. };
  2267. let r = self.s.m.cmp(c, p, a, b);
  2268. self.set(scc, Val::Bit(r));
  2269. return Ok(());
  2270. }
  2271. let wide = name.ends_with("_b64") || name.ends_with("_u64") || name.ends_with("_i64");
  2272. if wide {
  2273. let hi = dst_code.and_then(|c| inst.write(Reg::S(c + 1)));
  2274. let nonzero = |l: &mut Self, a: V, b: V| {
  2275. let o = l.s.m.bin(c, Bin::Or, a, b);
  2276. let z = l.s.m.i32(0);
  2277. l.s.m.cmp(c, pred::NE, o, z)
  2278. };
  2279. return match name {
  2280. "s_bcnt1_i32_b64" => {
  2281. let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
  2282. let i32t = self.s.t.i32;
  2283. let na = self
  2284. .s
  2285. .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 31, &[a]);
  2286. let nb = self
  2287. .s
  2288. .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 31, &[b]);
  2289. let r = self.s.m.bin(c, Bin::Add, na, nb);
  2290. self.set(lo, Val::I32(r));
  2291. let z = self.s.m.i32(0);
  2292. let s = self.s.m.cmp(c, pred::NE, r, z);
  2293. self.set(scc, Val::Bit(s));
  2294. Ok(())
  2295. }
  2296. "s_ff1_i32_b64" => {
  2297. // The lowest set bit; -1 for none (as DXIL's first bit low).
  2298. let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
  2299. let i32t = self.s.t.i32;
  2300. let fa = self
  2301. .s
  2302. .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[a]);
  2303. let fb = self
  2304. .s
  2305. .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[b]);
  2306. let (z, k32) = (self.s.m.i32(0), self.s.m.i32(32));
  2307. let fb32 = self.s.m.bin(c, Bin::Add, fb, k32);
  2308. let none = self.s.m.cmp(c, pred::EQ, b, z);
  2309. let fb = self.s.m.select(c, none, fb, fb32);
  2310. let low = self.s.m.cmp(c, pred::NE, a, z);
  2311. let r = self.s.m.select(c, low, fa, fb);
  2312. self.set(lo, Val::I32(r));
  2313. Ok(())
  2314. }
  2315. "s_and_b64" | "s_or_b64" | "s_xor_b64" | "s_andn2_b64" | "s_orn2_b64"
  2316. | "s_nand_b64" | "s_nor_b64" | "s_xnor_b64" | "s_not_b64" => {
  2317. let ones = self.s.m.i32(u32::MAX);
  2318. let mut r = Vec::new();
  2319. for h in 0..2u8 {
  2320. let a = half(self, 0, h)?;
  2321. let x = if name == "s_not_b64" {
  2322. self.s.m.bin(c, Bin::Xor, a, ones)
  2323. } else {
  2324. let mut b = half(self, 1, h)?;
  2325. if name.contains("n2") {
  2326. b = self.s.m.bin(c, Bin::Xor, b, ones);
  2327. }
  2328. let op = match &name[2..5] {
  2329. "and" | "nan" => Bin::And,
  2330. "or_" | "orn" | "nor" => Bin::Or,
  2331. _ => Bin::Xor,
  2332. };
  2333. let x = self.s.m.bin(c, op, a, b);
  2334. if matches!(name, "s_nand_b64" | "s_nor_b64" | "s_xnor_b64") {
  2335. self.s.m.bin(c, Bin::Xor, x, ones)
  2336. } else {
  2337. x
  2338. }
  2339. };
  2340. r.push(x);
  2341. }
  2342. self.set(lo, Val::I32(r[0]));
  2343. self.set(hi, Val::I32(r[1]));
  2344. let s = nonzero(self, r[0], r[1]);
  2345. self.set(scc, Val::Bit(s));
  2346. Ok(())
  2347. }
  2348. "s_lshl_b64" | "s_lshr_b64" | "s_ashr_i64" => {
  2349. let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
  2350. let n = src32(self, 1)?;
  2351. let i64t = self.s.m.int(64);
  2352. self.s.flags |= flags::INT64;
  2353. let a = self.s.m.cast(c, Cast::ZExt, a, i64t);
  2354. let b = self.s.m.cast(c, Cast::ZExt, b, i64t);
  2355. let k32 = self.s.m.int_const(i64t, 32);
  2356. let b = self.s.m.bin(c, Bin::Shl, b, k32);
  2357. let x = self.s.m.bin(c, Bin::Or, a, b);
  2358. let k63 = self.s.m.i32(63);
  2359. let n = self.s.m.bin(c, Bin::And, n, k63);
  2360. let n = self.s.m.cast(c, Cast::ZExt, n, i64t);
  2361. let op = match name {
  2362. "s_lshl_b64" => Bin::Shl,
  2363. "s_lshr_b64" => Bin::LShr,
  2364. _ => Bin::AShr,
  2365. };
  2366. let r = self.s.m.bin(c, op, x, n);
  2367. let rl = self.s.m.cast(c, Cast::Trunc, r, self.s.t.i32);
  2368. let rh = self.s.m.bin(c, Bin::LShr, r, k32);
  2369. let rh = self.s.m.cast(c, Cast::Trunc, rh, self.s.t.i32);
  2370. self.set(lo, Val::I32(rl));
  2371. self.set(hi, Val::I32(rh));
  2372. let s = nonzero(self, rl, rh);
  2373. self.set(scc, Val::Bit(s));
  2374. Ok(())
  2375. }
  2376. "s_mov_b64" => {
  2377. let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
  2378. self.set(lo, Val::I32(a));
  2379. self.set(hi, Val::I32(b));
  2380. Ok(())
  2381. }
  2382. "s_cselect_b64" => {
  2383. let cond = self.scc_in(inst)?;
  2384. for (h, v) in [(0, lo), (1, hi)] {
  2385. let (a, b) = (half(self, 0, h)?, half(self, 1, h)?);
  2386. let r = self.s.m.select(c, cond, a, b);
  2387. self.set(v, Val::I32(r));
  2388. }
  2389. Ok(())
  2390. }
  2391. _ => Err(name),
  2392. };
  2393. }
  2394. let m = &mut self.s.m;
  2395. let _ = m;
  2396. let (r, carry): (V, Option<V>) = match name {
  2397. "s_mov_b32" => (src32(self, 0)?, None),
  2398. "s_movk_i32" => (sext16(self), None),
  2399. "s_cselect_b32" => {
  2400. let cond = self.scc_in(inst)?;
  2401. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  2402. (self.s.m.select(c, cond, a, b), None)
  2403. }
  2404. "s_brev_b32" => {
  2405. let a = src32(self, 0)?;
  2406. let r = self
  2407. .s
  2408. .op(c, "unary.i32", Attr::ReadNone, self.s.t.i32, 30, &[a]);
  2409. (r, None)
  2410. }
  2411. "s_not_b32" => {
  2412. let a = src32(self, 0)?;
  2413. let ones = self.s.m.i32(u32::MAX);
  2414. (self.s.m.bin(c, Bin::Xor, a, ones), None)
  2415. }
  2416. "s_add_u32" | "s_add_i32" | "s_addk_i32" => {
  2417. let a = src32(self, 0)?;
  2418. let b = if name == "s_addk_i32" {
  2419. sext16(self)
  2420. } else {
  2421. src32(self, 1)?
  2422. };
  2423. let r = self.s.m.bin(c, Bin::Add, a, b);
  2424. let carry = if name == "s_add_u32" {
  2425. Some(self.s.m.cmp(c, pred::IULT, r, a))
  2426. } else {
  2427. None
  2428. };
  2429. (r, carry)
  2430. }
  2431. "s_sub_u32" | "s_sub_i32" => {
  2432. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  2433. let r = self.s.m.bin(c, Bin::Sub, a, b);
  2434. let carry = (name == "s_sub_u32").then(|| self.s.m.cmp(c, pred::IULT, a, b));
  2435. (r, carry)
  2436. }
  2437. "s_addc_u32" | "s_subb_u32" => {
  2438. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  2439. let cin = self.scc_in(inst)?;
  2440. let (r, carry) = self.add_sub_carry(c, name == "s_addc_u32", a, b, Some(cin));
  2441. (r, Some(carry))
  2442. }
  2443. "s_mul_i32" | "s_mulk_i32" => {
  2444. let a = src32(self, 0)?;
  2445. let b = if name == "s_mulk_i32" {
  2446. sext16(self)
  2447. } else {
  2448. src32(self, 1)?
  2449. };
  2450. (self.s.m.bin(c, Bin::Mul, a, b), None)
  2451. }
  2452. "s_mul_hi_u32" | "s_mul_hi_i32" => {
  2453. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  2454. (self.mul_hi(a, b, name.ends_with("i32")), None)
  2455. }
  2456. "s_flbit_i32_b32" | "s_flbit_i32" => {
  2457. // The first bit from the top (differing from the sign for
  2458. // the signed form), -1 for none: DXIL's first-bit-high.
  2459. let a = src32(self, 0)?;
  2460. let op = if name == "s_flbit_i32_b32" { 33 } else { 34 };
  2461. let r = self
  2462. .s
  2463. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]);
  2464. (r, None)
  2465. }
  2466. "s_ff1_i32_b32" | "s_bcnt1_i32_b32" => {
  2467. // First set bit (-1 for zero, as DXIL's), or the bit count.
  2468. let a = src32(self, 0)?;
  2469. let op = if name == "s_ff1_i32_b32" { 32 } else { 31 };
  2470. let r = self
  2471. .s
  2472. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]);
  2473. (r, None)
  2474. }
  2475. "s_bfe_u32" | "s_bfe_i32" => {
  2476. // src1: offset in bits 0-4, width in bits 16-22.
  2477. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  2478. let (k16, k127) = (self.s.m.i32(16), self.s.m.i32(0x7F));
  2479. let w = self.s.m.bin(c, Bin::LShr, b, k16);
  2480. let w = self.s.m.bin(c, Bin::And, w, k127);
  2481. (self.bfe(a, b, w, name == "s_bfe_i32"), None)
  2482. }
  2483. "s_and_b32" | "s_or_b32" | "s_xor_b32" | "s_andn2_b32" | "s_orn2_b32"
  2484. | "s_nand_b32" | "s_nor_b32" | "s_xnor_b32" => {
  2485. let (a, mut b) = (src32(self, 0)?, src32(self, 1)?);
  2486. let ones = self.s.m.i32(u32::MAX);
  2487. if name.contains("n2") {
  2488. b = self.s.m.bin(c, Bin::Xor, b, ones);
  2489. }
  2490. let op = match &name[2..5] {
  2491. "and" | "nan" => Bin::And,
  2492. "or_" | "orn" | "nor" => Bin::Or,
  2493. _ => Bin::Xor,
  2494. };
  2495. let mut r = self.s.m.bin(c, op, a, b);
  2496. if matches!(name, "s_nand_b32" | "s_nor_b32" | "s_xnor_b32") {
  2497. r = self.s.m.bin(c, Bin::Xor, r, ones);
  2498. }
  2499. (r, None)
  2500. }
  2501. "s_lshl_b32" | "s_lshr_b32" | "s_ashr_i32" => {
  2502. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  2503. let k31 = self.s.m.i32(31);
  2504. let b = self.s.m.bin(c, Bin::And, b, k31);
  2505. let op = match name {
  2506. "s_lshl_b32" => Bin::Shl,
  2507. "s_lshr_b32" => Bin::LShr,
  2508. _ => Bin::AShr,
  2509. };
  2510. (self.s.m.bin(c, op, a, b), None)
  2511. }
  2512. "s_lshl1_add_u32" | "s_lshl2_add_u32" | "s_lshl3_add_u32" | "s_lshl4_add_u32" => {
  2513. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  2514. let k = self.s.m.i32(u32::from(name.as_bytes()[6] - b'0'));
  2515. let t = self.s.m.bin(c, Bin::Shl, a, k);
  2516. (self.s.m.bin(c, Bin::Add, t, b), None)
  2517. }
  2518. "s_min_u32" | "s_max_u32" | "s_min_i32" | "s_max_i32" => {
  2519. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  2520. let p = match name {
  2521. "s_min_u32" => pred::IULT,
  2522. "s_max_u32" => pred::IUGT,
  2523. "s_min_i32" => pred::SLT,
  2524. _ => pred::SGT,
  2525. };
  2526. let t = self.s.m.cmp(c, p, a, b);
  2527. (self.s.m.select(c, t, a, b), None)
  2528. }
  2529. "s_abs_i32" => {
  2530. let a = src32(self, 0)?;
  2531. let z = self.s.m.i32(0);
  2532. let neg = self.s.m.cmp(c, pred::SLT, a, z);
  2533. let n = self.s.m.bin(c, Bin::Sub, z, a);
  2534. (self.s.m.select(c, neg, n, a), None)
  2535. }
  2536. "s_bitset0_b32" | "s_bitset1_b32" => {
  2537. // Sets (clears) bit src[4:0] of the destination it reads.
  2538. let old = self.operand(inst, dst.as_ref().ok_or("a missing operand")?)?;
  2539. let a = src32(self, 0)?;
  2540. let (k31, one) = (self.s.m.i32(31), self.s.m.i32(1));
  2541. let a = self.s.m.bin(c, Bin::And, a, k31);
  2542. let bit = self.s.m.bin(c, Bin::Shl, one, a);
  2543. if name == "s_bitset1_b32" {
  2544. (self.s.m.bin(c, Bin::Or, old, bit), None)
  2545. } else {
  2546. let ones = self.s.m.i32(u32::MAX);
  2547. let nb = self.s.m.bin(c, Bin::Xor, bit, ones);
  2548. (self.s.m.bin(c, Bin::And, old, nb), None)
  2549. }
  2550. }
  2551. "s_bfm_b32" => {
  2552. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  2553. let k31 = self.s.m.i32(31);
  2554. let one = self.s.m.i32(1);
  2555. let a = self.s.m.bin(c, Bin::And, a, k31);
  2556. let b = self.s.m.bin(c, Bin::And, b, k31);
  2557. let m = self.s.m.bin(c, Bin::Shl, one, a);
  2558. let m = self.s.m.bin(c, Bin::Sub, m, one);
  2559. (self.s.m.bin(c, Bin::Shl, m, b), None)
  2560. }
  2561. _ => return Err(name),
  2562. };
  2563. self.set(lo, Val::I32(r));
  2564. if let Some(scc) = scc {
  2565. let val = match carry {
  2566. Some(k) => Val::Bit(k),
  2567. None if matches!(
  2568. name,
  2569. "s_mov_b32"
  2570. | "s_movk_i32"
  2571. | "s_cselect_b32"
  2572. | "s_brev_b32"
  2573. | "s_mul_i32"
  2574. | "s_mulk_i32"
  2575. ) =>
  2576. {
  2577. return Ok(());
  2578. }
  2579. None if name.starts_with("s_add") || name.starts_with("s_sub") => {
  2580. Val::Missing("the carry of a scalar operation")
  2581. }
  2582. None => {
  2583. let z = self.s.m.i32(0);
  2584. Val::Bit(self.s.m.cmp(c, pred::NE, r, z))
  2585. }
  2586. };
  2587. self.vals.insert(scc, val);
  2588. }
  2589. Ok(())
  2590. }
  2591. /// `a + b (+ cin)` or `a - b (- cin)` with the carry (borrow) out, as the
  2592. /// scalar and vector add-with-carry instructions set it.
  2593. fn add_sub_carry(&mut self, c: usize, add: bool, a: V, b: V, cin: Option<V>) -> (V, V) {
  2594. let op = if add { Bin::Add } else { Bin::Sub };
  2595. let mut r = self.s.m.bin(c, op, a, b);
  2596. // Without a carry in: a + b wraps below a; a - b borrows when a < b.
  2597. let mut carry = if add {
  2598. self.s.m.cmp(c, pred::IULT, r, a)
  2599. } else {
  2600. self.s.m.cmp(c, pred::IULT, a, b)
  2601. };
  2602. if let Some(cin) = cin {
  2603. let one = self.s.m.cast(c, Cast::ZExt, cin, self.s.t.i32);
  2604. let t = r;
  2605. r = self.s.m.bin(c, op, t, one);
  2606. // The carry in carries on when the partial result is all ones
  2607. // (add) or zero (sub).
  2608. let edge = self.s.m.i32(if add { u32::MAX } else { 0 });
  2609. let at_edge = self.s.m.cmp(c, pred::EQ, t, edge);
  2610. let more = self.s.m.bin(c, Bin::And, cin, at_edge);
  2611. carry = self.s.m.bin(c, Bin::Or, carry, more);
  2612. }
  2613. (r, carry)
  2614. }
  2615. fn scc_in(&mut self, inst: &Inst) -> Result<V, Why> {
  2616. let v = inst.read(Reg::Scc).ok_or("an unread SCC")?;
  2617. match self.get(v)? {
  2618. Val::Bit(x) => Ok(x),
  2619. _ => Err("SCC without a value"),
  2620. }
  2621. }
  2622. fn smem(&mut self, inst: &Inst, site: Site) -> Result<(), Why> {
  2623. let Fields::Smem {
  2624. data,
  2625. offset,
  2626. soffset,
  2627. ..
  2628. } = &inst.fields
  2629. else {
  2630. unreachable!()
  2631. };
  2632. let name = inst.name();
  2633. if let Some(a) = self.scalar.get(&site).copied().filter(|a| a.param == CODE) {
  2634. return self.code_smem(inst, a);
  2635. }
  2636. let Some(rest) = name.strip_prefix("s_buffer_load_dword") else {
  2637. return self.descriptor_data(inst, site);
  2638. };
  2639. let count = match rest {
  2640. "" => 1,
  2641. "x2" => 2,
  2642. "x4" => 4,
  2643. "x8" => 8,
  2644. "x16" => 16,
  2645. _ => return Err("a scalar buffer load"),
  2646. };
  2647. let Some(Operand::Scalar { code, .. }) = *data else {
  2648. return Err("a scalar buffer load");
  2649. };
  2650. let src = self
  2651. .descriptors
  2652. .get(&(site, false))
  2653. .copied()
  2654. .ok_or("an untracked descriptor")?;
  2655. let kind = self.used_kind(src);
  2656. let c = self.cur;
  2657. let (base, extra) = self.built_offset(src)?;
  2658. let offset = &((*offset as u32).wrapping_add(base) as i32);
  2659. let mut addr = self.s.m.i32(*offset as u32);
  2660. if let Some(x) = extra {
  2661. addr = self.s.m.bin(c, Bin::Add, addr, x);
  2662. }
  2663. if !matches!(soffset, Operand::Scalar { code: NULL, .. }) {
  2664. let so = self.operand(inst, soffset)?;
  2665. addr = self.s.m.bin(c, Bin::Add, addr, so);
  2666. }
  2667. if matches!(src, Source::Built { address, .. } if address.param == CODE) {
  2668. // A descriptor built around a table in the code.
  2669. for k in 0..count {
  2670. let off = self.s.m.i32(4 * k);
  2671. let a = self.s.m.bin(c, Bin::Add, addr, off);
  2672. let x = self.code_dword(a)?;
  2673. self.write(inst, Reg::S(code + k as u8), x, None);
  2674. }
  2675. return Ok(());
  2676. }
  2677. if matches!(kind, Some(u) if u.kind == ResourceType::Srv) {
  2678. let h = self.handle(site, src, false, (11, 0))?;
  2679. for k in 0..count {
  2680. let off = self.s.m.i32(4 * k);
  2681. let a = self.s.m.bin(c, Bin::Add, addr, off);
  2682. let mask = self.s.m.i8(1);
  2683. let (u, al) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
  2684. let r = self.s.op(
  2685. c,
  2686. "rawBufferLoad.f32",
  2687. Attr::ReadOnly,
  2688. self.s.t.res_ret,
  2689. 139,
  2690. &[h, a, u, mask, al],
  2691. );
  2692. let x = self.s.m.extract(c, r, 0);
  2693. let x = self.as_int(x);
  2694. self.write(inst, Reg::S(code + k as u8), x, None);
  2695. }
  2696. return Ok(());
  2697. }
  2698. let h = self.handle(site, src, false, (13, 0x1_0000))?;
  2699. let constant = match addr {
  2700. V::Const(_)
  2701. if matches!(soffset, Operand::Scalar { code: NULL, .. }) && extra.is_none() =>
  2702. {
  2703. Some(*offset as u32)
  2704. }
  2705. _ => None,
  2706. };
  2707. let mut rows: HashMap<u32, V> = HashMap::new();
  2708. for k in 0..count {
  2709. let x = match constant {
  2710. Some(base) => {
  2711. let byte = base + 4 * k;
  2712. let row = match rows.get(&(byte >> 4)) {
  2713. Some(&r) => r,
  2714. None => {
  2715. let ri = self.s.m.i32(byte >> 4);
  2716. let r = self.s.op(
  2717. c,
  2718. "cbufferLoadLegacy.i32",
  2719. Attr::ReadOnly,
  2720. self.s.t.cbuf_ret,
  2721. 59,
  2722. &[h, ri],
  2723. );
  2724. rows.insert(byte >> 4, r);
  2725. r
  2726. }
  2727. };
  2728. self.s.m.extract(c, row, (byte >> 2) & 3)
  2729. }
  2730. None => {
  2731. let off = self.s.m.i32(4 * k);
  2732. let a = self.s.m.bin(c, Bin::Add, addr, off);
  2733. self.cbuffer_dword(h, a)
  2734. }
  2735. };
  2736. self.write(inst, Reg::S(code + k as u8), x, None);
  2737. }
  2738. Ok(())
  2739. }
  2740. /// A descriptor load (`s_load_dword*` from a table or heap) whose dwords
  2741. /// the code also reads as numbers: the console compiler computes sizes
  2742. /// from descriptor bits (an image's width, height, depth, levels; a
  2743. /// buffer's record count) instead of querying them. Those fields are
  2744. /// rebuilt from the host view's dimensions in the GFX10 layout (image
  2745. /// dword 1 bits 30-31 and dword 2 bits 0-13 width - 1, dword 2 bits
  2746. /// 14-29 height - 1, dword 3 identity swizzle, last level at 16, type at
  2747. /// 28, dword 4 depth or layers - 1; buffer dword 2 the record count).
  2748. // shortcut: the base level reads 0 (the host view starts at its own
  2749. // level 0, so sizes the code shifts by it come out right) and the other
  2750. // dwords (addresses, formats, tiling) have no host value: reading them
  2751. // stops the program.
  2752. fn descriptor_data(&mut self, inst: &Inst, site: Site) -> Result<(), Why> {
  2753. const OTHER: Why = "a descriptor's address or format read as data";
  2754. let Fields::Smem {
  2755. data: Some(Operand::Scalar { code, .. }),
  2756. ..
  2757. } = inst.fields
  2758. else {
  2759. return Err("a scalar memory read as data");
  2760. };
  2761. let count = match inst.name().strip_prefix("s_load_dword") {
  2762. Some("") => 1u32,
  2763. Some("x2") => 2,
  2764. Some("x4") => 4,
  2765. Some("x8") => 8,
  2766. Some("x16") => 16,
  2767. _ => return Err("a scalar memory read as data"),
  2768. };
  2769. // How the program uses the descriptor tells the view's kind.
  2770. let use_at = self
  2771. .x
  2772. .res
  2773. .descriptors
  2774. .iter()
  2775. .filter(|d| d.role == Role::Resource)
  2776. .find_map(|d| {
  2777. d.source.leaves().into_iter().find_map(|l| match *l {
  2778. Source::Loaded { load, first } if load == site => Some((d.site, first)),
  2779. _ => None,
  2780. })
  2781. });
  2782. let Some((at, first)) = use_at else {
  2783. return Err("a descriptor read only as data");
  2784. };
  2785. let src = Source::Loaded { load: site, first };
  2786. let used = self.used_kind(&src);
  2787. let ui: &Inst = &self.x.p.blocks[at.0].insts[at.1];
  2788. let un = ui.name();
  2789. let uav = un.contains("store")
  2790. || un.contains("atomic")
  2791. || used.is_some_and(|u| u.kind == ResourceType::Uav);
  2792. let u = if uav { 0x1000 } else { 0 };
  2793. let (props, image) = match &ui.fields {
  2794. Fields::Image { dim, .. } => {
  2795. let kind = match dim {
  2796. 0 => 1,
  2797. 1 => 2,
  2798. 2 => 4,
  2799. 4 => 6,
  2800. 5 => 7,
  2801. _ => return Err("an image dimension (cube or MSAA)"),
  2802. };
  2803. ((kind | u, 0x409), Some(kind))
  2804. }
  2805. Fields::Buffer { idxen, format, .. } => {
  2806. let stride = used.map_or(0, |u| u.stride);
  2807. let props = if un.starts_with("buffer_load_format")
  2808. || un.starts_with("buffer_store_format")
  2809. {
  2810. (10 | u, 0x409)
  2811. } else if *idxen && format.is_none() && stride >= 4 && stride.is_multiple_of(4) {
  2812. (12 | u, stride)
  2813. } else {
  2814. (11 | u, 0)
  2815. };
  2816. if used.is_some_and(|u| u.kind == ResourceType::Cbv) {
  2817. return Err("a constant buffer's descriptor read as data");
  2818. }
  2819. (props, None)
  2820. }
  2821. _ => return Err("a scalar memory read as data"),
  2822. };
  2823. let h = self.handle(site, &src, false, props)?;
  2824. let c = self.cur;
  2825. let i32t = self.s.t.i32;
  2826. let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
  2827. let mip = if image.is_some() && !uav {
  2828. self.s.m.i32(0)
  2829. } else {
  2830. self.s.m.undef(i32t)
  2831. };
  2832. let d = self
  2833. .s
  2834. .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]);
  2835. let field = |l: &mut Self, k: u32| l.s.m.extract(c, d, k);
  2836. let words: Vec<(u32, V)> = match image {
  2837. Some(kind) => {
  2838. let one = self.s.m.i32(1);
  2839. let w = field(self, 0);
  2840. let (height, depth) = match kind {
  2841. 1 => (one, one),
  2842. 2 => (field(self, 1), one),
  2843. 6 => (one, field(self, 1)),
  2844. _ => (field(self, 1), field(self, 2)),
  2845. };
  2846. let levels = if uav { one } else { field(self, 3) };
  2847. let less = |l: &mut Self, x: V| l.s.m.bin(c, Bin::Sub, x, one);
  2848. let (w, height, depth, levels) = (
  2849. less(self, w),
  2850. less(self, height),
  2851. less(self, depth),
  2852. less(self, levels),
  2853. );
  2854. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  2855. let (k30, k2, k14, k16, mask) = (
  2856. k(self, 30),
  2857. k(self, 2),
  2858. k(self, 14),
  2859. k(self, 16),
  2860. k(self, 0x3FFF),
  2861. );
  2862. let d1 = self.s.m.bin(c, Bin::Shl, w, k30);
  2863. let hi = self.s.m.bin(c, Bin::LShr, w, k2);
  2864. let hi = self.s.m.bin(c, Bin::And, hi, mask);
  2865. let ht = self.s.m.bin(c, Bin::Shl, height, k14);
  2866. let d2 = self.s.m.bin(c, Bin::Or, hi, ht);
  2867. let ty = [0, 8, 9, 0, 10, 0, 12, 13][kind as usize];
  2868. let base = k(self, 0xFAC | ty << 28);
  2869. let last = self.s.m.bin(c, Bin::Shl, levels, k16);
  2870. let d3 = self.s.m.bin(c, Bin::Or, base, last);
  2871. vec![(1, d1), (2, d2), (3, d3), (4, depth)]
  2872. }
  2873. None => vec![(2, field(self, 0))],
  2874. };
  2875. for k in 0..count {
  2876. let rel = k.wrapping_sub(u32::from(first));
  2877. match words.iter().find(|w| w.0 == rel) {
  2878. Some(&(_, x)) => self.write(inst, Reg::S(code + k as u8), x, None),
  2879. None => {
  2880. if let Some(v) = inst.write(Reg::S(code + k as u8)) {
  2881. self.vals.insert(v, Val::Missing(OTHER));
  2882. }
  2883. }
  2884. }
  2885. }
  2886. Ok(())
  2887. }
  2888. /// `s_load_dword*` from the program's constant table.
  2889. fn code_smem(&mut self, inst: &Inst, a: Address) -> Result<(), Why> {
  2890. let Fields::Smem {
  2891. data: Some(Operand::Scalar { code, .. }),
  2892. ..
  2893. } = inst.fields
  2894. else {
  2895. return Err("a scalar load");
  2896. };
  2897. let count = match inst.name().strip_prefix("s_load_dword") {
  2898. Some("") => 1u32,
  2899. Some("x2") => 2,
  2900. Some("x4") => 4,
  2901. Some("x8") => 8,
  2902. Some("x16") => 16,
  2903. _ => return Err("a scalar load from the code"),
  2904. };
  2905. let c = self.cur;
  2906. let mut addr = self.s.m.i32(a.offset);
  2907. if let Some(d) = a.dynamic {
  2908. let d = self.i32_of(d)?;
  2909. addr = self.s.m.bin(c, Bin::Add, addr, d);
  2910. }
  2911. for k in 0..count {
  2912. let off = self.s.m.i32(4 * k);
  2913. let at = self.s.m.bin(c, Bin::Add, addr, off);
  2914. let x = self.code_dword(at)?;
  2915. self.write(inst, Reg::S(code + k as u8), x, None);
  2916. }
  2917. Ok(())
  2918. }
  2919. /// The dword at a computed byte address of a constant buffer.
  2920. fn cbuffer_dword(&mut self, h: V, a: V) -> V {
  2921. let c = self.cur;
  2922. let four = self.s.m.i32(4);
  2923. let ri = self.s.m.bin(c, Bin::LShr, a, four);
  2924. let r = self.s.op(
  2925. c,
  2926. "cbufferLoadLegacy.i32",
  2927. Attr::ReadOnly,
  2928. self.s.t.cbuf_ret,
  2929. 59,
  2930. &[h, ri],
  2931. );
  2932. let two = self.s.m.i32(2);
  2933. let three = self.s.m.i32(3);
  2934. let comp = self.s.m.bin(c, Bin::LShr, a, two);
  2935. let comp = self.s.m.bin(c, Bin::And, comp, three);
  2936. let mut x = self.s.m.extract(c, r, 0);
  2937. for j in 1..4 {
  2938. let e = self.s.m.extract(c, r, j);
  2939. let jc = self.s.m.i32(j);
  2940. let is = self.s.m.cmp(c, pred::EQ, comp, jc);
  2941. x = self.s.m.select(c, is, e, x);
  2942. }
  2943. x
  2944. }
  2945. /// `channels` channels of the element at byte `off` of raw buffer `h`,
  2946. /// converted from the GFX10 buffer format `format` as the hardware's
  2947. /// typed loads do (channels past the format's read 0, 0, 0, 1).
  2948. // shortcut: the descriptor's channel swizzle is taken as the identity
  2949. // (it is for raw views and the descriptors code builds), elements of 4
  2950. // bytes or more as dword-aligned, and the packed float and 10_10_10_2
  2951. // layouts are refused; decode them when a program needs them. Norm
  2952. // formats divide, which the AMD driver does 1 ULP off the hardware's
  2953. // correctly rounded conversion for some values; correct it with an
  2954. // integer check if a title compares converted values exactly.
  2955. fn format_load(&mut self, h: V, off: V, format: u8, channels: u32) -> Result<Vec<V>, Why> {
  2956. let (bits, numeric) = buffer_format(format).ok_or("a buffer format")?;
  2957. let c = self.cur;
  2958. let total: u32 = bits.iter().sum();
  2959. let (u, align) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
  2960. let load = |l: &mut Self, at: V, n: u32| -> Vec<V> {
  2961. let mask = l.s.m.i8((1u8 << n) - 1);
  2962. let r = l.s.op(
  2963. c,
  2964. "rawBufferLoad.f32",
  2965. Attr::ReadOnly,
  2966. l.s.t.res_ret,
  2967. 139,
  2968. &[h, at, u, mask, align],
  2969. );
  2970. (0..n)
  2971. .map(|k| {
  2972. let x = l.s.m.extract(c, r, k);
  2973. l.as_int(x)
  2974. })
  2975. .collect()
  2976. };
  2977. let words = if total < 32 {
  2978. // A byte or half inside the dword that holds it.
  2979. let (not3, three) = (self.s.m.i32(!3), self.s.m.i32(3));
  2980. let at = self.s.m.bin(c, Bin::And, off, not3);
  2981. let w = load(self, at, 1)[0];
  2982. let byte = self.s.m.bin(c, Bin::And, off, three);
  2983. let sh = self.s.m.bin(c, Bin::Shl, byte, three);
  2984. vec![self.s.m.bin(c, Bin::LShr, w, sh)]
  2985. } else {
  2986. load(self, off, total / 32)
  2987. };
  2988. let float = |l: &mut Self, f: V| l.as_int(f);
  2989. let mut out = Vec::new();
  2990. let mut at = 0;
  2991. for &w in bits {
  2992. let word = words[(at / 32) as usize];
  2993. let field = if w == 32 {
  2994. word
  2995. } else {
  2996. let sh = self.s.m.i32(at % 32);
  2997. let t = self.s.m.bin(c, Bin::LShr, word, sh);
  2998. let m = self.s.m.i32((1 << w) - 1);
  2999. self.s.m.bin(c, Bin::And, t, m)
  3000. };
  3001. at += w;
  3002. // Sign-extended from the field's top bit.
  3003. let signed = |l: &mut Self| {
  3004. if w == 32 {
  3005. return field;
  3006. }
  3007. let k = l.s.m.i32(32 - w);
  3008. let t = l.s.m.bin(c, Bin::Shl, field, k);
  3009. l.s.m.bin(c, Bin::AShr, t, k)
  3010. };
  3011. let f32t = self.s.t.f32;
  3012. let x = match numeric {
  3013. Numeric::Unorm => {
  3014. let f = self.s.m.cast(c, Cast::UiToFp, field, f32t);
  3015. let max = self.s.m.f32((((1u64 << w) - 1) as f32).to_bits());
  3016. let q = self.s.m.bin(c, Bin::SDiv, f, max);
  3017. float(self, q)
  3018. }
  3019. Numeric::Snorm => {
  3020. let s = signed(self);
  3021. let f = self.s.m.cast(c, Cast::SiToFp, s, f32t);
  3022. let max = self.s.m.f32((((1u64 << (w - 1)) - 1) as f32).to_bits());
  3023. let q = self.s.m.bin(c, Bin::SDiv, f, max);
  3024. let lo = self.s.m.f32((-1.0f32).to_bits());
  3025. let q = self.binary(35, q, lo);
  3026. float(self, q)
  3027. }
  3028. Numeric::Uscaled => {
  3029. let f = self.s.m.cast(c, Cast::UiToFp, field, f32t);
  3030. float(self, f)
  3031. }
  3032. Numeric::Sscaled => {
  3033. let s = signed(self);
  3034. let f = self.s.m.cast(c, Cast::SiToFp, s, f32t);
  3035. float(self, f)
  3036. }
  3037. Numeric::Uint => field,
  3038. Numeric::Sint => signed(self),
  3039. Numeric::Float if w == 32 => field,
  3040. Numeric::Float => {
  3041. let f = self
  3042. .s
  3043. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[field]);
  3044. float(self, f)
  3045. }
  3046. };
  3047. out.push(x);
  3048. }
  3049. let one = match numeric {
  3050. Numeric::Uint | Numeric::Sint => 1,
  3051. _ => 1.0f32.to_bits(),
  3052. };
  3053. for k in out.len() as u32..channels {
  3054. out.push(self.s.m.i32(if k == 3 { one } else { 0 }));
  3055. }
  3056. out.truncate(channels as usize);
  3057. Ok(out)
  3058. }
  3059. /// The byte offset a buffer descriptor built around a root descriptor adds
  3060. /// (constant and computed parts); none for other descriptors.
  3061. fn built_offset(&mut self, src: &Source) -> Result<(u32, Option<V>), Why> {
  3062. match src {
  3063. Source::Built { address, .. } => {
  3064. let x = match address.dynamic {
  3065. Some(v) => Some(self.i32_of(v)?),
  3066. None => None,
  3067. };
  3068. Ok((address.offset, x))
  3069. }
  3070. _ => Ok((0, None)),
  3071. }
  3072. }
  3073. /// The used-resource entry a descriptor loaded from a table falls in.
  3074. fn used_kind(&self, src: &Source) -> Option<&'a UsedResource> {
  3075. if let Source::Phi { args, .. } = src {
  3076. return self.used_kind(args.first()?);
  3077. }
  3078. if let Source::Built { address, .. } = src {
  3079. let rp = self.x.native.layout.get(address.param)?;
  3080. return self
  3081. .x
  3082. .native
  3083. .used
  3084. .iter()
  3085. .find(|u| u.root == RootType::Descriptor && u.user_data == rp.user_data);
  3086. }
  3087. let Source::Loaded { load, first } = src else {
  3088. return None;
  3089. };
  3090. let a = self.scalar.get(load)?;
  3091. let rp = self.x.native.layout.get(a.param)?;
  3092. if rp.root != RootType::Table {
  3093. return None;
  3094. }
  3095. let dword = (a.offset / 4) + u32::from(*first);
  3096. self.x
  3097. .native
  3098. .used
  3099. .iter()
  3100. .filter(|u| {
  3101. u.root == RootType::Table
  3102. && u.user_data == rp.user_data
  3103. && u.table_offset_dwords <= dword
  3104. })
  3105. .max_by_key(|u| u.table_offset_dwords)
  3106. }
  3107. /// A handle for the descriptor `src` read at `site`.
  3108. fn handle(
  3109. &mut self,
  3110. site: Site,
  3111. src: &Source,
  3112. sampler: bool,
  3113. props: (u32, u32),
  3114. ) -> Result<V, Why> {
  3115. match src {
  3116. Source::Loaded { load, first } => {
  3117. let key = (self.cur, *load, *first, sampler, props.0);
  3118. if let Some(&h) = self.handles.get(&key) {
  3119. return Ok(h);
  3120. }
  3121. let index = self.heap_index(*load, *first, sampler)?;
  3122. let h = self.s.heap_handle(self.cur, index, sampler, props);
  3123. self.handles.insert(key, h);
  3124. Ok(h)
  3125. }
  3126. Source::Constant(words) if sampler => {
  3127. let words: [u32; 4] = words
  3128. .get(..4)
  3129. .and_then(|w| w.try_into().ok())
  3130. .ok_or("a sampler constant")?;
  3131. let n = match self.samplers.iter().position(|w| *w == words) {
  3132. Some(n) => n,
  3133. None => {
  3134. self.samplers.push(words);
  3135. self.samplers.len() - 1
  3136. }
  3137. };
  3138. if props.0 & 0x8000 != 0 {
  3139. // shortcut: one sampler used with and without comparison
  3140. // would need two static samplers; it becomes a comparison one.
  3141. self.s.cmp_samplers |= 1 << n;
  3142. }
  3143. Ok(self.s.sampler_handle(self.cur, n as u32))
  3144. }
  3145. Source::Constant(_) => Err("a constant resource descriptor"),
  3146. Source::Built { address, .. } => {
  3147. let rp = *self
  3148. .x
  3149. .native
  3150. .layout
  3151. .get(address.param)
  3152. .ok_or("a descriptor built around a table in the code")?;
  3153. let kind = self
  3154. .x
  3155. .native
  3156. .used
  3157. .iter()
  3158. .find(|u| u.user_data == rp.user_data)
  3159. .map(|u| u.kind);
  3160. match (rp.root, kind, props.0) {
  3161. (RootType::Descriptor, Some(ResourceType::Cbv) | None, 13) => {
  3162. Ok(self.s.root_cbv_handle(rp.slot))
  3163. }
  3164. (RootType::Descriptor, Some(ResourceType::Srv), 11) => {
  3165. Ok(self.s.root_srv_handle(rp.slot))
  3166. }
  3167. _ => Err("a root UAV or typed root view"),
  3168. }
  3169. }
  3170. Source::Phi { block, args } => {
  3171. // Each predecessor computes its heap index at its end; the
  3172. // join picks one with a phi.
  3173. let _ = site;
  3174. let mut incoming = Vec::new();
  3175. for (&q, arg) in self.x.p.blocks[*block].preds.iter().zip(args) {
  3176. if self.block[q].is_none() {
  3177. continue;
  3178. }
  3179. let (Some(tail), Source::Loaded { load, first }) = (self.tail[q], arg) else {
  3180. return Err("a descriptor chosen by control flow");
  3181. };
  3182. let at = self.edges.get(&(q, *block)).copied().unwrap_or(tail);
  3183. let here = std::mem::replace(&mut self.cur, at);
  3184. let index = self.heap_index(*load, *first, sampler);
  3185. self.cur = here;
  3186. incoming.push((index?, at));
  3187. }
  3188. let join = self.block[*block].ok_or("a descriptor chosen by control flow")?;
  3189. let phi = self.s.m.phi(join, self.s.t.i32);
  3190. self.s.m.set_phi(phi, incoming);
  3191. Ok(self.s.heap_handle(self.cur, phi, sampler, props))
  3192. }
  3193. }
  3194. }
  3195. /// The heap index of the descriptor at dword `first` of what the scalar
  3196. /// load at `load` reads, computed in the current block.
  3197. fn heap_index(&mut self, load: Site, first: u8, sampler: bool) -> Result<V, Why> {
  3198. let a = *self
  3199. .scalar
  3200. .get(&load)
  3201. .ok_or("an untracked descriptor load")?;
  3202. match self.x.native.layout.get(a.param).map(|p| p.root) {
  3203. Some(RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap) => {}
  3204. _ => return Err("a descriptor outside the heaps"),
  3205. }
  3206. let li: &Inst = &self.x.p.blocks[load.0].insts[load.1];
  3207. let Fields::Smem {
  3208. base,
  3209. offset,
  3210. soffset,
  3211. ..
  3212. } = &li.fields
  3213. else {
  3214. return Err("a descriptor load");
  3215. };
  3216. let Operand::Scalar { code, .. } = *base else {
  3217. return Err("a descriptor load");
  3218. };
  3219. let c = self.cur;
  3220. let base = li.read(Reg::S(code)).ok_or("a descriptor load")?;
  3221. let mut addr = self.i32_of(base)?;
  3222. let k = self
  3223. .s
  3224. .m
  3225. .i32((*offset as u32).wrapping_add(4 * u32::from(first)));
  3226. addr = self.s.m.bin(c, Bin::Add, addr, k);
  3227. if !matches!(soffset, Operand::Scalar { code: NULL, .. }) {
  3228. let so = self.operand(li, soffset)?;
  3229. addr = self.s.m.bin(c, Bin::Add, addr, so);
  3230. }
  3231. let shift = self.s.m.i32(if sampler { 4 } else { 5 });
  3232. Ok(self.s.m.bin(c, Bin::LShr, addr, shift))
  3233. }
  3234. fn valu(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  3235. let Fields::Valu(v) = &inst.fields else {
  3236. unreachable!()
  3237. };
  3238. let name = inst.name();
  3239. if let Some(rest) = name.strip_prefix("v_cmp_").or(name.strip_prefix("v_cmpx_")) {
  3240. let r = if v.dpp.is_some() {
  3241. Err("a compare with DPP")
  3242. } else {
  3243. self.compare(inst, rest)
  3244. };
  3245. if let Err(why) = r {
  3246. for &(_, w) in &inst.writes {
  3247. self.lane_fail.insert(w, why);
  3248. }
  3249. }
  3250. return r;
  3251. }
  3252. let mut guard = self.guard(b, i)?;
  3253. if let Some(d) = v.dpp {
  3254. let (x, enable) = self.dpp(inst, d)?;
  3255. guard = match (guard, enable) {
  3256. (Some(g), Some(e)) => Some(self.s.m.bin(self.cur, Bin::And, g, e)),
  3257. (g, e) => g.or(e),
  3258. };
  3259. self.src0 = Some(x);
  3260. }
  3261. let r = self.valu_op(inst, guard);
  3262. self.src0 = None;
  3263. r
  3264. }
  3265. /// DPP: src0 as read from another lane, and which lanes write their
  3266. /// result (none: all).
  3267. fn dpp(&mut self, inst: &Inst, dpp: Dpp) -> Result<(V, Option<V>), Why> {
  3268. let Fields::Valu(v) = &inst.fields else {
  3269. unreachable!()
  3270. };
  3271. let Some(&Operand::Vector { reg, .. }) = v.src.first() else {
  3272. return Err("a DPP operand");
  3273. };
  3274. let x = self.i32_of(inst.read(Reg::V(reg)).ok_or("a DPP operand")?)?;
  3275. // Quad permutations and DPP8 stay in groups the pixel layout shares.
  3276. let quad = matches!(dpp, Dpp::Row { ctrl: 0..=0xFF, .. });
  3277. let mesh_quad = self.s.mesh.is_some() && quad;
  3278. if !mesh_quad {
  3279. self.cross_lane(quad)?;
  3280. }
  3281. let c = self.cur;
  3282. let lane = self.lane_index();
  3283. let k = |l: &mut Self, n: u32| l.s.m.i32(n);
  3284. let (sixteen_mask, low) = (k(self, !15), k(self, 15));
  3285. let row = self.s.m.bin(c, Bin::And, lane, sixteen_mask);
  3286. let pos = self.s.m.bin(c, Bin::And, lane, low);
  3287. // Source lane, and whether it lies in the row.
  3288. let (src, inside, masks, zero) = match dpp {
  3289. Dpp::Lanes { sel, .. } => {
  3290. let (seven, not7, three) = (k(self, 7), k(self, !7), k(self, 3));
  3291. let p = self.s.m.bin(c, Bin::And, lane, seven);
  3292. let sh = self.s.m.bin(c, Bin::Mul, p, three);
  3293. let sel = k(self, sel);
  3294. let pick = self.s.m.bin(c, Bin::LShr, sel, sh);
  3295. let pick = self.s.m.bin(c, Bin::And, pick, seven);
  3296. let base = self.s.m.bin(c, Bin::And, lane, not7);
  3297. (self.s.m.bin(c, Bin::Or, base, pick), None, None, false)
  3298. }
  3299. Dpp::Row {
  3300. ctrl,
  3301. row_mask,
  3302. bank_mask,
  3303. bound_ctrl,
  3304. ..
  3305. } => {
  3306. let n = u32::from(ctrl & 15);
  3307. let (src, inside) = match ctrl {
  3308. 0..=0xFF => {
  3309. let (three, one, not3) = (k(self, 3), k(self, 1), k(self, !3));
  3310. let p = self.s.m.bin(c, Bin::And, lane, three);
  3311. let sh = self.s.m.bin(c, Bin::Shl, p, one);
  3312. let perm = k(self, u32::from(ctrl));
  3313. let pick = self.s.m.bin(c, Bin::LShr, perm, sh);
  3314. let pick = self.s.m.bin(c, Bin::And, pick, three);
  3315. let base = self.s.m.bin(c, Bin::And, lane, not3);
  3316. (self.s.m.bin(c, Bin::Or, base, pick), None)
  3317. }
  3318. 0x101..=0x10F | 0x111..=0x11F => {
  3319. let nn = k(self, n);
  3320. let left = ctrl < 0x110;
  3321. let (op, p) = if left {
  3322. (Bin::Add, pred::IULT)
  3323. } else {
  3324. (Bin::Sub, pred::IUGE)
  3325. };
  3326. let s = self.s.m.bin(c, op, lane, nn);
  3327. // Left: pos + n < 16; right: pos >= n.
  3328. let bound = if left { k(self, 16 - n) } else { nn };
  3329. (s, Some(self.s.m.cmp(c, p, pos, bound)))
  3330. }
  3331. 0x121..=0x12F => {
  3332. let nn = k(self, n);
  3333. let t = self.s.m.bin(c, Bin::Sub, pos, nn);
  3334. let t = self.s.m.bin(c, Bin::And, t, low);
  3335. (self.s.m.bin(c, Bin::Or, row, t), None)
  3336. }
  3337. 0x140 | 0x141 => {
  3338. let m = k(self, if ctrl == 0x140 { 15 } else { 7 });
  3339. let t = self.s.m.bin(c, Bin::Xor, lane, m);
  3340. (t, None)
  3341. }
  3342. 0x150..=0x15F => {
  3343. let nn = k(self, n);
  3344. (self.s.m.bin(c, Bin::Or, row, nn), None)
  3345. }
  3346. 0x160..=0x16F => {
  3347. let nn = k(self, n);
  3348. (self.s.m.bin(c, Bin::Xor, lane, nn), None)
  3349. }
  3350. _ => return Err("a DPP lane pattern"),
  3351. };
  3352. let masks = (row_mask != 0xF || bank_mask != 0xF).then_some((row_mask, bank_mask));
  3353. (src, inside, masks, bound_ctrl)
  3354. }
  3355. };
  3356. let mut r = if mesh_quad {
  3357. self.quad_pick(x, src)
  3358. } else {
  3359. self.read_lane(x, src)
  3360. };
  3361. let mut enable = None;
  3362. if let Some(inside) = inside {
  3363. if zero {
  3364. let z = k(self, 0);
  3365. r = self.s.m.select(c, inside, r, z);
  3366. } else {
  3367. enable = Some(inside);
  3368. }
  3369. }
  3370. if let Some((rows, banks)) = masks {
  3371. // Row (16 lanes) and bank (4 lanes of a row) write masks.
  3372. let (four, two, three) = (k(self, 4), k(self, 2), k(self, 3));
  3373. let ri = self.s.m.bin(c, Bin::LShr, lane, four);
  3374. let ri = self.s.m.bin(c, Bin::And, ri, three);
  3375. let bi = self.s.m.bin(c, Bin::LShr, lane, two);
  3376. let bi = self.s.m.bin(c, Bin::And, bi, three);
  3377. let (rm, bm) = (k(self, u32::from(rows)), k(self, u32::from(banks)));
  3378. let rb = self.s.m.bin(c, Bin::LShr, rm, ri);
  3379. let bb = self.s.m.bin(c, Bin::LShr, bm, bi);
  3380. let both = self.s.m.bin(c, Bin::And, rb, bb);
  3381. let (one, z) = (k(self, 1), k(self, 0));
  3382. let both = self.s.m.bin(c, Bin::And, both, one);
  3383. let on = self.s.m.cmp(c, pred::NE, both, z);
  3384. enable = Some(match enable {
  3385. Some(e) => self.s.m.bin(c, Bin::And, e, on),
  3386. None => on,
  3387. });
  3388. }
  3389. Ok((r, enable))
  3390. }
  3391. fn valu_op(&mut self, inst: &Inst, guard: Option<V>) -> Result<(), Why> {
  3392. let Fields::Valu(v) = &inst.fields else {
  3393. unreachable!()
  3394. };
  3395. let name = inst.name();
  3396. let c = self.cur;
  3397. let f = |l: &mut Self, k| l.fsrc(inst, k);
  3398. let s = |l: &mut Self, k| l.src(inst, k);
  3399. let float = |l: &mut Self, r: V| l.write_f(inst, r, guard);
  3400. let int = |l: &mut Self, r: V| l.write_i(inst, r, guard);
  3401. if let Some(r) = self.valu16(inst, name, guard) {
  3402. return r;
  3403. }
  3404. if let Some(op) = name.strip_prefix("v_pk_") {
  3405. return self.packed16(inst, op, guard);
  3406. }
  3407. match name {
  3408. "v_lshlrev_b64" | "v_lshrrev_b64" | "v_ashrrev_i64" => {
  3409. let n = s(self, 0)?;
  3410. let x = self.src64(inst, 1)?;
  3411. let i64t = self.s.m.int(64);
  3412. let k63 = self.s.m.i32(63);
  3413. let n = self.s.m.bin(c, Bin::And, n, k63);
  3414. let n = self.s.m.cast(c, Cast::ZExt, n, i64t);
  3415. let op = match name {
  3416. "v_lshlrev_b64" => Bin::Shl,
  3417. "v_lshrrev_b64" => Bin::LShr,
  3418. _ => Bin::AShr,
  3419. };
  3420. let r = self.s.m.bin(c, op, x, n);
  3421. let Some(Operand::Vector { reg, .. }) = v.dst else {
  3422. return Err("a 64-bit result");
  3423. };
  3424. let (lo, hi) = self.split64(r);
  3425. self.write(inst, Reg::V(reg), lo, guard);
  3426. self.write(inst, Reg::V(reg + 1), hi, guard);
  3427. Ok(())
  3428. }
  3429. "v_cubeid_f32" | "v_cubesc_f32" | "v_cubetc_f32" | "v_cubema_f32" => {
  3430. // Cube-map face coordinates (AMD's ISA): the major axis is z
  3431. // when |z| >= |x| and |z| >= |y|, else y when |y| >= |x|,
  3432. // else x.
  3433. let (x, y, z) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  3434. let (ax, ay, az) = (self.unary(6, x), self.unary(6, y), self.unary(6, z));
  3435. let zx = self.s.m.cmp(c, pred::OGE, az, ax);
  3436. let zy = self.s.m.cmp(c, pred::OGE, az, ay);
  3437. let zmaj = self.s.m.bin(c, Bin::And, zx, zy);
  3438. let ymaj = self.s.m.cmp(c, pred::OGE, ay, ax);
  3439. let zero = self.s.m.f32(0);
  3440. let neg = |l: &mut Self, v: V| l.s.m.cmp(c, pred::OLT, v, zero);
  3441. let minus = |l: &mut Self, v: V| {
  3442. let z = l.s.m.f32(0x8000_0000);
  3443. l.s.m.bin(c, Bin::Sub, z, v)
  3444. };
  3445. let pick = |l: &mut Self, zv: V, yv: V, xv: V| {
  3446. let t = l.s.m.select(c, ymaj, yv, xv);
  3447. l.s.m.select(c, zmaj, zv, t)
  3448. };
  3449. let r = match name {
  3450. "v_cubeid_f32" => {
  3451. let k = |l: &mut Self, v: f32| l.s.m.f32(v.to_bits());
  3452. let (nz, ny, nx) = (neg(self, z), neg(self, y), neg(self, x));
  3453. let (f5, f4, f3, f2, f1, f0) = (
  3454. k(self, 5.0),
  3455. k(self, 4.0),
  3456. k(self, 3.0),
  3457. k(self, 2.0),
  3458. k(self, 1.0),
  3459. k(self, 0.0),
  3460. );
  3461. let zf = self.s.m.select(c, nz, f5, f4);
  3462. let yf = self.s.m.select(c, ny, f3, f2);
  3463. let xf = self.s.m.select(c, nx, f1, f0);
  3464. pick(self, zf, yf, xf)
  3465. }
  3466. "v_cubesc_f32" => {
  3467. let (nz, nx) = (neg(self, z), neg(self, x));
  3468. let (mx, mz) = (minus(self, x), minus(self, z));
  3469. let zf = self.s.m.select(c, nz, mx, x);
  3470. let xf = self.s.m.select(c, nx, z, mz);
  3471. pick(self, zf, x, xf)
  3472. }
  3473. "v_cubetc_f32" => {
  3474. let ny = neg(self, y);
  3475. let (my, mz) = (minus(self, y), minus(self, z));
  3476. let yf = self.s.m.select(c, ny, mz, z);
  3477. pick(self, my, yf, my)
  3478. }
  3479. _ => {
  3480. let t = pick(self, z, y, x);
  3481. let two = self.s.m.f32(2.0f32.to_bits());
  3482. self.s.m.bin(c, Bin::Mul, t, two)
  3483. }
  3484. };
  3485. float(self, r)
  3486. }
  3487. "v_movrels_b32" | "v_movreld_b32" | "v_movrelsd_b32" => {
  3488. // M0 indexes the source (movrels), the destination (movreld)
  3489. // or both, from the encoded register up to the program's
  3490. // VGPR count (the registers the instruction reads or writes).
  3491. let m0 = self.i32_of(inst.read(Reg::S(crate::ir::M0)).ok_or("M0")?)?;
  3492. let (
  3493. Some(&Operand::Vector { reg: sreg, .. }),
  3494. Some(Operand::Vector { reg: dreg, .. }),
  3495. ) = (v.src.first(), v.dst)
  3496. else {
  3497. return Err("an M0-relative move");
  3498. };
  3499. let indexed_src = name != "v_movreld_b32";
  3500. let value = if indexed_src {
  3501. let mut r = self.s.m.i32(0);
  3502. for k in 0..=255u8.saturating_sub(sreg) {
  3503. let Some(x) = inst.read(Reg::V(sreg + k)) else {
  3504. break;
  3505. };
  3506. let x = self.i32_of(x)?;
  3507. let kk = self.s.m.i32(u32::from(k));
  3508. let is = self.s.m.cmp(c, pred::EQ, m0, kk);
  3509. r = self.s.m.select(c, is, x, r);
  3510. }
  3511. r
  3512. } else {
  3513. s(self, 0)?
  3514. };
  3515. if name == "v_movrels_b32" {
  3516. return int(self, value);
  3517. }
  3518. for k in 0..=255u8.saturating_sub(dreg) {
  3519. let Some(_) = inst.write(Reg::V(dreg + k)) else {
  3520. break;
  3521. };
  3522. let old = match inst.read(Reg::V(dreg + k)) {
  3523. Some(o) => self.i32_of(o)?,
  3524. None => self.s.m.i32(0),
  3525. };
  3526. let kk = self.s.m.i32(u32::from(k));
  3527. let is = self.s.m.cmp(c, pred::EQ, m0, kk);
  3528. let x = self.s.m.select(c, is, value, old);
  3529. self.write_placed(inst, Reg::V(dreg + k), x, guard);
  3530. }
  3531. Ok(())
  3532. }
  3533. "v_swap_b32" => {
  3534. let (
  3535. Some(&Operand::Vector { reg: sreg, .. }),
  3536. Some(Operand::Vector { reg: dreg, .. }),
  3537. ) = (v.src.first(), v.dst)
  3538. else {
  3539. return Err("v_swap_b32");
  3540. };
  3541. let a = self.i32_of(inst.read(Reg::V(dreg)).ok_or("v_swap_b32")?)?;
  3542. let b = self.i32_of(inst.read(Reg::V(sreg)).ok_or("v_swap_b32")?)?;
  3543. self.write_placed(inst, Reg::V(dreg), b, guard);
  3544. if dreg != sreg {
  3545. self.write_placed(inst, Reg::V(sreg), a, guard);
  3546. }
  3547. Ok(())
  3548. }
  3549. "v_ffbh_u32" | "v_ffbh_i32" => {
  3550. // Counted from the top bit, -1 when none (DXIL's too).
  3551. let a = s(self, 0)?;
  3552. let op = if name == "v_ffbh_u32" { 33 } else { 34 };
  3553. let r = self
  3554. .s
  3555. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]);
  3556. int(self, r)
  3557. }
  3558. "v_mov_b32" => {
  3559. if v.abs != 0 || v.neg != 0 || v.clamp || v.omod != 0 {
  3560. let a = f(self, 0)?;
  3561. return float(self, a);
  3562. }
  3563. let a = s(self, 0)?;
  3564. int(self, a)
  3565. }
  3566. "v_add_f32" | "v_sub_f32" | "v_subrev_f32" | "v_mul_f32" | "v_mul_legacy_f32"
  3567. | "v_max_f32" | "v_min_f32" => {
  3568. let (a, bb) = (f(self, 0)?, f(self, 1)?);
  3569. let r = match name {
  3570. "v_add_f32" => self.s.m.bin(c, Bin::Add, a, bb),
  3571. "v_sub_f32" => self.s.m.bin(c, Bin::Sub, a, bb),
  3572. "v_subrev_f32" => self.s.m.bin(c, Bin::Sub, bb, a),
  3573. "v_mul_f32" => self.s.m.bin(c, Bin::Mul, a, bb),
  3574. "v_mul_legacy_f32" => self.legacy_mul(a, bb),
  3575. "v_max_f32" => self.binary(35, a, bb),
  3576. _ => self.binary(36, a, bb),
  3577. };
  3578. float(self, r)
  3579. }
  3580. "v_fma_f32" | "v_fmaak_f32" | "v_fmamk_f32" => {
  3581. // shortcut: DXIL has no fused f32 multiply-add; FMad lets the driver fuse.
  3582. let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  3583. let r = self.fmad(a, bb, cc);
  3584. float(self, r)
  3585. }
  3586. "v_fmac_f32" | "v_mac_f32" | "v_mac_legacy_f32" => {
  3587. let (a, bb) = (f(self, 0)?, f(self, 1)?);
  3588. let Some(Operand::Vector { reg, .. }) = v.dst else {
  3589. return Err("an accumulator");
  3590. };
  3591. let acc = inst.read(Reg::V(reg)).ok_or("an accumulator")?;
  3592. let acc = match self.floats.get(&acc) {
  3593. Some(&x) => x,
  3594. None => {
  3595. let x = self.i32_of(acc)?;
  3596. self.as_float(x)
  3597. }
  3598. };
  3599. let r = match name {
  3600. "v_fmac_f32" => self.fmad(a, bb, acc),
  3601. "v_mac_f32" => {
  3602. let m = self.s.m.bin(c, Bin::Mul, a, bb);
  3603. self.s.m.bin(c, Bin::Add, m, acc)
  3604. }
  3605. _ => {
  3606. let m = self.legacy_mul(a, bb);
  3607. self.s.m.bin(c, Bin::Add, m, acc)
  3608. }
  3609. };
  3610. float(self, r)
  3611. }
  3612. "v_mad_f32" | "v_madak_f32" | "v_madmk_f32" | "v_mad_legacy_f32" => {
  3613. let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  3614. let m = if name == "v_mad_legacy_f32" {
  3615. self.legacy_mul(a, bb)
  3616. } else {
  3617. self.s.m.bin(c, Bin::Mul, a, bb)
  3618. };
  3619. let r = self.s.m.bin(c, Bin::Add, m, cc);
  3620. float(self, r)
  3621. }
  3622. "v_max3_f32" | "v_min3_f32" | "v_med3_f32" => {
  3623. let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  3624. let r = match name {
  3625. "v_max3_f32" => {
  3626. let t = self.binary(35, a, bb);
  3627. self.binary(35, t, cc)
  3628. }
  3629. "v_min3_f32" => {
  3630. let t = self.binary(36, a, bb);
  3631. self.binary(36, t, cc)
  3632. }
  3633. _ => self.med3(a, bb, cc),
  3634. };
  3635. float(self, r)
  3636. }
  3637. "v_rcp_f32" | "v_rcp_iflag_f32" => {
  3638. // shortcut: the hardware reciprocal is approximate (1 ULP); this divides.
  3639. let a = f(self, 0)?;
  3640. let one = self.s.m.f32(1.0f32.to_bits());
  3641. let r = self.s.m.bin(c, Bin::SDiv, one, a);
  3642. float(self, r)
  3643. }
  3644. "v_rsq_f32" | "v_sqrt_f32" | "v_log_f32" | "v_exp_f32" | "v_fract_f32"
  3645. | "v_trunc_f32" | "v_floor_f32" | "v_ceil_f32" | "v_rndne_f32" | "v_sin_f32"
  3646. | "v_cos_f32" => {
  3647. let a = f(self, 0)?;
  3648. let op = match name {
  3649. "v_rsq_f32" => 25,
  3650. "v_sqrt_f32" => 24,
  3651. "v_log_f32" => 23,
  3652. "v_exp_f32" => 21,
  3653. "v_fract_f32" => 22,
  3654. "v_trunc_f32" => 29,
  3655. "v_floor_f32" => 27,
  3656. "v_ceil_f32" => 28,
  3657. "v_rndne_f32" => 26,
  3658. "v_sin_f32" => 13,
  3659. _ => 12,
  3660. };
  3661. let r = match op {
  3662. 12 | 13 => self.trig_turns(a, op == 12),
  3663. 22 => self.fract(a, 1.0, f32::from_bits(0x3F7F_FFFF)),
  3664. _ => self.unary(op, a),
  3665. };
  3666. float(self, r)
  3667. }
  3668. "v_cvt_i32_f32" | "v_cvt_u32_f32" | "v_cvt_flr_i32_f32" | "v_cvt_rpi_i32_f32" => {
  3669. let mut a = f(self, 0)?;
  3670. if name == "v_cvt_rpi_i32_f32" {
  3671. let h = self.s.m.f32(0.5f32.to_bits());
  3672. a = self.s.m.bin(c, Bin::Add, a, h);
  3673. }
  3674. if name != "v_cvt_i32_f32" && name != "v_cvt_u32_f32" {
  3675. a = self.unary(27, a);
  3676. }
  3677. // D3D's conversions saturate and give 0 for NaN, as the
  3678. // hardware does (checked on the RX 6700 XT and WARP).
  3679. let op = if name == "v_cvt_u32_f32" {
  3680. Cast::FpToUi
  3681. } else {
  3682. Cast::FpToSi
  3683. };
  3684. let r = self.s.m.cast(c, op, a, self.s.t.i32);
  3685. int(self, r)
  3686. }
  3687. "v_cvt_f32_i32" | "v_cvt_f32_u32" | "v_cvt_f32_ubyte0" | "v_cvt_f32_ubyte1"
  3688. | "v_cvt_f32_ubyte2" | "v_cvt_f32_ubyte3" => {
  3689. let mut a = s(self, 0)?;
  3690. if let Some(n) = name.strip_prefix("v_cvt_f32_ubyte") {
  3691. let sh = self.s.m.i32(8 * u32::from(n.as_bytes()[0] - b'0'));
  3692. let ff = self.s.m.i32(0xff);
  3693. a = self.s.m.bin(c, Bin::LShr, a, sh);
  3694. a = self.s.m.bin(c, Bin::And, a, ff);
  3695. }
  3696. let op = if name == "v_cvt_f32_i32" {
  3697. Cast::SiToFp
  3698. } else {
  3699. Cast::UiToFp
  3700. };
  3701. let r = self.s.m.cast(c, op, a, self.s.t.f32);
  3702. float(self, r)
  3703. }
  3704. "v_fma_mix_f32" | "v_fma_mixlo_f16" | "v_fma_mixhi_f16" => {
  3705. // Each source is f32, or with op_sel_hi the low (op_sel: high)
  3706. // f16 half; neg_hi is the absolute value here.
  3707. let mut xs = Vec::new();
  3708. for i in 0..3 {
  3709. let op = v.src.get(i).ok_or("a missing operand")?;
  3710. let x = self.operand(inst, op)?;
  3711. let mut x = if v.opsel_hi >> i & 1 != 0 {
  3712. let h = if v.opsel >> i & 1 != 0 {
  3713. let k16 = self.s.m.i32(16);
  3714. self.s.m.bin(c, Bin::LShr, x, k16)
  3715. } else {
  3716. x
  3717. };
  3718. self.s
  3719. .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[h])
  3720. } else {
  3721. self.as_float(x)
  3722. };
  3723. if v.neg_hi >> i & 1 != 0 {
  3724. x = self.unary(6, x);
  3725. }
  3726. if v.neg >> i & 1 != 0 {
  3727. let z = self.s.m.f32(0x8000_0000);
  3728. x = self.s.m.bin(c, Bin::Sub, z, x);
  3729. }
  3730. xs.push(x);
  3731. }
  3732. let mut r = self.fmad(xs[0], xs[1], xs[2]);
  3733. if name == "v_fma_mix_f32" {
  3734. return float(self, r);
  3735. }
  3736. if v.clamp {
  3737. r = self.unary(7, r);
  3738. }
  3739. // The f16 result goes to one half; the other half stays.
  3740. let Some(Operand::Vector { reg, .. }) = v.dst else {
  3741. return Err("a mixed-precision result");
  3742. };
  3743. let old = match inst.read(Reg::V(reg)) {
  3744. Some(o) => self.i32_of(o)?,
  3745. None => self.s.m.i32(0),
  3746. };
  3747. let h = self
  3748. .s
  3749. .op(c, "legacyF32ToF16", Attr::ReadNone, self.s.t.i32, 130, &[r]);
  3750. let (keep, h) = if name == "v_fma_mixhi_f16" {
  3751. let k16 = self.s.m.i32(16);
  3752. (0xFFFF, self.s.m.bin(c, Bin::Shl, h, k16))
  3753. } else {
  3754. (0xFFFF_0000, h)
  3755. };
  3756. let keep = self.s.m.i32(keep);
  3757. let old = self.s.m.bin(c, Bin::And, old, keep);
  3758. let x = self.s.m.bin(c, Bin::Or, old, h);
  3759. self.write(inst, Reg::V(reg), x, guard);
  3760. Ok(())
  3761. }
  3762. "v_cvt_pkrtz_f16_f32" => {
  3763. let (a, bb) = (f(self, 0)?, f(self, 1)?);
  3764. let lo = self.f16_toward_zero(a);
  3765. let hi = self.f16_toward_zero(bb);
  3766. let sh = self.s.m.i32(16);
  3767. let hi = self.s.m.bin(c, Bin::Shl, hi, sh);
  3768. let r = self.s.m.bin(c, Bin::Or, lo, hi);
  3769. int(self, r)
  3770. }
  3771. "v_cvt_f16_f32" if v.opsel == 0 => {
  3772. // Rounded to nearest even (the MODE default) into the low half.
  3773. let a = f(self, 0)?;
  3774. let r = self
  3775. .s
  3776. .op(c, "legacyF32ToF16", Attr::ReadNone, self.s.t.i32, 130, &[a]);
  3777. let Some(Operand::Vector { reg, .. }) = v.dst else {
  3778. return Err("a 16-bit result outside a VGPR");
  3779. };
  3780. let r = self.low_half(inst, reg, r);
  3781. int(self, r)
  3782. }
  3783. "v_pack_b32_f16" => {
  3784. // Two f16 sources (op_sel: their high halves; abs and neg on
  3785. // the sign bit) into the low and high half.
  3786. let mut halves = Vec::new();
  3787. for k in 0..2 {
  3788. let op = v.src.get(k).ok_or("a missing operand")?;
  3789. let mut x = self.operand(inst, op)?;
  3790. if v.opsel >> k & 1 != 0 {
  3791. let k16 = self.s.m.i32(16);
  3792. x = self.s.m.bin(c, Bin::LShr, x, k16);
  3793. }
  3794. let mask = if v.abs >> k & 1 != 0 { 0x7FFF } else { 0xFFFF };
  3795. let mask = self.s.m.i32(mask);
  3796. x = self.s.m.bin(c, Bin::And, x, mask);
  3797. if v.neg >> k & 1 != 0 {
  3798. let sign = self.s.m.i32(0x8000);
  3799. x = self.s.m.bin(c, Bin::Xor, x, sign);
  3800. }
  3801. halves.push(x);
  3802. }
  3803. let k16 = self.s.m.i32(16);
  3804. let hi = self.s.m.bin(c, Bin::Shl, halves[1], k16);
  3805. let r = self.s.m.bin(c, Bin::Or, halves[0], hi);
  3806. int(self, r)
  3807. }
  3808. "v_cvt_f32_f16" if v.opsel == 0 => {
  3809. let a = s(self, 0)?;
  3810. let r = self
  3811. .s
  3812. .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[a]);
  3813. float(self, r)
  3814. }
  3815. "v_cndmask_b32" => {
  3816. let mask = match v.src.get(2) {
  3817. Some(&Operand::Scalar { code, .. }) => inst.read(Reg::S(code)),
  3818. _ => None,
  3819. };
  3820. let m = mask
  3821. .and_then(|m| self.x.st.masks.get(&m).copied())
  3822. .ok_or("a select on an untracked mask")?;
  3823. let cond = self.boolean(m, c)?;
  3824. if v.abs != 0 || v.neg != 0 {
  3825. let (a, bb) = (f(self, 0)?, f(self, 1)?);
  3826. let r = self.s.m.select(c, cond, bb, a);
  3827. return float(self, r);
  3828. }
  3829. let (a, bb) = (s(self, 0)?, s(self, 1)?);
  3830. let r = self.s.m.select(c, cond, bb, a);
  3831. int(self, r)
  3832. }
  3833. "v_add_co_u32" | "v_sub_co_u32" | "v_subrev_co_u32" | "v_add_co_ci_u32"
  3834. | "v_sub_co_ci_u32" | "v_subrev_co_ci_u32" => {
  3835. // The carry (borrow) out is a lane mask: this lane's bit.
  3836. let (mut a, mut bb) = (s(self, 0)?, s(self, 1)?);
  3837. if name.contains("subrev") {
  3838. std::mem::swap(&mut a, &mut bb);
  3839. }
  3840. let cin = if name.ends_with("_ci_u32") {
  3841. let m = match v.src.get(2) {
  3842. Some(&Operand::Scalar { code, .. }) => inst.read(Reg::S(code)),
  3843. _ => None,
  3844. };
  3845. let m = m
  3846. .and_then(|m| self.x.st.masks.get(&m).copied())
  3847. .ok_or("a carry-in from an untracked mask")?;
  3848. Some(self.boolean(m, c)?)
  3849. } else {
  3850. None
  3851. };
  3852. let (r, carry) = self.add_sub_carry(c, name.starts_with("v_add"), a, bb, cin);
  3853. int(self, r)?;
  3854. if let Some(Operand::Scalar { code, .. }) = v.carry
  3855. && let Some(w) = inst.write(Reg::S(code))
  3856. {
  3857. self.lane_bits.insert(w, carry);
  3858. }
  3859. for &(_, w) in &inst.writes {
  3860. self.vals
  3861. .entry(w)
  3862. .or_insert(Val::Missing("a lane mask read as data"));
  3863. }
  3864. Ok(())
  3865. }
  3866. "v_readlane_b32" => {
  3867. let (a, lane) = (s(self, 0)?, s(self, 1)?);
  3868. // A computed lane in a pixel or vertex program is a host lane
  3869. // (from a mask or `v_mbcnt`); a constant one is the console's.
  3870. if self.mask_data == MaskData::Host && !matches!(lane, V::Const(_)) {
  3871. self.s.flags |= flags::WAVE_OPS;
  3872. } else {
  3873. self.cross_lane(false)?;
  3874. }
  3875. let r = self.read_lane(a, lane);
  3876. int(self, r)
  3877. }
  3878. "v_writelane_b32" => {
  3879. // The lane given takes the scalar; the others keep their value.
  3880. let (a, lane) = (s(self, 0)?, s(self, 1)?);
  3881. let Some(Operand::Vector { reg, .. }) = v.dst else {
  3882. return Err("a lane write");
  3883. };
  3884. let old = match inst.read(Reg::V(reg)) {
  3885. Some(o) => self.i32_of(o)?,
  3886. None => self.s.m.i32(0),
  3887. };
  3888. self.cross_lane(false)?;
  3889. let me = self.lane_index();
  3890. let is = self.s.m.cmp(c, pred::EQ, me, lane);
  3891. let r = self.s.m.select(c, is, a, old);
  3892. int(self, r)
  3893. }
  3894. "v_readfirstlane_b32" => {
  3895. let a = s(self, 0)?;
  3896. self.s.flags |= flags::WAVE_OPS;
  3897. let r = self.s.op(
  3898. c,
  3899. "waveReadLaneFirst.i32",
  3900. Attr::NoUnwind,
  3901. self.s.t.i32,
  3902. 118,
  3903. &[a],
  3904. );
  3905. int(self, r)
  3906. }
  3907. _ => {
  3908. let r = self.integer(inst, name)?;
  3909. int(self, r)
  3910. }
  3911. }
  3912. }
  3913. /// A 64-bit source (a register pair; inline constants sign-extend).
  3914. fn src64(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  3915. let Fields::Valu(v) = &inst.fields else {
  3916. unreachable!()
  3917. };
  3918. if v.abs >> k & 1 != 0 || v.neg >> k & 1 != 0 || v.sdwa.is_some() || v.dpp.is_some() {
  3919. return Err("64-bit operand modifiers");
  3920. }
  3921. let c = self.cur;
  3922. let i64t = self.s.m.int(64);
  3923. self.s.flags |= flags::INT64;
  3924. let op = *v.src.get(k).ok_or("a missing operand")?;
  3925. let pair = |l: &mut Self, r: Reg, r1: Reg| -> Result<V, Why> {
  3926. let lo = l.i32_of(inst.read(r).ok_or("an unread operand")?)?;
  3927. let hi = l.i32_of(inst.read(r1).ok_or("an unread operand")?)?;
  3928. let lo = l.s.m.cast(c, Cast::ZExt, lo, i64t);
  3929. let hi = l.s.m.cast(c, Cast::ZExt, hi, i64t);
  3930. let k32 = l.s.m.int_const(i64t, 32);
  3931. let hi = l.s.m.bin(c, Bin::Shl, hi, k32);
  3932. Ok(l.s.m.bin(c, Bin::Or, lo, hi))
  3933. };
  3934. match op {
  3935. Operand::Vector { reg, .. } => pair(self, Reg::V(reg), Reg::V(reg + 1)),
  3936. Operand::Scalar { code, .. } if code != NULL => {
  3937. pair(self, Reg::S(code), Reg::S(code + 1))
  3938. }
  3939. Operand::Const(k @ 128..=208) => {
  3940. let x = crate::resource::inline(k).ok_or("a special operand")?;
  3941. Ok(self.s.m.int_const(i64t, i64::from(x as i32)))
  3942. }
  3943. _ => {
  3944. // Literals and the null register: zero-extended.
  3945. let x = self.operand(inst, &op)?;
  3946. Ok(self.s.m.cast(c, Cast::ZExt, x, i64t))
  3947. }
  3948. }
  3949. }
  3950. /// The low and high dwords of an i64.
  3951. fn split64(&mut self, x: V) -> (V, V) {
  3952. let c = self.cur;
  3953. let i64t = self.s.m.int(64);
  3954. let k32 = self.s.m.int_const(i64t, 32);
  3955. let lo = self.s.m.cast(c, Cast::Trunc, x, self.s.t.i32);
  3956. let hi = self.s.m.bin(c, Bin::LShr, x, k32);
  3957. let hi = self.s.m.cast(c, Cast::Trunc, hi, self.s.t.i32);
  3958. (lo, hi)
  3959. }
  3960. /// Source `k` of a 16-bit operation in the low 16 bits (the rest 0):
  3961. /// op_sel (or an SDWA word select) picks the high half; inline float
  3962. /// constants are f16 values here.
  3963. fn half_src(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  3964. let Fields::Valu(v) = &inst.fields else {
  3965. unreachable!()
  3966. };
  3967. let op = *v.src.get(k).ok_or("a missing operand")?;
  3968. let mut high = v.opsel >> k & 1 != 0;
  3969. if let Some(sd) = v.sdwa {
  3970. match sd.src_sel.get(k).copied().unwrap_or(6) {
  3971. 4 => {}
  3972. 5 => high = true,
  3973. 6 => {}
  3974. _ => return Err("a byte select on a 16-bit operation"),
  3975. }
  3976. }
  3977. let x = match (op, self.src0) {
  3978. (_, Some(x)) if k == 0 => x,
  3979. (Operand::Const(c @ 240..=248), _) => {
  3980. let h = [
  3981. 0x3800, 0xB800, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x4400, 0xC400, 0x3118,
  3982. ][usize::from(c - 240)];
  3983. self.s.m.i32(h)
  3984. }
  3985. _ => self.operand(inst, &op)?,
  3986. };
  3987. let c = self.cur;
  3988. let x = if high {
  3989. let k16 = self.s.m.i32(16);
  3990. self.s.m.bin(c, Bin::LShr, x, k16)
  3991. } else {
  3992. x
  3993. };
  3994. let m = self.s.m.i32(0xFFFF);
  3995. Ok(self.s.m.bin(c, Bin::And, x, m))
  3996. }
  3997. /// An f16 source as an f32 (exact), with its abs/neg modifiers.
  3998. fn half_fsrc(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  3999. let Fields::Valu(v) = &inst.fields else {
  4000. unreachable!()
  4001. };
  4002. let h = self.half_src(inst, k)?;
  4003. let f32t = self.s.t.f32;
  4004. let mut f = self
  4005. .s
  4006. .op(self.cur, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]);
  4007. if v.abs >> k & 1 != 0 {
  4008. f = self.unary(6, f);
  4009. }
  4010. if v.neg >> k & 1 != 0 {
  4011. let z = self.s.m.f32(0x8000_0000);
  4012. f = self.s.m.bin(self.cur, Bin::Sub, z, f);
  4013. }
  4014. Ok(f)
  4015. }
  4016. /// Writes a 16-bit result (low bits of `x`) into the destination's low
  4017. /// half, or its high half with op_sel bit 3 (or an SDWA WORD_1 select);
  4018. /// the other half is kept (GFX10).
  4019. fn write_half(&mut self, inst: &Inst, x: V, guard: Option<V>) -> Result<(), Why> {
  4020. let Fields::Valu(v) = &inst.fields else {
  4021. unreachable!()
  4022. };
  4023. let Some(Operand::Vector { reg, .. }) = v.dst else {
  4024. return Err("a 16-bit result outside a VGPR");
  4025. };
  4026. let mut high = v.opsel >> 3 & 1 != 0;
  4027. // SDWA: the word written, the other one kept (preserve) or zero
  4028. // (pad; a sign extension above the high word adds nothing).
  4029. let mut keep = true;
  4030. if let Some(sd) = v.sdwa {
  4031. match (sd.dst_sel, sd.dst_unused) {
  4032. (4, 2) => {}
  4033. (5, 2) => high = true,
  4034. (4 | 6, _) => keep = false,
  4035. (5, _) => (high, keep) = (true, false),
  4036. _ => return Err("an SDWA destination of a 16-bit operation"),
  4037. }
  4038. }
  4039. let c = self.cur;
  4040. let old = match inst.read(Reg::V(reg)).map(|o| self.i32_of(o)) {
  4041. Some(Ok(o)) if keep => o,
  4042. _ => self.s.m.i32(0),
  4043. };
  4044. let (k16, low) = (self.s.m.i32(16), self.s.m.i32(0xFFFF));
  4045. let x = self.s.m.bin(c, Bin::And, x, low);
  4046. let r = if high {
  4047. let o = self.s.m.bin(c, Bin::And, old, low);
  4048. let x = self.s.m.bin(c, Bin::Shl, x, k16);
  4049. self.s.m.bin(c, Bin::Or, o, x)
  4050. } else {
  4051. let keep = self.s.m.i32(0xFFFF_0000);
  4052. let o = self.s.m.bin(c, Bin::And, old, keep);
  4053. self.s.m.bin(c, Bin::Or, o, x)
  4054. };
  4055. self.write_placed(inst, Reg::V(reg), r, guard);
  4056. Ok(())
  4057. }
  4058. /// 16-bit operations, computed in f32 or i32: f16 sums, differences and
  4059. /// products are exact there and round once to f16 (f32 has the 2 x 11 +
  4060. /// 2 bits that make double rounding harmless); `None` if `name` is none.
  4061. fn valu16(&mut self, inst: &Inst, name: &str, guard: Option<V>) -> Option<Result<(), Why>> {
  4062. const FLOAT2: &[&str] = &[
  4063. "v_add_f16",
  4064. "v_sub_f16",
  4065. "v_subrev_f16",
  4066. "v_mul_f16",
  4067. "v_max_f16",
  4068. "v_min_f16",
  4069. ];
  4070. const FLOAT3: &[&str] = &[
  4071. "v_fma_f16",
  4072. "v_mad_f16",
  4073. "v_fmac_f16",
  4074. "v_mac_f16",
  4075. "v_max3_f16",
  4076. "v_min3_f16",
  4077. "v_med3_f16",
  4078. ];
  4079. const FLOAT1: &[&str] = &[
  4080. "v_rcp_f16",
  4081. "v_sqrt_f16",
  4082. "v_rsq_f16",
  4083. "v_log_f16",
  4084. "v_exp_f16",
  4085. "v_fract_f16",
  4086. "v_trunc_f16",
  4087. "v_floor_f16",
  4088. "v_ceil_f16",
  4089. "v_rndne_f16",
  4090. "v_sin_f16",
  4091. "v_cos_f16",
  4092. "v_cvt_f16_u16",
  4093. "v_cvt_f16_i16",
  4094. ];
  4095. const INT: &[&str] = &[
  4096. "v_add_nc_u16",
  4097. "v_sub_nc_u16",
  4098. "v_subrev_nc_u16",
  4099. "v_mul_lo_u16",
  4100. "v_lshlrev_b16",
  4101. "v_lshrrev_b16",
  4102. "v_ashrrev_i16",
  4103. "v_max_u16",
  4104. "v_max_i16",
  4105. "v_min_u16",
  4106. "v_min_i16",
  4107. "v_cvt_u16_f16",
  4108. "v_cvt_i16_f16",
  4109. ];
  4110. let all = [FLOAT1, FLOAT2, FLOAT3, INT];
  4111. if !all.iter().any(|l| l.contains(&name))
  4112. && !matches!(name, "v_cvt_f16_f32" | "v_cvt_f32_f16")
  4113. {
  4114. return None;
  4115. }
  4116. Some(self.valu16_op(inst, name, guard, FLOAT1, FLOAT2, FLOAT3))
  4117. }
  4118. #[allow(clippy::too_many_arguments)]
  4119. fn valu16_op(
  4120. &mut self,
  4121. inst: &Inst,
  4122. name: &str,
  4123. guard: Option<V>,
  4124. float1: &[&str],
  4125. float2: &[&str],
  4126. float3: &[&str],
  4127. ) -> Result<(), Why> {
  4128. let Fields::Valu(v) = &inst.fields else {
  4129. unreachable!()
  4130. };
  4131. let c = self.cur;
  4132. let i32t = self.s.t.i32;
  4133. let f32t = self.s.t.f32;
  4134. if name == "v_cvt_f32_f16" {
  4135. let f = self.half_fsrc(inst, 0)?;
  4136. return self.write_f(inst, f, guard);
  4137. }
  4138. let float_result = |l: &mut Self, mut f: V| -> Result<(), Why> {
  4139. if v.omod != 0 {
  4140. return Err("an output modifier on a 16-bit operation");
  4141. }
  4142. if v.clamp {
  4143. f = l.unary(7, f);
  4144. }
  4145. let h =
  4146. l.s.op(l.cur, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]);
  4147. l.write_half(inst, h, guard)
  4148. };
  4149. if name == "v_cvt_f16_f32" {
  4150. let f = self.fsrc(inst, 0)?;
  4151. return float_result(self, f);
  4152. }
  4153. if float2.contains(&name) {
  4154. let (a, b) = (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?);
  4155. let r = match name {
  4156. "v_add_f16" => self.s.m.bin(c, Bin::Add, a, b),
  4157. "v_sub_f16" => self.s.m.bin(c, Bin::Sub, a, b),
  4158. "v_subrev_f16" => self.s.m.bin(c, Bin::Sub, b, a),
  4159. "v_mul_f16" => self.s.m.bin(c, Bin::Mul, a, b),
  4160. "v_max_f16" => self.binary(35, a, b),
  4161. _ => self.binary(36, a, b),
  4162. };
  4163. return float_result(self, r);
  4164. }
  4165. if float3.contains(&name) {
  4166. let (a, b) = (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?);
  4167. let acc = if matches!(name, "v_fmac_f16" | "v_mac_f16") {
  4168. // The accumulator is the destination's half that is written.
  4169. let Some(Operand::Vector { reg, .. }) = v.dst else {
  4170. return Err("an accumulator");
  4171. };
  4172. let x = self.i32_of(inst.read(Reg::V(reg)).ok_or("an accumulator")?)?;
  4173. let x = if v.opsel >> 3 & 1 != 0 {
  4174. let k16 = self.s.m.i32(16);
  4175. self.s.m.bin(c, Bin::LShr, x, k16)
  4176. } else {
  4177. x
  4178. };
  4179. let m = self.s.m.i32(0xFFFF);
  4180. let x = self.s.m.bin(c, Bin::And, x, m);
  4181. self.s
  4182. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x])
  4183. } else {
  4184. self.half_fsrc(inst, 2)?
  4185. };
  4186. let r = match name {
  4187. // shortcut: fused f16 multiply-adds as FMad in f32 (the
  4188. // product is exact; the sum rounds twice).
  4189. "v_fma_f16" | "v_fmac_f16" | "v_mad_f16" | "v_mac_f16" => self.fmad(a, b, acc),
  4190. "v_max3_f16" => {
  4191. let t = self.binary(35, a, b);
  4192. self.binary(35, t, acc)
  4193. }
  4194. "v_min3_f16" => {
  4195. let t = self.binary(36, a, b);
  4196. self.binary(36, t, acc)
  4197. }
  4198. _ => self.med3(a, b, acc),
  4199. };
  4200. return float_result(self, r);
  4201. }
  4202. if float1.contains(&name) {
  4203. let r = match name {
  4204. "v_cvt_f16_u16" | "v_cvt_f16_i16" => {
  4205. let mut x = self.half_src(inst, 0)?;
  4206. let op = if name == "v_cvt_f16_i16" {
  4207. let k16 = self.s.m.i32(16);
  4208. let t = self.s.m.bin(c, Bin::Shl, x, k16);
  4209. x = self.s.m.bin(c, Bin::AShr, t, k16);
  4210. Cast::SiToFp
  4211. } else {
  4212. Cast::UiToFp
  4213. };
  4214. self.s.m.cast(c, op, x, f32t)
  4215. }
  4216. "v_rcp_f16" => {
  4217. let a = self.half_fsrc(inst, 0)?;
  4218. let one = self.s.m.f32(1.0f32.to_bits());
  4219. self.s.m.bin(c, Bin::SDiv, one, a)
  4220. }
  4221. _ => {
  4222. let a = self.half_fsrc(inst, 0)?;
  4223. let op = match name {
  4224. "v_sqrt_f16" => 24,
  4225. "v_rsq_f16" => 25,
  4226. "v_log_f16" => 23,
  4227. "v_exp_f16" => 21,
  4228. "v_fract_f16" => 22,
  4229. "v_trunc_f16" => 29,
  4230. "v_floor_f16" => 27,
  4231. "v_ceil_f16" => 28,
  4232. "v_rndne_f16" => 26,
  4233. "v_sin_f16" => 13,
  4234. _ => 12,
  4235. };
  4236. match op {
  4237. 12 | 13 => self.trig_turns(a, op == 12),
  4238. // Any f16 in (-2^-11, 0) has fract >= 1 - 2^-12; clamp to 0x3bff (1 - 2^-11).
  4239. 22 => self.fract(a, 1.0 - 1.0 / 4096.0, 1.0 - 1.0 / 2048.0),
  4240. _ => self.unary(op, a),
  4241. }
  4242. }
  4243. };
  4244. return float_result(self, r);
  4245. }
  4246. // 16-bit integers: computed on the low halves, the low 16 bits kept.
  4247. if v.clamp || v.omod != 0 || v.abs != 0 || v.neg != 0 {
  4248. return Err("modifiers on a 16-bit integer operation");
  4249. }
  4250. let r = match name {
  4251. "v_cvt_u16_f16" | "v_cvt_i16_f16" => {
  4252. // shortcut: converted through 32 bits, so out-of-range values
  4253. // wrap instead of saturating at 16 bits.
  4254. let a = self.half_fsrc(inst, 0)?;
  4255. let op = if name == "v_cvt_u16_f16" {
  4256. Cast::FpToUi
  4257. } else {
  4258. Cast::FpToSi
  4259. };
  4260. self.s.m.cast(c, op, a, i32t)
  4261. }
  4262. _ => {
  4263. let (mut a, mut b) = (self.half_src(inst, 0)?, self.half_src(inst, 1)?);
  4264. let k16 = self.s.m.i32(16);
  4265. let sext = |l: &mut Self, x: V| {
  4266. let t = l.s.m.bin(c, Bin::Shl, x, k16);
  4267. l.s.m.bin(c, Bin::AShr, t, k16)
  4268. };
  4269. if name.ends_with("_i16") {
  4270. a = sext(self, a);
  4271. b = sext(self, b);
  4272. }
  4273. let k15 = self.s.m.i32(15);
  4274. match name {
  4275. "v_add_nc_u16" => self.s.m.bin(c, Bin::Add, a, b),
  4276. "v_sub_nc_u16" => self.s.m.bin(c, Bin::Sub, a, b),
  4277. "v_subrev_nc_u16" => self.s.m.bin(c, Bin::Sub, b, a),
  4278. "v_mul_lo_u16" => self.s.m.bin(c, Bin::Mul, a, b),
  4279. "v_lshlrev_b16" | "v_lshrrev_b16" | "v_ashrrev_i16" => {
  4280. // src0 is the shift (4 bits), src1 the value.
  4281. let sh = self.s.m.bin(c, Bin::And, a, k15);
  4282. let x = if name == "v_ashrrev_i16" {
  4283. sext(self, b)
  4284. } else {
  4285. b
  4286. };
  4287. let op = match name {
  4288. "v_lshlrev_b16" => Bin::Shl,
  4289. "v_lshrrev_b16" => Bin::LShr,
  4290. _ => Bin::AShr,
  4291. };
  4292. self.s.m.bin(c, op, x, sh)
  4293. }
  4294. _ => {
  4295. let p = match name {
  4296. "v_max_u16" => pred::IUGT,
  4297. "v_min_u16" => pred::IULT,
  4298. "v_max_i16" => pred::SGT,
  4299. _ => pred::SLT,
  4300. };
  4301. let t = self.s.m.cmp(c, p, a, b);
  4302. self.s.m.select(c, t, a, b)
  4303. }
  4304. }
  4305. }
  4306. };
  4307. self.write_half(inst, r, guard)
  4308. }
  4309. /// Half `high` of source `k` of a packed (VOP3P) operation, in the low
  4310. /// 16 bits: op_sel picks the half the low result reads, op_sel_hi the
  4311. /// half the high result reads. Inline float constants are f16 values.
  4312. fn packed_src(&mut self, inst: &Inst, k: usize, high: bool) -> Result<V, Why> {
  4313. let Fields::Valu(v) = &inst.fields else {
  4314. unreachable!()
  4315. };
  4316. let op = *v.src.get(k).ok_or("a missing operand")?;
  4317. let sel = if high { v.opsel_hi } else { v.opsel } >> k & 1 != 0;
  4318. let x = match op {
  4319. Operand::Const(c @ 240..=248) => {
  4320. let h = [
  4321. 0x3800, 0xB800, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x4400, 0xC400, 0x3118,
  4322. ][usize::from(c - 240)];
  4323. // shortcut: taken to fill both halves.
  4324. self.s.m.i32(h | h << 16)
  4325. }
  4326. _ => self.operand(inst, &op)?,
  4327. };
  4328. let c = self.cur;
  4329. let x = if sel {
  4330. let k16 = self.s.m.i32(16);
  4331. self.s.m.bin(c, Bin::LShr, x, k16)
  4332. } else {
  4333. x
  4334. };
  4335. let m = self.s.m.i32(0xFFFF);
  4336. Ok(self.s.m.bin(c, Bin::And, x, m))
  4337. }
  4338. /// Packed 16-bit operations (`v_pk_*`): each half computed as the
  4339. /// 16-bit operation does, f16 through f32 as in [`Self::valu16`].
  4340. fn packed16(&mut self, inst: &Inst, op: &str, guard: Option<V>) -> Result<(), Why> {
  4341. let Fields::Valu(v) = &inst.fields else {
  4342. unreachable!()
  4343. };
  4344. let float = op.ends_with("_f16");
  4345. let n = match op {
  4346. "fma_f16" | "mad_u16" | "mad_i16" => 3,
  4347. "add_f16" | "mul_f16" | "min_f16" | "max_f16" | "add_u16" | "sub_u16" | "add_i16"
  4348. | "sub_i16" | "mul_lo_u16" | "lshlrev_b16" | "lshrrev_b16" | "ashrrev_i16"
  4349. | "max_u16" | "min_u16" | "max_i16" | "min_i16" => 2,
  4350. _ => return Err("a packed 16-bit operation"),
  4351. };
  4352. if v.omod != 0 || !float && (v.clamp || v.neg != 0 || v.neg_hi != 0) {
  4353. return Err("modifiers on a packed integer operation");
  4354. }
  4355. let c = self.cur;
  4356. let (i32t, f32t) = (self.s.t.i32, self.s.t.f32);
  4357. let mut halves = Vec::new();
  4358. for high in [false, true] {
  4359. let mut xs = Vec::new();
  4360. for k in 0..n {
  4361. let h = self.packed_src(inst, k, high)?;
  4362. if float {
  4363. let mut f = self
  4364. .s
  4365. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]);
  4366. let neg = if high { v.neg_hi } else { v.neg };
  4367. if neg >> k & 1 != 0 {
  4368. let z = self.s.m.f32(0x8000_0000);
  4369. f = self.s.m.bin(c, Bin::Sub, z, f);
  4370. }
  4371. xs.push(f);
  4372. } else {
  4373. xs.push(h);
  4374. }
  4375. }
  4376. let r = if float {
  4377. let mut f = match op {
  4378. "add_f16" => self.s.m.bin(c, Bin::Add, xs[0], xs[1]),
  4379. "mul_f16" => self.s.m.bin(c, Bin::Mul, xs[0], xs[1]),
  4380. "min_f16" => self.binary(36, xs[0], xs[1]),
  4381. "max_f16" => self.binary(35, xs[0], xs[1]),
  4382. // shortcut: FMad in f32, as v_fma_f16.
  4383. _ => self.fmad(xs[0], xs[1], xs[2]),
  4384. };
  4385. if v.clamp {
  4386. f = self.unary(7, f);
  4387. }
  4388. self.s
  4389. .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f])
  4390. } else {
  4391. let k16 = self.s.m.i32(16);
  4392. let sext = |l: &mut Self, x: V| {
  4393. let t = l.s.m.bin(c, Bin::Shl, x, k16);
  4394. l.s.m.bin(c, Bin::AShr, t, k16)
  4395. };
  4396. if op.ends_with("_i16") {
  4397. for x in &mut xs {
  4398. *x = sext(self, *x);
  4399. }
  4400. }
  4401. let k15 = self.s.m.i32(15);
  4402. match op {
  4403. "add_u16" | "add_i16" => self.s.m.bin(c, Bin::Add, xs[0], xs[1]),
  4404. "sub_u16" | "sub_i16" => self.s.m.bin(c, Bin::Sub, xs[0], xs[1]),
  4405. "mul_lo_u16" => self.s.m.bin(c, Bin::Mul, xs[0], xs[1]),
  4406. "mad_u16" | "mad_i16" => {
  4407. let m = self.s.m.bin(c, Bin::Mul, xs[0], xs[1]);
  4408. self.s.m.bin(c, Bin::Add, m, xs[2])
  4409. }
  4410. "lshlrev_b16" | "lshrrev_b16" | "ashrrev_i16" => {
  4411. let sh = self.s.m.bin(c, Bin::And, xs[0], k15);
  4412. let o = match op {
  4413. "lshlrev_b16" => Bin::Shl,
  4414. "lshrrev_b16" => Bin::LShr,
  4415. _ => Bin::AShr,
  4416. };
  4417. let x = if op == "ashrrev_i16" {
  4418. sext(self, xs[1])
  4419. } else {
  4420. xs[1]
  4421. };
  4422. self.s.m.bin(c, o, x, sh)
  4423. }
  4424. _ => {
  4425. let p = match op {
  4426. "max_u16" => pred::IUGT,
  4427. "min_u16" => pred::IULT,
  4428. "max_i16" => pred::SGT,
  4429. _ => pred::SLT,
  4430. };
  4431. let t = self.s.m.cmp(c, p, xs[0], xs[1]);
  4432. self.s.m.select(c, t, xs[0], xs[1])
  4433. }
  4434. }
  4435. };
  4436. let m = self.s.m.i32(0xFFFF);
  4437. halves.push(self.s.m.bin(c, Bin::And, r, m));
  4438. }
  4439. let k16 = self.s.m.i32(16);
  4440. let hi = self.s.m.bin(c, Bin::Shl, halves[1], k16);
  4441. let r = self.s.m.bin(c, Bin::Or, halves[0], hi);
  4442. let Some(Operand::Vector { reg, .. }) = v.dst else {
  4443. return Err("a packed result outside a VGPR");
  4444. };
  4445. self.write(inst, Reg::V(reg), r, guard);
  4446. Ok(())
  4447. }
  4448. fn integer(&mut self, inst: &Inst, name: &'static str) -> Result<V, Why> {
  4449. let c = self.cur;
  4450. let s = |l: &mut Self, k| l.src(inst, k);
  4451. let k = |l: &mut Self, x: u32| l.s.m.i32(x);
  4452. let m31 = |l: &mut Self, x: V| {
  4453. let k31 = l.s.m.i32(31);
  4454. l.s.m.bin(c, Bin::And, x, k31)
  4455. };
  4456. Ok(match name {
  4457. "v_and_b32" | "v_or_b32" | "v_xor_b32" | "v_add_nc_u32" | "v_sub_nc_u32"
  4458. | "v_subrev_nc_u32" | "v_mul_lo_u32" => {
  4459. let (a, b) = (s(self, 0)?, s(self, 1)?);
  4460. let (op, a, b) = match name {
  4461. "v_and_b32" => (Bin::And, a, b),
  4462. "v_or_b32" => (Bin::Or, a, b),
  4463. "v_xor_b32" => (Bin::Xor, a, b),
  4464. "v_add_nc_u32" => (Bin::Add, a, b),
  4465. "v_sub_nc_u32" => (Bin::Sub, a, b),
  4466. "v_subrev_nc_u32" => (Bin::Sub, b, a),
  4467. _ => (Bin::Mul, a, b),
  4468. };
  4469. self.s.m.bin(c, op, a, b)
  4470. }
  4471. "v_xnor_b32" => {
  4472. let (a, b) = (s(self, 0)?, s(self, 1)?);
  4473. let x = self.s.m.bin(c, Bin::Xor, a, b);
  4474. let ones = k(self, u32::MAX);
  4475. self.s.m.bin(c, Bin::Xor, x, ones)
  4476. }
  4477. "v_not_b32" => {
  4478. let a = s(self, 0)?;
  4479. let ones = k(self, u32::MAX);
  4480. self.s.m.bin(c, Bin::Xor, a, ones)
  4481. }
  4482. "v_lshlrev_b32" | "v_lshrrev_b32" | "v_ashrrev_i32" => {
  4483. let (sh, a) = (s(self, 0)?, s(self, 1)?);
  4484. let sh = m31(self, sh);
  4485. let op = match name {
  4486. "v_lshlrev_b32" => Bin::Shl,
  4487. "v_lshrrev_b32" => Bin::LShr,
  4488. _ => Bin::AShr,
  4489. };
  4490. self.s.m.bin(c, op, a, sh)
  4491. }
  4492. "v_lshl_add_u32" | "v_lshl_or_b32" | "v_add_lshl_u32" | "v_and_or_b32"
  4493. | "v_or3_b32" | "v_xad_u32" | "v_add3_u32" | "v_xor3_b32" => {
  4494. let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  4495. match name {
  4496. "v_lshl_add_u32" | "v_lshl_or_b32" => {
  4497. let b = m31(self, b);
  4498. let t = self.s.m.bin(c, Bin::Shl, a, b);
  4499. let op = if name == "v_lshl_add_u32" {
  4500. Bin::Add
  4501. } else {
  4502. Bin::Or
  4503. };
  4504. self.s.m.bin(c, op, t, d)
  4505. }
  4506. "v_add_lshl_u32" => {
  4507. let t = self.s.m.bin(c, Bin::Add, a, b);
  4508. let d = m31(self, d);
  4509. self.s.m.bin(c, Bin::Shl, t, d)
  4510. }
  4511. _ => {
  4512. let (o1, o2) = match name {
  4513. "v_and_or_b32" => (Bin::And, Bin::Or),
  4514. "v_or3_b32" => (Bin::Or, Bin::Or),
  4515. "v_xad_u32" => (Bin::Xor, Bin::Add),
  4516. "v_add3_u32" => (Bin::Add, Bin::Add),
  4517. _ => (Bin::Xor, Bin::Xor),
  4518. };
  4519. let t = self.s.m.bin(c, o1, a, b);
  4520. self.s.m.bin(c, o2, t, d)
  4521. }
  4522. }
  4523. }
  4524. "v_mul_u32_u24" | "v_mul_i32_i24" => {
  4525. let (a, b) = (s(self, 0)?, s(self, 1)?);
  4526. let (sh, op) = (
  4527. k(self, 8),
  4528. if name == "v_mul_i32_i24" {
  4529. Bin::AShr
  4530. } else {
  4531. Bin::LShr
  4532. },
  4533. );
  4534. let a = self.s.m.bin(c, Bin::Shl, a, sh);
  4535. let a = self.s.m.bin(c, op, a, sh);
  4536. let b = self.s.m.bin(c, Bin::Shl, b, sh);
  4537. let b = self.s.m.bin(c, op, b, sh);
  4538. self.s.m.bin(c, Bin::Mul, a, b)
  4539. }
  4540. "v_bfe_u32" | "v_bfe_i32" => {
  4541. let (a, off, w) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  4542. let w = m31(self, w);
  4543. self.bfe(a, off, w, name == "v_bfe_i32")
  4544. }
  4545. "v_bfi_b32" => {
  4546. let (m, a, b) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  4547. let ones = k(self, u32::MAX);
  4548. let nm = self.s.m.bin(c, Bin::Xor, m, ones);
  4549. let x = self.s.m.bin(c, Bin::And, m, a);
  4550. let y = self.s.m.bin(c, Bin::And, nm, b);
  4551. self.s.m.bin(c, Bin::Or, x, y)
  4552. }
  4553. "v_max_i32" | "v_min_i32" | "v_max_u32" | "v_min_u32" => {
  4554. let (a, b) = (s(self, 0)?, s(self, 1)?);
  4555. let p = match name {
  4556. "v_max_i32" => pred::SGT,
  4557. "v_min_i32" => pred::SLT,
  4558. "v_max_u32" => pred::IUGT,
  4559. _ => pred::IULT,
  4560. };
  4561. let t = self.s.m.cmp(c, p, a, b);
  4562. self.s.m.select(c, t, a, b)
  4563. }
  4564. "v_mul_hi_u32" | "v_mul_hi_i32" => {
  4565. let (a, b) = (s(self, 0)?, s(self, 1)?);
  4566. self.mul_hi(a, b, name == "v_mul_hi_i32")
  4567. }
  4568. "v_alignbit_b32" | "v_alignbyte_b32" => {
  4569. // The low dword of {a, b} >> shift.
  4570. let (a, b, sh) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  4571. let sh = if name == "v_alignbyte_b32" {
  4572. let three = k(self, 3);
  4573. let t = self.s.m.bin(c, Bin::And, sh, three);
  4574. let k3 = k(self, 3);
  4575. self.s.m.bin(c, Bin::Shl, t, k3)
  4576. } else {
  4577. m31(self, sh)
  4578. };
  4579. let k32 = k(self, 32);
  4580. let lo = self.s.m.bin(c, Bin::LShr, b, sh);
  4581. let left = self.s.m.bin(c, Bin::Sub, k32, sh);
  4582. let left = m31(self, left);
  4583. let hi = self.s.m.bin(c, Bin::Shl, a, left);
  4584. let zero = k(self, 0);
  4585. let none = self.s.m.cmp(c, pred::EQ, sh, zero);
  4586. let hi = self.s.m.select(c, none, zero, hi);
  4587. self.s.m.bin(c, Bin::Or, lo, hi)
  4588. }
  4589. "v_bfrev_b32" => {
  4590. let a = s(self, 0)?;
  4591. self.s
  4592. .op(c, "unary.i32", Attr::ReadNone, self.s.t.i32, 30, &[a])
  4593. }
  4594. "v_bcnt_u32_b32" => {
  4595. let (a, b) = (s(self, 0)?, s(self, 1)?);
  4596. let n = self
  4597. .s
  4598. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 31, &[a]);
  4599. self.s.m.bin(c, Bin::Add, n, b)
  4600. }
  4601. "v_mad_u32_u24" | "v_mad_i32_i24" => {
  4602. let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  4603. let (sh, op) = (
  4604. k(self, 8),
  4605. if name == "v_mad_i32_i24" {
  4606. Bin::AShr
  4607. } else {
  4608. Bin::LShr
  4609. },
  4610. );
  4611. let a = self.s.m.bin(c, Bin::Shl, a, sh);
  4612. let a = self.s.m.bin(c, op, a, sh);
  4613. let b = self.s.m.bin(c, Bin::Shl, b, sh);
  4614. let b = self.s.m.bin(c, op, b, sh);
  4615. let m = self.s.m.bin(c, Bin::Mul, a, b);
  4616. self.s.m.bin(c, Bin::Add, m, d)
  4617. }
  4618. "v_min3_i32" | "v_max3_i32" | "v_min3_u32" | "v_max3_u32" | "v_med3_i32"
  4619. | "v_med3_u32" => {
  4620. let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  4621. let signed = name.ends_with("i32");
  4622. let (lt, gt) = if signed {
  4623. (pred::SLT, pred::SGT)
  4624. } else {
  4625. (pred::IULT, pred::IUGT)
  4626. };
  4627. let pick = |l: &mut Self, p, x, y| {
  4628. let t = l.s.m.cmp(c, p, x, y);
  4629. l.s.m.select(c, t, x, y)
  4630. };
  4631. match &name[2..6] {
  4632. "min3" => {
  4633. let t = pick(self, lt, a, b);
  4634. pick(self, lt, t, d)
  4635. }
  4636. "max3" => {
  4637. let t = pick(self, gt, a, b);
  4638. pick(self, gt, t, d)
  4639. }
  4640. _ => {
  4641. let lo = pick(self, lt, a, b);
  4642. let hi = pick(self, gt, a, b);
  4643. let t = pick(self, lt, hi, d);
  4644. pick(self, gt, lo, t)
  4645. }
  4646. }
  4647. }
  4648. "v_perm_b32" => {
  4649. // Byte i of the result is byte S of {src0, src1} (src1 the
  4650. // low dword) for selector byte S below 8; 8-11 repeat the
  4651. // sign of bytes 1 and 3 of src1, then of src0; 12 is 0x00,
  4652. // higher 0xFF.
  4653. let Fields::Valu(v) = &inst.fields else {
  4654. unreachable!()
  4655. };
  4656. let sel = match v.src.get(2) {
  4657. Some(&Operand::Literal(x)) => x,
  4658. Some(&Operand::Const(k)) => crate::resource::inline(k).ok_or(name)?,
  4659. _ => {
  4660. // A computed selector: each byte picked at run time.
  4661. let (a, b, sv) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  4662. let i64t = self.s.m.int(64);
  4663. self.s.flags |= flags::INT64;
  4664. let wa = self.s.m.cast(c, Cast::ZExt, a, i64t);
  4665. let wb = self.s.m.cast(c, Cast::ZExt, b, i64t);
  4666. let k32 = self.s.m.int_const(i64t, 32);
  4667. let wa = self.s.m.bin(c, Bin::Shl, wa, k32);
  4668. let both = self.s.m.bin(c, Bin::Or, wa, wb);
  4669. let mut r = k(self, 0);
  4670. for i in 0..4u32 {
  4671. let (sh, ff) = (k(self, 8 * i), k(self, 0xFF));
  4672. let sel = self.s.m.bin(c, Bin::LShr, sv, sh);
  4673. let sel = self.s.m.bin(c, Bin::And, sel, ff);
  4674. // Bytes 0-7 of {src0, src1}.
  4675. let k3 = k(self, 3);
  4676. let bits = self.s.m.bin(c, Bin::Shl, sel, k3);
  4677. let bits = self.s.m.cast(c, Cast::ZExt, bits, i64t);
  4678. let x = self.s.m.bin(c, Bin::LShr, both, bits);
  4679. let x = self.s.m.cast(c, Cast::Trunc, x, self.s.t.i32);
  4680. let mut byte = self.s.m.bin(c, Bin::And, x, ff);
  4681. // 8-11: the sign of bytes 1, 3 of src1, then of src0.
  4682. for (n, src, bit) in [(8, b, 15), (9, b, 31), (10, a, 15), (11, a, 31)]
  4683. {
  4684. let left = k(self, 31 - bit);
  4685. let t = self.s.m.bin(c, Bin::Shl, src, left);
  4686. let k31 = k(self, 31);
  4687. let t = self.s.m.bin(c, Bin::AShr, t, k31);
  4688. let t = self.s.m.bin(c, Bin::And, t, ff);
  4689. let kn = k(self, n);
  4690. let is = self.s.m.cmp(c, pred::EQ, sel, kn);
  4691. byte = self.s.m.select(c, is, t, byte);
  4692. }
  4693. let (k12, z) = (k(self, 12), k(self, 0));
  4694. let is12 = self.s.m.cmp(c, pred::EQ, sel, k12);
  4695. byte = self.s.m.select(c, is12, z, byte);
  4696. let above = self.s.m.cmp(c, pred::IUGT, sel, k12);
  4697. byte = self.s.m.select(c, above, ff, byte);
  4698. let at = k(self, 8 * i);
  4699. let byte = self.s.m.bin(c, Bin::Shl, byte, at);
  4700. r = self.s.m.bin(c, Bin::Or, r, byte);
  4701. }
  4702. return Ok(r);
  4703. }
  4704. };
  4705. let (a, b) = (s(self, 0)?, s(self, 1)?);
  4706. let mut r = k(self, 0);
  4707. for i in 0..4 {
  4708. let pick = sel >> (8 * i) & 0xFF;
  4709. let byte = match pick {
  4710. 0..=7 => {
  4711. let (src, n) = if pick < 4 { (b, pick) } else { (a, pick - 4) };
  4712. let sh = k(self, 8 * n);
  4713. let t = self.s.m.bin(c, Bin::LShr, src, sh);
  4714. let ff = k(self, 0xFF);
  4715. self.s.m.bin(c, Bin::And, t, ff)
  4716. }
  4717. 8..=11 => {
  4718. let src = if pick < 10 { b } else { a };
  4719. let bit = if pick % 2 == 0 { 15 } else { 31 };
  4720. let left = k(self, 31 - bit);
  4721. let t = self.s.m.bin(c, Bin::Shl, src, left);
  4722. let k31 = k(self, 31);
  4723. let t = self.s.m.bin(c, Bin::AShr, t, k31);
  4724. let ff = k(self, 0xFF);
  4725. self.s.m.bin(c, Bin::And, t, ff)
  4726. }
  4727. 12 => continue,
  4728. _ => k(self, 0xFF),
  4729. };
  4730. let at = k(self, 8 * i);
  4731. let byte = self.s.m.bin(c, Bin::Shl, byte, at);
  4732. r = self.s.m.bin(c, Bin::Or, r, byte);
  4733. }
  4734. r
  4735. }
  4736. "v_bfm_b32" => {
  4737. // ((1 << src0[4:0]) - 1) << src1[4:0]
  4738. let (a, b) = (s(self, 0)?, s(self, 1)?);
  4739. let one = k(self, 1);
  4740. let (a, b) = (m31(self, a), m31(self, b));
  4741. let m = self.s.m.bin(c, Bin::Shl, one, a);
  4742. let m = self.s.m.bin(c, Bin::Sub, m, one);
  4743. self.s.m.bin(c, Bin::Shl, m, b)
  4744. }
  4745. "v_cvt_pk_u8_f32" => {
  4746. // src0 rounded to nearest even and saturated to a byte, into
  4747. // byte src1[1:0] of src2.
  4748. let f = self.fsrc(inst, 0)?;
  4749. let (b, d) = (s(self, 1)?, s(self, 2)?);
  4750. let f = self.unary(26, f);
  4751. let (zero, max) = (self.s.m.f32(0), self.s.m.f32(255.0f32.to_bits()));
  4752. let f = self.binary(35, f, zero);
  4753. let f = self.binary(36, f, max);
  4754. let x = self.s.m.cast(c, Cast::FpToUi, f, self.s.t.i32);
  4755. let (three, k3) = (k(self, 3), k(self, 3));
  4756. let sh = self.s.m.bin(c, Bin::And, b, three);
  4757. let sh = self.s.m.bin(c, Bin::Shl, sh, k3);
  4758. let x = self.s.m.bin(c, Bin::Shl, x, sh);
  4759. let ff = k(self, 0xFF);
  4760. let hole = self.s.m.bin(c, Bin::Shl, ff, sh);
  4761. let ones = k(self, u32::MAX);
  4762. let hole = self.s.m.bin(c, Bin::Xor, hole, ones);
  4763. let d = self.s.m.bin(c, Bin::And, d, hole);
  4764. self.s.m.bin(c, Bin::Or, d, x)
  4765. }
  4766. "v_ffbl_b32" => {
  4767. // -1 for zero, as DXIL's first-bit-low.
  4768. let a = s(self, 0)?;
  4769. self.s
  4770. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 32, &[a])
  4771. }
  4772. "v_mbcnt_lo_u32_b32" | "v_mbcnt_hi_u32_b32" => {
  4773. // Bits of the mask's low (high) half below this lane, plus src1:
  4774. // with an all-ones mask, the lane index.
  4775. let (a, b) = (s(self, 0)?, s(self, 1)?);
  4776. // Mesh lanes are the console's by construction; pixel and
  4777. // vertex lanes are the host's, as their masks are.
  4778. if self.mask_data == MaskData::Host {
  4779. // Host lanes: the mask must be one (a ballot) or all lanes.
  4780. let Fields::Valu(v) = &inst.fields else {
  4781. unreachable!()
  4782. };
  4783. let host = match v.src.first() {
  4784. Some(&Operand::Const(193)) => true,
  4785. Some(&Operand::Scalar { code, .. }) => {
  4786. inst.read(Reg::S(code)).is_some_and(|m| {
  4787. self.x.st.masks.contains_key(&m) || self.x.st.highs.contains_key(&m)
  4788. })
  4789. }
  4790. _ => false,
  4791. };
  4792. if !host {
  4793. return Err("v_mbcnt of a mask that is no ballot (console lane layout)");
  4794. }
  4795. self.s.flags |= flags::WAVE_OPS;
  4796. } else if self.s.mesh.is_none() {
  4797. self.cross_lane(false)?;
  4798. }
  4799. let lane = self.lane_index();
  4800. let below = if name == "v_mbcnt_lo_u32_b32" {
  4801. lane
  4802. } else {
  4803. let (k32, z) = (k(self, 32), k(self, 0));
  4804. let t = self.s.m.bin(c, Bin::Sub, lane, k32);
  4805. let low = self.s.m.cmp(c, pred::IULT, lane, k32);
  4806. self.s.m.select(c, low, z, t)
  4807. };
  4808. // (1 << below) - 1, all ones from 32 on.
  4809. let (one, k32, ones) = (k(self, 1), k(self, 32), k(self, u32::MAX));
  4810. let sh = m31(self, below);
  4811. let m = self.s.m.bin(c, Bin::Shl, one, sh);
  4812. let m = self.s.m.bin(c, Bin::Sub, m, one);
  4813. let full = self.s.m.cmp(c, pred::IUGE, below, k32);
  4814. let m = self.s.m.select(c, full, ones, m);
  4815. let x = self.s.m.bin(c, Bin::And, a, m);
  4816. let n = self
  4817. .s
  4818. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 31, &[x]);
  4819. self.s.m.bin(c, Bin::Add, n, b)
  4820. }
  4821. _ => return Err(name),
  4822. })
  4823. }
  4824. fn compare(&mut self, inst: &Inst, rest: &str) -> Result<(), Why> {
  4825. let (op, ty) = rest.rsplit_once('_').ok_or("a compare")?;
  4826. let c = self.cur;
  4827. let r = match ty {
  4828. "f32" if op == "class" => {
  4829. // Bit k of src1 tests class k: signalling NaN, quiet NaN,
  4830. // -inf, -normal, -denormal, -0, +0, +denormal, +normal, +inf.
  4831. let x = self.fsrc(inst, 0)?;
  4832. let x = self.as_int(x);
  4833. let mask = self.src(inst, 1)?;
  4834. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  4835. let (k23, k31, kff, mant, quiet) = (
  4836. k(self, 23),
  4837. k(self, 31),
  4838. k(self, 0xFF),
  4839. k(self, 0x7F_FFFF),
  4840. k(self, 0x40_0000),
  4841. );
  4842. let e = self.s.m.bin(c, Bin::LShr, x, k23);
  4843. let e = self.s.m.bin(c, Bin::And, e, kff);
  4844. let m = self.s.m.bin(c, Bin::And, x, mant);
  4845. let neg = self.s.m.bin(c, Bin::LShr, x, k31);
  4846. let zero = k(self, 0);
  4847. let (e0, e255) = (
  4848. self.s.m.cmp(c, pred::EQ, e, zero),
  4849. self.s.m.cmp(c, pred::EQ, e, kff),
  4850. );
  4851. let m0 = self.s.m.cmp(c, pred::EQ, m, zero);
  4852. let q = self.s.m.bin(c, Bin::And, x, quiet);
  4853. let q = self.s.m.cmp(c, pred::NE, q, zero);
  4854. // Positive classes 6-9; negative ones are 11 minus those.
  4855. let (normal, inf, zero_c, denorm) =
  4856. (k(self, 8), k(self, 9), k(self, 6), k(self, 7));
  4857. let t = self.s.m.select(c, m0, zero_c, denorm);
  4858. let t = self.s.m.select(c, e0, t, normal);
  4859. let t = self.s.m.select(c, e255, inf, t);
  4860. let eleven = k(self, 11);
  4861. let mirrored = self.s.m.bin(c, Bin::Sub, eleven, t);
  4862. let is_neg = self.s.m.cmp(c, pred::NE, neg, zero);
  4863. let t = self.s.m.select(c, is_neg, mirrored, t);
  4864. let (one, snan) = (k(self, 1), k(self, 0));
  4865. let nan_class = self.s.m.select(c, q, one, snan);
  4866. let yes = self.s.m.bool(true);
  4867. let nan = self.s.m.bin(c, Bin::Xor, m0, yes);
  4868. let nan = self.s.m.bin(c, Bin::And, nan, e255);
  4869. let t = self.s.m.select(c, nan, nan_class, t);
  4870. let bit = self.s.m.bin(c, Bin::LShr, mask, t);
  4871. let bit = self.s.m.bin(c, Bin::And, bit, one);
  4872. self.s.m.cmp(c, pred::NE, bit, zero)
  4873. }
  4874. "f32" | "f16" => {
  4875. let (a, b) = if ty == "f16" {
  4876. (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?)
  4877. } else {
  4878. (self.fsrc(inst, 0)?, self.fsrc(inst, 1)?)
  4879. };
  4880. let p = match op {
  4881. "f" => pred::FALSE,
  4882. "lt" => pred::OLT,
  4883. "eq" => pred::OEQ,
  4884. "le" => pred::OLE,
  4885. "gt" => pred::OGT,
  4886. "lg" => pred::ONE,
  4887. "ge" => pred::OGE,
  4888. "o" => pred::ORD,
  4889. "u" => pred::UNO,
  4890. "nge" => pred::ULT,
  4891. "nlg" => pred::UEQ,
  4892. "ngt" => pred::ULE,
  4893. "nle" => pred::UGT,
  4894. "neq" => pred::UNE,
  4895. "nlt" => pred::UGE,
  4896. "tru" => pred::TRUE,
  4897. _ => return Err(inst.name()),
  4898. };
  4899. self.s.m.cmp(c, p, a, b)
  4900. }
  4901. "u64" | "i64" => {
  4902. let (a, b) = (self.src64(inst, 0)?, self.src64(inst, 1)?);
  4903. let signed = ty == "i64";
  4904. let p = match op {
  4905. "eq" => pred::EQ,
  4906. "ne" | "lg" => pred::NE,
  4907. "lt" if signed => pred::SLT,
  4908. "le" if signed => pred::SLE,
  4909. "gt" if signed => pred::SGT,
  4910. "ge" if signed => pred::SGE,
  4911. "lt" => pred::IULT,
  4912. "le" => pred::IULE,
  4913. "gt" => pred::IUGT,
  4914. "ge" => pred::IUGE,
  4915. _ => return Err("a 64-bit compare"),
  4916. };
  4917. self.s.m.cmp(c, p, a, b)
  4918. }
  4919. "u32" | "i32" | "u16" | "i16" => {
  4920. let (a, b) = if ty.ends_with("16") {
  4921. let (mut a, mut b) = (self.half_src(inst, 0)?, self.half_src(inst, 1)?);
  4922. if ty == "i16" {
  4923. let k16 = self.s.m.i32(16);
  4924. for x in [&mut a, &mut b] {
  4925. let t = self.s.m.bin(c, Bin::Shl, *x, k16);
  4926. *x = self.s.m.bin(c, Bin::AShr, t, k16);
  4927. }
  4928. }
  4929. (a, b)
  4930. } else {
  4931. (self.src(inst, 0)?, self.src(inst, 1)?)
  4932. };
  4933. let signed = ty == "i32" || ty == "i16";
  4934. let p = match op {
  4935. "eq" => pred::EQ,
  4936. "ne" | "lg" => pred::NE,
  4937. "lt" if signed => pred::SLT,
  4938. "le" if signed => pred::SLE,
  4939. "gt" if signed => pred::SGT,
  4940. "ge" if signed => pred::SGE,
  4941. "lt" => pred::IULT,
  4942. "le" => pred::IULE,
  4943. "gt" => pred::IUGT,
  4944. "ge" => pred::IUGE,
  4945. "f" | "t" => {
  4946. self.lane(inst, Some(op == "t"));
  4947. return Ok(());
  4948. }
  4949. _ => return Err("an integer compare"),
  4950. };
  4951. self.s.m.cmp(c, p, a, b)
  4952. }
  4953. _ => return Err(inst.name()),
  4954. };
  4955. self.lane_bits_for(inst, r);
  4956. Ok(())
  4957. }
  4958. fn lane(&mut self, inst: &Inst, value: Option<bool>) {
  4959. let b = self.s.m.bool(value == Some(true));
  4960. self.lane_bits_for(inst, b);
  4961. }
  4962. fn lane_bits_for(&mut self, inst: &Inst, r: V) {
  4963. let Fields::Valu(v) = &inst.fields else {
  4964. return;
  4965. };
  4966. let code = if inst.name().starts_with("v_cmpx") {
  4967. Some(EXEC)
  4968. } else {
  4969. match v.dst {
  4970. Some(Operand::Scalar { code, .. }) => Some(code),
  4971. _ => None,
  4972. }
  4973. };
  4974. if let Some(lo) = code.and_then(|c| inst.write(Reg::S(c))) {
  4975. self.lane_bits.insert(lo, r);
  4976. }
  4977. for &(_, w) in &inst.writes {
  4978. self.vals
  4979. .entry(w)
  4980. .or_insert(Val::Missing("a lane mask read as data"));
  4981. }
  4982. }
  4983. fn interp(&mut self, inst: &Inst, site: Site) -> Result<(), Why> {
  4984. let Some(&interp) = self.interps.get(&site) else {
  4985. return Err("the first half of an interpolation");
  4986. };
  4987. let (attribute, mode) = match interp {
  4988. Interp::Interpolated {
  4989. attribute,
  4990. barycentric,
  4991. ..
  4992. } => (
  4993. attribute,
  4994. match barycentric {
  4995. Barycentric::PerspectiveCenter => 2,
  4996. Barycentric::PerspectiveCentroid => 3,
  4997. Barycentric::PerspectiveSample => 6,
  4998. Barycentric::LinearCenter => 4,
  4999. Barycentric::LinearCentroid => 5,
  5000. Barycentric::LinearSample => 7,
  5001. Barycentric::PerspectivePullModel => return Err("pull-model interpolation"),
  5002. },
  5003. ),
  5004. // P0, the provoking vertex: a flat (nointerpolation) input.
  5005. Interp::Vertex {
  5006. attribute,
  5007. vertex: 2,
  5008. } => (attribute, 1),
  5009. Interp::Vertex { .. } => return Err("a non-provoking vertex value"),
  5010. };
  5011. let dst = match &inst.fields {
  5012. Fields::Vintrp { dst, .. } => *dst,
  5013. Fields::Valu(v) => v.dst.ok_or("an interpolation")?,
  5014. _ => unreachable!(),
  5015. };
  5016. let Operand::Vector { reg, .. } = dst else {
  5017. return Err("an interpolation");
  5018. };
  5019. // A channel of an input element, interpolated as `mode` says.
  5020. let channel = |l: &mut Self, row: u8, ch: u8| -> Result<V, Why> {
  5021. let (id, col) = l
  5022. .find_input(row, ch)
  5023. .ok_or("an input the signature lacks")?;
  5024. let e = &mut l.s.inputs[id];
  5025. if e.interp != mode && e.usage != 0 {
  5026. return Err("one input interpolated two ways");
  5027. }
  5028. e.interp = mode;
  5029. match l.load_any_input(id, col) {
  5030. Val::I32(x) => Ok(x),
  5031. _ => Err("an input"),
  5032. }
  5033. };
  5034. let packing = match &self.x.native.io {
  5035. StageIo::Ps { inputs, .. } => inputs
  5036. .iter()
  5037. .find(|i| i.row == attribute.row && i.fp16)
  5038. .map(|i| (i.pack2, (i.row2 != i.row).then_some(i.row2))),
  5039. _ => None,
  5040. };
  5041. let f16 = inst.name().ends_with("_f16");
  5042. let x = match packing {
  5043. None if f16 || attribute.high => return Err("a 16-bit read of a 32-bit input"),
  5044. None => channel(self, attribute.row, attribute.channel)?,
  5045. Some((pack2, b)) => {
  5046. // 16-bit values: one in the low half of each dword, or two
  5047. // per dword (`packed_half`); the host's are 32-bit floats.
  5048. let half = |l: &mut Self, h: u8| -> Result<Option<V>, Why> {
  5049. let src = if pack2 {
  5050. packed_half(&l.s.inputs, attribute.row, b, h)
  5051. } else {
  5052. h.is_multiple_of(2).then_some((attribute.row, h / 2))
  5053. };
  5054. let Some((row, ch)) = src else {
  5055. return Ok(None);
  5056. };
  5057. let x = channel(l, row, ch)?;
  5058. let f = l.as_float(x);
  5059. let i32t = l.s.t.i32;
  5060. Ok(Some(l.s.op(
  5061. l.cur,
  5062. "legacyF32ToF16",
  5063. Attr::ReadNone,
  5064. i32t,
  5065. 130,
  5066. &[f],
  5067. )))
  5068. };
  5069. let h = 2 * attribute.channel;
  5070. let c = self.cur;
  5071. if f16 {
  5072. let lo = half(self, h + u8::from(attribute.high))?
  5073. .ok_or("a packed input half no element holds")?;
  5074. self.low_half(inst, reg, lo)
  5075. } else if mode == 1 {
  5076. // The whole dword of a flat input: both halves.
  5077. let z = self.s.m.i32(0);
  5078. let lo = half(self, h)?.unwrap_or(z);
  5079. let hi = half(self, h + 1)?.unwrap_or(z);
  5080. let k16 = self.s.m.i32(16);
  5081. let hi = self.s.m.bin(c, Bin::Shl, hi, k16);
  5082. self.s.m.bin(c, Bin::Or, lo, hi)
  5083. } else {
  5084. return Err("32-bit interpolation of a 16-bit input");
  5085. }
  5086. }
  5087. };
  5088. // A pixel interpolates in every lane; guards only hide inactive ones.
  5089. self.write(inst, Reg::V(reg), x, None);
  5090. Ok(())
  5091. }
  5092. /// `x` (an f16 in the low bits) as the low half of VGPR `reg`: 16-bit
  5093. /// results keep the register's high half (GFX10).
  5094. fn low_half(&mut self, inst: &Inst, reg: u8, x: V) -> V {
  5095. let c = self.cur;
  5096. let old = match inst.read(Reg::V(reg)).map(|o| self.i32_of(o)) {
  5097. Some(Ok(o)) => o,
  5098. _ => self.s.m.i32(0),
  5099. };
  5100. let (high, low) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF));
  5101. let old = self.s.m.bin(c, Bin::And, old, high);
  5102. let x = self.s.m.bin(c, Bin::And, x, low);
  5103. self.s.m.bin(c, Bin::Or, old, x)
  5104. }
  5105. fn image(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  5106. let Fields::Image {
  5107. data,
  5108. addr,
  5109. dmask,
  5110. dim,
  5111. unorm,
  5112. a16,
  5113. d16,
  5114. tfe,
  5115. lwe,
  5116. ..
  5117. } = &inst.fields
  5118. else {
  5119. unreachable!()
  5120. };
  5121. if *tfe || *lwe {
  5122. return Err("an image access with tfe or lwe");
  5123. }
  5124. let name = inst.name();
  5125. if *a16 && name.starts_with("image_sample_b") {
  5126. return Err("a biased image sample with 16-bit coordinates");
  5127. }
  5128. // A load or sample with no channel enabled returns the first.
  5129. let dmask = if *dmask == 0 { &1 } else { dmask };
  5130. let site = (b, i);
  5131. let guard = self.guard(b, i)?;
  5132. let c = self.cur;
  5133. let (kind, coords) = match dim {
  5134. 0 => (1, 1),
  5135. 1 => (2, 2),
  5136. 2 => (4, 3),
  5137. // Sampled (face coordinates and face, see `cube_direction`) or
  5138. // sized only.
  5139. 3 if name.starts_with("image_sample")
  5140. || name.starts_with("image_gather")
  5141. || name == "image_get_resinfo" =>
  5142. {
  5143. (5, 3)
  5144. }
  5145. 4 => (6, 2),
  5146. 5 => (7, 3),
  5147. _ => return Err("an image dimension (cube loads or MSAA)"),
  5148. };
  5149. // Address VGPRs in order.
  5150. let mut regs = Vec::new();
  5151. for a in addr {
  5152. if let Operand::Vector { reg, dwords } = *a {
  5153. regs.extend((0..dwords).map(|k| reg + k));
  5154. }
  5155. }
  5156. // With a16, two 16-bit components per VGPR, low half first.
  5157. let addr_val = |l: &mut Self, k: usize| -> Result<V, Why> {
  5158. let r = *regs
  5159. .get(if *a16 { k / 2 } else { k })
  5160. .ok_or("an image address")?;
  5161. let v = inst.read(Reg::V(r)).ok_or("an image address")?;
  5162. let x = l.i32_of(v)?;
  5163. if !*a16 {
  5164. return Ok(x);
  5165. }
  5166. let c = l.cur;
  5167. let (sh, mask) = (l.s.m.i32(16 * (k as u32 % 2)), l.s.m.i32(0xFFFF));
  5168. let x = l.s.m.bin(c, Bin::LShr, x, sh);
  5169. Ok(l.s.m.bin(c, Bin::And, x, mask))
  5170. };
  5171. let src = self
  5172. .descriptors
  5173. .get(&(site, false))
  5174. .copied()
  5175. .ok_or("an untracked image")?;
  5176. let store = name.starts_with("image_store");
  5177. let uav = store
  5178. || self
  5179. .used_kind(src)
  5180. .is_some_and(|u| u.kind == ResourceType::Uav);
  5181. let props = (kind | if uav { 0x1000 } else { 0 }, 0x409);
  5182. if let Some(op) = name.strip_prefix("image_atomic_") {
  5183. // DXIL's atomic operations on a 32-bit integer texture UAV; the
  5184. // old value returns with glc. Sub is the add of the negation.
  5185. let code = match op {
  5186. "add" | "sub" => 0,
  5187. "and" => 1,
  5188. "or" => 2,
  5189. "xor" => 3,
  5190. "smin" => 4,
  5191. "smax" => 5,
  5192. "umin" => 6,
  5193. "umax" => 7,
  5194. "swap" => 8,
  5195. "cmpswap" => u32::MAX,
  5196. _ => return Err(name),
  5197. };
  5198. let Fields::Image { cache, .. } = &inst.fields else {
  5199. unreachable!()
  5200. };
  5201. if *d16 || *a16 {
  5202. return Err("a 16-bit image atomic");
  5203. }
  5204. // dmask: the data dwords (cmpswap: twice the value's).
  5205. // shortcut: 64-bit image atomics (two dwords, an R32G32 view)
  5206. // need the host's 64-bit typed atomics; they stop the program.
  5207. if *dmask != if code == u32::MAX { 3 } else { 1 } {
  5208. return Err("a 64-bit image atomic");
  5209. }
  5210. let iu = self.s.m.undef(self.s.t.i32);
  5211. let mut cs = vec![iu; 3];
  5212. for (k, slot) in cs.iter_mut().enumerate().take(coords) {
  5213. *slot = addr_val(self, k)?;
  5214. }
  5215. let Operand::Vector { reg, .. } = *data else {
  5216. return Err("image atomic data");
  5217. };
  5218. let vals = self.vgprs(inst, data, if code == u32::MAX { 2 } else { 1 })?;
  5219. let mut value = vals[0];
  5220. if op == "sub" {
  5221. let z = self.s.m.i32(0);
  5222. value = self.s.m.bin(c, Bin::Sub, z, value);
  5223. }
  5224. let old = match inst.read(Reg::V(reg)) {
  5225. Some(v) if cache.glc => self.i32_of(v)?,
  5226. _ => self.s.m.i32(0),
  5227. };
  5228. let h = self.handle(site, src, false, (kind | 0x1000, 0x105))?;
  5229. let at = self.begin_guarded(guard);
  5230. let i32t = self.s.t.i32;
  5231. let mut args = vec![h];
  5232. let r = if code == u32::MAX {
  5233. // cmpswap: data is (new, compare).
  5234. args.extend(cs);
  5235. args.extend([vals[1], vals[0]]);
  5236. self.s.op(
  5237. self.cur,
  5238. "atomicCompareExchange.i32",
  5239. Attr::NoUnwind,
  5240. i32t,
  5241. 79,
  5242. &args,
  5243. )
  5244. } else {
  5245. args.push(self.s.m.i32(code));
  5246. args.extend(cs);
  5247. args.push(value);
  5248. self.s
  5249. .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args)
  5250. };
  5251. let r = self.end_guarded(at, &[(r, old)])[0];
  5252. if cache.glc {
  5253. self.write(inst, Reg::V(reg), r, None);
  5254. }
  5255. return Ok(());
  5256. }
  5257. if store {
  5258. if name != "image_store" {
  5259. return Err("an image store to a mip level");
  5260. }
  5261. // shortcut: stores are taken to write all four channels of a
  5262. // float format (the console converts by the view's format).
  5263. if *dmask != 0xF {
  5264. return Err("an image store of some channels");
  5265. }
  5266. let iu = self.s.m.undef(self.s.t.i32);
  5267. let mut cs = vec![iu; 3];
  5268. for (k, slot) in cs.iter_mut().enumerate().take(coords) {
  5269. *slot = addr_val(self, k)?;
  5270. }
  5271. let Operand::Vector { reg, .. } = *data else {
  5272. return Err("image store data");
  5273. };
  5274. let mut vals = Vec::new();
  5275. for k in 0..4u8 {
  5276. // d16: two f16 channels per VGPR, low half first.
  5277. let r = if *d16 { k / 2 } else { k };
  5278. let v = inst.read(Reg::V(reg + r)).ok_or("image store data")?;
  5279. vals.push(if *d16 {
  5280. let mut x = self.i32_of(v)?;
  5281. if k % 2 == 1 {
  5282. let k16 = self.s.m.i32(16);
  5283. x = self.s.m.bin(self.cur, Bin::LShr, x, k16);
  5284. }
  5285. let f32t = self.s.t.f32;
  5286. self.s
  5287. .op(self.cur, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x])
  5288. } else {
  5289. self.float_of(v)?
  5290. });
  5291. }
  5292. let h = self.handle(site, src, false, props)?;
  5293. let at = self.begin_guarded(guard);
  5294. let mut args = vec![h];
  5295. args.extend(cs);
  5296. args.extend(vals);
  5297. args.push(self.s.m.i8(0xF));
  5298. let void = self.s.t.void;
  5299. self.s.op(
  5300. self.cur,
  5301. "textureStore.f32",
  5302. Attr::NoUnwind,
  5303. void,
  5304. 67,
  5305. &args,
  5306. );
  5307. self.end_guarded(at, &[]);
  5308. return Ok(());
  5309. }
  5310. let (op, sample) = match name {
  5311. "image_sample" => (60, true),
  5312. "image_sample_lz" | "image_sample_l" => (62, true),
  5313. "image_sample_b" => (61, true),
  5314. "image_sample_c_lz" => (65, true),
  5315. "image_sample_d" => (63, true),
  5316. "image_get_lod" if self.s.pixel => (81, true),
  5317. // Implicit derivatives: pixel shaders only.
  5318. "image_sample_c" if self.s.pixel => (64, true),
  5319. "image_gather4" | "image_gather4_lz" | "image_gather4_lz_o" => (73, true),
  5320. "image_load" | "image_load_mip" => (66, false),
  5321. "image_get_resinfo" => (72, false),
  5322. _ => return Err(name),
  5323. };
  5324. if op == 72 {
  5325. // Width, height, depth or layers, levels (per dmask) of the level
  5326. // in the first address: DXIL's dimensions; a channel DXIL leaves
  5327. // out reads 1 (UAVs: one level).
  5328. let h = self.handle(site, src, false, props)?;
  5329. let mip = if uav {
  5330. self.s.m.undef(self.s.t.i32)
  5331. } else {
  5332. addr_val(self, 0)?
  5333. };
  5334. let i32t = self.s.t.i32;
  5335. let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
  5336. let d = self
  5337. .s
  5338. .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]);
  5339. let one = self.s.m.i32(1);
  5340. let present = match kind {
  5341. 1 => [true, false, false, true],
  5342. 2 | 5 | 6 => [true, true, false, true],
  5343. _ => [true, true, true, true],
  5344. };
  5345. let Operand::Vector { reg, .. } = *data else {
  5346. return Err("an image result");
  5347. };
  5348. for (k, ch) in (0..4u32).filter(|ch| dmask >> ch & 1 != 0).enumerate() {
  5349. let x = if ch == 3 && uav || !present[ch as usize] {
  5350. one
  5351. } else {
  5352. self.s.m.extract(c, d, ch)
  5353. };
  5354. self.write(inst, Reg::V(reg + k as u8), x, guard);
  5355. }
  5356. return Ok(());
  5357. }
  5358. if uav && op != 66 {
  5359. return Err("sampling a UAV");
  5360. }
  5361. let h = self.handle(site, src, false, props)?;
  5362. let fu = self.s.m.undef(self.s.t.f32);
  5363. let iu = self.s.m.undef(self.s.t.i32);
  5364. let r = if sample {
  5365. let ss = self
  5366. .descriptors
  5367. .get(&(site, true))
  5368. .copied()
  5369. .ok_or("an untracked sampler")?;
  5370. // Comparison: the reference value is the first address after
  5371. // the bias, and the sampler is a comparison sampler.
  5372. let cmp = matches!(op, 64 | 65);
  5373. if cmp && (*a16 || dmask.count_ones() != 1) {
  5374. return Err("a comparison sample of 16-bit coordinates or several channels");
  5375. }
  5376. let sh = self.handle(site, ss, true, (14 | if cmp { 0x8000 } else { 0 }, 0))?;
  5377. // Texel offsets (`_o`) come first: x in bits 0-5, y in 8-13,
  5378. // signed (programmable offsets: gathers only).
  5379. let offset_word = name.ends_with("_o");
  5380. let first =
  5381. usize::from(offset_word) + usize::from(name == "image_sample_b") + usize::from(cmp);
  5382. // Coordinates the size divides (not the array slice); explicit
  5383. // gradients (x then y) come before the coordinates.
  5384. let spatial = coords - usize::from(kind == 6 || kind == 7);
  5385. let grads = if op == 63 { 2 * spatial } else { 0 };
  5386. let mut cs = vec![fu; 4];
  5387. // With a16, sampling coordinates and LOD are f16.
  5388. let to_float = |l: &mut Self, x: V| {
  5389. if *a16 {
  5390. let f = l.s.t.f32;
  5391. l.s.op(l.cur, "legacyF16ToF32", Attr::ReadNone, f, 131, &[x])
  5392. } else {
  5393. l.as_float(x)
  5394. }
  5395. };
  5396. for (k, slot) in cs.iter_mut().enumerate().take(coords) {
  5397. let x = addr_val(self, first + grads + k)?;
  5398. *slot = to_float(self, x);
  5399. }
  5400. if kind == 5 {
  5401. if *unorm || op == 63 || op == 81 {
  5402. return Err("a cube sample with texel coordinates, gradients or a level query");
  5403. }
  5404. let dir = self.cube_direction(cs[0], cs[1], cs[2]);
  5405. cs[..3].copy_from_slice(&dir);
  5406. }
  5407. if *unorm {
  5408. // Texel coordinates: divided by the size of level 0.
  5409. let i32t = self.s.t.i32;
  5410. let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
  5411. let z = self.s.m.i32(0);
  5412. let d = self
  5413. .s
  5414. .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, z]);
  5415. for (k, slot) in cs.iter_mut().enumerate().take(spatial) {
  5416. let n = self.s.m.extract(c, d, k as u32);
  5417. let n = self.s.m.cast(c, Cast::UiToFp, n, self.s.t.f32);
  5418. *slot = self.s.m.bin(c, Bin::SDiv, *slot, n);
  5419. }
  5420. }
  5421. if op == 81 {
  5422. // The clamped then the unclamped level of detail.
  5423. let Operand::Vector { reg, .. } = *data else {
  5424. return Err("an image result");
  5425. };
  5426. let f32t = self.s.t.f32;
  5427. for (k, ch) in (0..2u32).filter(|ch| dmask >> ch & 1 != 0).enumerate() {
  5428. let clamped = self.s.m.bool(ch == 0);
  5429. let lod = self.s.op(
  5430. c,
  5431. "calculateLOD.f32",
  5432. Attr::ReadOnly,
  5433. f32t,
  5434. 81,
  5435. &[h, sh, cs[0], cs[1], cs[2], clamped],
  5436. );
  5437. let x = self.as_int(lod);
  5438. self.write(inst, Reg::V(reg + k as u8), x, guard);
  5439. }
  5440. return Ok(());
  5441. }
  5442. let offsets = if kind == 5 {
  5443. 0
  5444. } else {
  5445. (coords - usize::from(kind == 6 || kind == 7)).min(3)
  5446. };
  5447. let zero = self.s.m.i32(0);
  5448. let mut os = vec![iu; 3];
  5449. for o in os.iter_mut().take(offsets) {
  5450. *o = zero;
  5451. }
  5452. let mut args = vec![h, sh];
  5453. args.extend(&cs);
  5454. match op {
  5455. 60 => {
  5456. args.extend(&os);
  5457. args.push(fu);
  5458. self.s
  5459. .op(c, "sample.f32", Attr::ReadOnly, self.s.t.res_ret, 60, &args)
  5460. }
  5461. 61 => {
  5462. let bias = addr_val(self, 0)?;
  5463. let bias = self.as_float(bias);
  5464. args.extend(&os);
  5465. args.extend([bias, fu]);
  5466. self.s.op(
  5467. c,
  5468. "sampleBias.f32",
  5469. Attr::ReadOnly,
  5470. self.s.t.res_ret,
  5471. 61,
  5472. &args,
  5473. )
  5474. }
  5475. 63 => {
  5476. let mut g = vec![fu; 6];
  5477. for k in 0..spatial {
  5478. let x = addr_val(self, first + k)?;
  5479. g[k] = to_float(self, x);
  5480. let y = addr_val(self, first + spatial + k)?;
  5481. g[3 + k] = to_float(self, y);
  5482. }
  5483. args.extend(&os);
  5484. args.extend(g);
  5485. args.push(fu);
  5486. self.s.op(
  5487. c,
  5488. "sampleGrad.f32",
  5489. Attr::ReadOnly,
  5490. self.s.t.res_ret,
  5491. 63,
  5492. &args,
  5493. )
  5494. }
  5495. 64 | 65 => {
  5496. let reference = addr_val(self, first - 1)?;
  5497. let reference = self.as_float(reference);
  5498. args.extend(&os);
  5499. args.push(reference);
  5500. let name = if op == 64 {
  5501. args.push(fu);
  5502. "sampleCmp.f32"
  5503. } else {
  5504. "sampleCmpLevelZero.f32"
  5505. };
  5506. self.s
  5507. .op(c, name, Attr::ReadOnly, self.s.t.res_ret, op, &args)
  5508. }
  5509. 62 => {
  5510. let lod = if name == "image_sample_l" {
  5511. let x = addr_val(self, coords)?;
  5512. to_float(self, x)
  5513. } else {
  5514. self.s.m.f32(0)
  5515. };
  5516. args.extend(&os);
  5517. args.push(lod);
  5518. self.s.op(
  5519. c,
  5520. "sampleLevel.f32",
  5521. Attr::ReadOnly,
  5522. self.s.t.res_ret,
  5523. 62,
  5524. &args,
  5525. )
  5526. }
  5527. _ => {
  5528. if name == "image_gather4" {
  5529. return Err("a gather with implicit level");
  5530. }
  5531. if dmask.count_ones() != 1 {
  5532. return Err("a gather of several channels");
  5533. }
  5534. if offset_word {
  5535. let w = addr_val(self, 0)?;
  5536. for (k, at) in [(0, 26), (1, 18)] {
  5537. // Bits at..at+5 sign-extended: shift up, then down.
  5538. let left = self.s.m.i32(at);
  5539. let t = self.s.m.bin(c, Bin::Shl, w, left);
  5540. let k26 = self.s.m.i32(26);
  5541. os[k] = self.s.m.bin(c, Bin::AShr, t, k26);
  5542. }
  5543. }
  5544. args.extend(&os[..2]);
  5545. args.push(self.s.m.i32(dmask.trailing_zeros()));
  5546. self.s.op(
  5547. c,
  5548. "textureGather.f32",
  5549. Attr::ReadOnly,
  5550. self.s.t.res_ret,
  5551. 73,
  5552. &args,
  5553. )
  5554. }
  5555. }
  5556. } else {
  5557. let mut cs = vec![iu; 3];
  5558. for (k, slot) in cs.iter_mut().enumerate().take(coords) {
  5559. *slot = addr_val(self, k)?;
  5560. }
  5561. let mip = if name == "image_load_mip" {
  5562. addr_val(self, coords)?
  5563. } else if uav {
  5564. // Our declarations have four channels.
  5565. self.s.flags |= flags::TYPED_UAV_LOADS;
  5566. iu
  5567. } else {
  5568. self.s.m.i32(0)
  5569. };
  5570. let mut args = vec![h, mip];
  5571. args.extend(&cs);
  5572. args.extend([iu, iu, iu]);
  5573. self.s.op(
  5574. c,
  5575. "textureLoad.f32",
  5576. Attr::ReadOnly,
  5577. self.s.t.res_ret,
  5578. 66,
  5579. &args,
  5580. )
  5581. };
  5582. let Operand::Vector { reg, .. } = *data else {
  5583. return Err("an image result");
  5584. };
  5585. let channels: Vec<u32> = if op == 73 {
  5586. vec![0, 1, 2, 3]
  5587. } else {
  5588. (0..4).filter(|ch| dmask >> ch & 1 != 0).collect()
  5589. };
  5590. let mut xs = Vec::new();
  5591. for ch in channels {
  5592. let x = self.s.m.extract(c, r, ch);
  5593. xs.push(if *d16 {
  5594. // shortcut: d16 results are taken as floats (rounded to
  5595. // nearest even); integer formats would keep 16 bits.
  5596. let i32t = self.s.t.i32;
  5597. self.s
  5598. .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[x])
  5599. } else {
  5600. self.as_int(x)
  5601. });
  5602. }
  5603. if *d16 {
  5604. // Two channels per VGPR, low half first (an odd last high half 0).
  5605. let k16 = self.s.m.i32(16);
  5606. xs = xs
  5607. .chunks(2)
  5608. .map(|p| match *p {
  5609. [lo, hi] => {
  5610. let hi = self.s.m.bin(c, Bin::Shl, hi, k16);
  5611. self.s.m.bin(c, Bin::Or, lo, hi)
  5612. }
  5613. _ => p[0],
  5614. })
  5615. .collect();
  5616. }
  5617. for (k, x) in xs.into_iter().enumerate() {
  5618. self.write(inst, Reg::V(reg + k as u8), x, guard);
  5619. }
  5620. Ok(())
  5621. }
  5622. /// The direction a cube sample's face coordinates stand for: the
  5623. /// console takes s and t in [1, 2] (`v_cubesc`/`v_cubetc` over
  5624. /// `|v_cubema|`, plus 1.5) and the face id (`v_cubeid`), which the
  5625. /// host's cube sampling turns back into the same texel.
  5626. // shortcut: the view is taken as a cube, not a cube array (whose face
  5627. // operand adds 8 × the slice).
  5628. fn cube_direction(&mut self, s: V, t: V, face: V) -> [V; 3] {
  5629. let c = self.cur;
  5630. let k = |l: &mut Self, v: f32| l.s.m.f32(v.to_bits());
  5631. let (two, three) = (k(self, 2.0), k(self, 3.0));
  5632. let u = self.s.m.bin(c, Bin::Mul, s, two);
  5633. let u = self.s.m.bin(c, Bin::Sub, u, three);
  5634. let v = self.s.m.bin(c, Bin::Mul, t, two);
  5635. let v = self.s.m.bin(c, Bin::Sub, v, three);
  5636. let z = self.s.m.f32(0x8000_0000);
  5637. let (nu, nv) = (
  5638. self.s.m.bin(c, Bin::Sub, z, u),
  5639. self.s.m.bin(c, Bin::Sub, z, v),
  5640. );
  5641. let (one, mone) = (k(self, 1.0), k(self, -1.0));
  5642. let f = self.s.m.cast(c, Cast::FpToUi, face, self.s.t.i32);
  5643. // Per face +x, -x, +y, -y, +z, -z.
  5644. let table = [
  5645. [one, mone, u, u, u, nu],
  5646. [nv, nv, one, mone, nv, nv],
  5647. [nu, u, v, nv, one, mone],
  5648. ];
  5649. table.map(|row| {
  5650. let mut r = row[0];
  5651. for (n, &x) in row.iter().enumerate().skip(1) {
  5652. let kn = self.s.m.i32(n as u32);
  5653. let is = self.s.m.cmp(c, pred::EQ, f, kn);
  5654. r = self.s.m.select(c, is, x, r);
  5655. }
  5656. r
  5657. })
  5658. }
  5659. fn buffer(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  5660. let Fields::Buffer {
  5661. data,
  5662. addr,
  5663. soffset,
  5664. offset,
  5665. offen,
  5666. idxen,
  5667. format,
  5668. lds,
  5669. tfe,
  5670. ..
  5671. } = &inst.fields
  5672. else {
  5673. unreachable!()
  5674. };
  5675. let name = inst.name();
  5676. if *lds || *tfe {
  5677. return Err("a buffer access to LDS or with tfe");
  5678. }
  5679. if format.is_some() && !name.starts_with("tbuffer_load_format_") {
  5680. return Err(name);
  5681. }
  5682. let site = (b, i);
  5683. let guard = self.guard(b, i)?;
  5684. let c = self.cur;
  5685. let store = name.starts_with("buffer_store_");
  5686. // DXIL atomic operations: add, and, or, xor, signed and unsigned
  5687. // min and max, exchange; compare-exchange apart.
  5688. let atomic = match name.strip_prefix("buffer_atomic_") {
  5689. None => None,
  5690. Some("add") => Some(0),
  5691. Some("and") => Some(1),
  5692. Some("or") => Some(2),
  5693. Some("xor") => Some(3),
  5694. Some("smin") => Some(4),
  5695. Some("smax") => Some(5),
  5696. Some("umin") => Some(6),
  5697. Some("umax") => Some(7),
  5698. Some("swap") => Some(8),
  5699. Some("cmpswap") => Some(u32::MAX),
  5700. Some(_) => return Err(name),
  5701. };
  5702. // d16: two 16-bit channels per VGPR, low half first.
  5703. let d16 = name.starts_with("buffer_") && name.contains("_format_d16_");
  5704. let plain = name.replace("_format_d16_", "_format_");
  5705. let (typed, count) = match plain
  5706. .strip_prefix("buffer_load_")
  5707. .or(plain.strip_prefix("buffer_store_"))
  5708. .or(plain.strip_prefix("tbuffer_load_"))
  5709. {
  5710. _ if atomic.is_some() => (false, 1),
  5711. Some("dword") => (false, 1),
  5712. Some("dwordx2") => (false, 2),
  5713. Some("dwordx3") => (false, 3),
  5714. Some("dwordx4") => (false, 4),
  5715. Some("format_x") => (true, 1),
  5716. Some("format_xy") => (true, 2),
  5717. Some("format_xyz") => (true, 3),
  5718. Some("format_xyzw") => (true, 4),
  5719. _ => return Err(name),
  5720. };
  5721. let Operand::Vector { reg: areg, .. } = *addr else {
  5722. return Err("a buffer address");
  5723. };
  5724. let vaddr = |l: &mut Self, k: u8| -> Result<V, Why> {
  5725. let v = inst.read(Reg::V(areg + k)).ok_or("a buffer address")?;
  5726. l.i32_of(v)
  5727. };
  5728. let index = if *idxen { Some(vaddr(self, 0)?) } else { None };
  5729. let mut off = self.s.m.i32(u32::from(*offset));
  5730. if *offen {
  5731. let o = vaddr(self, u8::from(*idxen))?;
  5732. off = self.s.m.bin(c, Bin::Add, off, o);
  5733. }
  5734. if !matches!(
  5735. soffset,
  5736. Operand::Scalar { code: NULL, .. } | Operand::Const(128)
  5737. ) {
  5738. let so = self.operand(inst, soffset)?;
  5739. off = self.s.m.bin(c, Bin::Add, off, so);
  5740. }
  5741. let src = self
  5742. .descriptors
  5743. .get(&(site, false))
  5744. .copied()
  5745. .ok_or("an untracked buffer")?;
  5746. let used = self.used_kind(src);
  5747. let (base, extra) = self.built_offset(src)?;
  5748. if base != 0 {
  5749. let b = self.s.m.i32(base);
  5750. off = self.s.m.bin(c, Bin::Add, off, b);
  5751. }
  5752. if let Some(x) = extra {
  5753. off = self.s.m.bin(c, Bin::Add, off, x);
  5754. }
  5755. if used.is_some_and(|u| u.kind == ResourceType::Cbv) && !typed {
  5756. // A constant buffer read per lane (a dynamically indexed array).
  5757. // shortcut: the console's CBV descriptor is taken to have a 16-byte
  5758. // stride, as the vector loads of whole rows suggest.
  5759. let h = self.handle(site, src, false, (13, 0x1_0000))?;
  5760. let byte = match index {
  5761. Some(i) => {
  5762. let sixteen = self.s.m.i32(16);
  5763. let rows = self.s.m.bin(c, Bin::Mul, i, sixteen);
  5764. self.s.m.bin(c, Bin::Add, rows, off)
  5765. }
  5766. None => off,
  5767. };
  5768. let Some(Operand::Vector { reg, .. }) = *data else {
  5769. return Err("a buffer result");
  5770. };
  5771. for k in 0..count {
  5772. let four = self.s.m.i32(4 * k);
  5773. let a = self.s.m.bin(c, Bin::Add, byte, four);
  5774. let x = self.cbuffer_dword(h, a);
  5775. self.write(inst, Reg::V(reg + k as u8), x, guard);
  5776. }
  5777. return Ok(());
  5778. }
  5779. let uav = store || atomic.is_some() || used.is_some_and(|u| u.kind == ResourceType::Uav);
  5780. let u = if uav { 0x1000 } else { 0 };
  5781. let iu = self.s.m.undef(self.s.t.i32);
  5782. if let Some(op) = atomic {
  5783. let d = data.as_ref().ok_or("buffer atomic data")?;
  5784. let vals = self.vgprs(inst, d, if op == u32::MAX { 2 } else { 1 })?;
  5785. let (h, coords) = match index {
  5786. Some(index) => {
  5787. let stride = used.map_or(0, |u| u.stride);
  5788. if stride < 4 || !stride.is_multiple_of(4) {
  5789. return Err("a structured buffer of unknown stride");
  5790. }
  5791. let h = self.handle(site, src, false, (12 | u, stride))?;
  5792. (h, [index, off, iu])
  5793. }
  5794. None => (self.handle(site, src, false, (11 | u, 0))?, [off, iu, iu]),
  5795. };
  5796. let Operand::Vector { reg, .. } = *d else {
  5797. return Err("buffer atomic data");
  5798. };
  5799. let returns = matches!(inst.fields, Fields::Buffer { cache, .. } if cache.glc);
  5800. let old = match inst.read(Reg::V(reg)) {
  5801. Some(v) if returns => self.i32_of(v)?,
  5802. _ => self.s.m.i32(0),
  5803. };
  5804. let at = self.begin_guarded(guard);
  5805. let i32t = self.s.t.i32;
  5806. let r = if op == u32::MAX {
  5807. // cmpswap: data is (new, compare).
  5808. let mut args = vec![h];
  5809. args.extend(coords);
  5810. args.extend([vals[1], vals[0]]);
  5811. self.s.op(
  5812. self.cur,
  5813. "atomicCompareExchange.i32",
  5814. Attr::NoUnwind,
  5815. i32t,
  5816. 79,
  5817. &args,
  5818. )
  5819. } else {
  5820. let mut args = vec![h, self.s.m.i32(op)];
  5821. args.extend(coords);
  5822. args.push(vals[0]);
  5823. self.s
  5824. .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args)
  5825. };
  5826. let r = self.end_guarded(at, &[(r, old)])[0];
  5827. if returns {
  5828. self.write(inst, Reg::V(reg), r, None);
  5829. }
  5830. return Ok(());
  5831. }
  5832. if store {
  5833. let regs = if d16 { count.div_ceil(2) } else { count };
  5834. let mut vals =
  5835. self.vgprs(inst, data.as_ref().ok_or("buffer store data")?, regs as u8)?;
  5836. if d16 {
  5837. // shortcut: d16 data is taken as f16 (integer formats would
  5838. // keep 16 bits), widened for the 32-bit float store.
  5839. let mut wide = Vec::new();
  5840. for k in 0..count {
  5841. let mut x = vals[(k / 2) as usize];
  5842. if k % 2 == 1 {
  5843. let k16 = self.s.m.i32(16);
  5844. x = self.s.m.bin(c, Bin::LShr, x, k16);
  5845. }
  5846. let f32t = self.s.t.f32;
  5847. let f = self
  5848. .s
  5849. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]);
  5850. wide.push(self.as_int(f));
  5851. }
  5852. vals = wide;
  5853. }
  5854. let mut args = Vec::new();
  5855. let (op, name) = if typed {
  5856. // shortcut: typed stores are taken to write all four channels
  5857. // of a float format.
  5858. if count != 4 || *offen || *offset != 0 {
  5859. return Err("a typed buffer store of some channels or at an offset");
  5860. }
  5861. args.push(self.handle(site, src, false, (10 | u, 0x409))?);
  5862. args.extend([index.unwrap_or(self.s.m.i32(0)), iu]);
  5863. for x in vals {
  5864. args.push(self.as_float(x));
  5865. }
  5866. (69, "bufferStore.f32")
  5867. } else {
  5868. match index {
  5869. Some(index) => {
  5870. let stride = used.map_or(0, |u| u.stride);
  5871. if stride < 4 || !stride.is_multiple_of(4) {
  5872. return Err("a structured buffer of unknown stride");
  5873. }
  5874. args.push(self.handle(site, src, false, (12 | u, stride))?);
  5875. args.extend([index, off]);
  5876. }
  5877. None => {
  5878. args.push(self.handle(site, src, false, (11 | u, 0))?);
  5879. args.extend([off, iu]);
  5880. }
  5881. }
  5882. args.extend(&vals);
  5883. args.resize(3 + 4, iu);
  5884. (140, "rawBufferStore.i32")
  5885. };
  5886. args.push(self.s.m.i8(if typed { 0xF } else { (1u8 << count) - 1 }));
  5887. if !typed {
  5888. args.push(self.s.m.i32(4));
  5889. }
  5890. let at = self.begin_guarded(guard);
  5891. let void = self.s.t.void;
  5892. self.s.op(self.cur, name, Attr::NoUnwind, void, op, &args);
  5893. self.end_guarded(at, &[]);
  5894. return Ok(());
  5895. }
  5896. if let Some(f) = *format {
  5897. if index.is_some() {
  5898. return Err("a typed-format load by index");
  5899. }
  5900. let h = self.handle(site, src, false, (11 | u, 0))?;
  5901. let Some(Operand::Vector { reg, .. }) = *data else {
  5902. return Err("a buffer result");
  5903. };
  5904. for (k, x) in self.format_load(h, off, f, count)?.into_iter().enumerate() {
  5905. self.write(inst, Reg::V(reg + k as u8), x, guard);
  5906. }
  5907. return Ok(());
  5908. }
  5909. let r = if typed {
  5910. if *offen || matches!(off, V::Inst(_)) || *offset != 0 {
  5911. return Err("a typed buffer load at an offset");
  5912. }
  5913. if uav {
  5914. self.s.flags |= flags::TYPED_UAV_LOADS;
  5915. }
  5916. let h = self.handle(site, src, false, (10 | u, 0x409))?;
  5917. let index = index.unwrap_or(self.s.m.i32(0));
  5918. self.s.op(
  5919. c,
  5920. "bufferLoad.f32",
  5921. Attr::ReadOnly,
  5922. self.s.t.res_ret,
  5923. 68,
  5924. &[h, index, iu],
  5925. )
  5926. } else {
  5927. let mask = self.s.m.i8((1u8 << count) - 1);
  5928. let align = self.s.m.i32(4);
  5929. match index {
  5930. Some(index) => {
  5931. let stride = used.map_or(0, |u| u.stride);
  5932. if stride < 4 || !stride.is_multiple_of(4) {
  5933. return Err("a structured buffer of unknown stride");
  5934. }
  5935. let h = self.handle(site, src, false, (12 | u, stride))?;
  5936. self.s.op(
  5937. c,
  5938. "rawBufferLoad.f32",
  5939. Attr::ReadOnly,
  5940. self.s.t.res_ret,
  5941. 139,
  5942. &[h, index, off, mask, align],
  5943. )
  5944. }
  5945. None => {
  5946. let h = self.handle(site, src, false, (11 | u, 0))?;
  5947. self.s.op(
  5948. c,
  5949. "rawBufferLoad.f32",
  5950. Attr::ReadOnly,
  5951. self.s.t.res_ret,
  5952. 139,
  5953. &[h, off, iu, mask, align],
  5954. )
  5955. }
  5956. }
  5957. };
  5958. let Some(Operand::Vector { reg, .. }) = *data else {
  5959. return Err("a buffer result");
  5960. };
  5961. if d16 {
  5962. // Two f16 channels per VGPR (an odd last high half 0).
  5963. let k16 = self.s.m.i32(16);
  5964. let i32t = self.s.t.i32;
  5965. for k in 0..count.div_ceil(2) {
  5966. let mut x = None;
  5967. for ch in (2 * k..(2 * k + 2).min(count)).rev() {
  5968. let f = self.s.m.extract(c, r, ch);
  5969. let h = self
  5970. .s
  5971. .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]);
  5972. x = Some(match x {
  5973. Some(hi) => {
  5974. let hi = self.s.m.bin(c, Bin::Shl, hi, k16);
  5975. self.s.m.bin(c, Bin::Or, h, hi)
  5976. }
  5977. None => h,
  5978. });
  5979. }
  5980. self.write(inst, Reg::V(reg + k as u8), x.expect("a channel"), guard);
  5981. }
  5982. return Ok(());
  5983. }
  5984. for k in 0..count {
  5985. let x = self.s.m.extract(c, r, k);
  5986. let x = self.as_int(x);
  5987. self.write(inst, Reg::V(reg + k as u8), x, guard);
  5988. }
  5989. Ok(())
  5990. }
  5991. fn export(&mut self, b: usize, i: usize) -> Result<(), Why> {
  5992. let e = *self
  5993. .exports
  5994. .get(&(b, i))
  5995. .ok_or("an export I/O raising did not see")?;
  5996. if e.compressed {
  5997. return Err("a compressed export");
  5998. }
  5999. let guard = self.guard(b, i)?;
  6000. let mesh = self.s.mesh.is_some();
  6001. let c = self.cur;
  6002. if let Some(g) = guard
  6003. && !mesh
  6004. {
  6005. if !(e.done && self.s.pixel) {
  6006. return Err("a conditional export");
  6007. }
  6008. let t = self.s.m.bool(true);
  6009. let kill = self.s.m.bin(c, Bin::Xor, g, t);
  6010. self.s
  6011. .op(c, "discard", Attr::NoUnwind, self.s.t.void, 82, &[kill]);
  6012. }
  6013. if mesh && e.target == Target::Primitive {
  6014. return self.emit_indices(e, guard);
  6015. }
  6016. let param_row = |usage: Usage, row: u8| match usage {
  6017. // The 2020 compiler leaves a mesh program's first entry zeroed
  6018. // (usage "position"): its row is the one no other entry names.
  6019. Usage::Other(0) if mesh => self.unnamed_row(),
  6020. _ => Some(row),
  6021. };
  6022. // (output element, channel) per exported channel; per-primitive
  6023. // outputs are elements of `prims`.
  6024. let mut stores = Vec::new();
  6025. let primitive = matches!(e.target, Target::PrimitiveParam { .. });
  6026. let outputs = if primitive {
  6027. &self.s.prims
  6028. } else {
  6029. &self.s.outputs
  6030. };
  6031. let by_kind = |kind: u8| outputs.iter().position(|o| o.kind == kind);
  6032. // 16-bit vertex outputs: the halves each dword carries, as (output
  6033. // element, channel, high half) per channel.
  6034. let halves = match e.target {
  6035. Target::Param { usage, row } => {
  6036. param_row(usage, row).and_then(|r| self.half_outputs.get(&r).map(|&h| (r, h)))
  6037. }
  6038. _ => None,
  6039. };
  6040. if let Some((row, (pack2, b))) = halves {
  6041. for ch in 0..4u8 {
  6042. let Some(value) = e.values[usize::from(ch)] else {
  6043. continue;
  6044. };
  6045. for high in [false, true] {
  6046. let h = 2 * ch + u8::from(high);
  6047. let src = if pack2 {
  6048. packed_half(outputs, row, b, h)
  6049. } else {
  6050. (!high).then_some((row, ch))
  6051. };
  6052. let found = src.and_then(|(r, c)| {
  6053. outputs.iter().position(|o| {
  6054. o.row == Some(u32::from(r)) && c >= o.col && c < o.col + o.cols
  6055. })
  6056. });
  6057. if let Some(id) = found {
  6058. let col = src.expect("found").1 - outputs[id].col;
  6059. stores.push((id, col, value, Some(high)));
  6060. }
  6061. }
  6062. }
  6063. }
  6064. for ch in 0..4u8 {
  6065. let Some(value) = e.values[usize::from(ch)] else {
  6066. continue;
  6067. };
  6068. if halves.is_some() {
  6069. break;
  6070. }
  6071. let found = match e.target {
  6072. Target::Color(n) => outputs
  6073. .iter()
  6074. .position(|o| o.kind == 16 && o.row == Some(u32::from(n)))
  6075. .map(|id| (id, ch)),
  6076. Target::Position(0) => by_kind(3).map(|id| (id, ch)),
  6077. Target::Depth => match ch {
  6078. 0 => by_kind(17)
  6079. .or(by_kind(18))
  6080. .or(by_kind(19))
  6081. .map(|id| (id, 0)),
  6082. 1 => by_kind(20).map(|id| (id, 0)),
  6083. 2 => by_kind(14).map(|id| (id, 0)),
  6084. _ => None,
  6085. },
  6086. Target::Param { usage, row } | Target::PrimitiveParam { usage, row } => {
  6087. let row = param_row(usage, row);
  6088. outputs
  6089. .iter()
  6090. .position(|o| {
  6091. row.is_some_and(|r| o.row == Some(u32::from(r)))
  6092. && ch >= o.col
  6093. && ch < o.col + o.cols
  6094. })
  6095. .map(|id| (id, ch - outputs[id].col))
  6096. }
  6097. Target::Null | Target::Unread => None,
  6098. Target::Position(n @ 1..=2) => {
  6099. // shortcut: without the misc vector (point size, render
  6100. // target or viewport index) pos1 and pos2 carry the clip
  6101. // then cull distances, in semantic order.
  6102. if outputs.iter().any(|o| matches!(o.kind, 4 | 5)) {
  6103. return Err("render-target or viewport index exports");
  6104. }
  6105. let mut dists: Vec<usize> = (0..outputs.len())
  6106. .filter(|&i| matches!(outputs[i].kind, 6 | 7))
  6107. .collect();
  6108. dists.sort_by_key(|&i| (outputs[i].kind, outputs[i].index));
  6109. let flat: Vec<(usize, u8)> = dists
  6110. .iter()
  6111. .flat_map(|&i| (0..outputs[i].cols).map(move |c| (i, c)))
  6112. .collect();
  6113. // Channels past the distances the signature declares are
  6114. // ones the clipper does not enable (`PA_CL_VS_OUT_CNTL`).
  6115. let k = usize::from(n - 1) * 4 + usize::from(ch);
  6116. flat.get(k).copied()
  6117. }
  6118. Target::Position(_) => return Err("clip, cull or point-size exports"),
  6119. Target::Primitive => return Err("a primitive export"),
  6120. };
  6121. if let Some((id, col)) = found {
  6122. stores.push((id, col, value, None));
  6123. }
  6124. }
  6125. fn elements<'l>(l: &'l mut Lower, primitive: bool) -> &'l mut Vec<SigElement> {
  6126. if primitive {
  6127. &mut l.s.prims
  6128. } else {
  6129. &mut l.s.outputs
  6130. }
  6131. }
  6132. if stores
  6133. .iter()
  6134. .any(|s| s.3.is_none() && elements(self, primitive)[s.0].half)
  6135. {
  6136. return Err("a 16-bit output the stage data does not mark");
  6137. }
  6138. // A mesh lane writes its own vertex or primitive, where it exports.
  6139. let at = if mesh {
  6140. self.begin_guarded(guard)
  6141. } else {
  6142. None
  6143. };
  6144. let (name, opcode) = match (mesh, primitive) {
  6145. (false, _) => ("storeOutput", 5),
  6146. (true, false) => ("storeVertexOutput", 171),
  6147. (true, true) => ("storePrimitiveOutput", 172),
  6148. };
  6149. for (id, col, value, half) in stores {
  6150. let mut x = self.i32_of(value)?;
  6151. if let Some(high) = half {
  6152. // An f16 half, declared a 32-bit float on the host.
  6153. let c = self.cur;
  6154. if high {
  6155. let k16 = self.s.m.i32(16);
  6156. x = self.s.m.bin(c, Bin::LShr, x, k16);
  6157. }
  6158. let f32t = self.s.t.f32;
  6159. let f = self
  6160. .s
  6161. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]);
  6162. x = self.as_int(f);
  6163. }
  6164. let el = &mut elements(self, primitive)[id];
  6165. el.usage |= 1 << col;
  6166. let (suffix, x) = match el.comp {
  6167. 9 if half.is_some() => (".f32", self.as_float(x)),
  6168. 9 => {
  6169. let f = match self.floats.get(&value) {
  6170. Some(&f) => f,
  6171. None => self.as_float(x),
  6172. };
  6173. (".f32", f)
  6174. }
  6175. _ => (".i32", x),
  6176. };
  6177. let mut args = vec![
  6178. self.s.m.i32(id as u32),
  6179. self.s.m.i32(0),
  6180. self.s.m.i8(col),
  6181. x,
  6182. ];
  6183. if mesh {
  6184. args.push(self.mesh_thread());
  6185. }
  6186. let void = self.s.t.void;
  6187. self.s.op(
  6188. self.cur,
  6189. &format!("{name}{suffix}"),
  6190. Attr::NoUnwind,
  6191. void,
  6192. opcode,
  6193. &args,
  6194. );
  6195. }
  6196. self.end_guarded(at, &[]);
  6197. Ok(())
  6198. }
  6199. /// Mesh: `exp prim` as the lane's primitive. Bit 31 culls it (all
  6200. /// indices 0: no area).
  6201. fn emit_indices(&mut self, e: &Export, guard: Option<V>) -> Result<(), Why> {
  6202. let v = e.values[0].ok_or("a primitive export without its indices")?;
  6203. let x = self.i32_of(v)?;
  6204. let at = self.begin_guarded(guard);
  6205. let c = self.cur;
  6206. let z = self.s.m.i32(0);
  6207. let culled = self.s.m.cmp(c, pred::SLT, x, z);
  6208. let mut args = vec![self.mesh_thread()];
  6209. for k in 0..3 {
  6210. let (shift, mask) = (self.s.m.i32(10 * k), self.s.m.i32(0x3FF));
  6211. let i = self.s.m.bin(c, Bin::LShr, x, shift);
  6212. let i = self.s.m.bin(c, Bin::And, i, mask);
  6213. args.push(self.s.m.select(c, culled, z, i));
  6214. }
  6215. let void = self.s.t.void;
  6216. self.s
  6217. .op(c, "emitIndices", Attr::NoUnwind, void, 169, &args);
  6218. self.end_guarded(at, &[]);
  6219. Ok(())
  6220. }
  6221. /// The per-vertex arbitrary row no mesh output entry names but one
  6222. /// (the 2020 compiler's zeroed entry).
  6223. fn unnamed_row(&self) -> Option<u8> {
  6224. let StageIo::Ms(ms) = &self.x.native.io else {
  6225. return None;
  6226. };
  6227. let named = |r: u32| {
  6228. ms.outputs
  6229. .iter()
  6230. .any(|o| o.param & 0x80 == 0 && o.usage != Usage::Other(0) && u32::from(o.row) == r)
  6231. };
  6232. let free: std::collections::BTreeSet<u32> = self
  6233. .s
  6234. .outputs
  6235. .iter()
  6236. .filter(|o| o.kind == 0)
  6237. .filter_map(|o| o.row)
  6238. .filter(|&r| !named(r))
  6239. .collect();
  6240. match free.into_iter().collect::<Vec<_>>()[..] {
  6241. [r] => u8::try_from(r).ok(),
  6242. _ => None,
  6243. }
  6244. }
  6245. fn exit(&mut self, b: usize) -> Result<(), Stop> {
  6246. let offset = self.x.p.blocks[b]
  6247. .insts
  6248. .last()
  6249. .map_or(self.x.p.blocks[b].offset, |i| i.machine.offset);
  6250. let term = match self.x.st.exits[b] {
  6251. LaneExit::Jump(t) if self.counters.contains_key(&t) && self.rpo[t] <= self.rpo[b] => {
  6252. let ok = self.count_iteration(t, pred::IULT);
  6253. let abort = self.abort_block();
  6254. Term::CondBr(ok, self.block[t].expect("reachable"), abort)
  6255. }
  6256. LaneExit::Jump(t) => {
  6257. self.enter_loop(b, t, self.cur);
  6258. Term::Br(self.block[t].expect("reachable"))
  6259. }
  6260. LaneExit::Branch {
  6261. when,
  6262. taken,
  6263. not_taken,
  6264. } => {
  6265. // A negated condition branches the other way round.
  6266. let (cond, taken, not_taken) = match self.x.st.bools.node(when) {
  6267. Some((atom, Bool::TRUE, Bool::FALSE)) => {
  6268. let a = self
  6269. .atom(atom, self.cur)
  6270. .map_err(|w| unsupported(offset, w))?;
  6271. (a, not_taken, taken)
  6272. }
  6273. _ => {
  6274. let c = self
  6275. .boolean(when, self.cur)
  6276. .map_err(|w| unsupported(offset, w))?;
  6277. (c, taken, not_taken)
  6278. }
  6279. };
  6280. // A back edge is taken only below the iteration limit.
  6281. let back =
  6282. |l: &Self, to: usize| l.counters.contains_key(&to) && l.rpo[to] <= l.rpo[b];
  6283. // (No `xor` of a compare: a loop exit testing one hung the
  6284. // AMD driver.)
  6285. let cond = if back(self, taken) {
  6286. let ok = self.count_iteration(taken, pred::IULT);
  6287. self.s.m.bin(self.cur, Bin::And, cond, ok)
  6288. } else if back(self, not_taken) {
  6289. let stop = self.count_iteration(not_taken, pred::IUGE);
  6290. self.s.m.bin(self.cur, Bin::Or, cond, stop)
  6291. } else {
  6292. cond
  6293. };
  6294. // Critical edges get a block of their own, so loops have
  6295. // dedicated exits and preheaders as DXC emits them.
  6296. let (t, f) = (self.edge(b, taken), self.edge(b, not_taken));
  6297. for (to, via) in [(taken, t), (not_taken, f)] {
  6298. if !back(self, to) {
  6299. // From an edge block, or from here.
  6300. let from = if Some(via) == self.block[to] {
  6301. self.cur
  6302. } else {
  6303. via
  6304. };
  6305. self.enter_loop(b, to, from);
  6306. }
  6307. }
  6308. Term::CondBr(cond, t, f)
  6309. }
  6310. LaneExit::End => {
  6311. if self.s.pixel && !self.exported[b] && !self.has_done_export(b) {
  6312. // A lane leaving without its final export was killed.
  6313. let t = self.s.m.bool(true);
  6314. self.s
  6315. .op(self.cur, "discard", Attr::NoUnwind, self.s.t.void, 82, &[t]);
  6316. }
  6317. Term::Ret
  6318. }
  6319. LaneExit::Indirect => return Err(unsupported(offset, "an indirect jump")),
  6320. };
  6321. let _ = Exit::End;
  6322. self.s.m.terminate(self.cur, term);
  6323. Ok(())
  6324. }
  6325. /// A forward edge into loop header `to` (from DXIL block `via`) starts
  6326. /// its count at 0.
  6327. fn enter_loop(&mut self, _from: usize, to: usize, via: usize) {
  6328. if let Some((_, incoming)) = self.counters.get_mut(&to) {
  6329. let z = self.s.m.i32(0);
  6330. incoming.push((z, via));
  6331. }
  6332. }
  6333. /// A back edge to header `to` (a back edge keeps its block, no
  6334. /// critical-edge block): the count goes up; the result compares it with
  6335. /// [`LOOP_LIMIT`] by `p` (below: go on; at or above: stop).
  6336. fn count_iteration(&mut self, to: usize, p: u8) -> V {
  6337. let c = self.cur;
  6338. let (phi, _) = self.counters[&to];
  6339. let one = self.s.m.i32(1);
  6340. let next = self.s.m.bin(c, Bin::Add, phi, one);
  6341. let limit = self.s.m.i32(super::loop_limit());
  6342. self.counters
  6343. .get_mut(&to)
  6344. .expect("header")
  6345. .1
  6346. .push((next, c));
  6347. self.s.m.cmp(c, p, next, limit)
  6348. }
  6349. /// The block a lane stopped by [`LOOP_LIMIT`] leaves through.
  6350. fn abort_block(&mut self) -> usize {
  6351. if let Some(a) = self.abort {
  6352. return a;
  6353. }
  6354. let a = self.s.m.new_block();
  6355. if self.s.pixel {
  6356. let t = self.s.m.bool(true);
  6357. self.s
  6358. .op(a, "discard", Attr::NoUnwind, self.s.t.void, 82, &[t]);
  6359. }
  6360. self.s.m.terminate(a, Term::Ret);
  6361. self.abort = Some(a);
  6362. a
  6363. }
  6364. /// The DXIL block a branch from IR block `from` to `to` goes to.
  6365. fn edge(&mut self, from: usize, to: usize) -> usize {
  6366. let target = self.block[to].expect("reachable");
  6367. let preds = self.x.p.blocks[to]
  6368. .preds
  6369. .iter()
  6370. .filter(|&&q| self.block[q].is_some())
  6371. .count();
  6372. // Back edges stay as they are: the exiting block is the latch.
  6373. if preds < 2 || self.rpo[to] <= self.rpo[from] {
  6374. return target;
  6375. }
  6376. let e = self.s.m.new_block();
  6377. self.s.m.terminate(e, Term::Br(target));
  6378. self.edges.insert((from, to), e);
  6379. e
  6380. }
  6381. fn fill_phis(&mut self) -> Result<(), Stop> {
  6382. let p = self.x.p;
  6383. for (v, b, i) in std::mem::take(&mut self.data_phis) {
  6384. let phi = &p.blocks[b].phis[i];
  6385. let bit = phi.reg == Reg::Scc;
  6386. let mut incoming = Vec::new();
  6387. for (n, &q) in p.blocks[b].preds.iter().enumerate() {
  6388. let Some(qb) = self.tail[q] else { continue };
  6389. let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb);
  6390. let arg = phi.args[n];
  6391. let x = match (self.vals.get(&arg).copied(), bit) {
  6392. (Some(Val::I32(x)), false) | (Some(Val::Bit(x)), true) => x,
  6393. (Some(Val::Bit(_)), false) if self.read_phis.contains(&phi.value) => {
  6394. return Err(Stop::Retry(phi.value, "an SCC joined with SGPR values"));
  6395. }
  6396. (Some(Val::Missing(why)), _) if self.read_phis.contains(&phi.value) => {
  6397. return Err(Stop::Retry(phi.value, why));
  6398. }
  6399. _ if self.read_phis.contains(&phi.value) => {
  6400. return Err(Stop::Retry(phi.value, "a join of mismatched values"));
  6401. }
  6402. _ if bit => self.s.m.bool(false),
  6403. _ => self.s.m.i32(0),
  6404. };
  6405. incoming.push((x, qb));
  6406. }
  6407. self.s.m.set_phi(v, incoming);
  6408. }
  6409. for (phi, incoming) in std::mem::take(&mut self.counters).into_values() {
  6410. self.s.m.set_phi(phi, incoming);
  6411. }
  6412. while let Some((v, b, i)) = self.pending_masks.pop() {
  6413. let phi = &p.blocks[b].phis[i];
  6414. let offset = p.blocks[b].offset;
  6415. let mut incoming = Vec::new();
  6416. for (n, &q) in p.blocks[b].preds.iter().enumerate() {
  6417. let Some(qb) = self.tail[q] else { continue };
  6418. let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb);
  6419. let m =
  6420. *self.x.st.masks.get(&phi.args[n]).ok_or_else(|| {
  6421. unsupported(offset, "a lane-mask join of an untracked mask")
  6422. })?;
  6423. let x = self.boolean(m, qb).map_err(|w| unsupported(offset, w))?;
  6424. incoming.push((x, qb));
  6425. }
  6426. self.s.m.set_phi(v, incoming);
  6427. }
  6428. Ok(())
  6429. }
  6430. }
  6431. #[cfg(test)]
  6432. mod tests {
  6433. use super::{Numeric, Parts, buffer_format, lower};
  6434. use crate::native::{ComputeIo, HwStage, NativeProgram, StageIo};
  6435. use crate::{io, ir, resource, structure};
  6436. const S_ENDPGM: u32 = 0xBF81_0000;
  6437. /// Whether a synthetic compute program translates with these input registers.
  6438. fn lowers(words: &[u32], rsrc2: u32) -> Result<(), crate::ShaderError> {
  6439. let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
  6440. let native = NativeProgram {
  6441. stage: HwStage::Cs,
  6442. wave64: false,
  6443. vgprs: 256,
  6444. layout: vec![],
  6445. used: vec![],
  6446. io: StageIo::Cs(ComputeIo {
  6447. rsrc2,
  6448. threads: [1, 1, 1],
  6449. }),
  6450. code,
  6451. };
  6452. let p = ir::build(&native.code, false, 256).unwrap();
  6453. let res = resource::track(&p, &native.layout, native.stage).unwrap();
  6454. let io = io::raise(&p, &native).unwrap();
  6455. let st = structure::structure(&p).unwrap();
  6456. lower(&Parts {
  6457. native: &native,
  6458. p: &p,
  6459. st: &st,
  6460. io: &io,
  6461. res: &res,
  6462. inputs: vec![],
  6463. outputs: vec![],
  6464. prims: vec![],
  6465. mesh_stride: 0,
  6466. })
  6467. .map(|_| ())
  6468. }
  6469. #[test]
  6470. fn a_scalar_carry_chain_reaches_the_select() {
  6471. // The high dword of a 64-bit add or subtract, then a select on the
  6472. // carry (borrow) the high half leaves in SCC, and a branch on it
  6473. // (only code with an effect needs its operands).
  6474. let add = [
  6475. 0xBE80_03C1, // s_mov_b32 s0, -1
  6476. 0xBE81_0380, // s_mov_b32 s1, 0
  6477. 0x8000_8100, // s_add_u32 s0, s0, 1
  6478. 0x8201_8001, // s_addc_u32 s1, s1, 0
  6479. 0x8502_0001, // s_cselect_b32 s2, s1, s0
  6480. 0xBF07_8002, // s_cmp_lg_u32 s2, 0
  6481. 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm
  6482. 0xBE83_0380, // s_mov_b32 s3, 0
  6483. S_ENDPGM,
  6484. ];
  6485. let sub = [
  6486. 0xBE80_0380, // s_mov_b32 s0, 0
  6487. 0xBE81_0380, // s_mov_b32 s1, 0
  6488. 0x8080_8100, // s_sub_u32 s0, s0, 1
  6489. 0x8281_8001, // s_subb_u32 s1, s1, 0
  6490. 0x8502_0001, // s_cselect_b32 s2, s1, s0
  6491. 0xBF07_8002, // s_cmp_lg_u32 s2, 0
  6492. 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm
  6493. 0xBE83_0380, // s_mov_b32 s3, 0
  6494. S_ENDPGM,
  6495. ];
  6496. for words in [add, sub] {
  6497. lowers(&words, 0).unwrap();
  6498. }
  6499. }
  6500. #[test]
  6501. fn a_missing_value_stays_missing_through_two_live_joins() {
  6502. let mut words = [
  6503. 0xF490_0180,
  6504. 0, // s_memtime s[6:7]
  6505. 0xBF06_8000, // s_cmp_eq_u32 s0, 0 (s0 = group id X)
  6506. 0xBF85_0001, // skip the first overwrite
  6507. 0xBE86_0380, // s_mov_b32 s6, 0
  6508. 0xBF06_8101, // s_cmp_eq_u32 s1, 1 (s1 = group id Y)
  6509. 0xBF85_0001, // skip the second overwrite
  6510. 0xBE86_0381, // s_mov_b32 s6, 1
  6511. 0xBF07_8006, // s_cmp_lg_u32 s6, 0
  6512. 0xBF85_0001, // use the result to branch
  6513. 0xBE83_0380,
  6514. S_ENDPGM,
  6515. ];
  6516. let group_ids_xy = 3 << 7;
  6517. // Compare to a direct read so future timestamp support works in both cases.
  6518. let refusal = |code: &[u32]| match lowers(code, group_ids_xy) {
  6519. Ok(()) => None,
  6520. Err(crate::ShaderError::Unsupported { what, .. }) => Some(what),
  6521. Err(error) => panic!("{error}"),
  6522. };
  6523. let direct = [&words[..2], &words[8..]].concat();
  6524. assert_eq!(refusal(&words), refusal(&direct));
  6525. words[8] = 0xBF07_8000; // read the group id instead; the timestamp is dead
  6526. lowers(&words, group_ids_xy).expect("dead timestamp");
  6527. }
  6528. #[test]
  6529. fn buffer_formats_by_number() {
  6530. // The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM,
  6531. // 2_10_10_10_UNORM, 16_FLOAT, 32_32_32_32_FLOAT.
  6532. assert_eq!(buffer_format(56), Some((&[8, 8, 8, 8][..], Numeric::Unorm)));
  6533. assert_eq!(buffer_format(24), Some((&[16, 16][..], Numeric::Snorm)));
  6534. assert_eq!(
  6535. buffer_format(50),
  6536. Some((&[10, 10, 10, 2][..], Numeric::Unorm))
  6537. );
  6538. assert_eq!(buffer_format(13), Some((&[16][..], Numeric::Float)));
  6539. assert_eq!(
  6540. buffer_format(77),
  6541. Some((&[32, 32, 32, 32][..], Numeric::Float))
  6542. );
  6543. // Invalid, a packed float, past the table.
  6544. assert_eq!(buffer_format(0), None);
  6545. assert_eq!(buffer_format(36), None);
  6546. assert_eq!(buffer_format(78), None);
  6547. }
  6548. }