lower.rs 269 KB

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