lower.rs 283 KB

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