lower.rs 544 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844
  1. //! IR to DXIL, one machine instruction at a time (decision 0003).
  2. //!
  3. //! Every register dword is an `i32` (SCC an `i1`); float operations bitcast
  4. //! their operands. Lane masks exist only as the per-lane booleans of
  5. //! structurisation; branches and guards are built from them. A value the
  6. //! emitter cannot express is `Missing` with a reason, and only fails the
  7. //! program when something with an effect (an export, a branch) needs it.
  8. use std::collections::{BTreeMap, HashMap, HashSet};
  9. use super::UserData;
  10. use super::bitcode::{Attr, Bin, Cast, Rmw, Tag, Term, V, pred};
  11. use super::container::SigElement;
  12. use super::shader::{Shader, flags};
  13. use crate::ShaderError;
  14. use crate::gfx10::{Dpp, Fields, NULL, Operand};
  15. use crate::io::{Barycentric, Export, Input, Interp, Io, Target};
  16. use crate::ir::{EXEC, Exit, Inst, Program, Reg, Value};
  17. use crate::native::{HwStage, NativeProgram, ResourceType, RootType, StageIo, Usage, UsedResource};
  18. use crate::resource::{Address, CODE, MEMORY, Resources, Role, Site, Source};
  19. use crate::structure::{Atom, Bool, LaneExit, Structured};
  20. /// The ray-tracing node test (`image_bvh_intersect_ray`), a child module so
  21. /// it shares the emitter's state.
  22. #[path = "intersect.rs"]
  23. pub(super) mod intersect;
  24. type Why = &'static str;
  25. /// How an interpolation evaluates an input channel.
  26. #[derive(Debug, Clone, Copy)]
  27. enum Eval {
  28. /// Loaded with this DXIL interpolation mode (1: constant, P0).
  29. Mode(u8),
  30. /// From the vertex values of a constant element: P0 when `p0`, plus
  31. /// i (P1 - P0), plus j (P2 - P0), weights as floats.
  32. Weights {
  33. p0: bool,
  34. i: Option<V>,
  35. j: Option<V>,
  36. },
  37. }
  38. #[derive(Debug, Clone, Copy)]
  39. enum Val {
  40. I32(V),
  41. Bit(V),
  42. Missing(Why),
  43. }
  44. pub(crate) struct Lowered {
  45. pub dxil: Vec<u8>,
  46. /// Bit n: immediate sampler n is a comparison sampler.
  47. pub cmp_samplers: u64,
  48. pub root_cbvs: Vec<u8>,
  49. pub root_srvs: Vec<u8>,
  50. pub root_uavs: Vec<u8>,
  51. pub user_data: Vec<UserData>,
  52. pub samplers: Vec<[u32; 4]>,
  53. /// The wave size the shader requires of the host, if any.
  54. pub wave_size: Option<u32>,
  55. /// Heap handles made with a non-uniform index.
  56. #[cfg(test)]
  57. pub nonuniform_handles: u32,
  58. /// Whether the program uses wave operations.
  59. #[cfg(test)]
  60. pub wave_ops: bool,
  61. }
  62. pub(crate) struct Parts<'a> {
  63. pub native: &'a NativeProgram,
  64. pub p: &'a Program,
  65. pub st: &'a Structured,
  66. pub io: &'a Io,
  67. pub res: &'a Resources,
  68. pub inputs: Vec<SigElement>,
  69. pub outputs: Vec<SigElement>,
  70. pub prims: Vec<SigElement>,
  71. /// Mesh: what the group id arrives multiplied by.
  72. pub mesh_stride: u32,
  73. }
  74. enum Stop {
  75. /// A phi whose incoming value has no DXIL form was read: redo with it missing.
  76. Retry(Value, Why),
  77. Fail(ShaderError),
  78. }
  79. pub(crate) fn lower(parts: &Parts) -> Result<Lowered, ShaderError> {
  80. let mut bad = HashMap::new();
  81. loop {
  82. match Lower::new(parts, &bad).run() {
  83. Ok(l) => return Ok(l),
  84. Err(Stop::Retry(v, why)) => {
  85. if bad.insert(v, why).is_some() {
  86. return Err(ShaderError::Unsupported {
  87. offset: 0,
  88. what: "a phi that does not settle",
  89. });
  90. }
  91. }
  92. Err(Stop::Fail(e)) => return Err(e),
  93. }
  94. }
  95. }
  96. const TWO_PI: f32 = std::f32::consts::TAU;
  97. /// `s_sendmsg` id of a mesh or NGG stage's output allocation request.
  98. const GS_ALLOC_REQ: u16 = 9;
  99. /// `s_sendmsg` id that ends a pixel wave's ordered section.
  100. const ORDERED_PS_DONE: u16 = 7;
  101. /// Hardware register (of `s_setreg_b32`) a pixel wave names its packer in
  102. /// before it waits for the waves it overlaps.
  103. const POPS_PACKER: u16 = 25;
  104. /// The operand `src_pops_exiting_wave_id`.
  105. const POPS_EXITING: u8 = 239;
  106. /// The instructions inside a pixel program's ordered section
  107. /// (primitive-ordered pixel shading, which the console compiler makes of
  108. /// rasterizer ordered views): from the write of `POPS_PACKER`, along every
  109. /// path, to the message that ends the section or the program's end. The
  110. /// console waits there until the waves holding earlier primitives' samples
  111. /// of the same pixels have left their sections; a host's rasterizer ordered
  112. /// views wait by themselves, at their first access. Empty for a program
  113. /// without such a section.
  114. fn ordered_section(p: &Program) -> HashSet<Site> {
  115. let starts = |i: &Inst| {
  116. i.name() == "s_setreg_b32"
  117. && matches!(i.fields, Fields::Sop { imm: Some(imm), .. } if imm & 0x3F == POPS_PACKER)
  118. };
  119. let ends = |i: &Inst| {
  120. i.name() == "s_sendmsg"
  121. && matches!(i.fields, Fields::Sopp { imm } if imm & 0xF == ORDERED_PS_DONE)
  122. };
  123. let mut section = HashSet::new();
  124. let mut entered = vec![false; p.blocks.len()];
  125. let mut work: Vec<Site> = p
  126. .blocks
  127. .iter()
  128. .enumerate()
  129. .flat_map(|(b, block)| {
  130. (0..block.insts.len())
  131. .filter(|&i| starts(&block.insts[i]))
  132. .map(move |i| (b, i))
  133. })
  134. .collect();
  135. while let Some((b, from)) = work.pop() {
  136. let block = &p.blocks[b];
  137. let mut done = false;
  138. for i in from..block.insts.len() {
  139. if ends(&block.insts[i]) {
  140. done = true;
  141. break;
  142. }
  143. section.insert((b, i));
  144. }
  145. if done {
  146. continue;
  147. }
  148. for (t, next) in p.blocks.iter().enumerate() {
  149. if next.preds.contains(&b) && !std::mem::replace(&mut entered[t], true) {
  150. work.push((t, 0));
  151. }
  152. }
  153. }
  154. section
  155. }
  156. /// The f16 bits of inline float constant `c` (240..=248: 0.5, -0.5, 1.0,
  157. /// -1.0, 2.0, -2.0, 4.0, -4.0, 1/(2 pi)).
  158. fn inline_f16(c: u8) -> u32 {
  159. [
  160. 0x3800, 0xB800, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x4400, 0xC400, 0x3118,
  161. ][usize::from(c - 240)]
  162. }
  163. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  164. enum Numeric {
  165. Unorm,
  166. Snorm,
  167. Uscaled,
  168. Sscaled,
  169. Uint,
  170. Sint,
  171. Float,
  172. }
  173. /// A GFX10 buffer format (the unified format of typed buffer loads): the
  174. /// channel widths from the lowest bits up, and how the channels convert.
  175. /// Formats are numbered in families (`8`, `16`, `8_8`, ...: AMD names
  176. /// list channels from the highest bits), each with its numeric formats in
  177. /// the order unorm, snorm, uscaled, sscaled, uint, sint, float.
  178. fn buffer_format(format: u8) -> Option<(&'static [u32], Numeric)> {
  179. use Numeric::*;
  180. const NORM: &[Numeric] = &[Unorm, Snorm, Uscaled, Sscaled, Uint, Sint];
  181. const ALL: &[Numeric] = &[Unorm, Snorm, Uscaled, Sscaled, Uint, Sint, Float];
  182. const WIDE: &[Numeric] = &[Uint, Sint, Float];
  183. // Numbers and order from LLVM's `UfmtGFX10` (`SIDefines.h`); the GFX10
  184. // buffer formats have no 5_9_9_9. Channel order from Mesa
  185. // (`ac_formats.c`): R11G11B10_FLOAT is 10_11_11, and 10_10_10_2 has
  186. // its 2-bit channel in the lowest bits.
  187. const FAMILIES: [(&[u32], &[Numeric]); 14] = [
  188. (&[8], NORM),
  189. (&[16], ALL),
  190. (&[8, 8], NORM),
  191. (&[32], WIDE),
  192. (&[16, 16], ALL),
  193. (&[11, 11, 10], ALL), // 10_11_11
  194. (&[10, 11, 11], ALL), // 11_11_10
  195. (&[2, 10, 10, 10], NORM), // 10_10_10_2
  196. (&[10, 10, 10, 2], NORM), // 2_10_10_10
  197. (&[8, 8, 8, 8], NORM),
  198. (&[32, 32], WIDE),
  199. (&[16, 16, 16, 16], ALL),
  200. (&[32, 32, 32], WIDE),
  201. (&[32, 32, 32, 32], WIDE),
  202. ];
  203. let mut n = usize::from(format.checked_sub(1)?);
  204. for (bits, numerics) in FAMILIES {
  205. if n < numerics.len() {
  206. return Some((bits, numerics[n]));
  207. }
  208. n -= numerics.len();
  209. }
  210. None
  211. }
  212. /// How far a float channel of `width` bits (16, or the unsigned 11- and
  213. /// 10-bit floats of the packed formats) shifts up to be a half:
  214. /// the small floats are a half's exponent (5 bits, biased 15) and the top
  215. /// of its mantissa, without the sign, so `legacyF16ToF32` widens them
  216. /// exactly, denormals, infinities and NaNs included.
  217. fn half_shift(width: u32) -> u32 {
  218. debug_assert!(matches!(width, 10 | 11 | 16), "{width}-bit float");
  219. if width == 16 { 0 } else { 15 - width }
  220. }
  221. struct Lower<'a> {
  222. s: Shader,
  223. x: &'a Parts<'a>,
  224. bad: &'a HashMap<Value, Why>,
  225. lane_fail: HashMap<Value, Why>,
  226. vals: HashMap<Value, Val>,
  227. floats: HashMap<Value, V>,
  228. /// DXIL block per IR block (unreachable: none).
  229. block: Vec<Option<usize>>,
  230. cur: usize,
  231. bools: HashMap<(usize, Bool), V>,
  232. lane_bits: HashMap<Value, V>,
  233. /// IR phi location by value.
  234. phi_at: HashMap<Value, (usize, usize)>,
  235. /// Descriptor dwords with no host value (addresses, formats, all of a constant
  236. /// buffer's): no program reads them as numbers ([`Self::dead`]).
  237. stale: HashSet<Value>,
  238. /// See [`ordered_section`] (pixel programs).
  239. ordered: HashSet<Site>,
  240. /// Raw UAV buffers (see [`Lower::entry`]) the program loads from past its
  241. /// wave's cache (GLC): other groups write what it waits for. On the host
  242. /// they are globally coherent; a load in a loop that only waits would
  243. /// be made once otherwise.
  244. coherent: HashSet<(usize, u32)>,
  245. mask_phis: HashMap<Value, V>,
  246. pending_masks: Vec<(V, usize, usize)>,
  247. data_phis: Vec<(V, usize, usize)>,
  248. read_phis: HashSet<Value>,
  249. params: HashMap<Value, (usize, u32)>,
  250. user_data: Option<V>,
  251. user_reads: BTreeMap<u32, UserData>,
  252. samplers: Vec<[u32; 4]>,
  253. descriptors: HashMap<(Site, bool), &'a Source>,
  254. scalar: HashMap<Site, Address>,
  255. exports: HashMap<Site, &'a Export>,
  256. interps: HashMap<Site, &'a Interp>,
  257. handles: HashMap<(usize, Site, u8, bool, (u32, u32)), V>,
  258. /// Element strides read from the host's table by heap slot
  259. /// ([`super::shader::SLOT_STRIDES`]), by block and descriptor load.
  260. strides: HashMap<(usize, Site, u8), V>,
  261. /// Blocks splitting the edge from one IR block to another.
  262. edges: HashMap<(usize, usize), usize>,
  263. /// Per IR block: a `done` export is behind every lane entering it.
  264. exported: Vec<bool>,
  265. /// Reverse-postorder index per IR block.
  266. rpo: Vec<usize>,
  267. /// DXIL block each IR block ends in (guarded stores split blocks).
  268. tail: Vec<Option<usize>>,
  269. /// The program writes UAVs: barriers fence them too.
  270. writes_uavs: bool,
  271. /// src0 of the current instruction as DPP fetched it.
  272. src0: Option<V>,
  273. /// Compute code that reads other lanes: thread ids follow the host
  274. /// lanes, so lane n is console lane n.
  275. console_lanes: bool,
  276. /// Mesh: the thread index in the group (made in the entry block).
  277. flat: Option<V>,
  278. /// Mesh: IR blocks whose `s_barrier` is left out.
  279. no_barrier: HashSet<usize>,
  280. /// IR blocks whose `s_barrier` not every lane is sure to reach (a lane
  281. /// branch lies between the entry and the block, or the program has a
  282. /// loop a lane can be cut out of): the barrier there keeps its fences
  283. /// and does not wait for the group ([`super::group_sync`]).
  284. fence_only: HashSet<usize>,
  285. /// A group barrier before every LDS access (a console wave run as two host waves).
  286. split_lds: bool,
  287. /// With `split_lds`, LDS accesses in lane branches: per IR block whether every lane runs
  288. /// it, and whether the host waves meet at its start and before its exit ([`lds_meetings`]).
  289. lds_meet: Option<(Vec<bool>, Vec<(bool, bool)>)>,
  290. /// A console wave64 program run as two host waves of 32 that exchange through LDS: the first
  291. /// of two exchange dwords, whether the group has no upper half (32 threads or fewer), and per
  292. /// IR block whether every lane runs it (exchanges need both halves there).
  293. exchange: Option<(u32, bool, Vec<bool>)>,
  294. /// With `exchange`: nothing is exchanged, each host wave acts as a wave
  295. /// of its own ([`with_local_waves`]).
  296. local: bool,
  297. /// The instruction being lowered may read a lane mask as a number under
  298. /// `local` (a bit count, a first set bit, `v_mbcnt`).
  299. local_ok: bool,
  300. /// With `local`: every mask read and lane read is taken per host wave
  301. /// ([`with_local_waves_any`]).
  302. local_any: bool,
  303. /// With `exchange`: VGPR values every lane holds alike ([`lane_uniform`]); a first-lane
  304. /// read of one needs nothing from the other host wave.
  305. uniform: HashSet<Value>,
  306. /// With `exchange`: the wave ORs that only steer a loop over each lane's own bits, which
  307. /// a host wave takes over its own lanes wherever they stand ([`super::own_bits`]).
  308. own_bits: super::own_bits::OwnBits,
  309. /// The console lane (0..63) of this thread, made in the entry block.
  310. clane: Option<V>,
  311. /// The first exchange dword of this thread's console wave ([`Self::exchange_pair`]).
  312. pair: Option<V>,
  313. /// A console wave64 program in host waves of 32: the LDS dword counting the console threads
  314. /// handed to host waves (`wave_base`), and the base made in the entry block.
  315. halves: Option<u32>,
  316. wave_base: Option<V>,
  317. /// Vertex and mesh outputs holding 16-bit values: row, whether two per
  318. /// dword, and the row packed after it.
  319. half_outputs: HashMap<u8, (bool, Option<u8>)>,
  320. /// How lane masks become data.
  321. mask_data: MaskData,
  322. /// The instruction being lowered may read lane masks as data.
  323. mask_ok: bool,
  324. /// Ballots of masks read as data, by low dword: (low, high).
  325. ballots: HashMap<Value, (V, V)>,
  326. /// Masks whose ballot is being built: a mask whose lane bit needs its
  327. /// own value as a number (an opaque mask keyed by a dword it shares
  328. /// with another) would otherwise recurse until the stack overflows.
  329. balloting: HashSet<Value>,
  330. /// Block writing each value.
  331. def_block: HashMap<Value, usize>,
  332. /// IR block being lowered.
  333. cur_ir: usize,
  334. /// Whole-wave sections by block and start index.
  335. sections: HashMap<usize, HashMap<usize, super::wave::Section>>,
  336. /// Values written in a section that code outside it reads.
  337. section_out: HashSet<Value>,
  338. /// The program's constant table (the code from the first byte read
  339. /// through `s_getpc_b64` on): global, first byte, dwords.
  340. code_table: Option<(V, u32, u32)>,
  341. /// Loop headers' iteration counters (see [`LOOP_LIMIT`]): the phi by
  342. /// IR block, and its incoming (value, DXIL block) pairs.
  343. counters: HashMap<usize, (V, Vec<(V, usize)>)>,
  344. /// The block a loop stopped by [`LOOP_LIMIT`] leaves the program from.
  345. abort: Option<usize>,
  346. }
  347. /// Iterations after which a loop is left (per entry into it), unless
  348. /// [`super::loop_limit`] says otherwise. The console runs a loop as long as
  349. /// its data says; data the host has not mirrored yet (a null view reads
  350. /// zeros) can make that four billion iterations, which hangs the host GPU
  351. /// until the driver resets it. A lane that reaches the limit leaves the
  352. /// program as killed (a pixel discards).
  353. // shortcut: a genuine loop of more iterations than this is cut short too.
  354. pub(super) const LOOP_LIMIT: u32 = 1 << 20;
  355. /// Lane masks read as numbers (`s_bcnt1`, `s_ff1`, `v_mbcnt`, scalar
  356. /// compares, bit tests) are ballots of the lanes' booleans, taken where the
  357. /// mask is written: structurisation's `active` masks hold only lanes that
  358. /// reach that block, so the ballot misses none.
  359. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  360. enum MaskData {
  361. /// Compute: host lane n is console lane n (the program declares the
  362. /// console's wave size), so ballots are the console's masks bit for bit
  363. /// and any use is exact.
  364. Console,
  365. /// Pixel and vertex programs: ballots over the host's wave, whatever its
  366. /// size. Only uses that mean the same on any wave are allowed: counts,
  367. /// the first lane, the count below a lane, equality (the HLSL wave
  368. /// operations the console compiler expands). Lane numbers stay host
  369. /// lanes throughout (`v_mbcnt`, `v_readlane` at a computed lane).
  370. Host,
  371. /// Mesh programs: their lanes and waves (LDS per console wave) are the
  372. /// console's but no host wave size can be declared.
  373. None,
  374. }
  375. /// What a value holding a lane mask read as a number stops with.
  376. pub(super) const LANE_MASK: Why = "a lane mask read as data";
  377. /// A mask with lanes outside EXEC where it is written, read as a number where the lanes that
  378. /// run that block are not all of the wave.
  379. pub(super) const MASK_ELSEWHERE: Why = "a lane mask holding lanes elsewhere read as data";
  380. /// Instructions that read a lane mask (not EXEC implicitly, not a lane's
  381. /// bit) as a number.
  382. /// Per IR block: every lane of the wave that started the program runs it – no per-lane branch
  383. /// separates it from the entry (it lies in no lane branch's region: the blocks reachable from
  384. /// the branch that do not post-dominate it). None with an indirect exit (not followed).
  385. fn all_lane_blocks(st: &Structured) -> Option<Vec<bool>> {
  386. let n = st.exits.len();
  387. let mut all = vec![true; n];
  388. for (_, region) in lane_regions(st)? {
  389. for b in (0..n).filter(|&b| region[b]) {
  390. all[b] = false;
  391. }
  392. }
  393. Some(all)
  394. }
  395. /// Every per-lane branch (by its block) with its region: the blocks reachable from it that do
  396. /// not post-dominate it, which only some lanes run. Not the branches the wave takes together
  397. /// ([`Structured::wide`]), nor those on scalar conditions. None with an indirect exit.
  398. fn lane_regions(st: &Structured) -> Option<Vec<(usize, Vec<bool>)>> {
  399. let n = st.exits.len();
  400. let mut succ: Vec<Vec<usize>> = vec![Vec::new(); n];
  401. for (b, e) in st.exits.iter().enumerate() {
  402. match *e {
  403. LaneExit::Jump(t) => succ[b].push(t),
  404. LaneExit::Branch { taken, not_taken, .. } => {
  405. succ[b].push(taken);
  406. succ[b].push(not_taken);
  407. }
  408. LaneExit::End => {}
  409. LaneExit::Indirect => return None,
  410. }
  411. }
  412. // post-dominators (bitsets; a virtual exit after every End)
  413. let words = n.div_ceil(64);
  414. let full = vec![u64::MAX; words];
  415. let mut pdom: Vec<Vec<u64>> = (0..n).map(|b| if succ[b].is_empty() { let mut v = vec![0; words]; v[b / 64] |= 1 << (b % 64); v } else { full.clone() }).collect();
  416. let mut changed = true;
  417. while changed {
  418. changed = false;
  419. for b in (0..n).rev() {
  420. if succ[b].is_empty() {
  421. continue;
  422. }
  423. let mut v = full.clone();
  424. for &t in &succ[b] {
  425. for w in 0..words {
  426. v[w] &= pdom[t][w];
  427. }
  428. }
  429. v[b / 64] |= 1 << (b % 64);
  430. if v != pdom[b] {
  431. pdom[b] = v;
  432. changed = true;
  433. }
  434. }
  435. }
  436. let mut regions = Vec::new();
  437. for (d, e) in st.exits.iter().enumerate() {
  438. let LaneExit::Branch { when, .. } = *e else { continue };
  439. if st.wide.contains(&d) || st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_))) {
  440. continue; // a wave-wide or uniform branch: all lanes go the same way
  441. }
  442. // blocks reachable from the lane branch that do not post-dominate it
  443. let mut seen = vec![false; n];
  444. let mut stack: Vec<usize> = succ[d].clone();
  445. while let Some(b) = stack.pop() {
  446. if seen[b] || pdom[d][b / 64] >> (b % 64) & 1 == 1 {
  447. continue;
  448. }
  449. seen[b] = true;
  450. stack.extend(succ[b].iter().copied());
  451. }
  452. regions.push((d, seen));
  453. }
  454. Some(regions)
  455. }
  456. /// The per-lane branches (by block) whose regions hold a block of `needs` (blocks where two
  457. /// host waves must meet, [`take_needs`]): the ones to take wave-wide
  458. /// ([`crate::structure::structure_wide`]) so that every lane runs those blocks. None if one
  459. /// of them is a branch whose wave-wide meaning is not known ([`Structured::wave_any`]).
  460. pub(super) fn branches_around(st: &Structured, needs: &[usize]) -> Option<Vec<usize>> {
  461. let mut out = Vec::new();
  462. for (d, region) in lane_regions(st)? {
  463. if needs.iter().any(|&b| region.get(b).copied().unwrap_or(false)) {
  464. st.wave_any.get(d).copied().flatten()?;
  465. out.push(d);
  466. }
  467. }
  468. Some(out)
  469. }
  470. /// Whether a refusal is of code that needs every lane of the wave where it stands (two host
  471. /// waves meeting there), which the other forms of the program may give it.
  472. pub(super) fn needs_every_lane(what: &str) -> bool {
  473. what.ends_with("where not every lane runs") || what == MASK_ELSEWHERE
  474. }
  475. /// The blocks where the last lowering on this thread wanted every lane and did not have it
  476. /// (its "... where not every lane runs" refusals), which it forgets.
  477. pub(super) fn take_needs() -> Vec<usize> {
  478. NEEDS.take()
  479. }
  480. fn need(block: usize) {
  481. NEEDS.with_borrow_mut(|n| {
  482. if !n.contains(&block) {
  483. n.push(block);
  484. }
  485. });
  486. }
  487. /// VGPR values that are the same in every lane holding them (`all` is [`all_lane_blocks`]):
  488. /// written by an instruction every arriving lane runs (no guard), lane by lane, from scalars,
  489. /// constants and such values; or loaded from an address made of them. The compiler keeps
  490. /// wave-uniform data in VGPRs and fetches it with `v_readfirstlane`.
  491. /// shortcut: a value joined by a phi counts only where every predecessor is a block all lanes
  492. /// run (no lane branch can have split the arriving lanes); loop-carried values never do.
  493. fn lane_uniform(p: &Program, st: &Structured, all: &[bool]) -> HashSet<Value> {
  494. let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v);
  495. let mut same: HashSet<Value> = HashSet::new();
  496. for b in crate::ir::reverse_postorder(&p.blocks) {
  497. let block = &p.blocks[b];
  498. let whole = block.preds.iter().all(|&q| all.get(q).copied().unwrap_or(false));
  499. for phi in &block.phis {
  500. if matches!(phi.reg, Reg::V(_)) && whole && phi.args.iter().all(|a| same.contains(a)) {
  501. same.insert(phi.value);
  502. }
  503. }
  504. for (i, inst) in block.insts.iter().enumerate() {
  505. let name = inst.name();
  506. let ops: Vec<Operand> = match &inst.fields {
  507. Fields::Valu(v)
  508. if v.dpp.is_none()
  509. && v.sdwa.is_none()
  510. && !name.starts_with("v_mbcnt")
  511. && !name.starts_with("v_cmpx")
  512. && !name.contains("lane") =>
  513. {
  514. v.src.clone()
  515. }
  516. _ => continue,
  517. };
  518. if st.guards[b][i].is_some() {
  519. continue; // lanes outside EXEC keep another value
  520. }
  521. let alike = ops.iter().all(|op| match *op {
  522. Operand::Vector { reg, .. } => {
  523. // every dword of the operand the instruction reads from that register on
  524. let read: Vec<Value> =
  525. inst.reads.iter().filter(|r| matches!(r.0, Reg::V(x) if x >= reg)).map(|r| r.1).collect();
  526. !read.is_empty() && read.iter().all(|x| same.contains(x))
  527. }
  528. // a scalar is one value; a lane mask is not, unless a compare of such values made it
  529. Operand::Scalar { code, .. } if code != NULL => {
  530. inst.read(Reg::S(code)).is_none_or(|x| !is_mask(x) || same.contains(&x))
  531. }
  532. _ => true,
  533. });
  534. if alike {
  535. same.extend(inst.writes.iter().filter(|w| w.0 != Reg::Scc).map(|w| w.1));
  536. }
  537. }
  538. }
  539. same
  540. }
  541. /// What a register value holds, for [`wave_local`].
  542. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  543. enum Wave {
  544. /// Nothing that depends on how the threads are divided into waves.
  545. Plain,
  546. /// The number of the wave's first lane in a mask (`s_ff1`).
  547. First,
  548. /// A reduction over the wave's lanes: a count, a sum, a minimum...
  549. Total(super::wave::Op),
  550. /// A count or sum over the lanes below this one.
  551. Prefix,
  552. /// Derived from what a first-lane atomic returned: the slots the wave reserved.
  553. Base,
  554. /// A mix the idiom does not make.
  555. Mixed,
  556. }
  557. /// Whether a console wave64 program may run with each host wave as a wave of its own
  558. /// ([`with_local_waves`]): its wave-wide values are used only as the allocation idiom uses
  559. /// them, which does not care how the threads are divided into waves. A first-lane number only
  560. /// picks the first lane; a count or sum only goes into that lane's atomic on a shared counter;
  561. /// a prefix only goes onto the base that atomic returned; the first lane does nothing else.
  562. /// Anything else done with them takes one wave to be the whole thread group (a tile's result,
  563. /// say) and is refused, with the offset and what was found.
  564. /// Lane masks read as numbers by other instructions and lane reads outside whole-wave sections
  565. /// are stopped by the lowering itself.
  566. // shortcut: `v_readfirstlane` of a value that differs between lanes is taken as it is (this
  567. // host wave's first lane), and a guarded write of a plain value over a wave-dependent one is
  568. // the only mix of old and new lanes that is looked at.
  569. pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'static str)> {
  570. use super::wave::{Op, Shape};
  571. const FIRST: Why = "a wave's first-lane number used as data";
  572. const TOTAL: Why = "a count or sum over the wave used as data";
  573. const PREFIX: Why = "a count or sum over the lanes below used without a reserved base";
  574. const MIXED: Why = "a value that depends on the wave on some paths only";
  575. const EFFECT: Why = "a write by the wave's first lane other than its reservation";
  576. fn of(kind: &HashMap<Value, Wave>, v: Option<Value>) -> Wave {
  577. v.and_then(|v| kind.get(&v).copied()).unwrap_or(Wave::Plain)
  578. }
  579. fn put(kind: &mut HashMap<Value, Wave>, v: Value, k: Wave) {
  580. if k == Wave::Plain {
  581. kind.remove(&v);
  582. } else {
  583. kind.insert(v, k);
  584. }
  585. }
  586. let wild = |k: Wave| !matches!(k, Wave::Plain | Wave::Base);
  587. let why = |k: Wave| match k {
  588. Wave::First => FIRST,
  589. Wave::Total(_) => TOTAL,
  590. Wave::Prefix => PREFIX,
  591. _ => MIXED,
  592. };
  593. // a mask (by its low dword) under which only a wave's first lane runs
  594. let first_mask = |firsts: &HashSet<Value>, m: Option<Value>| {
  595. m.and_then(|m| st.masks.get(&m)).is_some_and(|&b| {
  596. st.bools
  597. .support(b)
  598. .iter()
  599. .any(|a| matches!(a, Atom::Lane(v) if firsts.contains(v)))
  600. })
  601. };
  602. // One instruction outside a section: the kind of what it writes, and whether it is a
  603. // first lane's reservation.
  604. let step = |inst: &Inst, kind: &HashMap<Value, Wave>, firsts: &mut HashSet<Value>| -> Result<(Wave, bool), Why> {
  605. let name = inst.name();
  606. let val = |op: &Operand| match *op {
  607. Operand::Vector { reg, .. } => inst.read(Reg::V(reg)),
  608. Operand::Scalar { code, .. } if code != NULL => inst.read(Reg::S(code)),
  609. _ => None,
  610. };
  611. let ops: Vec<Operand> = match &inst.fields {
  612. Fields::Valu(v) => v.src.clone(),
  613. Fields::Sop { dst, src, .. } => {
  614. let mut o = src.clone();
  615. if matches!(name, "s_addk_i32" | "s_mulk_i32") {
  616. o.extend(dst.iter().copied());
  617. }
  618. o
  619. }
  620. Fields::Buffer { data, .. } if name.contains("_atomic_") || name.contains("_store_") => {
  621. data.iter().copied().collect()
  622. }
  623. _ => Vec::new(),
  624. };
  625. let kinds: Vec<Wave> = ops.iter().map(|o| of(kind, val(o))).collect();
  626. // Everything else it reads (addresses, descriptors, SCC, the high dwords of wide
  627. // operands) must not depend on the wave. Not EXEC, and not the old value of a VGPR it
  628. // writes, which only the lanes outside EXEC keep.
  629. let named: Vec<Value> = ops.iter().filter_map(&val).collect();
  630. for &(r, v) in &inst.reads {
  631. let kept = matches!(r, Reg::V(_)) && inst.writes.iter().any(|w| w.0 == r);
  632. if matches!(r, Reg::S(c) if c == EXEC || c == EXEC + 1) || kept || named.contains(&v) {
  633. continue;
  634. }
  635. let k = of(kind, Some(v));
  636. if wild(k) {
  637. return Err(why(k));
  638. }
  639. }
  640. let w = kinds.iter().copied().find(|&k| wild(k)).unwrap_or(Wave::Mixed);
  641. let sum = |k: Wave| k == Wave::Total(Op::AddU);
  642. let is_mask = |o: &Operand| {
  643. val(o).is_some_and(|v| st.masks.contains_key(&v) || st.highs.contains_key(&v))
  644. };
  645. let mut reserved = false;
  646. let out = match (name, &kinds[..]) {
  647. ("s_ff1_i32_b64" | "s_ff1_i32_b32", _) if ops.first().is_some_and(is_mask) => Wave::First,
  648. ("s_bcnt1_i32_b64" | "s_bcnt1_i32_b32", _) if ops.first().is_some_and(is_mask) => {
  649. Wave::Total(Op::AddU)
  650. }
  651. // bits of a mask below the lane; with -1 for the mask, the lane's number
  652. ("v_mbcnt_lo_u32_b32" | "v_mbcnt_hi_u32_b32", [_, b]) => {
  653. match (matches!(ops[0], Operand::Scalar { .. }), *b) {
  654. (_, Wave::Prefix) | (true, Wave::Plain | Wave::Base) => Wave::Prefix,
  655. (false, Wave::Plain | Wave::Base) => Wave::Plain,
  656. (_, k) => return Err(why(k)),
  657. }
  658. }
  659. // nothing wave-dependent goes in; what derives from a reserved base stays marked
  660. _ if !kinds.iter().any(|&k| wild(k)) => {
  661. let derives = matches!(inst.fields, Fields::Valu(_) | Fields::Sop { .. });
  662. if derives && kinds.contains(&Wave::Base) { Wave::Base } else { Wave::Plain }
  663. }
  664. ("v_mov_b32" | "s_mov_b32", [k]) => *k,
  665. ("v_cmp_eq_i32" | "v_cmp_eq_u32" | "v_cmpx_eq_i32" | "v_cmpx_eq_u32", [a, b]) => {
  666. // the lane whose own number is the first lane's
  667. let lane = match (*a, *b) {
  668. (Wave::First, k) if !wild(k) => &ops[1],
  669. (k, Wave::First) if !wild(k) => &ops[0],
  670. _ => return Err(why(w)),
  671. };
  672. if !matches!(lane, Operand::Vector { .. }) {
  673. return Err(FIRST);
  674. }
  675. let mask = match &inst.fields {
  676. _ if name.starts_with("v_cmpx") => inst.write(Reg::S(EXEC)),
  677. Fields::Valu(v) => match v.dst {
  678. Some(Operand::Scalar { code, .. }) => inst.write(Reg::S(code)),
  679. _ => None,
  680. },
  681. _ => None,
  682. };
  683. firsts.extend(mask);
  684. Wave::Plain
  685. }
  686. ("v_add_nc_u32" | "s_add_i32", [a, b]) => match (*a, *b) {
  687. (Wave::Prefix, Wave::Base) | (Wave::Base, Wave::Prefix) => Wave::Base,
  688. (Wave::Prefix, Wave::Plain | Wave::Prefix) | (Wave::Plain, Wave::Prefix) => Wave::Prefix,
  689. (x, y) if sum(x) && sum(y) => x,
  690. _ => return Err(why(w)),
  691. },
  692. ("v_sub_nc_u32" | "s_sub_i32", [a, b]) => match (*a, *b) {
  693. (Wave::Base, Wave::Prefix) => Wave::Base,
  694. (Wave::Prefix, Wave::Plain) => Wave::Prefix,
  695. (Wave::Plain, y) if sum(y) && matches!(ops[0], Operand::Const(128)) => y,
  696. _ => return Err(why(w)),
  697. },
  698. ("s_mul_i32" | "v_mul_lo_u32" | "v_mul_u32_u24", [a, b]) => match (*a, *b) {
  699. (x, Wave::Plain) | (Wave::Plain, x) if sum(x) || x == Wave::Prefix => x,
  700. _ => return Err(why(w)),
  701. },
  702. ("s_lshl_b32", [x, Wave::Plain]) | ("v_lshlrev_b32", [Wave::Plain, x])
  703. if sum(*x) || *x == Wave::Prefix =>
  704. {
  705. *x
  706. }
  707. ("v_lshl_add_u32", [Wave::Prefix, Wave::Plain, c]) if !wild(*c) => {
  708. if *c == Wave::Base { Wave::Base } else { Wave::Prefix }
  709. }
  710. // the reservation: the first lane adds its wave's total to a shared counter
  711. (_, [Wave::Total(op)]) if name.contains("_atomic_") => {
  712. let want = match op {
  713. Op::AddU => "buffer_atomic_add",
  714. Op::MinU => "buffer_atomic_umin",
  715. Op::MaxU => "buffer_atomic_umax",
  716. Op::MinI => "buffer_atomic_smin",
  717. Op::MaxI => "buffer_atomic_smax",
  718. Op::Or => "buffer_atomic_or",
  719. Op::And => "buffer_atomic_and",
  720. Op::Xor => "buffer_atomic_xor",
  721. _ => "",
  722. };
  723. if name != want || !first_mask(firsts, inst.read(Reg::S(EXEC))) {
  724. return Err(TOTAL);
  725. }
  726. reserved = true;
  727. Wave::Base
  728. }
  729. _ => return Err(why(w)),
  730. };
  731. Ok((out, reserved))
  732. };
  733. let sections: Vec<_> = (0..p.blocks.len()).map(|b| super::wave::sections(p, b)).collect();
  734. let order = crate::ir::reverse_postorder(&p.blocks);
  735. let pass = |kind: &mut HashMap<Value, Wave>, firsts: &mut HashSet<Value>, check: bool| -> Result<(), (usize, Why)> {
  736. for &b in &order {
  737. let block = &p.blocks[b];
  738. for phi in &block.phis {
  739. let mut k = Wave::Plain;
  740. for (n, &a) in phi.args.iter().enumerate() {
  741. let x = of(kind, Some(a));
  742. k = match (k, x) {
  743. _ if n == 0 => x,
  744. (k, x) if k == x => k,
  745. (Wave::Plain, m @ (Wave::Base | Wave::Prefix))
  746. | (m @ (Wave::Base | Wave::Prefix), Wave::Plain) => m,
  747. _ => Wave::Mixed,
  748. };
  749. }
  750. put(kind, phi.value, k);
  751. }
  752. for (i, inst) in block.insts.iter().enumerate() {
  753. // inside a whole-wave section: what the simulation found each value to be
  754. if let Some((_, sec)) = sections[b].iter().find(|(s, sec)| i > **s && i < sec.end) {
  755. for &(_, w) in &inst.writes {
  756. let k = match sec.shapes.get(&w) {
  757. None => Wave::Mixed,
  758. Some(&Shape::K(_)) => Wave::Plain,
  759. Some(&Shape::Value(v)) => of(kind, Some(v)),
  760. Some(&Shape::Masked(src, _, _)) => of(kind, Some(src)),
  761. Some(&Shape::Active(op, src, mask, _)) => match of(kind, Some(src)) {
  762. Wave::Plain | Wave::Base => Wave::Total(op),
  763. // the first lane's own sum of a total is that total
  764. Wave::Total(o) if o == op && first_mask(firsts, Some(mask)) => Wave::Total(op),
  765. _ => Wave::Mixed,
  766. },
  767. Some(&Shape::Prefix(Op::AddU, src, mask, _, _)) => match of(kind, Some(src)) {
  768. Wave::Plain | Wave::Base => Wave::Prefix,
  769. Wave::Total(Op::AddU) if first_mask(firsts, Some(mask)) => Wave::Prefix,
  770. _ => Wave::Mixed,
  771. },
  772. Some(_) => Wave::Mixed,
  773. };
  774. put(kind, w, k);
  775. }
  776. continue;
  777. }
  778. let name = inst.name();
  779. if name.starts_with("s_cbranch") {
  780. continue; // with the block's exit, below
  781. }
  782. let (k, reserved) = match step(inst, kind, firsts) {
  783. Ok(r) => r,
  784. Err(why) if check => return Err((inst.machine.offset, why)),
  785. Err(_) => (Wave::Mixed, false),
  786. };
  787. // the same test as `Lower::inst`'s `effect`
  788. let effect = matches!(inst.fields, Fields::Exp { .. })
  789. || matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_")
  790. || name.contains("store")
  791. || name.contains("atomic")
  792. || matches!(inst.fields, Fields::Ds { .. })
  793. && !(name.starts_with("ds_read")
  794. || name.starts_with("ds_swizzle")
  795. || name.contains("permute"));
  796. if check && effect && !reserved && first_mask(firsts, inst.read(Reg::S(EXEC))) {
  797. return Err((inst.machine.offset, EFFECT));
  798. }
  799. let guarded = st.guards[b][i].is_some();
  800. for &(r, w) in &inst.writes {
  801. let mut kw = match r {
  802. // "some lane is counted" keeps the count's kind; any other SCC is one bit of data
  803. Reg::Scc if !name.starts_with("s_bcnt1") => {
  804. if wild(k) { Wave::Mixed } else { Wave::Plain }
  805. }
  806. _ => k,
  807. };
  808. // a guarded write leaves the old value in the lanes outside EXEC
  809. if guarded
  810. && matches!(r, Reg::V(_))
  811. && kw == Wave::Plain
  812. && matches!(of(kind, inst.read(r)), Wave::First | Wave::Total(_) | Wave::Prefix)
  813. {
  814. kw = Wave::Mixed;
  815. }
  816. put(kind, w, kw);
  817. }
  818. }
  819. // a branch on "some lane is counted": fine where the structure made it the lane's
  820. // own bit (the mask is EXEC under a scalar condition)
  821. if check
  822. && let Some(last) = block.insts.last()
  823. && last.name().starts_with("s_cbranch_scc")
  824. && let Some(scc) = last.read(Reg::Scc)
  825. && wild(of(kind, Some(scc)))
  826. {
  827. let own = matches!(st.exits[b], LaneExit::Branch { when, .. }
  828. if !st.bools.support(when).iter().any(|a| matches!(a, Atom::Uniform(v) if *v == scc)));
  829. if !own {
  830. return Err((last.machine.offset, TOTAL));
  831. }
  832. }
  833. }
  834. Ok(())
  835. };
  836. let mut kind: HashMap<Value, Wave> = HashMap::new();
  837. let mut firsts: HashSet<Value> = HashSet::new();
  838. // to a fixpoint (values carried around loops), then once more to say what is wrong
  839. let mut settled = false;
  840. for _ in 0..16 {
  841. let before = (kind.clone(), firsts.len());
  842. pass(&mut kind, &mut firsts, false)?;
  843. if (&before.0, before.1) == (&kind, firsts.len()) {
  844. settled = true;
  845. break;
  846. }
  847. }
  848. if !settled {
  849. return Err((0, MIXED));
  850. }
  851. pass(&mut kind, &mut firsts, true)
  852. }
  853. /// The mode of a group barrier the translation adds (host waves meeting):
  854. /// a wait for the group with a shared-memory fence; the fence alone with
  855. /// `VICTORY_GROUP_SYNC=0` ([`super::group_sync`]).
  856. fn meeting_mode() -> u32 {
  857. if super::group_sync() == 0 { 8 } else { 1 | 8 }
  858. }
  859. /// LDS accesses of a console wave run as two host waves, where some sit in blocks that only
  860. /// some lanes run (`all` is [`all_lane_blocks`]): per IR block, whether the host waves meet (a
  861. /// group barrier) at its start and before its exit. `None` if barriers cannot keep the
  862. /// console's order.
  863. ///
  864. /// The console runs the wave's lanes in step, so an LDS write is seen by every later read. Two
  865. /// host waves keep that order if they meet between any two accesses of which one writes. A
  866. /// barrier must be run by every thread, so it cannot stand in a lane branch's region; but
  867. /// every way into and out of such a region passes a block all lanes run, and the waves meet
  868. /// there: before the exit of an all-lane block into a region with LDS accesses, and at the
  869. /// start of an all-lane block entered from one. Accesses in all-lane blocks get their own
  870. /// barrier as before. What that cannot order is a write and a read inside one region (blocks
  871. /// joined without an all-lane block between them): refused.
  872. /// shortcut: two writes in one region are taken not to hit the same dword from both halves.
  873. fn lds_meetings(p: &crate::ir::Program, st: &Structured, all: &[bool]) -> Option<Vec<(bool, bool)>> {
  874. let n = st.exits.len();
  875. let succ = |b: usize| -> Vec<usize> {
  876. match st.exits[b] {
  877. LaneExit::Jump(t) => vec![t],
  878. LaneExit::Branch { taken, not_taken, .. } => vec![taken, not_taken],
  879. LaneExit::End | LaneExit::Indirect => Vec::new(),
  880. }
  881. };
  882. // regions: blocks not every lane runs, joined by the edges between them
  883. let mut region: Vec<usize> = (0..n).collect();
  884. fn find(region: &mut [usize], mut b: usize) -> usize {
  885. while region[b] != b {
  886. region[b] = region[region[b]];
  887. b = region[b];
  888. }
  889. b
  890. }
  891. for b in 0..n {
  892. for t in succ(b) {
  893. if !all[b] && !all[t] {
  894. let (x, y) = (find(&mut region, b), find(&mut region, t));
  895. region[x] = y;
  896. }
  897. }
  898. }
  899. // per region: LDS reads, LDS writes
  900. let mut reads = vec![false; n];
  901. let mut writes = vec![false; n];
  902. for (b, block) in p.blocks.iter().enumerate().take(n) {
  903. if all[b] {
  904. continue;
  905. }
  906. let r = find(&mut region, b);
  907. for i in &block.insts {
  908. let name = i.name();
  909. if !matches!(i.fields, Fields::Ds { .. }) || name.starts_with("ds_swizzle") || name.contains("permute") {
  910. continue;
  911. }
  912. if name.starts_with("ds_read") {
  913. reads[r] = true;
  914. } else {
  915. writes[r] = true;
  916. }
  917. }
  918. }
  919. if (0..n).any(|r| reads[r] && writes[r]) {
  920. return None;
  921. }
  922. let mut meet = vec![(false, false); n];
  923. for b in 0..n {
  924. for t in succ(b) {
  925. if all[b] && !all[t] {
  926. let r = find(&mut region, t);
  927. meet[b].1 |= reads[r] || writes[r];
  928. } else if !all[b] && all[t] {
  929. let r = find(&mut region, b);
  930. meet[t].0 |= reads[r] || writes[r];
  931. }
  932. }
  933. }
  934. Some(meet)
  935. }
  936. /// Masks held as numbers or constant lane sets in guards or lane branches: the lane tests its
  937. /// own bit by its console lane.
  938. fn lane_constant_masks(st: &Structured) -> bool {
  939. let whens = st.exits.iter().filter_map(|e| match *e {
  940. LaneExit::Branch { when, .. } => Some(when),
  941. _ => None,
  942. });
  943. let mut work: Vec<Bool> = st.guards.iter().flatten().flatten().copied().chain(whens).collect();
  944. // Through lane-mask joins too: an edge that brings a number or a constant lane set needs
  945. // the lane's own bit of it.
  946. // shortcut: masks only selects read (`v_cndmask_b32`, carries in) are not followed; such
  947. // a program still stops with "a constant lane mask" or "an opaque lane mask".
  948. let (mut seen, mut joins) = (HashSet::new(), HashSet::new());
  949. while let Some(g) = work.pop() {
  950. if !seen.insert(g) {
  951. continue;
  952. }
  953. for a in st.bools.support(g) {
  954. match a {
  955. Atom::Opaque(_) | Atom::Constant(_) => return true,
  956. Atom::Phi(id) if joins.insert(id) => {
  957. if let Some(edges) = st.phi_masks.get(&id) {
  958. work.extend(edges.iter().copied());
  959. }
  960. }
  961. _ => {}
  962. }
  963. }
  964. }
  965. false
  966. }
  967. /// The widest wave the host GPU runs (0: not known – no host-specific forms); see
  968. /// [`set_host_max_wave`].
  969. static HOST_MAX_WAVE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
  970. /// The host GPU's `WaveLaneCountMax`: 32 lets console wave64 compute programs whose cross-lane
  971. /// code stays inside 32-lane halves run in waves of 32 instead of being refused.
  972. pub fn set_host_max_wave(lanes: u32) {
  973. HOST_MAX_WAVE.store(lanes, std::sync::atomic::Ordering::Relaxed);
  974. }
  975. thread_local! {
  976. /// See [`take_needs`].
  977. static NEEDS: std::cell::RefCell<Vec<usize>> = const { std::cell::RefCell::new(Vec::new()) };
  978. /// See [`with_local_waves`].
  979. static LOCAL_WAVES: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
  980. /// See [`with_local_waves_any`].
  981. static LOCAL_ANY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
  982. }
  983. /// As [`with_local_waves`], with every other use of a lane mask as a number
  984. /// and every lane read and write taken per host wave too: the program runs
  985. /// as it would on a console of 32-lane waves, lanes numbered 0..31 or
  986. /// 32..63 by half. Right for code that only relies on what HLSL's wave
  987. /// operations promise; a program that takes one wave to be its whole
  988. /// thread group gets per-half results. The last resort for programs that
  989. /// do not translate otherwise.
  990. pub(super) fn with_local_waves_any<R>(f: impl FnOnce() -> R) -> R {
  991. let was = LOCAL_ANY.replace(true);
  992. let r = with_local_waves(f);
  993. LOCAL_ANY.set(was);
  994. r
  995. }
  996. /// Runs `f` with console wave64 programs on 32-lane hosts lowered with each
  997. /// host wave as a wave of its own ("local"): no exchange between the two
  998. /// halves of a console wave, so no barriers and no need for every lane to
  999. /// reach the code. What HLSL's wave operations promise holds for any
  1000. /// division of the threads into waves, and the idiom the title's compute
  1001. /// programs use them for does not care which wave a thread is in: count or
  1002. /// sum over the wave, the first lane reserves that many slots with an atomic
  1003. /// add, every lane takes the base (`WaveReadLaneFirst`) plus its prefix.
  1004. /// Each lane still gets a slot of its own; only the order differs.
  1005. /// Only that idiom's operations are lowered this way: a lane mask read as
  1006. /// a number by anything but a bit count, a first-set-bit or `v_mbcnt`, and
  1007. /// lane reads and writes outside whole-wave sections, stop the translation.
  1008. /// shortcut: where a count or sum goes is not checked. A program that uses
  1009. /// a wave-wide result as data for the whole console wave (a tile's maximum,
  1010. /// say, with one wave per thread group) gets its half's result. It is used
  1011. /// only for programs that do not translate otherwise.
  1012. pub(super) fn with_local_waves<R>(f: impl FnOnce() -> R) -> R {
  1013. let was = LOCAL_WAVES.replace(true);
  1014. let r = f();
  1015. LOCAL_WAVES.set(was);
  1016. r
  1017. }
  1018. /// `VICTORY_F16_NEAREST=1`: the results of 16-bit float operations (`v_add_f16`,
  1019. /// `v_mul_f16`, `v_cvt_f16_f32` ...) are rounded to nearest as the console rounds them
  1020. /// ([`Lower::f16_nearest`]) instead of as the host's `f32tof16` does (toward zero on NVIDIA:
  1021. /// the last place of a result that is not exact is then one lower than the console's).
  1022. /// Off by default: it is exact but untried in a game run, and adds instructions to every
  1023. /// such operation. The wave sum of 16-bit floats ([`Lower::half_sum`]) is always exact.
  1024. fn f16_nearest_on() -> bool {
  1025. #[cfg(test)]
  1026. if let Some(on) = TEST_F16_NEAREST.get() {
  1027. return on;
  1028. }
  1029. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1030. *ON.get_or_init(|| std::env::var_os("VICTORY_F16_NEAREST").is_some_and(|v| v == "1"))
  1031. }
  1032. #[cfg(test)]
  1033. thread_local! {
  1034. /// A test's choice for [`f16_nearest_on`], for its thread only.
  1035. pub(super) static TEST_F16_NEAREST: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
  1036. }
  1037. /// `VICTORY_WAVE_OWN_BITS=0`: a wave OR where not every lane runs is refused as before
  1038. /// ([`super::own_bits`]).
  1039. fn own_bits_on() -> bool {
  1040. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1041. *ON.get_or_init(|| std::env::var_os("VICTORY_WAVE_OWN_BITS").is_none_or(|v| v != "0"))
  1042. }
  1043. /// What the translator was told of the host, for a cache's key: the widest
  1044. /// wave, the view heap's limit and where the raw twins of its views start.
  1045. pub fn host_settings() -> [u32; 3] {
  1046. [host_max_wave(), super::shader::view_heap_limit(), super::shader::raw_views()]
  1047. }
  1048. /// The refusal of a first half of an interpolation whose result is read
  1049. /// as data ([`Lower::interp`]).
  1050. pub(super) const FIRST_HALF: &str = "the first half of an interpolation";
  1051. thread_local! {
  1052. /// Whether first halves of interpolations are evaluated as the pair
  1053. /// they start ([`with_first_half_pairs`]).
  1054. static FIRST_HALF_PAIRS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
  1055. }
  1056. /// Runs `translate` with first halves of interpolations evaluated as the
  1057. /// pair they start: the translation of a program refused with
  1058. /// [`FIRST_HALF`] (`VICTORY_FIRST_HALF=0`: refused again, as before).
  1059. pub(super) fn with_first_half_pairs<R>(translate: impl FnOnce() -> R) -> R {
  1060. let before = FIRST_HALF_PAIRS.replace(true);
  1061. let result = translate();
  1062. FIRST_HALF_PAIRS.set(before);
  1063. result
  1064. }
  1065. pub(super) fn host_max_wave() -> u32 {
  1066. #[cfg(test)]
  1067. if let Some(lanes) = TEST_HOST_WAVE.get() {
  1068. return lanes;
  1069. }
  1070. HOST_MAX_WAVE.load(std::sync::atomic::Ordering::Relaxed)
  1071. }
  1072. #[cfg(test)]
  1073. thread_local! {
  1074. /// A test's host wave size, for its thread only ([`set_host_max_wave`] is the process's).
  1075. pub(super) static TEST_HOST_WAVE: std::cell::Cell<Option<u32>> = const { std::cell::Cell::new(None) };
  1076. }
  1077. pub(super) fn reads_mask_as_data(st: &Structured, i: &Inst) -> bool {
  1078. let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v);
  1079. let ops: Vec<&Operand> = match &i.fields {
  1080. // A mask operation (its result a mask) is no data use.
  1081. Fields::Sop { .. }
  1082. if i.writes
  1083. .iter()
  1084. .any(|&(r, w)| matches!(r, Reg::S(_)) && is_mask(w)) =>
  1085. {
  1086. return false;
  1087. }
  1088. Fields::Sop { src, .. } => src.iter().collect(),
  1089. Fields::Valu(v)
  1090. if !matches!(i.name(), "v_cndmask_b32") && !i.name().contains("_co_ci_") =>
  1091. {
  1092. v.src.iter().collect()
  1093. }
  1094. _ => return false,
  1095. };
  1096. ops.into_iter().any(|op| match *op {
  1097. Operand::Scalar { code, .. } if code != NULL => i.read(Reg::S(code)).is_some_and(is_mask),
  1098. _ => false,
  1099. })
  1100. }
  1101. /// The parameters packing 16-bit rows two per dword and where each lays
  1102. /// its elements out: (first row, [(dword, register, column, columns)]).
  1103. ///
  1104. /// The console gives every 16-bit element whole dwords. A parameter leads
  1105. /// with the first element of its first row, then the first element of its
  1106. /// second row. An element that shares a register behind another one (the
  1107. /// signature packs a short element into the free columns of an earlier
  1108. /// register) is NOT in that row's halves: it follows in the first
  1109. /// parameter, in row order, that has whole dwords left.
  1110. /// The title's packed pedestrian shaders show both cases: TEXCOORD7 (register 1,
  1111. /// columns 2-3, behind the two columns of TEXCOORD0) is exported in dword 3
  1112. /// of parameter 0, after TEXCOORD1's two dwords; TEXCOORD6 (register 4,
  1113. /// column 3, behind the three columns of TEXCOORD4) in dword 3 of
  1114. /// parameter 3, after TEXCOORD5 and TEXCOORD7, while the high half of
  1115. /// TEXCOORD4's second dword stays zero.
  1116. type PackedLayout = Vec<(u8, Vec<(u8, u8, u8, u8)>)>;
  1117. fn packed_layout(elements: &[SigElement], packs: &[(u8, Option<u8>)]) -> PackedLayout {
  1118. let of_row = |r: u8| {
  1119. let mut of: Vec<&SigElement> = elements
  1120. .iter()
  1121. .filter(|e| e.row == Some(u32::from(r)))
  1122. .collect();
  1123. of.sort_by_key(|e| e.col);
  1124. of
  1125. };
  1126. let mut packs = packs.to_vec();
  1127. packs.sort_unstable();
  1128. packs.dedup_by_key(|p| p.0);
  1129. // Per parameter: its first row, the dwords used, the elements.
  1130. let mut layout: Vec<(u8, u8, Vec<(u8, u8, u8, u8)>)> = Vec::new();
  1131. let mut behind = Vec::new();
  1132. for &(a, b) in &packs {
  1133. let mut placed = Vec::new();
  1134. let mut at = 0u8;
  1135. if !of_row(a).is_empty() {
  1136. for r in [Some(a), b].into_iter().flatten() {
  1137. let of = of_row(r);
  1138. let Some((lead, more)) = of.split_first() else {
  1139. continue;
  1140. };
  1141. placed.push((at, r, lead.col, lead.cols));
  1142. at += lead.cols.div_ceil(2);
  1143. behind.extend(more.iter().map(|e| (r, e.col, e.cols)));
  1144. }
  1145. }
  1146. layout.push((a, at, placed));
  1147. }
  1148. behind.sort_unstable();
  1149. for (r, col, cols) in behind {
  1150. let need = cols.div_ceil(2);
  1151. if let Some(p) = layout.iter_mut().find(|p| p.1 + need <= 4) {
  1152. p.2.push((p.1, r, col, cols));
  1153. p.1 += need;
  1154. }
  1155. }
  1156. layout.into_iter().map(|(a, _, of)| (a, of)).collect()
  1157. }
  1158. /// Where half `h` (dword h / 2, the high half when odd) of the parameter
  1159. /// whose first 16-bit row is `a` comes from: a register and column of
  1160. /// `elements`, none for padding ([`packed_layout`]; `packs` lists every
  1161. /// parameter packing two 16-bit rows per dword).
  1162. fn packed_half(
  1163. elements: &[SigElement],
  1164. packs: &[(u8, Option<u8>)],
  1165. a: u8,
  1166. h: u8,
  1167. ) -> Option<(u8, u8)> {
  1168. let layout = packed_layout(elements, packs);
  1169. let (_, of) = layout.iter().find(|p| p.0 == a)?;
  1170. of.iter().find_map(|&(dword, row, col, cols)| {
  1171. let k = h.checked_sub(2 * dword)?;
  1172. (k < cols).then_some((row, col + k))
  1173. })
  1174. }
  1175. /// The pixel inputs packing two 16-bit rows per dword, as (first row,
  1176. /// second row) ([`packed_layout`]).
  1177. fn input_packs(io: &StageIo, inputs: &[SigElement]) -> Vec<(u8, Option<u8>)> {
  1178. let StageIo::Ps {
  1179. inputs: entries, ..
  1180. } = io
  1181. else {
  1182. return Vec::new();
  1183. };
  1184. let partners = half_input_partners(io, inputs);
  1185. entries
  1186. .iter()
  1187. .filter(|i| i.fp16 && i.pack2)
  1188. .map(|i| {
  1189. let b = if i.row2 != i.row {
  1190. Some(i.row2)
  1191. } else {
  1192. partners.get(&i.row).copied()
  1193. };
  1194. (i.row, b)
  1195. })
  1196. .collect()
  1197. }
  1198. /// Vertex or mesh outputs of 16-bit values (see [`Lower::half_outputs`]):
  1199. /// a packed row's partner is the next 16-bit row of the signature that no
  1200. /// output entry names, taken in row order.
  1201. fn half_outputs(io: &StageIo, outputs: &[SigElement]) -> HashMap<u8, (bool, Option<u8>)> {
  1202. let entries = match io {
  1203. StageIo::Vs { outputs, .. } => outputs,
  1204. StageIo::Ms(ms) => &ms.outputs,
  1205. _ => return HashMap::new(),
  1206. };
  1207. let per_vertex = || entries.iter().filter(|o| o.param & 0x80 == 0);
  1208. let mut free: Vec<u8> = outputs
  1209. .iter()
  1210. .filter(|e| e.half && e.kind == 0)
  1211. .filter_map(|e| u8::try_from(e.row?).ok())
  1212. .filter(|&r| !per_vertex().any(|o| o.row == r))
  1213. .collect();
  1214. free.sort_unstable();
  1215. free.dedup();
  1216. let mut halves: Vec<_> = per_vertex().filter(|o| o.fp16).collect();
  1217. halves.sort_by_key(|o| o.row);
  1218. halves
  1219. .into_iter()
  1220. .map(|o| {
  1221. let b = o
  1222. .pack2
  1223. .then(|| free.iter().position(|&r| r > o.row))
  1224. .flatten();
  1225. (o.row, (o.pack2, b.map(|i| free.remove(i))))
  1226. })
  1227. .collect()
  1228. }
  1229. /// Pixel inputs packing two 16-bit rows per dword whose second row the
  1230. /// metadata leaves out (`row2` = `row`): as for outputs
  1231. /// ([`half_outputs`]), the next 16-bit row of the signature that no input
  1232. /// entry names, taken in row order (rows the metadata does give are taken
  1233. /// first).
  1234. fn half_input_partners(io: &StageIo, inputs: &[SigElement]) -> HashMap<u8, u8> {
  1235. let StageIo::Ps {
  1236. inputs: entries, ..
  1237. } = io
  1238. else {
  1239. return HashMap::new();
  1240. };
  1241. let packed = || entries.iter().filter(|i| i.fp16 && i.pack2);
  1242. let mut free: Vec<u8> = inputs
  1243. .iter()
  1244. .filter(|e| e.half && e.kind == 0)
  1245. .filter_map(|e| u8::try_from(e.row?).ok())
  1246. .filter(|&r| !entries.iter().any(|i| i.row == r))
  1247. .filter(|&r| !packed().any(|i| i.row2 != i.row && i.row2 == r))
  1248. .collect();
  1249. free.sort_unstable();
  1250. free.dedup();
  1251. let mut missing: Vec<_> = packed().filter(|i| i.row2 == i.row).collect();
  1252. missing.sort_by_key(|i| i.row);
  1253. let mut partners = HashMap::new();
  1254. for i in missing {
  1255. if let Some(k) = free.iter().position(|&r| r > i.row) {
  1256. partners.insert(i.row, free.remove(k));
  1257. }
  1258. }
  1259. partners
  1260. }
  1261. fn unsupported(offset: usize, what: Why) -> Stop {
  1262. Stop::Fail(ShaderError::Unsupported { offset, what })
  1263. }
  1264. impl<'a> Lower<'a> {
  1265. fn new(x: &'a Parts<'a>, bad: &'a HashMap<Value, Why>) -> Self {
  1266. let p = x.p;
  1267. let mut phi_at = HashMap::new();
  1268. for (b, block) in p.blocks.iter().enumerate() {
  1269. for (i, phi) in block.phis.iter().enumerate() {
  1270. phi_at.insert(phi.value, (b, i));
  1271. }
  1272. }
  1273. let mut s = Shader::new(x.native.stage == HwStage::Ps);
  1274. s.inputs = x.inputs.clone();
  1275. s.outputs = x.outputs.clone();
  1276. let insts = || p.blocks.iter().flat_map(|b| &b.insts);
  1277. let writes_uavs = insts().any(|i| {
  1278. matches!(i.fields, Fields::Image { .. } | Fields::Buffer { .. })
  1279. && (i.name().contains("store") || i.name().contains("atomic"))
  1280. });
  1281. let mut console_lanes = false;
  1282. // LDS accesses get a group barrier each (a console wave split in two host waves)
  1283. let mut split_lds = false;
  1284. // with `split_lds`, LDS accesses in lane branches: the blocks every lane runs, and
  1285. // where the host waves meet around those branches (`lds_meetings`)
  1286. let mut lds_meet: Option<(Vec<bool>, Vec<(bool, bool)>)> = None;
  1287. // a console wave64 program in two host waves of 32 (`exchange`)
  1288. let mut exchange: Option<(u32, bool, Vec<bool>)> = None;
  1289. // a console wave64 program in host waves of 32: the LDS dword of `wave_base`'s counter
  1290. let mut halves: Option<u32> = None;
  1291. if let StageIo::Cs(cs) = x.native.io {
  1292. s.threads = Some(cs.threads);
  1293. s.lds_dwords = cs.lds_bytes() / 4;
  1294. // Code reading other lanes needs the console's wave size and
  1295. // lane order; so do lane masks read as numbers, and LDS shared
  1296. // within one wave, where the console compiler leaves out barriers.
  1297. console_lanes = insts().any(|i| {
  1298. let n = i.name();
  1299. n.starts_with("ds_swizzle")
  1300. || n.contains("permute")
  1301. || n.starts_with("v_permlane")
  1302. || n.starts_with("v_mbcnt")
  1303. || matches!(n, "v_readlane_b32" | "v_writelane_b32")
  1304. || matches!(&i.fields, Fields::Valu(v) if v.dpp.is_some())
  1305. || reads_mask_as_data(x.st, i)
  1306. }) || lane_constant_masks(x.st)
  1307. // (a branch the wave takes together asks the wave)
  1308. || !x.st.wide.is_empty();
  1309. let mut wave = if x.native.wave64 { 64 } else { 32 };
  1310. let group = cs.threads.iter().product::<u32>();
  1311. let one_wave = group <= wave;
  1312. // A host whose waves are at most 32 lanes (NVIDIA) refuses `WaveSize(64)`. A console
  1313. // wave64 program whose cross-lane code stays inside 32-lane halves – DPP rows,
  1314. // `ds_swizzle`, `v_permlane16` / `v_permlanex16`, which the ISA confines there – runs
  1315. // exactly in waves of 32: the thread relabelling makes each host wave one half of a
  1316. // console wave (lanes 32k..32k+31). Not when it crosses halves (`v_mbcnt`,
  1317. // `v_readlane`, `v_writelane`, `ds_(b)permute`, masks as numbers or lane-constant
  1318. // masks), nor when LDS may be shared within the console wave without barriers (a
  1319. // group over 32 threads with LDS): those still need 64-lane waves.
  1320. if wave == 64 && host_max_wave() == 32 && (console_lanes || one_wave && s.lds_dwords > 0) {
  1321. let crosses = insts().any(|i| {
  1322. let n = i.name();
  1323. n.starts_with("v_mbcnt")
  1324. || matches!(n, "v_readlane_b32" | "v_writelane_b32")
  1325. || n.starts_with("ds_permute")
  1326. || n.starts_with("ds_bpermute")
  1327. || reads_mask_as_data(x.st, i)
  1328. }) || lane_constant_masks(x.st)
  1329. || !x.st.wide.is_empty();
  1330. if !crosses && (s.lds_dwords == 0 || group <= 32) {
  1331. wave = 32;
  1332. } else {
  1333. // (Groups of several console waves too: each console wave is two host
  1334. // waves, which exchange through their own pair of dwords.)
  1335. // LDS the console shares within its one wave without barriers: split into
  1336. // two waves of 32, a group barrier before every LDS access keeps their order
  1337. // – where every thread of the group gets there (no lane branch around it,
  1338. // no guard), else a barrier would hang the group
  1339. let lds = |i: &Inst| {
  1340. matches!(i.fields, Fields::Ds { .. })
  1341. && !(i.name().starts_with("ds_swizzle") || i.name().contains("permute"))
  1342. };
  1343. if let Some(all) = all_lane_blocks(x.st) {
  1344. let ok = p.blocks.iter().enumerate().all(|(b, blk)| {
  1345. blk.insts.iter().all(|inst| {
  1346. !lds(inst) || all.get(b).copied().unwrap_or(false)
  1347. })
  1348. });
  1349. let mut lds_ok = !(s.lds_dwords > 0 && group > 32) || ok;
  1350. if !lds_ok && let Some(meet) = lds_meetings(p, x.st, &all) {
  1351. lds_meet = Some((all.clone(), meet));
  1352. lds_ok = true;
  1353. }
  1354. if !lds_ok {
  1355. // (the blocks whose LDS accesses not every lane runs: with the
  1356. // branches around them taken wave-wide they get their barriers)
  1357. for (b, blk) in p.blocks.iter().enumerate() {
  1358. if !all.get(b).copied().unwrap_or(false) && blk.insts.iter().any(lds) {
  1359. need(b);
  1360. }
  1361. }
  1362. }
  1363. if lds_ok {
  1364. wave = 32;
  1365. split_lds = s.lds_dwords > 0 && group > 32;
  1366. if crosses {
  1367. // lanes 32..63 are the other host wave: masks, lane reads and lane
  1368. // numbers go through two exchange dwords past the program's LDS
  1369. exchange = Some((s.lds_dwords, group <= 32, all));
  1370. s.lds_dwords += 2 * group.div_ceil(64);
  1371. }
  1372. }
  1373. }
  1374. }
  1375. // `VICTORY_WAVE_WHY=1`: why a program keeps 64-lane waves (one line per reason)
  1376. if wave == 64 && std::env::var_os("VICTORY_WAVE_WHY").is_some() {
  1377. let mut why: Vec<&str> = Vec::new();
  1378. for i in insts() {
  1379. let n = i.name();
  1380. let r = if n.starts_with("v_mbcnt") {
  1381. "v_mbcnt"
  1382. } else if n == "v_readlane_b32" {
  1383. "v_readlane"
  1384. } else if n == "v_writelane_b32" {
  1385. "v_writelane"
  1386. } else if n.starts_with("ds_permute") || n.starts_with("ds_bpermute") {
  1387. "ds_(b)permute"
  1388. } else if reads_mask_as_data(x.st, i) {
  1389. "mask as data"
  1390. } else {
  1391. continue;
  1392. };
  1393. if !why.contains(&r) {
  1394. why.push(r);
  1395. }
  1396. }
  1397. if lane_constant_masks(x.st) {
  1398. why.push("lane-constant mask");
  1399. }
  1400. if s.lds_dwords > 0 && group > 32 {
  1401. why.push("LDS in a group over 32");
  1402. match all_lane_blocks(x.st) {
  1403. None => why.push("an indirect exit"),
  1404. Some(all) if lds_meetings(p, x.st, &all).is_none() => {
  1405. why.push("an LDS read and write in one lane-branch region")
  1406. }
  1407. Some(_) => {}
  1408. }
  1409. }
  1410. why.sort_unstable();
  1411. eprintln!("WAVE64-WHY group={group} lds={} [{}]", s.lds_dwords > 0, why.join(", "));
  1412. }
  1413. }
  1414. if wave == 32 && x.native.wave64 {
  1415. // console threads go to host waves in the order the waves take them (`wave_base`)
  1416. halves = Some(s.lds_dwords);
  1417. s.lds_dwords += 1;
  1418. }
  1419. if console_lanes || one_wave && s.lds_dwords > 0 {
  1420. s.wave_size = Some(wave);
  1421. }
  1422. }
  1423. // The title's barriers a thread of the group may never reach, which
  1424. // leaves the others waiting on the host: those in blocks some lanes
  1425. // do not run, and all of them in a program with a loop closed by a
  1426. // plain jump (a lane still in it at the iteration limit leaves the
  1427. // program there, `abort_block`).
  1428. let fence_only: HashSet<usize> = if insts().any(|i| i.name() == "s_barrier") {
  1429. let order = crate::ir::reverse_postorder(&p.blocks);
  1430. let mut place = vec![usize::MAX; p.blocks.len()];
  1431. for (n, &b) in order.iter().enumerate() {
  1432. place[b] = n;
  1433. }
  1434. let back = |from: usize, to: usize| {
  1435. let at = |b: usize| place.get(b).copied().unwrap_or(usize::MAX);
  1436. at(from) != usize::MAX && at(to) <= at(from)
  1437. };
  1438. let cut_short = x
  1439. .st
  1440. .exits
  1441. .iter()
  1442. .enumerate()
  1443. .any(|(b, e)| matches!(*e, LaneExit::Jump(t) if back(b, t)));
  1444. let all = all_lane_blocks(x.st);
  1445. (0..p.blocks.len())
  1446. .filter(|&b| p.blocks[b].insts.iter().any(|i| i.name() == "s_barrier"))
  1447. .filter(|&b| {
  1448. cut_short
  1449. || all
  1450. .as_ref()
  1451. .is_none_or(|all| !all.get(b).copied().unwrap_or(false))
  1452. })
  1453. .collect()
  1454. } else {
  1455. HashSet::new()
  1456. };
  1457. let mut no_barrier = HashSet::new();
  1458. if let StageIo::Ms(ms) = &x.native.io {
  1459. s.prims = x.prims.clone();
  1460. s.threads = Some([ms.threads, 1, 1]);
  1461. s.lds_dwords = ms.lds_bytes.div_ceil(4);
  1462. s.mesh = Some(super::shader::Mesh {
  1463. max_vertices: ms.max_vertices,
  1464. max_primitives: ms.max_primitives,
  1465. topology: ms.topology,
  1466. });
  1467. // Barriers order the lanes' LDS accesses; the console's
  1468. // allocation request needs them too, but the host does not. One
  1469. // lane sends that request, and what it dominates (the path for
  1470. // counts out of range) runs in that lane alone, so its barrier
  1471. // would hang the host.
  1472. let order = crate::ir::reverse_postorder(&p.blocks);
  1473. let mut index = vec![usize::MAX; p.blocks.len()];
  1474. for (n, &b) in order.iter().enumerate() {
  1475. index[b] = n;
  1476. }
  1477. let idom = crate::ir::idoms(&p.blocks, &order, &index);
  1478. let alloc: Vec<usize> = (0..p.blocks.len())
  1479. .filter(|&b| {
  1480. p.blocks[b].insts.iter().any(|i| {
  1481. i.name() == "s_sendmsg"
  1482. && matches!(i.fields, Fields::Sopp { imm } if imm & 0xF == GS_ALLOC_REQ)
  1483. })
  1484. })
  1485. .collect();
  1486. for &b in &order {
  1487. let mut d = b;
  1488. let dominated = loop {
  1489. if alloc.contains(&d) {
  1490. break true;
  1491. }
  1492. if idom[d] == d || idom[d] == usize::MAX {
  1493. break false;
  1494. }
  1495. d = idom[d];
  1496. };
  1497. if ms.lds_bytes == 0 || dominated {
  1498. no_barrier.insert(b);
  1499. }
  1500. }
  1501. }
  1502. Lower {
  1503. s,
  1504. x,
  1505. bad,
  1506. lane_fail: HashMap::new(),
  1507. vals: HashMap::new(),
  1508. floats: HashMap::new(),
  1509. block: vec![None; p.blocks.len()],
  1510. cur: 0,
  1511. bools: HashMap::new(),
  1512. lane_bits: HashMap::new(),
  1513. phi_at,
  1514. mask_phis: HashMap::new(),
  1515. pending_masks: Vec::new(),
  1516. data_phis: Vec::new(),
  1517. read_phis: HashSet::new(),
  1518. stale: HashSet::new(),
  1519. coherent: HashSet::new(),
  1520. ordered: if x.native.stage == HwStage::Ps {
  1521. ordered_section(p)
  1522. } else {
  1523. HashSet::new()
  1524. },
  1525. params: x.res.params.iter().map(|&(v, p, d)| (v, (p, d))).collect(),
  1526. user_data: None,
  1527. user_reads: BTreeMap::new(),
  1528. samplers: Vec::new(),
  1529. descriptors: x
  1530. .res
  1531. .descriptors
  1532. .iter()
  1533. .map(|d| ((d.site, d.role == Role::Sampler), &d.source))
  1534. .collect(),
  1535. scalar: x.res.scalar.iter().copied().collect(),
  1536. exports: x.io.exports.iter().map(|e| (e.site, e)).collect(),
  1537. interps: {
  1538. let mut m: HashMap<Site, &Interp> = x.io.interps.iter().map(|(s, i)| (*s, i)).collect();
  1539. // A first half whose result is also read as data (an f16 second half keeps
  1540. // the other half of its dst, PS_DeferredTextured): evaluated as the pair it
  1541. // starts. Approximate for those other bits (P0 + i P10 on the console); a
  1542. // first half only the second half reads is gone before lowering.
  1543. // Only in the second translation of a program the first
  1544. // one refused for it ([`with_first_half_pairs`]).
  1545. if FIRST_HALF_PAIRS.get() && std::env::var_os("VICTORY_FIRST_HALF").is_none_or(|v| v != "0") {
  1546. for (_, i) in &x.io.interps {
  1547. if let Interp::Interpolated { first, .. } = i {
  1548. for s in first {
  1549. m.entry(*s).or_insert(i);
  1550. }
  1551. }
  1552. }
  1553. }
  1554. m
  1555. },
  1556. handles: HashMap::new(),
  1557. strides: HashMap::new(),
  1558. edges: HashMap::new(),
  1559. exported: vec![false; p.blocks.len()],
  1560. rpo: vec![usize::MAX; p.blocks.len()],
  1561. tail: vec![None; p.blocks.len()],
  1562. writes_uavs,
  1563. src0: None,
  1564. console_lanes,
  1565. split_lds,
  1566. lds_meet,
  1567. local: exchange.is_some() && LOCAL_WAVES.get(),
  1568. local_ok: false,
  1569. local_any: LOCAL_ANY.get(),
  1570. uniform: match &exchange {
  1571. Some((_, false, all)) if !LOCAL_WAVES.get() => lane_uniform(p, x.st, all),
  1572. _ => HashSet::new(),
  1573. },
  1574. own_bits: match &exchange {
  1575. Some((_, false, _)) if !LOCAL_WAVES.get() && own_bits_on() => {
  1576. super::own_bits::find(p, x.st, std::env::var_os("VICTORY_WAVE_WHY").is_some())
  1577. }
  1578. _ => Default::default(),
  1579. },
  1580. exchange,
  1581. clane: None,
  1582. pair: None,
  1583. halves,
  1584. wave_base: None,
  1585. flat: None,
  1586. no_barrier,
  1587. fence_only,
  1588. half_outputs: half_outputs(&x.native.io, &x.outputs),
  1589. mask_data: match x.native.stage {
  1590. HwStage::Cs => MaskData::Console,
  1591. HwStage::Ps | HwStage::Vs => MaskData::Host,
  1592. _ => MaskData::None,
  1593. },
  1594. mask_ok: false,
  1595. ballots: HashMap::new(),
  1596. balloting: HashSet::new(),
  1597. def_block: p
  1598. .blocks
  1599. .iter()
  1600. .enumerate()
  1601. .flat_map(|(b, block)| {
  1602. block
  1603. .insts
  1604. .iter()
  1605. .flat_map(move |i| i.writes.iter().map(move |w| (w.1, b)))
  1606. .chain(block.phis.iter().map(move |phi| (phi.value, b)))
  1607. })
  1608. .collect(),
  1609. cur_ir: 0,
  1610. sections: HashMap::new(),
  1611. section_out: HashSet::new(),
  1612. code_table: None,
  1613. counters: HashMap::new(),
  1614. abort: None,
  1615. }
  1616. }
  1617. /// The dword of the program's code at byte `byte` (a constant table
  1618. /// the compiler appends to the code), as an internal constant array.
  1619. // shortcut: an index outside the table reads its last dword (the
  1620. // console would read whatever memory follows the code).
  1621. fn code_dword(&mut self, byte: V) -> Result<V, Why> {
  1622. let (g, base, len) = match self.code_table {
  1623. Some(t) => t,
  1624. None => {
  1625. let first = self
  1626. .x
  1627. .res
  1628. .scalar
  1629. .iter()
  1630. .map(|s| s.1)
  1631. .chain(self.x.res.descriptors.iter().flat_map(|d| {
  1632. d.source.leaves().into_iter().filter_map(|l| match l {
  1633. Source::Built { address, .. } => Some(*address),
  1634. _ => None,
  1635. })
  1636. }))
  1637. .filter(|a| a.param == CODE)
  1638. .map(|a| a.offset & !3)
  1639. .min()
  1640. .ok_or("a code table")?;
  1641. let code = &self.x.native.code;
  1642. let words: Vec<u32> = code
  1643. .get(first as usize..)
  1644. .ok_or("a code table past the code")?
  1645. .chunks(4)
  1646. .map(|c| {
  1647. let mut w = [0u8; 4];
  1648. w[..c.len()].copy_from_slice(c);
  1649. u32::from_le_bytes(w)
  1650. })
  1651. .collect();
  1652. if words.is_empty() {
  1653. return Err("a code table past the code");
  1654. }
  1655. let elems: Vec<V> = words.iter().map(|&w| self.s.m.i32(w)).collect();
  1656. let arr = self.s.m.array(words.len() as u32, self.s.t.i32);
  1657. let init = self.s.m.aggregate(arr, &elems);
  1658. let g = self.s.m.constant_global("code", init);
  1659. let t = (g, first, words.len() as u32);
  1660. self.code_table = Some(t);
  1661. t
  1662. }
  1663. };
  1664. let c = self.cur;
  1665. let k = self.s.m.i32(base);
  1666. let rel = self.s.m.bin(c, Bin::Sub, byte, k);
  1667. let two = self.s.m.i32(2);
  1668. let index = self.s.m.bin(c, Bin::LShr, rel, two);
  1669. let last = self.s.m.i32(len - 1);
  1670. let over = self.s.m.cmp(c, pred::IUGT, index, last);
  1671. let index = self.s.m.select(c, over, last, index);
  1672. let at = self.s.m.element(c, g, index);
  1673. Ok(self.s.m.load(c, at))
  1674. }
  1675. /// A global memory load (`global_load_*`): from the program's constant
  1676. /// table, or from a root SRV at the address the title sets.
  1677. fn flat(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  1678. let Fields::Flat { dst, .. } = &inst.fields else {
  1679. unreachable!()
  1680. };
  1681. let name = inst.name();
  1682. if self.scalar.get(&(b, i)).is_some_and(|a| a.param == MEMORY) {
  1683. return self.memory_flat(inst, b, i);
  1684. }
  1685. let rest = name
  1686. .strip_prefix("global_load_")
  1687. .ok_or("a global memory write")?;
  1688. let (n, sub) = match rest {
  1689. "dword" => (1, None),
  1690. "dwordx2" => (2, None),
  1691. "dwordx3" => (3, None),
  1692. "dwordx4" => (4, None),
  1693. "ubyte" => (1, Some((8, false))),
  1694. "sbyte" => (1, Some((8, true))),
  1695. "ushort" => (1, Some((16, false))),
  1696. "sshort" => (1, Some((16, true))),
  1697. _ => return Err(name),
  1698. };
  1699. let a = *self
  1700. .scalar
  1701. .get(&(b, i))
  1702. .ok_or("an untracked global address")?;
  1703. let guard = self.guard(b, i)?;
  1704. let Some(Operand::Vector { reg, .. }) = *dst else {
  1705. return Err("a global load result");
  1706. };
  1707. let c = self.cur;
  1708. let mut off = self.s.m.i32(a.offset);
  1709. if let Some(d) = a.dynamic {
  1710. let d = self.i32_of(d)?;
  1711. off = self.s.m.bin(c, Bin::Add, off, d);
  1712. }
  1713. let h = if a.param == CODE {
  1714. None
  1715. } else {
  1716. let src = Source::Built {
  1717. address: a,
  1718. bits: 0,
  1719. words: [0, 0],
  1720. };
  1721. if let Some(bias) = self.root_bias(a.param) {
  1722. off = self.s.m.bin(c, Bin::Add, off, bias);
  1723. }
  1724. Some(self.handle((b, i), &src, false, (11, 0))?)
  1725. };
  1726. let dword = |l: &mut Self, byte: V| -> Result<V, Why> {
  1727. match h {
  1728. None => l.code_dword(byte),
  1729. Some(h) => {
  1730. let c = l.cur;
  1731. let (u, mask, al) = (l.s.m.undef(l.s.t.i32), l.s.m.i8(1), l.s.m.i32(4));
  1732. let r = l.s.op(
  1733. c,
  1734. "rawBufferLoad.f32",
  1735. Attr::ReadOnly,
  1736. l.s.t.res_ret,
  1737. 139,
  1738. &[h, byte, u, mask, al],
  1739. );
  1740. let x = l.s.m.extract(c, r, 0);
  1741. Ok(l.as_int(x))
  1742. }
  1743. }
  1744. };
  1745. for k in 0..n {
  1746. let x = match sub {
  1747. None => {
  1748. let four = self.s.m.i32(4 * k);
  1749. let at = self.s.m.bin(c, Bin::Add, off, four);
  1750. dword(self, at)?
  1751. }
  1752. Some((width, signed)) => {
  1753. // shortcut: the field is taken not to cross a dword.
  1754. let (not3, three) = (self.s.m.i32(!3), self.s.m.i32(3));
  1755. let at = self.s.m.bin(c, Bin::And, off, not3);
  1756. let w = dword(self, at)?;
  1757. let byte = self.s.m.bin(c, Bin::And, off, three);
  1758. let sh = self.s.m.bin(c, Bin::Shl, byte, three);
  1759. let x = self.s.m.bin(c, Bin::LShr, w, sh);
  1760. let left = self.s.m.i32(32 - width);
  1761. let x = self.s.m.bin(c, Bin::Shl, x, left);
  1762. self.s
  1763. .m
  1764. .bin(c, if signed { Bin::AShr } else { Bin::LShr }, x, left)
  1765. }
  1766. };
  1767. self.write(inst, Reg::V(reg + k as u8), x, guard);
  1768. }
  1769. Ok(())
  1770. }
  1771. /// Finds the whole-wave sections and the values they leave.
  1772. fn find_sections(&mut self) {
  1773. let p = self.x.p;
  1774. let mut inside: HashMap<Value, (usize, usize, usize)> = HashMap::new();
  1775. for b in 0..p.blocks.len() {
  1776. let found = super::wave::sections(p, b);
  1777. for (&start, sec) in &found {
  1778. for i in start + 1..sec.end {
  1779. for &(_, w) in &p.blocks[b].insts[i].writes {
  1780. inside.insert(w, (b, start, sec.end));
  1781. }
  1782. }
  1783. }
  1784. if !found.is_empty() {
  1785. self.sections.insert(b, found);
  1786. }
  1787. }
  1788. if inside.is_empty() {
  1789. return;
  1790. }
  1791. for (b, block) in p.blocks.iter().enumerate() {
  1792. for phi in &block.phis {
  1793. self.section_out
  1794. .extend(phi.args.iter().filter(|a| inside.contains_key(a)));
  1795. }
  1796. for (i, inst) in block.insts.iter().enumerate() {
  1797. for &(_, r) in &inst.reads {
  1798. if let Some(&(sb, start, end)) = inside.get(&r)
  1799. && !(sb == b && i > start && i < end)
  1800. {
  1801. self.section_out.insert(r);
  1802. }
  1803. }
  1804. }
  1805. }
  1806. }
  1807. /// An instruction inside a whole-wave section: the values that leave
  1808. /// the section are made from what the simulation found them to be.
  1809. fn section_inst(&mut self, b: usize, i: usize, start: usize) {
  1810. const UNKNOWN: Why = "a whole-wave section step the simulation does not follow";
  1811. let inst = &self.x.p.blocks[b].insts[i];
  1812. for &(_, w) in &inst.writes {
  1813. let val = if self.section_out.contains(&w) {
  1814. let shape = self.sections[&b][&start].shapes.get(&w).copied();
  1815. let own = self.own_bits.totals.contains(&w);
  1816. match shape.ok_or(UNKNOWN).and_then(|sh| self.shape(sh, own)) {
  1817. Ok(x) => Val::I32(x),
  1818. Err(why) => Val::Missing(why),
  1819. }
  1820. } else {
  1821. Val::Missing(UNKNOWN)
  1822. };
  1823. self.vals.insert(w, val);
  1824. }
  1825. }
  1826. /// A value a whole-wave section leaves, as DXIL wave operations over the
  1827. /// host's active lanes: the console's result with console lanes; on
  1828. /// another wave size, what the HLSL wave operation the console compiler
  1829. /// expanded gives on that wave.
  1830. ///
  1831. /// `own`: a wave OR that only steers a loop over each lane's own bits
  1832. /// ([`super::own_bits`]); where two host waves cannot exchange their halves' ORs it is
  1833. /// this host wave's.
  1834. fn shape(&mut self, shape: super::wave::Shape, own: bool) -> Result<V, Why> {
  1835. use super::wave::{Op, Shape};
  1836. let (op, src, mask, ident, prefix) = match shape {
  1837. Shape::K(k) => return Ok(self.s.m.i32(k)),
  1838. Shape::Value(v) => return self.i32_of(v),
  1839. Shape::Active(op, src, mask, ident) => (op, src, mask, ident, None),
  1840. Shape::ActiveF64(lo, hi, mask, high) => {
  1841. return self.active_f64_sum(lo, hi, mask, high);
  1842. }
  1843. Shape::Masked(src, mask, ident) => {
  1844. let c = self.cur;
  1845. let &m = self
  1846. .x
  1847. .st
  1848. .masks
  1849. .get(&mask)
  1850. .ok_or("a wave reduction's untracked mask")?;
  1851. let on = self.boolean(m, c)?;
  1852. let x = self.i32_of(src)?;
  1853. let id = self.s.m.i32(ident);
  1854. return Ok(self.s.m.select(c, on, x, id));
  1855. }
  1856. Shape::Prefix(op, src, mask, ident, inclusive) => {
  1857. (op, src, mask, ident, Some(inclusive))
  1858. }
  1859. };
  1860. // Mesh: no host wave size can be declared, so a reduction is over this host wave
  1861. // only. A minimum or maximum is taken that way: the compiler's "next distinct
  1862. // value" loop (the wave's minimum, then the lanes that hold it) serves every
  1863. // lane however the lanes are divided into waves. A sum, a bit reduction or a
  1864. // prefix would be of part of a console wave: still refused.
  1865. if self.mask_data == MaskData::None
  1866. && (prefix.is_some()
  1867. || !matches!(
  1868. op,
  1869. Op::MinU | Op::MaxU | Op::MinI | Op::MaxI | Op::MinF | Op::MaxF
  1870. ))
  1871. {
  1872. return Err("a wave reduction in a mesh shader");
  1873. }
  1874. let c = self.cur;
  1875. let &m = self
  1876. .x
  1877. .st
  1878. .masks
  1879. .get(&mask)
  1880. .ok_or("a wave reduction's untracked mask")?;
  1881. let on = self.boolean(m, c)?;
  1882. let x = self.i32_of(src)?;
  1883. let id = self.s.m.i32(ident);
  1884. let x = self.s.m.select(c, on, x, id);
  1885. self.s.flags |= flags::WAVE_OPS;
  1886. if op == Op::AddH {
  1887. return match prefix {
  1888. Some(_) => Err("a wave prefix of an operation other than a sum"),
  1889. None => self.half_sum(x),
  1890. };
  1891. }
  1892. let float = matches!(op, Op::AddF | Op::MinF | Op::MaxF);
  1893. let (i32t, f32t) = (self.s.t.i32, self.s.t.f32);
  1894. let arg = if float { self.as_float(x) } else { x };
  1895. let ty = if float { f32t } else { i32t };
  1896. let sfx = if float { "f32" } else { "i32" };
  1897. let r = match (op, prefix) {
  1898. (Op::AddU | Op::AddF, Some(inclusive)) => {
  1899. let (k0, k1) = (self.s.m.i8(0), self.s.m.i8(1));
  1900. let r = self.s.op(
  1901. c,
  1902. &format!("wavePrefixOp.{sfx}"),
  1903. Attr::NoUnwind,
  1904. ty,
  1905. 121,
  1906. &[arg, k0, k1],
  1907. );
  1908. if inclusive {
  1909. self.s.m.bin(c, Bin::Add, r, arg)
  1910. } else {
  1911. r
  1912. }
  1913. }
  1914. (_, Some(_)) => return Err("a wave prefix of an operation other than a sum"),
  1915. (Op::Or | Op::And | Op::Xor, None) => {
  1916. let k = self.s.m.i8(match op {
  1917. Op::And => 0,
  1918. Op::Or => 1,
  1919. _ => 2,
  1920. });
  1921. self.s
  1922. .op(c, "waveActiveBit.i32", Attr::NoUnwind, i32t, 120, &[arg, k])
  1923. }
  1924. (_, None) => {
  1925. let (code, unsigned) = match op {
  1926. Op::AddU => (0, 1),
  1927. Op::AddF => (0, 0),
  1928. Op::MinU => (2, 1),
  1929. Op::MaxU => (3, 1),
  1930. Op::MinI | Op::MinF => (2, 0),
  1931. _ => (3, 0),
  1932. };
  1933. let (k, u) = (self.s.m.i8(code), self.s.m.i8(unsigned));
  1934. self.s.op(
  1935. c,
  1936. &format!("waveActiveOp.{sfx}"),
  1937. Attr::NoUnwind,
  1938. ty,
  1939. 119,
  1940. &[arg, k, u],
  1941. )
  1942. }
  1943. };
  1944. // two host waves of 32 hold the console's 64 lanes: their results combine
  1945. let r = if self.local || self.exchange.as_ref().is_some_and(|e| e.1) {
  1946. // this host wave's own result (and prefix): each wave on its own, or a group of
  1947. // 32 threads or fewer, which one host wave holds whole (combining with the 0 a
  1948. // missing half "gives" broke AND, MIN and signed MAX)
  1949. r
  1950. } else if own && prefix.is_none() && op == Op::Or && !self.all_lanes(self.cur_ir) {
  1951. // each thread walks the bits of this value and works only at its own, which the
  1952. // host wave's OR holds: the same run as with the console wave's OR
  1953. r
  1954. } else if self.exchange.is_some() {
  1955. if !self.all_lanes(self.cur_ir) {
  1956. need(self.cur_ir);
  1957. return Err("a wave reduction where not every lane runs");
  1958. }
  1959. let bits = |l: &mut Self, v: V| if float { l.as_int(v) } else { v };
  1960. let back = |l: &mut Self, v: V| if float { l.as_float(v) } else { v };
  1961. match prefix {
  1962. Some(_) => {
  1963. // the upper half adds the lower half's total to its prefix
  1964. let (k0, ku) = (self.s.m.i8(0), self.s.m.i8(u8::from(!float)));
  1965. let total = self.s.op(c, &format!("waveActiveOp.{sfx}"), Attr::NoUnwind, ty, 119, &[arg, k0, ku]);
  1966. let tb = bits(self, total);
  1967. let c = self.cur;
  1968. let (lo, _) = self.exchange_halves(c, tb);
  1969. let lo = back(self, lo);
  1970. let cl = self.console_lane();
  1971. let k32 = self.s.m.i32(32);
  1972. let upper = self.s.m.cmp(c, pred::IUGE, cl, k32);
  1973. let zero = if float { self.s.m.f32(0) } else { self.s.m.i32(0) };
  1974. let add = self.s.m.select(c, upper, lo, zero);
  1975. self.s.m.bin(c, Bin::Add, r, add)
  1976. }
  1977. None => {
  1978. let rb = bits(self, r);
  1979. let c = self.cur;
  1980. let (lo, hi) = self.exchange_halves(c, rb);
  1981. let (lo, hi) = (back(self, lo), back(self, hi));
  1982. match op {
  1983. Op::AddU | Op::AddF => self.s.m.bin(c, Bin::Add, lo, hi),
  1984. Op::Or => self.s.m.bin(c, Bin::Or, lo, hi),
  1985. Op::And => self.s.m.bin(c, Bin::And, lo, hi),
  1986. Op::Xor => self.s.m.bin(c, Bin::Xor, lo, hi),
  1987. _ => {
  1988. // FMax 35, FMin 36, IMax 37, IMin 38, UMax 39, UMin 40
  1989. let code = match op {
  1990. Op::MaxF => 35,
  1991. Op::MinF => 36,
  1992. Op::MinU => 40,
  1993. Op::MaxU => 39,
  1994. Op::MinI => 38,
  1995. _ => 37,
  1996. };
  1997. self.s.op(c, &format!("binary.{sfx}"), Attr::ReadNone, ty, code, &[lo, hi])
  1998. }
  1999. }
  2000. }
  2001. }
  2002. } else {
  2003. r
  2004. };
  2005. Ok(if float { self.as_int(r) } else { r })
  2006. }
  2007. /// `WaveActiveSum` of 64-bit floats (`f64(lo, hi)` in active lanes, `+0.0` elsewhere),
  2008. /// returning the low (`!high`) or high (`high`) 32-bit word.
  2009. fn active_f64_sum(
  2010. &mut self,
  2011. lo: Value,
  2012. hi: Value,
  2013. mask: Value,
  2014. high: bool,
  2015. ) -> Result<V, Why> {
  2016. if self.mask_data == MaskData::None {
  2017. return Err("a wave reduction in a mesh shader");
  2018. }
  2019. let c = self.cur;
  2020. let &m = self
  2021. .x
  2022. .st
  2023. .masks
  2024. .get(&mask)
  2025. .ok_or("a wave reduction's untracked mask")?;
  2026. let on = self.boolean(m, c)?;
  2027. let lo = self.i32_of(lo)?;
  2028. let hi = self.i32_of(hi)?;
  2029. let z = self.s.m.i32(0);
  2030. let lo = self.s.m.select(c, on, lo, z);
  2031. let hi = self.s.m.select(c, on, hi, z);
  2032. self.s.flags |= flags::WAVE_OPS | flags::DOUBLES;
  2033. let f64t = self.s.m.double();
  2034. let i32t = self.s.t.i32;
  2035. let split_ty = self
  2036. .s
  2037. .m
  2038. .named_struct("dx.types.splitdouble", vec![i32t, i32t]);
  2039. let arg = self
  2040. .s
  2041. .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo, hi]);
  2042. let (k0, k0b) = (self.s.m.i8(0), self.s.m.i8(0));
  2043. let sum = self
  2044. .s
  2045. .op(c, "waveActiveOp.f64", Attr::NoUnwind, f64t, 119, &[arg, k0, k0b]);
  2046. let split = self
  2047. .s
  2048. .op(c, "splitDouble.f64", Attr::ReadNone, split_ty, 102, &[sum]);
  2049. let mut r_lo = self.s.m.extract(c, split, 0);
  2050. let mut r_hi = self.s.m.extract(c, split, 1);
  2051. if self.exchange.is_some() {
  2052. if !self.all_lanes(self.cur_ir) {
  2053. need(self.cur_ir);
  2054. return Err("a wave reduction where not every lane runs");
  2055. }
  2056. let (lo0, lo1) = self.exchange_halves(self.cur, r_lo);
  2057. let (hi0, hi1) = self.exchange_halves(self.cur, r_hi);
  2058. let c = self.cur;
  2059. let d0 = self
  2060. .s
  2061. .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo0, hi0]);
  2062. let d1 = self
  2063. .s
  2064. .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo1, hi1]);
  2065. let total = self.s.m.bin(c, Bin::Add, d0, d1);
  2066. let split = self
  2067. .s
  2068. .op(c, "splitDouble.f64", Attr::ReadNone, split_ty, 102, &[total]);
  2069. r_lo = self.s.m.extract(c, split, 0);
  2070. r_hi = self.s.m.extract(c, split, 1);
  2071. }
  2072. Ok(if high { r_hi } else { r_lo })
  2073. }
  2074. /// The sum of two 16-bit floats (the low halves of `a` and `b`) as the console's
  2075. /// `v_add_f16` gives it: added in f32 and rounded to 16 bits, to nearest
  2076. /// ([`Self::f16_nearest`]).
  2077. fn add_halves(&mut self, a: V, b: V) -> V {
  2078. let c = self.cur;
  2079. let f32t = self.s.t.f32;
  2080. let low = self.s.m.i32(0xFFFF);
  2081. let wide = |l: &mut Self, x: V| {
  2082. let h = l.s.m.bin(c, Bin::And, x, low);
  2083. l.s.op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h])
  2084. };
  2085. let (fa, fb) = (wide(self, a), wide(self, b));
  2086. let f = self.s.m.bin(c, Bin::Add, fa, fb);
  2087. self.f16_nearest(f)
  2088. }
  2089. /// `WaveActiveSum` of 16-bit floats (`x`: each lane's term in its low half, +0 in the
  2090. /// lanes outside the mask), bit for bit as the console adds it: every addition rounds to
  2091. /// 16 bits, so the order counts, and the compiler's is the balanced tree over the lanes
  2092. /// in their order (lanes 2k and 2k+1, then pairs, ... then the wave's two halves;
  2093. /// [`super::wave::buddies`]). Each lane adds its partner's partial sum, read from the
  2094. /// lane whose number differs in one bit, step by step; two host waves of 32 then exchange
  2095. /// their halves' sums for the last addition. The high half of the result is lane 0's,
  2096. /// which no `v_add_f16` writes.
  2097. /// On a host wave of 64 lanes where not every lane runs, the lanes that are elsewhere
  2098. /// count as the console's do (it masks them to +0): a partner's partial sum is read from
  2099. /// the first lane there is of the partner's run of lanes, and is +0 without one. Two host
  2100. /// waves of 32 can only exchange where every lane runs: refused elsewhere, in a thread
  2101. /// group that does not fill its waves, and for each half-wave on its own (half a sum is
  2102. /// no sum).
  2103. fn half_sum(&mut self, x: V) -> Result<V, Why> {
  2104. const WHERE: Why = "a wave sum of 16-bit floats where not every lane runs";
  2105. let threads = self.s.threads.ok_or("a wave sum of 16-bit floats outside compute")?;
  2106. if threads.iter().product::<u32>() % 64 != 0 {
  2107. return Err("a wave sum of 16-bit floats in a wave that is not full");
  2108. }
  2109. if self.local {
  2110. return Err("a wave sum of 16-bit floats in a half-wave");
  2111. }
  2112. // two host waves of 32 that exchange, or one host wave of 64 lanes
  2113. let halves = match (&self.exchange, self.s.wave_size) {
  2114. (Some((_, false, _)), _) => true,
  2115. (None, Some(64)) if self.x.p.wave64 => false,
  2116. _ => return Err("a wave sum of 16-bit floats on these waves"),
  2117. };
  2118. let every = if halves {
  2119. self.all_lanes(self.cur_ir)
  2120. } else {
  2121. all_lane_blocks(self.x.st).is_some_and(|all| all.get(self.cur_ir).copied().unwrap_or(false))
  2122. };
  2123. if !every && halves {
  2124. need(self.cur_ir);
  2125. return Err(WHERE);
  2126. }
  2127. let c = self.cur;
  2128. let i32t = self.s.t.i32;
  2129. let lane = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
  2130. let (high, low, zero) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF), self.s.m.i32(0));
  2131. // the lanes that are here, when not all are
  2132. let here = (!every).then(|| {
  2133. self.s.flags |= flags::WAVE_OPS;
  2134. let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]);
  2135. let yes = self.s.m.bool(true);
  2136. let r = self.s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[yes]);
  2137. (self.s.m.extract(c, r, 0), self.s.m.extract(c, r, 1))
  2138. });
  2139. // `v` of the first lane here of the `n` (a power of two) lanes from `base`: +0 of none
  2140. let first_of = |l: &mut Self, v: V, base: V, n: u32| {
  2141. let Some((lo, hi)) = here else {
  2142. return l.read_lane(v, base);
  2143. };
  2144. let (k31, k32) = (l.s.m.i32(31), l.s.m.i32(32));
  2145. let lower = l.s.m.cmp(c, pred::IULT, base, k32);
  2146. let word = l.s.m.select(c, lower, lo, hi);
  2147. let shift = l.s.m.bin(c, Bin::And, base, k31);
  2148. let word = l.s.m.bin(c, Bin::LShr, word, shift);
  2149. let run = l.s.m.i32(u32::MAX >> (32 - n));
  2150. let word = l.s.m.bin(c, Bin::And, word, run);
  2151. let any = l.s.m.cmp(c, pred::NE, word, zero);
  2152. let nth = l.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[word]);
  2153. let from = l.s.m.bin(c, Bin::Add, base, nth);
  2154. // (no lane there: this one, which is here; the read is not used)
  2155. let from = l.s.m.select(c, any, from, lane);
  2156. let got = l.read_lane(v, from);
  2157. l.s.m.select(c, any, got, zero)
  2158. };
  2159. let mut sum = x;
  2160. for step in 0..if halves { 5 } else { 6 } {
  2161. let bit = self.s.m.i32(1 << step);
  2162. let mut partner = self.s.m.bin(c, Bin::Xor, lane, bit);
  2163. if !every {
  2164. let run = self.s.m.i32(!((1 << step) - 1));
  2165. partner = self.s.m.bin(c, Bin::And, partner, run);
  2166. }
  2167. let theirs = first_of(self, sum, partner, 1 << step);
  2168. sum = self.add_halves(sum, theirs);
  2169. }
  2170. let first = first_of(self, x, zero, 1);
  2171. let first = self.s.m.bin(c, Bin::And, first, high);
  2172. let sum = self.s.m.bin(c, Bin::And, sum, low);
  2173. let mine = self.s.m.bin(c, Bin::Or, first, sum);
  2174. if !halves {
  2175. return Ok(mine);
  2176. }
  2177. let (lo, hi) = self.exchange_halves(c, mine);
  2178. let c = self.cur;
  2179. let total = self.add_halves(lo, hi);
  2180. let total = self.s.m.bin(c, Bin::And, total, low);
  2181. let first = self.s.m.bin(c, Bin::And, lo, high);
  2182. Ok(self.s.m.bin(c, Bin::Or, first, total))
  2183. }
  2184. fn run(mut self) -> Result<Lowered, Stop> {
  2185. let p = self.x.p;
  2186. self.find_coherent();
  2187. let order = crate::ir::reverse_postorder(&p.blocks);
  2188. for (n, &b) in order.iter().enumerate() {
  2189. self.rpo[b] = n;
  2190. }
  2191. for (n, &b) in order.iter().enumerate() {
  2192. self.block[b] = Some(if n == 0 {
  2193. self.s.entry
  2194. } else {
  2195. self.s.m.new_block()
  2196. });
  2197. }
  2198. // Loop headers count iterations (`LOOP_LIMIT`).
  2199. for &b in &order {
  2200. let header = p.blocks[b]
  2201. .preds
  2202. .iter()
  2203. .any(|&q| self.block[q].is_some() && self.rpo[b] <= self.rpo[q]);
  2204. if header {
  2205. let blk = self.block[b].expect("reachable");
  2206. let phi = self.s.m.phi(blk, self.s.t.i32);
  2207. self.counters.insert(b, (phi, Vec::new()));
  2208. }
  2209. }
  2210. self.cur = self.s.entry;
  2211. self.find_sections();
  2212. self.inputs()?;
  2213. if let Some(mesh) = self.s.mesh {
  2214. self.mesh_prologue(mesh).map_err(|w| unsupported(0, w))?;
  2215. self.block[order[0]] = Some(self.cur);
  2216. }
  2217. for &b in &order {
  2218. self.cur = self.block[b].expect("reachable");
  2219. self.cur_ir = b;
  2220. let preds: Vec<usize> = p.blocks[b]
  2221. .preds
  2222. .iter()
  2223. .copied()
  2224. .filter(|&q| self.block[q].is_some())
  2225. .collect();
  2226. self.exported[b] = !preds.is_empty() && preds.iter().all(|&q| self.exported_out(q));
  2227. for (i, phi) in p.blocks[b].phis.iter().enumerate() {
  2228. let val = match phi.reg {
  2229. Reg::S(c) if c == EXEC || c == EXEC + 1 => Val::Missing("a lane mask"),
  2230. _ if self.bad.contains_key(&phi.value) => Val::Missing(self.bad[&phi.value]),
  2231. Reg::Scc => {
  2232. let v = self.s.m.phi(self.cur, self.s.t.i1);
  2233. self.data_phis.push((v, b, i));
  2234. Val::Bit(v)
  2235. }
  2236. _ => {
  2237. let v = self.s.m.phi(self.cur, self.s.t.i32);
  2238. self.data_phis.push((v, b, i));
  2239. Val::I32(v)
  2240. }
  2241. };
  2242. self.vals.insert(phi.value, val);
  2243. }
  2244. if self.lds_meet.as_ref().is_some_and(|(_, meet)| meet[b].0) {
  2245. self.lds_meeting();
  2246. }
  2247. let mut i = 0;
  2248. while i < p.blocks[b].insts.len() {
  2249. self.inst(b, i)?;
  2250. if let Some(end) = self.sections.get(&b).and_then(|s| s.get(&i)).map(|s| s.end) {
  2251. for j in i + 1..end {
  2252. self.section_inst(b, j, i);
  2253. }
  2254. i = end;
  2255. continue;
  2256. }
  2257. i += 1;
  2258. }
  2259. self.mask_ok = self.mask_data == MaskData::Console;
  2260. if self.lds_meet.as_ref().is_some_and(|(_, meet)| meet[b].1) {
  2261. self.lds_meeting();
  2262. }
  2263. self.tail[b] = Some(self.cur);
  2264. self.exit(b)?;
  2265. }
  2266. self.fill_phis()?;
  2267. let user_data = self.user_reads.values().copied().collect();
  2268. self.s.samplers = self.samplers.len() as u32;
  2269. let root_cbvs = self.s.root_cbvs.iter().map(|r| r.0).collect();
  2270. let root_srvs = self.s.root_srvs.iter().map(|r| r.0).collect();
  2271. let root_uavs = self.s.root_uavs.iter().map(|r| r.0).collect();
  2272. let cmp_samplers = self.s.cmp_samplers;
  2273. let wave_size = self.s.wave_size;
  2274. Ok(Lowered {
  2275. wave_size,
  2276. cmp_samplers,
  2277. root_cbvs,
  2278. root_srvs,
  2279. root_uavs,
  2280. #[cfg(test)]
  2281. nonuniform_handles: self.s.nonuniform_handles,
  2282. #[cfg(test)]
  2283. wave_ops: self.s.flags & flags::WAVE_OPS != 0,
  2284. dxil: self.s.finish(),
  2285. user_data,
  2286. samplers: self.samplers,
  2287. })
  2288. }
  2289. fn exported_out(&self, b: usize) -> bool {
  2290. self.exported[b] || self.has_done_export(b)
  2291. }
  2292. fn has_done_export(&self, b: usize) -> bool {
  2293. (0..self.x.p.blocks[b].insts.len())
  2294. .any(|i| self.exports.get(&(b, i)).is_some_and(|e| e.done))
  2295. }
  2296. /// Values of the program's input registers.
  2297. fn inputs(&mut self) -> Result<(), Stop> {
  2298. let io_inputs: HashMap<Value, Input> = self.x.io.inputs.iter().copied().collect();
  2299. for &(reg, v) in &self.x.p.inputs {
  2300. let val = match reg {
  2301. Reg::S(_) if self.params.contains_key(&v) => continue, // loaded on first use
  2302. // Most programs only interpolate with them: loaded on first
  2303. // use as a value (`get`).
  2304. Reg::V(_) if matches!(io_inputs.get(&v), Some(Input::Barycentric { .. })) => {
  2305. continue;
  2306. }
  2307. Reg::S(n) => match io_inputs.get(&v) {
  2308. Some(&input) => self.input(input),
  2309. // Above the SGPRs the hardware initializes, a register
  2310. // holds what the last wave left, so no program depends
  2311. // on it: a read the paths only seem to allow (a branch
  2312. // past the write, taken only with one past the read)
  2313. // reads zero, as VGPRs do.
  2314. None if n <= 105 && self.x.io.initialized_sgprs.is_some_and(|k| n >= k) => {
  2315. Val::I32(self.s.m.i32(0))
  2316. }
  2317. // A scalar parked in a VGPR lane (`ir::unspill`), read where the
  2318. // paths only seem to allow it before any save: the lane of a VGPR
  2319. // nobody wrote, and VGPRs nobody set read as zero.
  2320. None if n >= crate::ir::PARKED => Val::I32(self.s.m.i32(0)),
  2321. // No wave overlaps this one (see `ordered_section`).
  2322. None if self.pops_collision(v) => Val::I32(self.s.m.i32(0)),
  2323. None => Val::Missing("a hardware SGPR input"),
  2324. },
  2325. Reg::Scc => Val::Missing("SCC on entry"),
  2326. Reg::V(_) => match io_inputs.get(&v) {
  2327. Some(&input) => self.input(input),
  2328. // Registers no one set read as zero (the validator
  2329. // refuses reads of undef).
  2330. None => Val::I32(self.s.m.i32(0)),
  2331. },
  2332. };
  2333. self.vals.insert(v, val);
  2334. }
  2335. Ok(())
  2336. }
  2337. /// Whether the input SGPR `v` is the POPS collision wave id: a program
  2338. /// with an ordered section only takes its fields apart (bit 31 says
  2339. /// that the wave overlaps another, the others which packer and waves).
  2340. fn pops_collision(&self, v: Value) -> bool {
  2341. if self.ordered.is_empty() {
  2342. return false;
  2343. }
  2344. let mut packer = false;
  2345. for block in &self.x.p.blocks {
  2346. if block.phis.iter().any(|p| p.args.contains(&v)) {
  2347. return false;
  2348. }
  2349. for i in &block.insts {
  2350. if !i.reads.iter().any(|r| r.1 == v) {
  2351. continue;
  2352. }
  2353. let Fields::Sop { src, .. } = &i.fields else {
  2354. return false;
  2355. };
  2356. match (i.name(), src.get(1)) {
  2357. // bits 28 and 29: the packer
  2358. ("s_bfe_u32", Some(Operand::Literal(0x0002_001C))) => packer = true,
  2359. ("s_bfe_u32" | "s_lshr_b32", _) => {}
  2360. _ => return false,
  2361. }
  2362. }
  2363. }
  2364. packer
  2365. }
  2366. fn input(&mut self, input: Input) -> Val {
  2367. let (kind, col) = match input {
  2368. Input::VertexId => (1, 0),
  2369. Input::InstanceId => (2, 0),
  2370. Input::Position(c) => (3, c),
  2371. Input::Attribute { row, channel } => {
  2372. return match self.find_input(row, channel) {
  2373. Some((id, col)) => self.load_input(id, col),
  2374. None => Val::Missing("a vertex input the signature lacks"),
  2375. };
  2376. }
  2377. Input::Barycentric { kind, index } => return self.barycentric(kind, index),
  2378. Input::PrimitiveId => return Val::Missing("the primitive id"),
  2379. // The console code tests it against 0 (`v_cmp_ne_u32`), as the
  2380. // host's value can be.
  2381. Input::FrontFace => (13, 0),
  2382. Input::ThreadIdInGroup(c) => return self.thread_id(c),
  2383. Input::GroupId(c) => return self.compute_id("groupId.i32", 94, c),
  2384. Input::GroupInfo => return Val::Missing("the thread-group info SGPR"),
  2385. Input::MeshGroup => {
  2386. let Val::I32(g) = self.compute_id("groupId.i32", 94, 0) else {
  2387. unreachable!()
  2388. };
  2389. let n = self.s.m.i32(self.x.mesh_stride);
  2390. return Val::I32(self.s.m.bin(self.s.entry, Bin::Mul, g, n));
  2391. }
  2392. Input::MergedWaveInfo => {
  2393. // shortcut: only the wave index (bits 24-27) is set; the
  2394. // console's other bits (lane counts) are read by no program.
  2395. let f = self.mesh_thread();
  2396. let shift = self.s.m.i32(self.wave().trailing_zeros());
  2397. let w = self.s.m.bin(self.s.entry, Bin::LShr, f, shift);
  2398. let k24 = self.s.m.i32(24);
  2399. return Val::I32(self.s.m.bin(self.s.entry, Bin::Shl, w, k24));
  2400. }
  2401. _ => return Val::Missing("a pixel system input"),
  2402. };
  2403. let free = self
  2404. .s
  2405. .inputs
  2406. .iter()
  2407. .filter_map(|e| e.row)
  2408. .map(|r| r + 1)
  2409. .max()
  2410. .unwrap_or(0);
  2411. let id = match self.s.inputs.iter().position(|e| e.kind == kind) {
  2412. Some(id) => {
  2413. if kind != 3 {
  2414. self.s.inputs[id].row.get_or_insert(free);
  2415. }
  2416. id
  2417. }
  2418. None if kind >= 3 => return Val::Missing("a pixel system input the signature lacks"),
  2419. None => {
  2420. // The console signature leaves out vertex and instance ids; PC
  2421. // gives them a row after the others.
  2422. let row = self
  2423. .s
  2424. .inputs
  2425. .iter()
  2426. .filter_map(|e| e.row)
  2427. .map(|r| r + 1)
  2428. .max()
  2429. .unwrap_or(0);
  2430. self.s.inputs.push(SigElement {
  2431. name: ["", "SV_VertexID", "SV_InstanceID"][kind as usize].into(),
  2432. index: 0,
  2433. kind,
  2434. comp: 5,
  2435. interp: 0,
  2436. row: Some(row),
  2437. col: 0,
  2438. cols: 1,
  2439. usage: 0,
  2440. half: false,
  2441. });
  2442. self.s.inputs.len() - 1
  2443. }
  2444. };
  2445. self.load_input(id, col)
  2446. }
  2447. /// A component of a compute thread or group id, read in the entry block.
  2448. fn compute_id(&mut self, name: &str, opcode: u32, c: u8) -> Val {
  2449. let (entry, c) = (self.s.entry, self.s.m.i32(u32::from(c)));
  2450. Val::I32(
  2451. self.s
  2452. .op(entry, name, Attr::ReadNone, self.s.t.i32, opcode, &[c]),
  2453. )
  2454. }
  2455. fn find_input(&self, row: u8, channel: u8) -> Option<(usize, u8)> {
  2456. self.s.inputs.iter().enumerate().find_map(|(id, e)| {
  2457. let r = e.row?;
  2458. // `then`, not `then_some`: the channel is only past `col` when
  2459. // the condition holds.
  2460. (r == u32::from(row) && channel >= e.col && channel < e.col + e.cols)
  2461. .then(|| (id, channel - e.col))
  2462. })
  2463. }
  2464. fn load_input(&mut self, id: usize, col: u8) -> Val {
  2465. if self.s.inputs[id].half {
  2466. // shortcut: 16-bit vertex inputs (the fetch routine's) are not
  2467. // unpacked; pixel inputs are (`interp`).
  2468. return Val::Missing("a 16-bit input");
  2469. }
  2470. self.load_any_input(id, col)
  2471. }
  2472. /// An input element's channel as declared (16-bit ones as 32-bit floats).
  2473. fn load_any_input(&mut self, id: usize, col: u8) -> Val {
  2474. let e = &mut self.s.inputs[id];
  2475. e.usage |= 1 << col;
  2476. let (int, bit) = (e.comp != 9, e.comp == 1);
  2477. let ty = if bit {
  2478. self.s.t.i1
  2479. } else if int {
  2480. self.s.t.i32
  2481. } else {
  2482. self.s.t.f32
  2483. };
  2484. let suffix = if bit {
  2485. ".i1"
  2486. } else if int {
  2487. ".i32"
  2488. } else {
  2489. ".f32"
  2490. };
  2491. let entry = self.s.entry;
  2492. let args = [
  2493. self.s.m.i32(id as u32),
  2494. self.s.m.i32(0),
  2495. self.s.m.i8(col),
  2496. self.s.m.undef(self.s.t.i32),
  2497. ];
  2498. let v = self.s.op(
  2499. entry,
  2500. &format!("loadInput{suffix}"),
  2501. Attr::ReadNone,
  2502. ty,
  2503. 4,
  2504. &args,
  2505. );
  2506. if bit {
  2507. let z = self.s.m.cast(entry, Cast::ZExt, v, self.s.t.i32);
  2508. Val::I32(z)
  2509. } else if int {
  2510. Val::I32(v)
  2511. } else {
  2512. Val::I32(self.s.m.cast(entry, Cast::Bitcast, v, self.s.t.i32))
  2513. }
  2514. }
  2515. /// The DXIL form of an IR value.
  2516. fn get(&mut self, v: Value) -> Result<Val, Why> {
  2517. if self.phi_at.contains_key(&v) {
  2518. self.read_phis.insert(v);
  2519. }
  2520. let is_mask = self.x.st.masks.contains_key(&v) || self.x.st.highs.contains_key(&v);
  2521. match self.vals.get(&v) {
  2522. Some(&Val::Missing(_)) | None if self.mask_ok && is_mask => {
  2523. return self.mask_dword(v).map(Val::I32);
  2524. }
  2525. Some(&Val::Missing(w)) => return Err(w),
  2526. Some(&val) => return Ok(val),
  2527. None => {}
  2528. }
  2529. if let Some(&(param, dword)) = self.params.get(&v) {
  2530. let val = self.user(param, dword);
  2531. self.vals.insert(v, val);
  2532. return Ok(val);
  2533. }
  2534. if let Some(loaded) = self.lazy_barycentric(v) {
  2535. loaded?;
  2536. return Ok(self.vals[&v]);
  2537. }
  2538. Err("a value defined after its use")
  2539. }
  2540. /// Loads `v` if it is a barycentric input VGPR not loaded yet (see
  2541. /// `inputs`): `None` if it is not one.
  2542. fn lazy_barycentric(&mut self, v: Value) -> Option<Result<(), Why>> {
  2543. let (kind, index) = self.x.io.inputs.iter().find_map(|&(w, i)| match i {
  2544. Input::Barycentric { kind, index } if w == v => Some((kind, index)),
  2545. _ => None,
  2546. })?;
  2547. let val = self.barycentric(kind, index);
  2548. self.vals.insert(v, val);
  2549. Some(match val {
  2550. Val::Missing(w) => Err(w),
  2551. _ => Ok(()),
  2552. })
  2553. }
  2554. /// Barycentric `index` (0 i, 1 j) of `kind` as a value: a channel of
  2555. /// `SV_Barycentrics` declared with the same interpolation mode.
  2556. ///
  2557. /// GFX10 interpolates P0 + i (P1 - P0) + j (P2 - P0), so i and j are
  2558. /// the weights of vertices 1 and 2. The host's weights (x, y, z) are
  2559. /// those of vertices 0, 1 and 2, vertex 0 being the provoking vertex,
  2560. /// which is the console's P0 (`v_interp_mov` P0 is lowered to a flat
  2561. /// input): i is y and j is z.
  2562. /// shortcut: triangles only; on lines and points the console's i and j
  2563. /// are not checked against the host's weights.
  2564. fn barycentric(&mut self, kind: Barycentric, index: u8) -> Val {
  2565. let Some(mode) = interp_mode(kind) else {
  2566. return Val::Missing("pull-model barycentrics");
  2567. };
  2568. if index > 1 {
  2569. return Val::Missing("pull-model barycentrics");
  2570. }
  2571. // One element per interpolation mode (the console's own, if its
  2572. // signature declares one): DXIL allows two.
  2573. let bary = |e: &SigElement| e.kind == 28;
  2574. let id = match self
  2575. .s
  2576. .inputs
  2577. .iter()
  2578. .position(|e| bary(e) && (e.interp == mode || e.usage == 0))
  2579. {
  2580. Some(id) => id,
  2581. None => {
  2582. let index = self.s.inputs.iter().filter(|e| bary(e)).count() as u32;
  2583. if index >= 2 {
  2584. return Val::Missing("barycentrics of a third interpolation mode");
  2585. }
  2586. // A system value the validator wants unpacked (packing
  2587. // location -1), like other non-packed system values.
  2588. self.s.inputs.push(SigElement {
  2589. name: "SV_Barycentrics".into(),
  2590. index,
  2591. kind: 28,
  2592. comp: 9,
  2593. interp: mode,
  2594. row: None,
  2595. col: 0,
  2596. cols: 3,
  2597. usage: 0,
  2598. half: false,
  2599. });
  2600. self.s.inputs.len() - 1
  2601. }
  2602. };
  2603. let e = &mut self.s.inputs[id];
  2604. if e.col != 0 || e.cols < 3 {
  2605. return Val::Missing("a console barycentrics element without i and j");
  2606. }
  2607. e.row = None;
  2608. e.interp = mode;
  2609. self.s.flags |= flags::BARYCENTRICS;
  2610. self.load_any_input(id, index + 1)
  2611. }
  2612. fn i32_of(&mut self, v: Value) -> Result<V, Why> {
  2613. match self.get(v)? {
  2614. Val::I32(x) => Ok(x),
  2615. Val::Bit(x) => Ok(self.s.m.cast(self.cur, Cast::ZExt, x, self.s.t.i32)),
  2616. Val::Missing(w) => Err(w),
  2617. }
  2618. }
  2619. /// A user-data dword: a root parameter's value.
  2620. fn user(&mut self, param: usize, dword: u32) -> Val {
  2621. let rp = self.x.native.layout[param];
  2622. match rp.root {
  2623. RootType::ResourceHeap | RootType::SamplerHeap => return Val::I32(self.s.m.i32(0)),
  2624. RootType::Constants | RootType::Table => {}
  2625. _ => return Val::Missing("a root descriptor"),
  2626. }
  2627. let index = u32::from(rp.user_data) + dword - self.user_first();
  2628. self.user_reads.insert(
  2629. index,
  2630. UserData {
  2631. index,
  2632. slot: rp.slot,
  2633. root: rp.root,
  2634. dword,
  2635. },
  2636. );
  2637. Val::I32(self.user_at(index))
  2638. }
  2639. /// The user-data index that is dword 0 of the host's user data: 0, or
  2640. /// 16 for a program with a spilled user-data table, whose parameters
  2641. /// all sit at 16 and above. (The host's root signature has 64 dwords:
  2642. /// a builder stage with constants up to index 45, eight root views,
  2643. /// their biases and the memory directory would not fit with 16 dwords
  2644. /// nothing reads in front.)
  2645. fn user_first(&self) -> u32 {
  2646. if crate::spill::is_spilled(self.x.native) {
  2647. 16
  2648. } else {
  2649. 0
  2650. }
  2651. }
  2652. /// A user-data dword no register of the console's holds: one the host
  2653. /// computes when it binds (`root` says what, an `Other` code of
  2654. /// `shader.rs`), placed after the layout's own dwords.
  2655. fn host_word(&mut self, root: RootType, slot: u8, dword: u32) -> V {
  2656. let known = self
  2657. .user_reads
  2658. .values()
  2659. .find(|u| u.root == root && u.slot == slot && u.dword == dword)
  2660. .map(|u| u.index);
  2661. let index = match known {
  2662. Some(index) => index,
  2663. None => {
  2664. let first = self.user_first();
  2665. let layout = &self.x.native.layout;
  2666. let mut index = layout
  2667. .iter()
  2668. .map(|e| u32::from(e.user_data) + e.sgprs)
  2669. .max()
  2670. .unwrap_or(0)
  2671. .saturating_sub(first);
  2672. while self.user_reads.contains_key(&index) {
  2673. index += 1;
  2674. }
  2675. self.user_reads.insert(
  2676. index,
  2677. UserData {
  2678. index,
  2679. slot,
  2680. root,
  2681. dword,
  2682. },
  2683. );
  2684. index
  2685. }
  2686. };
  2687. self.user_at(index)
  2688. }
  2689. /// User-data dword `index`, loaded in the entry block.
  2690. fn user_at(&mut self, index: u32) -> V {
  2691. self.s.user_data = self.s.user_data.max(index + 1);
  2692. let h = match self.user_data {
  2693. Some(h) => h,
  2694. None => {
  2695. let h = self.s.user_data_handle();
  2696. self.user_data = Some(h);
  2697. h
  2698. }
  2699. };
  2700. let entry = self.s.entry;
  2701. let row = self.s.m.i32(index / 4);
  2702. let r = self.s.op(
  2703. entry,
  2704. "cbufferLoadLegacy.i32",
  2705. Attr::ReadOnly,
  2706. self.s.t.cbuf_ret,
  2707. 59,
  2708. &[h, row],
  2709. );
  2710. self.s.m.extract(entry, r, index % 4)
  2711. }
  2712. /// Whether some instruction reads `v` as a number (or may, through a
  2713. /// join), rather than in a descriptor operand.
  2714. fn read_as_number(&self, v: Value) -> bool {
  2715. self.x.p.blocks.iter().any(|b| {
  2716. b.phis.iter().any(|p| p.args.contains(&v))
  2717. || b.insts.iter().any(|i| {
  2718. matches!(i.fields, Fields::Sop { .. } | Fields::Valu(_))
  2719. && i.reads.iter().any(|r| r.1 == v)
  2720. })
  2721. })
  2722. }
  2723. /// Whether some instruction computes with `v` (scalar or vector
  2724. /// arithmetic), rather than only naming it in a descriptor operand,
  2725. /// moving it (at most `depth` moves are followed) or comparing it: a
  2726. /// waterfall loop keeps a descriptor's dwords per lane, reads the first
  2727. /// lane's back and compares the lanes' with them.
  2728. fn computed_with(&self, v: Value, depth: u32) -> bool {
  2729. self.x.p.blocks.iter().flat_map(|b| &b.insts).any(|i| {
  2730. if !i.reads.iter().any(|r| r.1 == v) {
  2731. return false;
  2732. }
  2733. let name = i.name();
  2734. let moves = matches!(
  2735. name,
  2736. "s_mov_b32"
  2737. | "s_mov_b64"
  2738. | "v_mov_b32"
  2739. | "v_readfirstlane_b32"
  2740. | "v_readlane_b32"
  2741. | "v_writelane_b32"
  2742. | "v_cndmask_b32"
  2743. );
  2744. match &i.fields {
  2745. Fields::Sop { .. } | Fields::Valu(_) if moves => {
  2746. depth > 0 && i.writes.iter().any(|w| self.computed_with(w.1, depth - 1))
  2747. }
  2748. Fields::Sop { .. } | Fields::Valu(_) => {
  2749. !(name.starts_with("v_cmp") || name.starts_with("s_cmp"))
  2750. }
  2751. _ => false,
  2752. }
  2753. })
  2754. }
  2755. /// Whether the image `src` names is one of 32-bit integers (one channel):
  2756. /// the program has an integer atomic on the same table entry, which
  2757. /// takes no other view.
  2758. fn is_counter(&self, src: &Source) -> bool {
  2759. let Some(this) = self.entry(src) else {
  2760. return false;
  2761. };
  2762. self.x.res.descriptors.iter().any(|d| {
  2763. let i = &self.x.p.blocks[d.site.0].insts[d.site.1];
  2764. d.role == Role::Resource
  2765. && matches!(i.fields, Fields::Image { dmask: 1, .. })
  2766. && matches!(
  2767. i.name(),
  2768. "image_atomic_add"
  2769. | "image_atomic_sub"
  2770. | "image_atomic_and"
  2771. | "image_atomic_or"
  2772. | "image_atomic_xor"
  2773. | "image_atomic_smin"
  2774. | "image_atomic_smax"
  2775. | "image_atomic_umin"
  2776. | "image_atomic_umax"
  2777. )
  2778. && self.entry(&d.source) == Some(this)
  2779. })
  2780. }
  2781. /// Which table entry `src` is loaded from: its root parameter and byte.
  2782. fn entry(&self, src: &Source) -> Option<(usize, u32)> {
  2783. let Source::Loaded { load, first } = src else {
  2784. return None;
  2785. };
  2786. let a = self.scalar.get(load).filter(|a| a.dynamic.is_none())?;
  2787. Some((a.param, a.offset + 4 * u32::from(*first)))
  2788. }
  2789. /// See [`Lower::coherent`].
  2790. fn find_coherent(&mut self) {
  2791. let found: Vec<_> = self
  2792. .x
  2793. .res
  2794. .descriptors
  2795. .iter()
  2796. .filter(|d| {
  2797. let i = &self.x.p.blocks[d.site.0].insts[d.site.1];
  2798. matches!(&i.fields, Fields::Buffer { cache, .. } if cache.glc)
  2799. && i.name().starts_with("buffer_load_dword")
  2800. && self.used_kind(&d.source).is_some_and(|u| u.kind == ResourceType::Uav)
  2801. })
  2802. .filter_map(|d| self.entry(&d.source))
  2803. .collect();
  2804. self.coherent.extend(found);
  2805. }
  2806. /// The kind of a view no instruction uses (in this program, or through
  2807. /// another load of its address), by what the code reads of the
  2808. /// descriptor the load `inst` at `site` writes to the SGPRs from `code`:
  2809. /// `Some(true)` for a 2D image, read only for its size, `Some(false)`
  2810. /// for a structured buffer, read only for its record count.
  2811. ///
  2812. /// - Eight dwords are an image's. `GetDimensions` of a 2D one reads the
  2813. /// width (dwords 1 and 2), the height (dword 2, bits 14-29, with one
  2814. /// `s_bfe_u32`) and the base level or the last (dword 3); of an array,
  2815. /// a cube or a volume also dword 4.
  2816. /// - Four dwords at a table entry the used resources list as an SRV or
  2817. /// UAV are a buffer's. A stride above 4 bytes there is an element's
  2818. /// (a typed or raw view has at most 4): a test for a null view reads
  2819. /// the record count, nothing else.
  2820. fn sized_view(&self, inst: &Inst, site: Site, code: u8, count: u32) -> Option<bool> {
  2821. let dword = |k: u8| inst.write(Reg::S(code + k));
  2822. let read = |v: Value| {
  2823. self.x.p.blocks.iter().any(|b| {
  2824. b.insts.iter().any(|i| i.reads.iter().any(|r| r.1 == v))
  2825. || b.phis.iter().any(|p| p.args.contains(&v))
  2826. })
  2827. };
  2828. let only = |allowed: &[u8]| {
  2829. (0..count as u8).all(|k| allowed.contains(&k) || !dword(k).is_some_and(read))
  2830. };
  2831. match count {
  2832. 8 => {
  2833. const HEIGHT: u32 = 16 << 16 | 14;
  2834. let v = dword(2)?;
  2835. let height = self.x.p.blocks.iter().flat_map(|b| &b.insts).any(|i| {
  2836. i.name() == "s_bfe_u32"
  2837. && i.reads.iter().any(|r| r.1 == v)
  2838. && matches!(&i.fields, Fields::Sop { src, .. }
  2839. if matches!(src.get(1), Some(Operand::Literal(HEIGHT))))
  2840. });
  2841. (height && only(&[1, 2, 3])).then_some(true)
  2842. }
  2843. 4 => {
  2844. let used = self.used_kind(&Source::Loaded { load: site, first: 0 })?;
  2845. let a = self.scalar.get(&site)?;
  2846. let buffer = used.dwords == 4
  2847. && a.dynamic.is_none()
  2848. && used.table_offset_dwords == a.offset / 4
  2849. && matches!(used.kind, ResourceType::Srv | ResourceType::Uav)
  2850. && used.stride > 4
  2851. && used.stride.is_multiple_of(4);
  2852. (buffer && only(&[2])).then_some(false)
  2853. }
  2854. _ => None,
  2855. }
  2856. }
  2857. /// The title address (low dword, bits from 32 up) of the buffer view
  2858. /// whose descriptor the scalar load at `site` reads from the start of
  2859. /// a table entry, as the host tells it when it binds (`shader.rs`
  2860. /// `USER_VIEW_ADDRESS`); none for anything else. (The console's
  2861. /// descriptor holds more in the second dword, the stride from bit 16
  2862. /// up; code that takes the address masks those away.)
  2863. fn view_address(&mut self, site: Site) -> Option<(V, V)> {
  2864. use super::shader::USER_VIEW_ADDRESS;
  2865. let a = self.scalar.get(&site).copied()?;
  2866. let rp = *self.x.native.layout.get(a.param)?;
  2867. if rp.root != RootType::Table || a.dynamic.is_some() || a.offset % 32 != 0 {
  2868. return None;
  2869. }
  2870. let dword = a.offset / 4;
  2871. let used = self
  2872. .x
  2873. .native
  2874. .used
  2875. .iter()
  2876. .filter(|u| {
  2877. u.root == RootType::Table
  2878. && u.user_data == rp.user_data
  2879. && u.table_offset_dwords <= dword
  2880. })
  2881. .max_by_key(|u| u.table_offset_dwords)?;
  2882. if used.dwords != 4 || !matches!(used.kind, ResourceType::Srv | ResourceType::Uav) {
  2883. return None;
  2884. }
  2885. let lo = self.host_word(RootType::Other(USER_VIEW_ADDRESS), rp.slot, dword);
  2886. let hi = self.host_word(RootType::Other(USER_VIEW_ADDRESS + 1), rp.slot, dword);
  2887. Some((lo, hi))
  2888. }
  2889. /// `lo`, `hi` plus the instruction's byte offset `off`, with the carry.
  2890. fn address_plus(&mut self, lo: V, hi: V, off: i32) -> (V, V) {
  2891. if off == 0 {
  2892. return (lo, hi);
  2893. }
  2894. let c = self.cur;
  2895. let i32t = self.s.t.i32;
  2896. let k = self.s.m.i32(off as u32);
  2897. let sum = self.s.m.bin(c, Bin::Add, lo, k);
  2898. // Up: a carry when the sum wrapped below `lo`. Down: a borrow when
  2899. // it wrapped above.
  2900. let wrapped = self
  2901. .s
  2902. .m
  2903. .cmp(c, if off > 0 { pred::IULT } else { pred::IUGT }, sum, lo);
  2904. let one = self.s.m.cast(c, Cast::ZExt, wrapped, i32t);
  2905. let hi = self.s.m.bin(c, if off > 0 { Bin::Add } else { Bin::Sub }, hi, one);
  2906. (sum, hi)
  2907. }
  2908. /// Title memory at the 40-bit address `lo`, `hi` (`shader.rs`
  2909. /// `SLOT_MEMORY`): the handle of the raw view of the host copy holding
  2910. /// it and the byte in that view. A page without a copy reads zeros
  2911. /// (and drops writes) through the null view at the first slot, and its
  2912. /// number is left for the host, for lanes that run (`guard`).
  2913. fn memory(&mut self, lo: V, hi: V, guard: Option<V>) -> (V, V) {
  2914. use super::shader::{MEMORY_FAULTS, MEMORY_PAGES, SLOT_FAULTS, SLOT_MEMORY, USER_MEMORY_BASE};
  2915. let c = self.cur;
  2916. let (i32t, res) = (self.s.t.i32, self.s.t.res_ret);
  2917. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  2918. let (k16, k8) = (k(self, 16), k(self, 0xFF));
  2919. let low = self.s.m.bin(c, Bin::LShr, lo, k16);
  2920. let high = self.s.m.bin(c, Bin::And, hi, k8);
  2921. let high = self.s.m.bin(c, Bin::Shl, high, k16);
  2922. let page = self.s.m.bin(c, Bin::Or, low, high);
  2923. // Inside the directory whatever the address (lanes that do not run
  2924. // compute one too); its last entry is never filled.
  2925. let last = k(self, MEMORY_PAGES - 1);
  2926. let page = self
  2927. .s
  2928. .op(c, "binary.i32", Attr::ReadNone, i32t, 40, &[page, last]);
  2929. self.s.m.tag(page, Tag::Clamp);
  2930. let k3 = k(self, 3);
  2931. let at = self.s.m.bin(c, Bin::Shl, page, k3);
  2932. let directory = self.s.root_srv_handle(SLOT_MEMORY);
  2933. let (iu, both, align) = (self.s.m.undef(i32t), self.s.m.i8(3), k(self, 4));
  2934. let entry = self.s.op(
  2935. c,
  2936. "rawBufferLoad.f32",
  2937. Attr::ReadOnly,
  2938. res,
  2939. 139,
  2940. &[directory, at, iu, both, align],
  2941. );
  2942. let (copy, start) = (self.s.m.extract(c, entry, 0), self.s.m.extract(c, entry, 1));
  2943. let (copy, start) = (self.as_int(copy), self.as_int(start));
  2944. // A page without a copy: its number, at a place by the number, or
  2945. // at the sink for lanes that do not run and pages that have one.
  2946. let zero = k(self, 0);
  2947. let mut missing = self.s.m.cmp(c, pred::EQ, copy, zero);
  2948. if let Some(g) = guard {
  2949. missing = self.s.m.bin(c, Bin::And, missing, g);
  2950. }
  2951. let places = k(self, MEMORY_FAULTS - 1);
  2952. let place = self.s.m.bin(c, Bin::URem, page, places);
  2953. let one = k(self, 1);
  2954. let place = self.s.m.bin(c, Bin::Add, place, one);
  2955. let k2 = k(self, 2);
  2956. let place = self.s.m.bin(c, Bin::Shl, place, k2);
  2957. let place = self.s.m.select(c, missing, place, zero);
  2958. let faults = self.s.root_uav_handle(SLOT_FAULTS);
  2959. let void = self.s.t.void;
  2960. let mask = self.s.m.i8(1);
  2961. self.s.op(
  2962. c,
  2963. "rawBufferStore.i32",
  2964. Attr::NoUnwind,
  2965. void,
  2966. 140,
  2967. &[faults, place, iu, page, iu, iu, iu, mask, align],
  2968. );
  2969. let base = self.host_word(RootType::Other(USER_MEMORY_BASE), 0, 0);
  2970. let slot = self.s.m.bin(c, Bin::Add, base, copy);
  2971. let h = self.s.heap_handle(c, slot, false, true, (11 | 0x1000, 0));
  2972. let k64k = k(self, 0xFFFF);
  2973. let within = self.s.m.bin(c, Bin::And, lo, k64k);
  2974. let byte = self.s.m.bin(c, Bin::Add, start, within);
  2975. (h, byte)
  2976. }
  2977. /// `global_load_*`, `global_store_*` and `global_atomic_*` on title
  2978. /// memory by address (`resource::MEMORY`): the address is the VGPR
  2979. /// pair, each lane its own.
  2980. fn memory_flat(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  2981. let Fields::Flat {
  2982. dst,
  2983. addr,
  2984. data,
  2985. saddr,
  2986. offset,
  2987. lds,
  2988. cache,
  2989. } = &inst.fields
  2990. else {
  2991. unreachable!()
  2992. };
  2993. if *lds || !matches!(saddr, None | Some(Operand::Scalar { code: NULL, .. })) {
  2994. return Err("a global address with a scalar base");
  2995. }
  2996. let Some(Operand::Vector { reg: areg, .. }) = *addr else {
  2997. return Err("a global address not in VGPRs");
  2998. };
  2999. let word = |l: &mut Self, k: u8| -> Result<V, Why> {
  3000. let v = inst.read(Reg::V(areg + k)).ok_or("a global address")?;
  3001. l.i32_of(v)
  3002. };
  3003. let (lo, hi) = (word(self, 0)?, word(self, 1)?);
  3004. let (lo, hi) = self.address_plus(lo, hi, i32::from(*offset));
  3005. let guard = self.guard(b, i)?;
  3006. let c = self.cur;
  3007. let (i32t, res, void) = (self.s.t.i32, self.s.t.res_ret, self.s.t.void);
  3008. let iu = self.s.m.undef(i32t);
  3009. let align = self.s.m.i32(4);
  3010. let name = inst.name();
  3011. let count = |rest: &str| match rest {
  3012. "dword" => Ok(1u8),
  3013. "dwordx2" => Ok(2),
  3014. "dwordx3" => Ok(3),
  3015. "dwordx4" => Ok(4),
  3016. _ => Err(name),
  3017. };
  3018. if let Some(rest) = name.strip_prefix("global_load_") {
  3019. let n = count(rest)?;
  3020. let Some(Operand::Vector { reg, .. }) = *dst else {
  3021. return Err("a global load result");
  3022. };
  3023. let (h, byte) = self.memory(lo, hi, guard);
  3024. let mask = self.s.m.i8((1u8 << n) - 1);
  3025. let r = self.s.op(
  3026. c,
  3027. "rawBufferLoad.f32",
  3028. Attr::ReadOnly,
  3029. res,
  3030. 139,
  3031. &[h, byte, iu, mask, align],
  3032. );
  3033. for k in 0..n {
  3034. let x = self.s.m.extract(c, r, u32::from(k));
  3035. let x = self.as_int(x);
  3036. self.write(inst, Reg::V(reg + k), x, guard);
  3037. }
  3038. return Ok(());
  3039. }
  3040. if let Some(rest) = name.strip_prefix("global_store_") {
  3041. let n = count(rest)?;
  3042. let d = data.as_ref().ok_or("global store data")?;
  3043. let vals = self.vgprs(inst, d, n)?;
  3044. let (h, byte) = self.memory(lo, hi, guard);
  3045. let mut args = vec![h, byte, iu];
  3046. args.extend(&vals);
  3047. args.resize(3 + 4, iu);
  3048. args.push(self.s.m.i8((1u8 << n) - 1));
  3049. args.push(align);
  3050. let at = self.begin_guarded(guard);
  3051. self.s
  3052. .op(self.cur, "rawBufferStore.i32", Attr::NoUnwind, void, 140, &args);
  3053. self.end_guarded(at, &[]);
  3054. return Ok(());
  3055. }
  3056. let Some(op) = name.strip_prefix("global_atomic_") else {
  3057. return Err(name);
  3058. };
  3059. let d = data.as_ref().ok_or("global atomic data")?;
  3060. let v = self.vgprs(inst, d, 1)?[0];
  3061. // With `glc` the value from before comes back, in the result
  3062. // register the instruction names.
  3063. let back = match (*dst, cache.glc) {
  3064. (Some(Operand::Vector { reg, .. }), true) => Some(reg),
  3065. _ => None,
  3066. };
  3067. let old = match back.and_then(|reg| inst.read(Reg::V(reg))) {
  3068. Some(x) => self.i32_of(x)?,
  3069. None => self.s.m.i32(0),
  3070. };
  3071. let (h, byte) = self.memory(lo, hi, guard);
  3072. // DXIL's atomic operations: add 0, and 1, or 2, xor 3, signed
  3073. // minimum 4 and maximum 5, unsigned 6 and 7, exchange 8.
  3074. let simple = match op {
  3075. "add" => Some((0, v)),
  3076. "sub" => {
  3077. let zero = self.s.m.i32(0);
  3078. Some((0, self.s.m.bin(c, Bin::Sub, zero, v)))
  3079. }
  3080. "and" => Some((1, v)),
  3081. "or" => Some((2, v)),
  3082. "xor" => Some((3, v)),
  3083. "smin" => Some((4, v)),
  3084. "smax" => Some((5, v)),
  3085. "umin" => Some((6, v)),
  3086. "umax" => Some((7, v)),
  3087. "swap" => Some((8, v)),
  3088. "fmin" | "fmax" => None,
  3089. _ => return Err(name),
  3090. };
  3091. let at = self.begin_guarded(guard);
  3092. let was = match simple {
  3093. Some((code, x)) => {
  3094. let code = self.s.m.i32(code);
  3095. self.s.op(
  3096. self.cur,
  3097. "atomicBinOp.i32",
  3098. Attr::NoUnwind,
  3099. i32t,
  3100. 78,
  3101. &[h, code, byte, iu, iu, x],
  3102. )
  3103. }
  3104. None => {
  3105. // A float minimum or maximum has no atomic operation on
  3106. // the host: the dword is exchanged for the smaller (larger)
  3107. // of itself and the value until no other thread got in
  3108. // between. Each failed pass means another one's succeeded;
  3109. // the limit only keeps a broken card from hanging.
  3110. let head = self.cur;
  3111. let mask = self.s.m.i8(1);
  3112. let first = self.s.op(
  3113. head,
  3114. "rawBufferLoad.f32",
  3115. Attr::ReadOnly,
  3116. res,
  3117. 139,
  3118. &[h, byte, iu, mask, align],
  3119. );
  3120. let first = self.s.m.extract(head, first, 0);
  3121. let first = self.as_int(first);
  3122. let (pass, done) = (self.s.m.new_block(), self.s.m.new_block());
  3123. self.s.m.terminate(head, Term::Br(pass));
  3124. self.cur = pass;
  3125. let seen = self.s.m.phi(pass, i32t);
  3126. let n = self.s.m.phi(pass, i32t);
  3127. let (f32t, fv) = (self.s.t.f32, self.as_float(v));
  3128. let fseen = self.as_float(seen);
  3129. // `dx.op.binary`: FMax 35, FMin 36.
  3130. let pick = if op == "fmin" { 36 } else { 35 };
  3131. let wanted = self
  3132. .s
  3133. .op(pass, "binary.f32", Attr::ReadNone, f32t, pick, &[fseen, fv]);
  3134. let wanted = self.as_int(wanted);
  3135. let found = self.s.op(
  3136. pass,
  3137. "atomicCompareExchange.i32",
  3138. Attr::NoUnwind,
  3139. i32t,
  3140. 79,
  3141. &[h, byte, iu, iu, seen, wanted],
  3142. );
  3143. let one = self.s.m.i32(1);
  3144. let n1 = self.s.m.bin(pass, Bin::Add, n, one);
  3145. let lost = self.s.m.cmp(pass, pred::NE, found, seen);
  3146. let limit = self.s.m.i32(1 << 16);
  3147. let more = self.s.m.cmp(pass, pred::IULT, n1, limit);
  3148. let again = self.s.m.bin(pass, Bin::And, lost, more);
  3149. self.s.m.terminate(pass, Term::CondBr(again, pass, done));
  3150. let zero = self.s.m.i32(0);
  3151. self.s.m.set_phi(seen, vec![(first, head), (found, pass)]);
  3152. self.s.m.set_phi(n, vec![(zero, head), (n1, pass)]);
  3153. self.cur = done;
  3154. found
  3155. }
  3156. };
  3157. let was = self.end_guarded(at, &[(was, old)])[0];
  3158. if let Some(reg) = back {
  3159. self.write(inst, Reg::V(reg), was, None);
  3160. }
  3161. Ok(())
  3162. }
  3163. /// `s_load_dword*` from title memory by address (`resource::MEMORY`):
  3164. /// the SGPR pair plus the instruction's offsets.
  3165. fn memory_smem(&mut self, inst: &Inst) -> Result<(), Why> {
  3166. let Fields::Smem {
  3167. data: Some(Operand::Scalar { code, .. }),
  3168. base: Operand::Scalar { code: base, .. },
  3169. offset,
  3170. soffset,
  3171. ..
  3172. } = inst.fields
  3173. else {
  3174. return Err("a scalar load from memory");
  3175. };
  3176. let count = match inst.name().strip_prefix("s_load_dword") {
  3177. Some("") => 1u8,
  3178. Some("x2") => 2,
  3179. Some("x4") => 4,
  3180. Some("x8") => 8,
  3181. Some("x16") => 16,
  3182. _ => return Err("a scalar memory access by address"),
  3183. };
  3184. let word = |l: &mut Self, k: u8| -> Result<V, Why> {
  3185. let v = inst.read(Reg::S(base + k)).ok_or("an address not in SGPRs")?;
  3186. l.i32_of(v)
  3187. };
  3188. let (mut lo, mut hi) = (word(self, 0)?, word(self, 1)?);
  3189. let c = self.cur;
  3190. let (i32t, res) = (self.s.t.i32, self.s.t.res_ret);
  3191. if !matches!(soffset, Operand::Scalar { code: NULL, .. }) {
  3192. // An offset register counts up from the address.
  3193. let so = self.operand(inst, &soffset)?;
  3194. let sum = self.s.m.bin(c, Bin::Add, lo, so);
  3195. let carry = self.s.m.cmp(c, pred::IULT, sum, lo);
  3196. let carry = self.s.m.cast(c, Cast::ZExt, carry, i32t);
  3197. hi = self.s.m.bin(c, Bin::Add, hi, carry);
  3198. lo = sum;
  3199. }
  3200. let (iu, align) = (self.s.m.undef(i32t), self.s.m.i32(4));
  3201. for first in (0..count).step_by(4) {
  3202. let n = (count - first).min(4);
  3203. let (lo, hi) = self.address_plus(lo, hi, offset + 4 * i32::from(first));
  3204. let (h, byte) = self.memory(lo, hi, None);
  3205. let mask = self.s.m.i8((1u8 << n) - 1);
  3206. let r = self.s.op(
  3207. c,
  3208. "rawBufferLoad.f32",
  3209. Attr::ReadOnly,
  3210. res,
  3211. 139,
  3212. &[h, byte, iu, mask, align],
  3213. );
  3214. for k in 0..n {
  3215. let x = self.s.m.extract(c, r, u32::from(k));
  3216. let x = self.as_int(x);
  3217. self.write(inst, Reg::S(code + first + k), x, None);
  3218. }
  3219. }
  3220. Ok(())
  3221. }
  3222. /// A dword of a lane mask as a number: the ballot of the lanes' bits,
  3223. /// taken in the block that writes the mask (see [`MaskData`]).
  3224. fn mask_dword(&mut self, v: Value) -> Result<V, Why> {
  3225. let (lo, high) = match self.x.st.highs.get(&v) {
  3226. Some(&lo) => (lo, true),
  3227. None => (v, false),
  3228. };
  3229. let &m = self.x.st.masks.get(&lo).ok_or(LANE_MASK)?;
  3230. // A mask that holds lanes outside EXEC where it is written (the complement of one,
  3231. // say) is the ballot of the lanes that are there: all of them, where two exchanging
  3232. // host waves know every lane runs that block.
  3233. let made = self.def_block.get(&lo).copied();
  3234. let whole = self.exchange.is_some() && !self.local && made.is_none_or(|b| self.all_lanes(b));
  3235. if !self.x.st.active.contains(&lo) && !whole {
  3236. if self.exchange.is_some() && !self.local {
  3237. need(made.unwrap_or(0));
  3238. }
  3239. return Err(MASK_ELSEWHERE);
  3240. }
  3241. let (x, y) = match self.ballots.get(&lo) {
  3242. Some(&xy) => xy,
  3243. None => {
  3244. let at = match self.def_block.get(&lo) {
  3245. // Program inputs (EXEC on entry).
  3246. None => self.s.entry,
  3247. Some(&b) if b == self.cur_ir => self.cur,
  3248. Some(&b) => self.tail[b].ok_or("a lane mask written after its use")?,
  3249. };
  3250. if !self.balloting.insert(lo) {
  3251. return Err("a lane mask whose lanes depend on its own value");
  3252. }
  3253. let bit = self.boolean(m, at);
  3254. self.balloting.remove(&lo);
  3255. let bit = bit?;
  3256. let i32t = self.s.t.i32;
  3257. let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]);
  3258. let r = self
  3259. .s
  3260. .op(at, "waveActiveBallot", Attr::NoUnwind, four, 116, &[bit]);
  3261. self.s.flags |= flags::WAVE_OPS;
  3262. let mut xy = (self.s.m.extract(at, r, 0), self.s.m.extract(at, r, 1));
  3263. if self.exchange.is_some() {
  3264. // a host wave's ballot is its half's 32 bits: the halves exchange them
  3265. let b = self.def_block.get(&lo).copied();
  3266. if self.local {
  3267. if !self.local_ok && !self.local_any {
  3268. return Err("a lane mask read as data in a half-wave");
  3269. }
  3270. } else if !self.exchange.as_ref().is_some_and(|e| e.1) && !b.is_none_or(|b| self.all_lanes(b)) {
  3271. // (a group of 32 or fewer has no other half to exchange with)
  3272. need(b.unwrap_or(0));
  3273. return Err("a lane mask exchanged where not every lane runs");
  3274. }
  3275. xy = self.exchange_halves(at, xy.0);
  3276. }
  3277. self.ballots.insert(lo, xy);
  3278. xy
  3279. }
  3280. };
  3281. Ok(if high { y } else { x })
  3282. }
  3283. // ---- operands ----
  3284. fn operand(&mut self, inst: &Inst, op: &Operand) -> Result<V, Why> {
  3285. match *op {
  3286. Operand::Scalar { code: NULL, .. } => Ok(self.s.m.i32(0)),
  3287. Operand::Scalar { code, .. } => {
  3288. let v = inst.read(Reg::S(code)).ok_or("an unread operand")?;
  3289. self.i32_of(v)
  3290. }
  3291. Operand::Vector { reg, .. } => {
  3292. let v = inst.read(Reg::V(reg)).ok_or("an unread operand")?;
  3293. self.i32_of(v)
  3294. }
  3295. // src_scc: SCC as 0 or 1 (VIctory upstream 0b35b7f, as the dot
  3296. // products and packed multiply-adds below).
  3297. Operand::Const(253) => {
  3298. let bit = self.scc_in(inst)?;
  3299. Ok(self.s.m.cast(self.cur, Cast::ZExt, bit, self.s.t.i32))
  3300. }
  3301. // Nothing to wait for (see `ordered_section`).
  3302. Operand::Const(POPS_EXITING) if !self.ordered.is_empty() => Ok(self.s.m.i32(0)),
  3303. Operand::Const(c) => crate::resource::inline(c)
  3304. .map(|x| self.s.m.i32(x))
  3305. .ok_or("a special operand (vccz, execz, scc, lds_direct)"),
  3306. Operand::Literal(x) => Ok(self.s.m.i32(x)),
  3307. Operand::Attr { .. } => Err("an attribute operand"),
  3308. }
  3309. }
  3310. /// An operand read as f16 data: GFX10 puts an inline f16 constant in
  3311. /// the low half of the operand (upstream PR #637, checked there against
  3312. /// the instruction encodings; the half-and-half reading taken from PR
  3313. /// #458 gave the high half the constant too).
  3314. fn f16_operand(&mut self, inst: &Inst, op: &Operand) -> Result<V, Why> {
  3315. match *op {
  3316. Operand::Const(c @ 240..=248) => Ok(self.s.m.i32(inline_f16(c))),
  3317. _ => self.operand(inst, op),
  3318. }
  3319. }
  3320. fn as_float(&mut self, x: V) -> V {
  3321. self.s.m.cast(self.cur, Cast::Bitcast, x, self.s.t.f32)
  3322. }
  3323. fn as_int(&mut self, f: V) -> V {
  3324. self.s.m.cast(self.cur, Cast::Bitcast, f, self.s.t.i32)
  3325. }
  3326. /// The SDWA operand selection of source `k`: a byte or word of the
  3327. /// dword, zero- or sign-extended (none: the whole dword).
  3328. fn sdwa_src(inst: &Inst, k: usize) -> Option<(u8, bool)> {
  3329. let Fields::Valu(v) = &inst.fields else {
  3330. return None;
  3331. };
  3332. let s = v.sdwa?;
  3333. let sel = *s.src_sel.get(k)?;
  3334. let sext = s.sext >> k & 1 != 0;
  3335. (sel < 6).then_some((sel, sext))
  3336. }
  3337. /// Bits `sel` (0-3 a byte, 4-5 a word) of `x`, extended.
  3338. fn select_bits(&mut self, x: V, sel: u8, sext: bool) -> V {
  3339. let c = self.cur;
  3340. let (width, at) = if sel < 4 {
  3341. (8, 8 * sel)
  3342. } else {
  3343. (16, 16 * (sel - 4))
  3344. };
  3345. let left = self.s.m.i32(u32::from(32 - width - at));
  3346. let t = self.s.m.bin(c, Bin::Shl, x, left);
  3347. let right = self.s.m.i32(32 - u32::from(width));
  3348. let op = if sext { Bin::AShr } else { Bin::LShr };
  3349. self.s.m.bin(c, op, t, right)
  3350. }
  3351. /// A float source with its abs/neg modifiers.
  3352. fn fsrc(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  3353. let Fields::Valu(v) = &inst.fields else {
  3354. unreachable!()
  3355. };
  3356. let op = *v.src.get(k).ok_or("a missing operand")?;
  3357. let selected = Self::sdwa_src(inst, k);
  3358. let mut f = match op {
  3359. _ if selected.is_some() => {
  3360. let (sel, sext) = selected.expect("checked");
  3361. let x = self.operand(inst, &op)?;
  3362. let x = self.select_bits(x, sel, sext);
  3363. self.as_float(x)
  3364. }
  3365. _ if k == 0 && self.src0.is_some() => {
  3366. let x = self.src0.expect("checked");
  3367. self.as_float(x)
  3368. }
  3369. Operand::Vector { reg, .. } | Operand::Scalar { code: reg, .. }
  3370. if !matches!(op, Operand::Scalar { code: NULL, .. }) =>
  3371. {
  3372. let r = if matches!(op, Operand::Vector { .. }) {
  3373. Reg::V(reg)
  3374. } else {
  3375. Reg::S(reg)
  3376. };
  3377. let val = inst.read(r).ok_or("an unread operand")?;
  3378. match self.floats.get(&val) {
  3379. Some(&f) => f,
  3380. None => {
  3381. let x = self.i32_of(val)?;
  3382. self.as_float(x)
  3383. }
  3384. }
  3385. }
  3386. _ => {
  3387. let x = self.operand(inst, &op)?;
  3388. self.as_float(x)
  3389. }
  3390. };
  3391. if v.abs >> k & 1 != 0 {
  3392. f = self.unary(6, f);
  3393. }
  3394. if v.neg >> k & 1 != 0 {
  3395. let z = self.s.m.f32(0x8000_0000);
  3396. f = self.s.m.bin(self.cur, Bin::Sub, z, f);
  3397. }
  3398. Ok(f)
  3399. }
  3400. fn src(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  3401. let Fields::Valu(v) = &inst.fields else {
  3402. unreachable!()
  3403. };
  3404. let op = *v.src.get(k).ok_or("a missing operand")?;
  3405. if v.abs >> k & 1 != 0 || v.neg >> k & 1 != 0 {
  3406. return Err("integer operand modifiers");
  3407. }
  3408. match self.src0 {
  3409. Some(x) if k == 0 => Ok(x),
  3410. _ => {
  3411. let x = self.operand(inst, &op)?;
  3412. Ok(match Self::sdwa_src(inst, k) {
  3413. Some((sel, sext)) => self.select_bits(x, sel, sext),
  3414. None => x,
  3415. })
  3416. }
  3417. }
  3418. }
  3419. fn unary(&mut self, op: u32, f: V) -> V {
  3420. self.s.op(
  3421. self.cur,
  3422. "unary.f32",
  3423. Attr::ReadNone,
  3424. self.s.t.f32,
  3425. op,
  3426. &[f],
  3427. )
  3428. }
  3429. fn binary(&mut self, op: u32, a: V, b: V) -> V {
  3430. self.s.op(
  3431. self.cur,
  3432. "binary.f32",
  3433. Attr::ReadNone,
  3434. self.s.t.f32,
  3435. op,
  3436. &[a, b],
  3437. )
  3438. }
  3439. /// The hardware's maximum (`max`) or minimum of two floats: as DXIL's
  3440. /// FMax/FMin, but -0 orders below +0 (RDNA2 ISA, `v_max_f32`), where
  3441. /// the compare and select DXIL specifies gives either zero.
  3442. fn max_min(&mut self, max: bool, a: V, b: V) -> V {
  3443. let c = self.cur;
  3444. let r = self.binary(if max { 35 } else { 36 }, a, b);
  3445. let (ia, ib) = (self.as_int(a), self.as_int(b));
  3446. let either = self.s.m.bin(c, Bin::Or, ia, ib);
  3447. let magnitude = self.s.m.i32(0x7FFF_FFFF);
  3448. let either = self.s.m.bin(c, Bin::And, either, magnitude);
  3449. let zero = self.s.m.i32(0);
  3450. let zeros = self.s.m.cmp(c, pred::EQ, either, zero);
  3451. // Of two zeros, +0 unless both are -0 (max), -0 unless neither (min).
  3452. let op = if max { Bin::And } else { Bin::Or };
  3453. let sign = self.s.m.bin(c, op, ia, ib);
  3454. let signed = self.as_float(sign);
  3455. self.s.m.select(c, zeros, signed, r)
  3456. }
  3457. fn fmad(&mut self, a: V, b: V, c: V) -> V {
  3458. self.s.op(
  3459. self.cur,
  3460. "tertiary.f32",
  3461. Attr::ReadNone,
  3462. self.s.t.f32,
  3463. 46,
  3464. &[a, b, c],
  3465. )
  3466. }
  3467. /// `f` as an f16 in the low bits, rounded toward zero: the nearest-even
  3468. /// conversion, one step back toward zero where it rounded away (which
  3469. /// also turns an overflow to infinity into the largest finite half).
  3470. fn f16_toward_zero(&mut self, f: V) -> V {
  3471. let c = self.cur;
  3472. let i32t = self.s.t.i32;
  3473. let h = self
  3474. .s
  3475. .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]);
  3476. let back = self
  3477. .s
  3478. .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[h]);
  3479. let (fa, ba) = (self.unary(6, f), self.unary(6, back));
  3480. // Ordered: never for NaN.
  3481. let away = self.s.m.cmp(c, pred::OGT, ba, fa);
  3482. let one = self.s.m.i32(1);
  3483. let stepped = self.s.m.bin(c, Bin::Sub, h, one);
  3484. self.s.m.select(c, away, stepped, h)
  3485. }
  3486. /// `f` as an f16 in the low bits, rounded to nearest, ties to even, as the console's
  3487. /// 16-bit float operations round, whatever the host's own conversion does: D3D lets
  3488. /// `f32tof16` round toward zero, and the NVIDIA driver's does (measured on an RTX 4070:
  3489. /// `wave64_tests`). The conversion toward zero, or the next half away from zero where
  3490. /// that one is nearer, or as near and the first one odd. Past the largest half the next
  3491. /// one counts as 2^16, the bound IEEE rounds by, so 65520 and up become infinity.
  3492. /// (`f` is an f32 result of two halves here; rounding it again to 16 bits gives the
  3493. /// rounding of the exact result, 24 bits being more than twice 11 and two.)
  3494. fn f16_nearest(&mut self, f: V) -> V {
  3495. let c = self.cur;
  3496. let f32t = self.s.t.f32;
  3497. let lo = self.f16_toward_zero(f);
  3498. let (one, zero) = (self.s.m.i32(1), self.s.m.i32(0));
  3499. let hi = self.s.m.bin(c, Bin::Add, lo, one);
  3500. let size = |l: &mut Self, h: V| {
  3501. let w = l.s.op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]);
  3502. l.unary(6, w)
  3503. };
  3504. let (below, above) = (size(self, lo), size(self, hi));
  3505. let (magnitude, infinity) = (self.s.m.i32(0x7FFF), self.s.m.i32(0x7C00));
  3506. let m = self.s.m.bin(c, Bin::And, hi, magnitude);
  3507. let top = self.s.m.cmp(c, pred::EQ, m, infinity);
  3508. let bound = self.s.m.f32(65536.0f32.to_bits());
  3509. let above = self.s.m.select(c, top, bound, above);
  3510. let fa = self.unary(6, f);
  3511. // (both differences are exact: the three values lie within one half's step)
  3512. let under = self.s.m.bin(c, Bin::Sub, fa, below);
  3513. let over = self.s.m.bin(c, Bin::Sub, above, fa);
  3514. // Ordered: never for NaN, which stays what the conversion made of it.
  3515. let nearer = self.s.m.cmp(c, pred::OLT, over, under);
  3516. let tie = self.s.m.cmp(c, pred::OEQ, over, under);
  3517. let odd = self.s.m.bin(c, Bin::And, lo, one);
  3518. let odd = self.s.m.cmp(c, pred::NE, odd, zero);
  3519. let tie = self.s.m.bin(c, Bin::And, tie, odd);
  3520. let up = self.s.m.bin(c, Bin::Or, nearer, tie);
  3521. self.s.m.select(c, up, hi, lo)
  3522. }
  3523. /// `(a >> off[4:0]) & ((1 << width) - 1)`, sign-extended from the field's
  3524. /// top bit when `signed`; widths from 32 on take every bit. A signed
  3525. /// field that runs past bit 31 extends from bit 31, as the hardware
  3526. /// does: the shift is arithmetic then.
  3527. fn bfe(&mut self, a: V, off: V, width: V, signed: bool) -> V {
  3528. let c = self.cur;
  3529. let (k31, k32, zero, one, ones) = (
  3530. self.s.m.i32(31),
  3531. self.s.m.i32(32),
  3532. self.s.m.i32(0),
  3533. self.s.m.i32(1),
  3534. self.s.m.i32(u32::MAX),
  3535. );
  3536. let off = self.s.m.bin(c, Bin::And, off, k31);
  3537. let shift = if signed { Bin::AShr } else { Bin::LShr };
  3538. let shifted = self.s.m.bin(c, shift, a, off);
  3539. let full = self.s.m.cmp(c, pred::IUGE, width, k32);
  3540. let w = self.s.m.bin(c, Bin::And, width, k31);
  3541. let mask = self.s.m.bin(c, Bin::Shl, one, w);
  3542. let mask = self.s.m.bin(c, Bin::Sub, mask, one);
  3543. let mask = self.s.m.select(c, full, ones, mask);
  3544. let r = self.s.m.bin(c, Bin::And, shifted, mask);
  3545. if !signed {
  3546. return r;
  3547. }
  3548. // Sign-extend a field narrower than 32 bits (none for width 0).
  3549. let left = self.s.m.bin(c, Bin::Sub, k32, w);
  3550. let left = self.s.m.bin(c, Bin::And, left, k31);
  3551. let t = self.s.m.bin(c, Bin::Shl, r, left);
  3552. let t = self.s.m.bin(c, Bin::AShr, t, left);
  3553. let is0 = self.s.m.cmp(c, pred::EQ, w, zero);
  3554. let keep = self.s.m.bin(c, Bin::Or, full, is0);
  3555. self.s.m.select(c, keep, r, t)
  3556. }
  3557. /// Whether an f32 value is NaN, tested in integer arithmetic so host
  3558. /// drivers (such as NVIDIA) do not fold `fcmp uno` away under fast-math.
  3559. fn is_nan_f32(&mut self, f: V) -> V {
  3560. let c = self.cur;
  3561. let bits = self.as_int(f);
  3562. let mask = self.s.m.i32(0x7FFF_FFFF);
  3563. let abs = self.s.m.bin(c, Bin::And, bits, mask);
  3564. let inf = self.s.m.i32(0x7F80_0000);
  3565. self.s.m.cmp(c, pred::IUGT, abs, inf)
  3566. }
  3567. /// The median of three. With a NaN among them the hardware gives the
  3568. /// minimum of the three instead (the host's minimum skips NaNs, so that
  3569. /// is the smallest number among them).
  3570. fn med3(&mut self, a: V, b: V, third: V) -> V {
  3571. let c = self.cur;
  3572. let lo = self.binary(36, a, b);
  3573. let hi = self.binary(35, a, b);
  3574. let t = self.binary(36, hi, third);
  3575. let median = self.binary(35, lo, t);
  3576. let least = self.binary(36, lo, third);
  3577. let nan_a = self.is_nan_f32(a);
  3578. let nan_b = self.is_nan_f32(b);
  3579. let nan_3 = self.is_nan_f32(third);
  3580. let nan_ab = self.s.m.bin(c, Bin::Or, nan_a, nan_b);
  3581. let nan = self.s.m.bin(c, Bin::Or, nan_ab, nan_3);
  3582. self.s.m.select(c, nan, least, median)
  3583. }
  3584. /// `a - floor(a)`, which on the hardware never reaches 1.0: where it
  3585. /// would round to it (a tiny negative `a`), the result is `below_one`,
  3586. /// the largest value under 1.0 in the operation's width. Hosts differ
  3587. /// here (some give 1.0). Comparing against a `threshold` distinct from
  3588. /// `below_one` prevents drivers (observed on NVIDIA) from folding
  3589. /// `r > k ? k : r` into `minNum` (`FMNMX`) and swallowing NaN.
  3590. fn fract(&mut self, a: V, threshold: f32, below_one: f32) -> V {
  3591. let c = self.cur;
  3592. let r = self.unary(22, a);
  3593. let limit = self.s.m.f32(threshold.to_bits());
  3594. let k = self.s.m.f32(below_one.to_bits());
  3595. let over = self.s.m.cmp(c, pred::OGE, r, limit);
  3596. self.s.m.select(c, over, k, r)
  3597. }
  3598. /// Sine, or cosine, of an angle in turns, as the hardware takes it. The
  3599. /// whole turns are taken off first (`x - round_even(x)`, exact, within
  3600. /// half a turn), so a large angle keeps its fraction; scaling to radians
  3601. /// first rounds it away. A zero passes unreduced (the sine of -0 is -0).
  3602. /// The sine of a half turn and the cosine of a quarter turn are exactly
  3603. /// +0 on the hardware, where the host's function of the rounded angle
  3604. /// gives about 1e-7. Infinities and NaN give NaN.
  3605. /// shortcut: below 2^-12 turns the hardware scales by a slightly
  3606. /// different constant than 2π (a last-place difference).
  3607. fn trig_turns(&mut self, x: V, cosine: bool) -> V {
  3608. let c = self.cur;
  3609. let zero = self.s.m.f32(0);
  3610. let whole = self.unary(26, x);
  3611. let part = self.s.m.bin(c, Bin::Sub, x, whole);
  3612. let is_zero = self.s.m.cmp(c, pred::OEQ, x, zero);
  3613. let part = self.s.m.select(c, is_zero, x, part);
  3614. let k = self.s.m.f32(TWO_PI.to_bits());
  3615. let angle = self.s.m.bin(c, Bin::Mul, part, k);
  3616. let r = self.unary(if cosine { 12 } else { 13 }, angle);
  3617. let at = if cosine { 0.25f32 } else { 0.5 };
  3618. let at = self.s.m.f32(at.to_bits());
  3619. let size = self.unary(6, part);
  3620. let exact = self.s.m.cmp(c, pred::OEQ, size, at);
  3621. self.s.m.select(c, exact, zero, r)
  3622. }
  3623. /// The high dword of a 32 × 32-bit product.
  3624. fn mul_hi(&mut self, a: V, b: V, signed: bool) -> V {
  3625. let c = self.cur;
  3626. let i64t = self.s.m.int(64);
  3627. let ext = if signed { Cast::SExt } else { Cast::ZExt };
  3628. let a = self.s.m.cast(c, ext, a, i64t);
  3629. let b = self.s.m.cast(c, ext, b, i64t);
  3630. let m = self.s.m.bin(c, Bin::Mul, a, b);
  3631. let k32 = self.s.m.int_const(i64t, 32);
  3632. let hi = self.s.m.bin(c, Bin::LShr, m, k32);
  3633. self.s.flags |= flags::INT64;
  3634. self.s.m.cast(c, Cast::Trunc, hi, self.s.t.i32)
  3635. }
  3636. /// `0 × anything = 0`, as in D3D9.
  3637. fn legacy_mul(&mut self, a: V, b: V) -> V {
  3638. let c = self.cur;
  3639. let m = self.s.m.bin(c, Bin::Mul, a, b);
  3640. let zero = self.s.m.f32(0);
  3641. let az = self.s.m.cmp(c, pred::OEQ, a, zero);
  3642. let bz = self.s.m.cmp(c, pred::OEQ, b, zero);
  3643. let z = self.s.m.bin(c, Bin::Or, az, bz);
  3644. self.s.m.select(c, z, zero, m)
  3645. }
  3646. // ---- lane booleans ----
  3647. fn boolean(&mut self, b: Bool, at: usize) -> Result<V, Why> {
  3648. if b == Bool::TRUE || b == Bool::FALSE {
  3649. return Ok(self.s.m.bool(b == Bool::TRUE));
  3650. }
  3651. if let Some(&v) = self.bools.get(&(at, b)) {
  3652. return Ok(v);
  3653. }
  3654. let (atom, lo, hi) = self.x.st.bools.node(b).expect("not a constant");
  3655. let a = self.atom(atom, at)?;
  3656. let m = &mut self.s.m;
  3657. let v = match (lo, hi) {
  3658. (Bool::FALSE, Bool::TRUE) => a,
  3659. (Bool::TRUE, Bool::FALSE) => {
  3660. let t = m.bool(true);
  3661. m.bin(at, Bin::Xor, a, t)
  3662. }
  3663. (Bool::FALSE, h) => {
  3664. let h = self.boolean(h, at)?;
  3665. self.s.m.bin(at, Bin::And, a, h)
  3666. }
  3667. (l, Bool::TRUE) => {
  3668. let l = self.boolean(l, at)?;
  3669. self.s.m.bin(at, Bin::Or, a, l)
  3670. }
  3671. (l, h) => {
  3672. let l = self.boolean(l, at)?;
  3673. let h = self.boolean(h, at)?;
  3674. self.s.m.select(at, a, h, l)
  3675. }
  3676. };
  3677. self.bools.insert((at, b), v);
  3678. Ok(v)
  3679. }
  3680. fn atom(&mut self, atom: Atom, at: usize) -> Result<V, Why> {
  3681. match atom {
  3682. Atom::Lane(v) => self.lane_bits.get(&v).copied().ok_or_else(|| {
  3683. self.lane_fail
  3684. .get(&v)
  3685. .copied()
  3686. .unwrap_or("a lane mask from a carry")
  3687. }),
  3688. Atom::Uniform(v) => match self.get(v)? {
  3689. Val::Bit(x) => Ok(x),
  3690. Val::I32(x) => {
  3691. let z = self.s.m.i32(0);
  3692. Ok(self.s.m.cmp(at, pred::NE, x, z))
  3693. }
  3694. Val::Missing(w) => Err(w),
  3695. },
  3696. Atom::Phi(id) => {
  3697. if let Some(&v) = self.mask_phis.get(&id) {
  3698. return Ok(v);
  3699. }
  3700. let &(b, i) = self
  3701. .phi_at
  3702. .get(&id)
  3703. .ok_or("a lane-mask join without a phi")?;
  3704. let blk = self.block[b].ok_or("an unreachable join")?;
  3705. let v = self.s.m.phi(blk, self.s.t.i1);
  3706. self.mask_phis.insert(id, v);
  3707. self.pending_masks.push((v, b, i));
  3708. Ok(v)
  3709. }
  3710. // shortcut: "some lane of the quad is set" is taken as true: the
  3711. // lanes it adds only feed derivatives, and exports keep their own
  3712. // masks. Wrong if such a section had a side effect.
  3713. Atom::Quad(_) => Ok(self.s.m.bool(true)),
  3714. // With console lanes, a mask held as a number is the console's:
  3715. // the lane tests its own bit.
  3716. Atom::Opaque(v) if self.console_lanes => {
  3717. let hi = match self.pair_high(v) {
  3718. Some(h) => Some(self.get(h)?),
  3719. None => None,
  3720. };
  3721. let lo = self.get(v)?;
  3722. let word = |w: Val| match w {
  3723. Val::I32(x) => Ok(x),
  3724. _ => Err("an opaque lane mask"),
  3725. };
  3726. let lo = word(lo)?;
  3727. let hi = hi.map(word).transpose()?;
  3728. Ok(self.lane_bit(at, lo, hi))
  3729. }
  3730. Atom::Constant(k) if self.console_lanes => {
  3731. let lo = self.s.m.i32(k as u32);
  3732. let hi = self.s.m.i32((k >> 32) as u32);
  3733. Ok(self.lane_bit(at, lo, Some(hi)))
  3734. }
  3735. Atom::Opaque(_) => Err("an opaque lane mask"),
  3736. Atom::Constant(_) => Err("a constant lane mask"),
  3737. }
  3738. }
  3739. /// A console wave64 program in host waves of 32: the first console thread of this host wave
  3740. /// (0, 32, 64, ...). A GPU need not give a host wave consecutive thread indices (NVIDIA's
  3741. /// 8 x 8 groups), so each wave takes the next 32 from an LDS counter instead: every thread
  3742. /// zeroes it, the group meets, each wave's first lane adds 32 and the wave takes what it
  3743. /// found. Branch-free, in the entry block, which every thread runs.
  3744. fn wave_base(&mut self) -> Option<V> {
  3745. let slot = self.halves?;
  3746. if let Some(v) = self.wave_base {
  3747. return Some(v);
  3748. }
  3749. let (e, i32t) = (self.s.entry, self.s.t.i32);
  3750. let lds = self.s.lds();
  3751. let k = self.s.m.i32(slot);
  3752. let ptr = self.s.m.element(e, lds, k);
  3753. let zero = self.s.m.i32(0);
  3754. self.s.m.store(e, ptr, zero);
  3755. self.group_sync(e);
  3756. let lane = self.s.op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
  3757. let first = self.s.m.cmp(e, pred::EQ, lane, zero);
  3758. let k32 = self.s.m.i32(32);
  3759. let add = self.s.m.select(e, first, k32, zero);
  3760. let ptr = self.s.m.element(e, lds, k);
  3761. let old = self.s.m.atomic(e, Rmw::Add, ptr, add);
  3762. let base = self.s.op(e, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[old]);
  3763. self.s.flags |= flags::WAVE_OPS;
  3764. self.wave_base = Some(base);
  3765. Some(base)
  3766. }
  3767. /// The console thread index of this thread in the group: `wave_base` plus the host lane
  3768. /// (host waves of 32), else the wave's first thread index rounded down plus the lane.
  3769. fn console_thread(&mut self) -> V {
  3770. let (e, i32t) = (self.s.entry, self.s.t.i32);
  3771. let lane = self.s.op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
  3772. if let Some(base) = self.wave_base() {
  3773. return self.s.m.bin(e, Bin::Add, base, lane);
  3774. }
  3775. let flat = self.s.op(e, "flattenedThreadIdInGroup.i32", Attr::ReadNone, i32t, 96, &[]);
  3776. let first = self.s.op(e, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[flat]);
  3777. let wave = self.s.wave_size.unwrap_or(32);
  3778. let mask = self.s.m.i32(!(wave - 1));
  3779. let base = self.s.m.bin(e, Bin::And, first, mask);
  3780. self.s.m.bin(e, Bin::Add, base, lane)
  3781. }
  3782. /// This thread's console lane (0..63): its relabelled thread index (`thread_id`), whose host
  3783. /// wave holds a 32-aligned run of console lanes. Without `exchange`: the host lane.
  3784. fn console_lane(&mut self) -> V {
  3785. if self.exchange.is_none() {
  3786. return self.lane_index();
  3787. }
  3788. if let Some(v) = self.clane {
  3789. return v;
  3790. }
  3791. let (e, i32t) = (self.s.entry, self.s.t.i32);
  3792. let f = self.console_thread();
  3793. let _ = i32t;
  3794. let k63 = self.s.m.i32(63);
  3795. let cl = self.s.m.bin(e, Bin::And, f, k63);
  3796. self.s.flags |= flags::WAVE_OPS;
  3797. self.clane = Some(cl);
  3798. cl
  3799. }
  3800. /// A group barrier with an LDS fence in `block`.
  3801. fn group_sync(&mut self, block: usize) {
  3802. let mode = self.s.m.i32(meeting_mode());
  3803. let void = self.s.t.void;
  3804. self.s.op(block, "barrier", Attr::NoDuplicate, void, 80, &[mode]);
  3805. }
  3806. /// `exchange`: each host wave gives `mine` (the same in all its lanes) for its half; both get
  3807. /// (lower half's, upper half's). A group with no upper half gets 0 for it.
  3808. fn exchange_halves(&mut self, at: usize, mine: V) -> (V, V) {
  3809. let Some((slot, small, _)) = self.exchange.as_ref().map(|(a, b, _)| (*a, *b, ())) else {
  3810. let z = self.s.m.i32(0);
  3811. return (mine, z);
  3812. };
  3813. if small {
  3814. let z = self.s.m.i32(0);
  3815. return (mine, z);
  3816. }
  3817. if self.local {
  3818. // each host wave on its own: its half holds `mine`, the other nothing
  3819. let cl = self.console_lane();
  3820. let (k32, z) = (self.s.m.i32(32), self.s.m.i32(0));
  3821. let upper = self.s.m.cmp(at, pred::IUGE, cl, k32);
  3822. let lo = self.s.m.select(at, upper, z, mine);
  3823. let hi = self.s.m.select(at, upper, mine, z);
  3824. return (lo, hi);
  3825. }
  3826. // the pair of dwords of this thread's console wave: its half's, then both
  3827. let pair = self.exchange_pair(slot);
  3828. let cl = self.console_lane();
  3829. let five = self.s.m.i32(5);
  3830. let half = self.s.m.bin(at, Bin::LShr, cl, five);
  3831. let index = self.s.m.bin(at, Bin::Add, pair, half);
  3832. let lds = self.s.lds();
  3833. let ptr = self.s.m.element(at, lds, index);
  3834. self.s.m.store(at, ptr, mine);
  3835. self.group_sync(at);
  3836. let one = self.s.m.i32(1);
  3837. let k1 = self.s.m.bin(at, Bin::Add, pair, one);
  3838. let p0 = self.s.m.element(at, lds, pair);
  3839. let p1 = self.s.m.element(at, lds, k1);
  3840. let lo = self.s.m.load(at, p0);
  3841. let hi = self.s.m.load(at, p1);
  3842. // the slots are written again only after every thread read them
  3843. self.group_sync(at);
  3844. (lo, hi)
  3845. }
  3846. /// The first of the two exchange dwords of this thread's console wave (made in the entry
  3847. /// block): a group of several console waves has a pair for each.
  3848. fn exchange_pair(&mut self, slot: u32) -> V {
  3849. if let Some(v) = self.pair {
  3850. return v;
  3851. }
  3852. let e = self.s.entry;
  3853. let thread = self.console_thread();
  3854. let six = self.s.m.i32(6);
  3855. let wave = self.s.m.bin(e, Bin::LShr, thread, six);
  3856. let one = self.s.m.i32(1);
  3857. let twice = self.s.m.bin(e, Bin::Shl, wave, one);
  3858. let base = self.s.m.i32(slot);
  3859. let v = self.s.m.bin(e, Bin::Add, base, twice);
  3860. self.pair = Some(v);
  3861. v
  3862. }
  3863. /// The console's decision of the branch closing IR block `b`, which the wave takes
  3864. /// together ([`Structured::wide`]): `when` is the lane's own bit, and the branch is taken
  3865. /// when some lane's `when` holds (`execnz`, `vccnz`, SCC of a mask operation set) or
  3866. /// when every lane's does (`execz`, `vccz`, that SCC clear), [`Structured::wave_any`].
  3867. /// Each host wave asks its lanes and the halves exchange the answers, so both go the
  3868. /// same way and can meet again inside the branch.
  3869. /// SCC of a mask operation as data ([`Structured::scc_some`]): whether some lane of the
  3870. /// console wave has its bit of the result, asked where the operation stands. The lanes
  3871. /// that are elsewhere have no bit (the result is ANDed with EXEC or is EXEC), so with
  3872. /// the console's waves the host wave's answer is the console's; two host waves of 32
  3873. /// exchange theirs, which needs every lane there.
  3874. fn scc_some(&mut self, scc: Value) -> Result<V, Why> {
  3875. let &m = self.x.st.scc_some.get(&scc).ok_or(LANE_MASK)?;
  3876. // (not for a console wave cut into host waves that do not exchange)
  3877. if !self.console_lanes || self.local || self.exchange.is_none() && self.halves.is_some() {
  3878. return Err(LANE_MASK);
  3879. }
  3880. let made = self.def_block.get(&scc).copied();
  3881. let at = match made {
  3882. None => self.s.entry,
  3883. Some(b) if b == self.cur_ir => self.cur,
  3884. Some(b) => self.tail[b].ok_or("a lane mask written after its use")?,
  3885. };
  3886. let bit = self.boolean(m, at)?;
  3887. let (i1t, i32t) = (self.s.t.i1, self.s.t.i32);
  3888. let some = self.s.op(at, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[bit]);
  3889. self.s.flags |= flags::WAVE_OPS;
  3890. if !self.exchange.as_ref().is_some_and(|e| !e.1) {
  3891. return Ok(some);
  3892. }
  3893. if !made.is_none_or(|b| self.all_lanes(b)) {
  3894. need(made.unwrap_or(0));
  3895. return Err("a lane mask exchanged where not every lane runs");
  3896. }
  3897. let some = self.s.m.cast(at, Cast::ZExt, some, i32t);
  3898. let (lo, hi) = self.exchange_halves(at, some);
  3899. let both = self.s.m.bin(at, Bin::Or, lo, hi);
  3900. let z = self.s.m.i32(0);
  3901. Ok(self.s.m.cmp(at, pred::NE, both, z))
  3902. }
  3903. fn wave_wide(&mut self, b: usize, when: Bool) -> Result<V, Why> {
  3904. const WHY: Why = "a wave-wide branch where not every lane runs";
  3905. let any = self.x.st.wave_any.get(b).copied().flatten().ok_or("a wave-wide branch on a scalar condition")?;
  3906. if self.exchange.is_none() && self.halves.is_none() && self.console_lanes && self.mask_data == MaskData::Console {
  3907. // The host's waves are the console's: the wave's own answer. The lanes that are
  3908. // elsewhere have no bit set, as on the console, so "some lane" needs no one but
  3909. // the lanes here, and "every lane's bit is clear" is true of the others anyway.
  3910. let c = self.cur;
  3911. let mine = self.boolean(when, c)?;
  3912. let i1t = self.s.t.i1;
  3913. self.s.flags |= flags::WAVE_OPS;
  3914. let (name, code) = if any { ("waveAnyTrue", 113) } else { ("waveAllTrue", 114) };
  3915. return Ok(self.s.op(c, name, Attr::NoUnwind, i1t, code, &[mine]));
  3916. }
  3917. if self.local || !self.exchange.as_ref().is_some_and(|e| !e.1) {
  3918. return Err(WHY);
  3919. }
  3920. if !self.all_lanes(b) {
  3921. need(b);
  3922. return Err(WHY);
  3923. }
  3924. let c = self.cur;
  3925. let mine = self.boolean(when, c)?;
  3926. // what the halves exchange is "some lane speaks against" either way (for `any`:
  3927. // some lane's `when` holds; else: some lane's does not), so a half with no lane says
  3928. // nothing
  3929. let set = if any {
  3930. mine
  3931. } else {
  3932. let t = self.s.m.bool(true);
  3933. self.s.m.bin(c, Bin::Xor, mine, t)
  3934. };
  3935. let (i1t, i32t) = (self.s.t.i1, self.s.t.i32);
  3936. let some = self.s.op(c, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[set]);
  3937. self.s.flags |= flags::WAVE_OPS;
  3938. let some = self.s.m.cast(c, Cast::ZExt, some, i32t);
  3939. let (lo, hi) = self.exchange_halves(c, some);
  3940. let c = self.cur;
  3941. let both = self.s.m.bin(c, Bin::Or, lo, hi);
  3942. let z = self.s.m.i32(0);
  3943. Ok(self.s.m.cmp(c, if any { pred::NE } else { pred::EQ }, both, z))
  3944. }
  3945. /// Whether every lane runs IR block `b` (always true without `exchange`).
  3946. fn all_lanes(&self, b: usize) -> bool {
  3947. self.exchange.as_ref().is_none_or(|(_, _, all)| all.get(b).copied().unwrap_or(false))
  3948. }
  3949. /// This lane's bit of the mask `lo`, `hi` (wave64).
  3950. fn lane_bit(&mut self, at: usize, lo: V, hi: Option<V>) -> V {
  3951. self.s.flags |= flags::WAVE_OPS;
  3952. let lane = if self.exchange.is_some() {
  3953. self.console_lane()
  3954. } else {
  3955. self.s.op(at, "waveGetLaneIndex", Attr::ReadOnly, self.s.t.i32, 111, &[])
  3956. };
  3957. let (k31, k32, one, z) = (
  3958. self.s.m.i32(31),
  3959. self.s.m.i32(32),
  3960. self.s.m.i32(1),
  3961. self.s.m.i32(0),
  3962. );
  3963. let word = match hi {
  3964. Some(hi) => {
  3965. let low = self.s.m.cmp(at, pred::IULT, lane, k32);
  3966. self.s.m.select(at, low, lo, hi)
  3967. }
  3968. None => lo,
  3969. };
  3970. let sh = self.s.m.bin(at, Bin::And, lane, k31);
  3971. let t = self.s.m.bin(at, Bin::LShr, word, sh);
  3972. let t = self.s.m.bin(at, Bin::And, t, one);
  3973. self.s.m.cmp(at, pred::NE, t, z)
  3974. }
  3975. /// The value of the high dword of the wave64 register pair whose low
  3976. /// dword holds `lo` (none in wave32).
  3977. fn pair_high(&self, lo: Value) -> Option<Value> {
  3978. if !self.x.native.wave64 {
  3979. return None;
  3980. }
  3981. let p = self.x.p;
  3982. let pick = |reg: Reg| match reg {
  3983. Reg::S(c) => Some(Reg::S(c + 1)),
  3984. _ => None,
  3985. };
  3986. if let Some(&(reg, _)) = p.inputs.iter().find(|i| i.1 == lo) {
  3987. let h = pick(reg)?;
  3988. return p.inputs.iter().find(|i| i.0 == h).map(|i| i.1);
  3989. }
  3990. if let Some(&(b, i)) = self.phi_at.get(&lo) {
  3991. let h = pick(p.blocks[b].phis[i].reg)?;
  3992. return p.blocks[b]
  3993. .phis
  3994. .iter()
  3995. .find(|q| q.reg == h)
  3996. .map(|q| q.value);
  3997. }
  3998. let b = *self.def_block.get(&lo)?;
  3999. let inst = p.blocks[b]
  4000. .insts
  4001. .iter()
  4002. .find(|i| i.writes.iter().any(|w| w.1 == lo))?;
  4003. let &(reg, _) = inst.writes.iter().find(|w| w.1 == lo)?;
  4004. inst.write(pick(reg)?)
  4005. }
  4006. fn guard(&mut self, b: usize, i: usize) -> Result<Option<V>, Why> {
  4007. match self.x.st.guards[b][i] {
  4008. None => Ok(None),
  4009. Some(g) => Ok(Some(self.boolean(g, self.cur)?)),
  4010. }
  4011. }
  4012. // ---- results ----
  4013. fn set(&mut self, v: Option<Value>, val: Val) {
  4014. if let Some(v) = v {
  4015. self.vals.insert(v, val);
  4016. }
  4017. }
  4018. /// Writes VGPR `reg` (or the SGPR of a lane read), under `guard`.
  4019. fn write(&mut self, inst: &Inst, reg: Reg, x: V, guard: Option<V>) {
  4020. let x = match (Self::sdwa_dst(inst), reg) {
  4021. (Some((sel, unused)), Reg::V(_)) => self.place_bits(inst, reg, x, sel, unused),
  4022. _ => x,
  4023. };
  4024. self.write_placed(inst, reg, x, guard);
  4025. }
  4026. /// [`Self::write`] of a dword already placed (SDWA applied).
  4027. fn write_placed(&mut self, inst: &Inst, reg: Reg, x: V, guard: Option<V>) {
  4028. let Some(new) = inst.write(reg) else { return };
  4029. let x = match (guard, reg) {
  4030. (Some(g), Reg::V(_)) => {
  4031. let old = match inst.read(reg).map(|o| self.i32_of(o)) {
  4032. Some(Ok(o)) => o,
  4033. // The validator refuses reads of undef.
  4034. _ => self.s.m.i32(0),
  4035. };
  4036. let v = self.s.m.select(self.cur, g, x, old);
  4037. self.s.m.tag(v, Tag::Guard);
  4038. v
  4039. }
  4040. _ => x,
  4041. };
  4042. self.vals.insert(new, Val::I32(x));
  4043. }
  4044. /// The SDWA destination selection: a byte or word, and what the other
  4045. /// bits get (0 zeros, 1 the sign above the field, 2 the old bits).
  4046. fn sdwa_dst(inst: &Inst) -> Option<(u8, u8)> {
  4047. let Fields::Valu(v) = &inst.fields else {
  4048. return None;
  4049. };
  4050. let s = v.sdwa?;
  4051. (s.dst_sel < 6).then_some((s.dst_sel, s.dst_unused))
  4052. }
  4053. /// The low byte or word of `x` placed at `sel` in VGPR `reg`.
  4054. fn place_bits(&mut self, inst: &Inst, reg: Reg, x: V, sel: u8, unused: u8) -> V {
  4055. let c = self.cur;
  4056. let (width, at) = if sel < 4 {
  4057. (8u32, 8 * u32::from(sel))
  4058. } else {
  4059. (16, 16 * u32::from(sel - 4))
  4060. };
  4061. let left = self.s.m.i32(32 - width);
  4062. let t = self.s.m.bin(c, Bin::Shl, x, left);
  4063. let right = self.s.m.i32(32 - width - at);
  4064. if unused == 1 {
  4065. // Bits below the field shift in as zeros.
  4066. return self.s.m.bin(c, Bin::AShr, t, right);
  4067. }
  4068. let field = self.s.m.bin(c, Bin::LShr, t, right);
  4069. if unused != 2 {
  4070. return field;
  4071. }
  4072. let old = match inst.read(reg).map(|o| self.i32_of(o)) {
  4073. Some(Ok(o)) => o,
  4074. _ => self.s.m.i32(0),
  4075. };
  4076. let keep = self.s.m.i32(!((((1u64 << width) - 1) as u32) << at));
  4077. let old = self.s.m.bin(c, Bin::And, old, keep);
  4078. self.s.m.bin(c, Bin::Or, old, field)
  4079. }
  4080. fn write_f(&mut self, inst: &Inst, f: V, guard: Option<V>) -> Result<(), Why> {
  4081. let Fields::Valu(v) = &inst.fields else {
  4082. unreachable!()
  4083. };
  4084. let mut f = f;
  4085. match v.omod {
  4086. 0 => {}
  4087. k => {
  4088. let factor = [1.0f32, 2.0, 4.0, 0.5][usize::from(k)];
  4089. let c = self.s.m.f32(factor.to_bits());
  4090. f = self.s.m.bin(self.cur, Bin::Mul, f, c);
  4091. }
  4092. }
  4093. if v.clamp {
  4094. f = self.unary(7, f);
  4095. }
  4096. let Some(Operand::Vector { reg, .. }) = v.dst else {
  4097. return Err("a float result outside a VGPR");
  4098. };
  4099. let x = self.as_int(f);
  4100. self.write(inst, Reg::V(reg), x, guard);
  4101. if guard.is_none()
  4102. && Self::sdwa_dst(inst).is_none()
  4103. && let Some(new) = inst.write(Reg::V(reg))
  4104. {
  4105. self.floats.insert(new, f);
  4106. }
  4107. Ok(())
  4108. }
  4109. fn write_i(&mut self, inst: &Inst, x: V, guard: Option<V>) -> Result<(), Why> {
  4110. let Fields::Valu(v) = &inst.fields else {
  4111. unreachable!()
  4112. };
  4113. if v.clamp || v.omod != 0 {
  4114. return Err("integer output modifiers");
  4115. }
  4116. match v.dst {
  4117. Some(Operand::Vector { reg, .. }) => self.write(inst, Reg::V(reg), x, guard),
  4118. Some(Operand::Scalar { code, .. }) => self.write(inst, Reg::S(code), x, None),
  4119. _ => return Err("a result without a register"),
  4120. }
  4121. Ok(())
  4122. }
  4123. /// Starts code only the lanes where `guard` holds run (a store under a
  4124. /// lane guard): returns where it started and the join block.
  4125. fn begin_guarded(&mut self, guard: Option<V>) -> Option<(usize, usize)> {
  4126. let g = guard?;
  4127. let (then, join) = (self.s.m.new_block(), self.s.m.new_block());
  4128. self.s.m.terminate(self.cur, Term::CondBr(g, then, join));
  4129. let head = self.cur;
  4130. self.cur = then;
  4131. Some((head, join))
  4132. }
  4133. /// Ends guarded code; each (value inside, value outside) becomes a phi.
  4134. fn end_guarded(&mut self, at: Option<(usize, usize)>, values: &[(V, V)]) -> Vec<V> {
  4135. let Some((head, join)) = at else {
  4136. return values.iter().map(|v| v.0).collect();
  4137. };
  4138. let then = self.cur;
  4139. self.s.m.terminate(then, Term::Br(join));
  4140. self.cur = join;
  4141. values
  4142. .iter()
  4143. .map(|&(inside, outside)| {
  4144. let ty = self.s.m.type_of(inside);
  4145. let phi = self.s.m.phi(join, ty);
  4146. self.s.m.set_phi(phi, vec![(inside, then), (outside, head)]);
  4147. phi
  4148. })
  4149. .collect()
  4150. }
  4151. /// Code that depends on the lane layout: wave operations, and in compute
  4152. /// the console's wave size (lanes are thread ids in group order there).
  4153. /// Pixel lanes match only within a quad.
  4154. fn cross_lane(&mut self, quad: bool) -> Result<(), Why> {
  4155. if self.s.mesh.is_some() {
  4156. // shortcut: no wave size for mesh shaders in SM 6.6, so host
  4157. // lanes cannot follow the console's; emulate through group-shared
  4158. // memory if mesh programs turn out to need these.
  4159. return Err("a cross-lane operation in a mesh shader");
  4160. }
  4161. if self.s.threads.is_none() && !(quad && self.s.pixel) {
  4162. return Err("a cross-lane operation outside compute");
  4163. }
  4164. debug_assert!(self.s.threads.is_none() || self.console_lanes);
  4165. self.s.flags |= flags::WAVE_OPS;
  4166. Ok(())
  4167. }
  4168. /// Component `c` of the thread id in the group. With console lanes, the
  4169. /// thread is relabelled so that its host lane is its console lane: the
  4170. /// flat id is the wave's first lane's, rounded down to the wave size,
  4171. /// plus the lane index. (A bijection while each host wave holds a
  4172. /// wave-aligned run of flat ids, as the console's waves do.)
  4173. fn thread_id(&mut self, c: u8) -> Val {
  4174. if !self.console_lanes {
  4175. return self.compute_id("threadIdInGroup.i32", 95, c);
  4176. }
  4177. let [x, y, _] = self.s.threads.expect("compute");
  4178. let e = self.s.entry;
  4179. let i32t = self.s.t.i32;
  4180. if self.halves.is_some() {
  4181. let f = self.console_thread();
  4182. self.s.flags |= flags::WAVE_OPS;
  4183. let (xk, yk, xy) = (self.s.m.i32(x), self.s.m.i32(y), self.s.m.i32(x * y));
  4184. return Val::I32(match c {
  4185. 0 => self.s.m.bin(e, Bin::URem, f, xk),
  4186. 1 => {
  4187. let t = self.s.m.bin(e, Bin::UDiv, f, xk);
  4188. self.s.m.bin(e, Bin::URem, t, yk)
  4189. }
  4190. _ => self.s.m.bin(e, Bin::UDiv, f, xy),
  4191. });
  4192. }
  4193. let flat = self.s.op(
  4194. e,
  4195. "flattenedThreadIdInGroup.i32",
  4196. Attr::ReadNone,
  4197. i32t,
  4198. 96,
  4199. &[],
  4200. );
  4201. let first = self.s.op(
  4202. e,
  4203. "waveReadLaneFirst.i32",
  4204. Attr::NoUnwind,
  4205. i32t,
  4206. 118,
  4207. &[flat],
  4208. );
  4209. let wave = self.s.wave_size.expect("set with console lanes");
  4210. let mask = self.s.m.i32(!(wave - 1));
  4211. let base = self.s.m.bin(e, Bin::And, first, mask);
  4212. let lane = self.lane_index();
  4213. let f = self.s.m.bin(e, Bin::Add, base, lane);
  4214. self.s.flags |= flags::WAVE_OPS;
  4215. let (xk, yk, xy) = (self.s.m.i32(x), self.s.m.i32(y), self.s.m.i32(x * y));
  4216. Val::I32(match c {
  4217. 0 => self.s.m.bin(e, Bin::URem, f, xk),
  4218. 1 => {
  4219. let t = self.s.m.bin(e, Bin::UDiv, f, xk);
  4220. self.s.m.bin(e, Bin::URem, t, yk)
  4221. }
  4222. _ => self.s.m.bin(e, Bin::UDiv, f, xy),
  4223. })
  4224. }
  4225. /// Mesh: the counts and the primitives no lane exports. The console's
  4226. /// counts come from one lane's allocation request, which DXIL cannot
  4227. /// express (one call, dominating every output write).
  4228. // shortcut: the counts are the declared maxima and each lane first culls
  4229. // its primitive (all indices 0, zero area), so primitives past the
  4230. // program's count are culled and vertices past it unused; this costs
  4231. // the host the unused vertex and primitive slots. Pass the program's own
  4232. // counts if that shows in frame time.
  4233. fn mesh_prologue(&mut self, mut mesh: super::shader::Mesh) -> Result<(), Why> {
  4234. let threads = self.s.threads.expect("mesh")[0];
  4235. if mesh.topology != 2 {
  4236. return Err("a mesh shader not drawing triangles");
  4237. }
  4238. if threads > 128 || mesh.max_vertices > 256 || mesh.max_primitives > 256 {
  4239. return Err("a mesh shader beyond the host's limits");
  4240. }
  4241. // D3D12 caps the outputs of the declared maxima at 32 KiB. Lane n
  4242. // writes only vertex n and primitive n, so maxima past the lanes are
  4243. // never reached: they come down to the lane count when the outputs
  4244. // do not fit.
  4245. use super::container::{MESH_OUTPUT_LIMIT, mesh_output_bytes};
  4246. let (outputs, prims) = (&self.s.outputs, &self.s.prims);
  4247. let fits = |m: super::shader::Mesh| {
  4248. mesh_output_bytes(outputs, prims, m.max_vertices, m.max_primitives) <= MESH_OUTPUT_LIMIT
  4249. };
  4250. if !fits(mesh) {
  4251. mesh.max_vertices = mesh.max_vertices.min(threads);
  4252. mesh.max_primitives = mesh.max_primitives.min(threads);
  4253. // shortcut: outputs past the cap even at the lane count are
  4254. // still emitted with the lower maxima (drivers take them);
  4255. // refuse them here if one hangs.
  4256. // Experiment (`VICTORY_MESH_OUTPUT_STRICT=1`): they are refused.
  4257. if !fits(mesh) && std::env::var_os("VICTORY_MESH_OUTPUT_STRICT").is_some() {
  4258. return Err("a mesh shader whose outputs pass the host's 32 KiB");
  4259. }
  4260. self.s.mesh = Some(mesh);
  4261. }
  4262. let e = self.s.entry;
  4263. let void = self.s.t.void;
  4264. let (v, p) = (
  4265. self.s.m.i32(mesh.max_vertices),
  4266. self.s.m.i32(mesh.max_primitives),
  4267. );
  4268. self.s
  4269. .op(e, "setMeshOutputCounts", Attr::NoUnwind, void, 168, &[v, p]);
  4270. let flat = self.mesh_thread();
  4271. let z = self.s.m.i32(0);
  4272. // Every primitive of the declared count starts culled, also those
  4273. // past the lanes (a count of 256 with 128 lanes): lane n culls
  4274. // primitives n, n + lanes, ... The host draws all it was promised,
  4275. // and one never written has whatever indices its memory held: long
  4276. // triangles over the whole target, each pixel of them shaded.
  4277. let passes = mesh.max_primitives.div_ceil(threads.max(1));
  4278. for pass in 0..passes {
  4279. let index = if pass == 0 {
  4280. flat
  4281. } else {
  4282. let past = self.s.m.i32(pass * threads);
  4283. self.s.m.bin(self.cur, Bin::Add, flat, past)
  4284. };
  4285. let guard = ((pass + 1) * threads > mesh.max_primitives)
  4286. .then(|| self.s.m.cmp(self.cur, pred::IULT, index, p));
  4287. let at = self.begin_guarded(guard);
  4288. self.s.op(
  4289. self.cur,
  4290. "emitIndices",
  4291. Attr::NoUnwind,
  4292. void,
  4293. 169,
  4294. &[index, z, z, z],
  4295. );
  4296. self.end_guarded(at, &[]);
  4297. }
  4298. Ok(())
  4299. }
  4300. /// Mesh: the thread's index in the group, which is its vertex and
  4301. /// primitive index.
  4302. fn mesh_thread(&mut self) -> V {
  4303. if let Some(f) = self.flat {
  4304. return f;
  4305. }
  4306. let e = self.s.entry;
  4307. let f = self.s.op(
  4308. e,
  4309. "flattenedThreadIdInGroup.i32",
  4310. Attr::ReadNone,
  4311. self.s.t.i32,
  4312. 96,
  4313. &[],
  4314. );
  4315. self.flat = Some(f);
  4316. f
  4317. }
  4318. /// The console wave size.
  4319. fn wave(&self) -> u32 {
  4320. if self.x.native.wave64 { 64 } else { 32 }
  4321. }
  4322. fn lane_index(&mut self) -> V {
  4323. if self.s.mesh.is_some() {
  4324. // The console's lane: mesh code reads no other lanes, so host
  4325. // waves need not match the console's.
  4326. let f = self.mesh_thread();
  4327. let m = self.s.m.i32(self.wave() - 1);
  4328. return self.s.m.bin(self.s.entry, Bin::And, f, m);
  4329. }
  4330. self.s.op(
  4331. self.cur,
  4332. "waveGetLaneIndex",
  4333. Attr::ReadOnly,
  4334. self.s.t.i32,
  4335. 111,
  4336. &[],
  4337. )
  4338. }
  4339. /// `x` of lane `src` (in this lane's quad) through quad reads, whose
  4340. /// lane must be a constant.
  4341. fn quad_pick(&mut self, x: V, src: V) -> V {
  4342. self.s.flags |= flags::WAVE_OPS;
  4343. let c = self.cur;
  4344. let three = self.s.m.i32(3);
  4345. let q = self.s.m.bin(c, Bin::And, src, three);
  4346. let mut r = x;
  4347. for n in 0..4 {
  4348. let kn = self.s.m.i32(n);
  4349. let read = self.s.op(
  4350. c,
  4351. "quadReadLaneAt.i32",
  4352. Attr::NoUnwind,
  4353. self.s.t.i32,
  4354. 122,
  4355. &[x, kn],
  4356. );
  4357. let is = self.s.m.cmp(c, pred::EQ, q, kn);
  4358. r = self.s.m.select(c, is, read, r);
  4359. }
  4360. r
  4361. }
  4362. /// Whether a quad-local read takes its lane with the host's quad
  4363. /// operations: in a pixel program always. Lanes of a quad the primitive
  4364. /// does not cover, or that were discarded, are helpers on the host;
  4365. /// wave reads leave those out (AMD gives 0 from them), quad reads are
  4366. /// what reaches them.
  4367. fn helpers_read(&self, quad: bool) -> bool {
  4368. quad && self.s.pixel
  4369. }
  4370. /// `x` of the lane of this lane's quad that `lanes` names for each of
  4371. /// the quad's four, by the host's quad operations.
  4372. fn quad_read(&mut self, x: V, lanes: [u8; 4]) -> V {
  4373. self.s.flags |= flags::WAVE_OPS;
  4374. let c = self.cur;
  4375. let i32t = self.s.t.i32;
  4376. if lanes == [0, 1, 2, 3] {
  4377. return x;
  4378. }
  4379. // One lane for all.
  4380. if lanes.iter().all(|&l| l == lanes[0]) {
  4381. let n = self.s.m.i32(lanes[0].into());
  4382. return self.s.op(
  4383. c,
  4384. "quadReadLaneAt.i32",
  4385. Attr::NoUnwind,
  4386. i32t,
  4387. 122,
  4388. &[x, n],
  4389. );
  4390. }
  4391. // Else each lane's own, its neighbour across in x (1) or y (2), or
  4392. // the diagonal one (3).
  4393. let across = |i: usize| i as u8 ^ lanes[i];
  4394. let mut r = None;
  4395. for by in 0..4u8 {
  4396. if !(0..4).any(|i| across(i) == by) {
  4397. continue;
  4398. }
  4399. let read = if by == 0 {
  4400. x
  4401. } else {
  4402. // QuadReadAcrossX, Y, Diagonal.
  4403. let kind = self.s.m.i8(by - 1);
  4404. self.s
  4405. .op(c, "quadOp.i32", Attr::NoUnwind, i32t, 123, &[x, kind])
  4406. };
  4407. r = Some(match r {
  4408. None => read,
  4409. Some(r) => {
  4410. let mut here = self.s.m.bool(false);
  4411. let lane = self.lane_index();
  4412. let three = self.s.m.i32(3);
  4413. let at = self.s.m.bin(c, Bin::And, lane, three);
  4414. for i in (0..4).filter(|&i| across(i) == by) {
  4415. let k = self.s.m.i32(i as u32);
  4416. let is = self.s.m.cmp(c, pred::EQ, at, k);
  4417. here = self.s.m.bin(c, Bin::Or, here, is);
  4418. }
  4419. self.s.m.select(c, here, read, r)
  4420. }
  4421. });
  4422. }
  4423. r.unwrap_or(x)
  4424. }
  4425. /// `x` in the first lane of this host wave where `guard` holds, and whether it has such a
  4426. /// lane: the console reads the first lane of EXEC, and a lane that got here with EXEC clear
  4427. /// (a guard, not a branch) is not one. With none, `x` of the wave's first lane here.
  4428. ///
  4429. /// A helper lane of a pixel shader takes its own value: the console's whole-quad mode has
  4430. /// helper lanes in EXEC, so a waterfall loop serves them too, and the host's wave operations
  4431. /// leave them out. Once only helper lanes are left in such a loop none of them ever matched:
  4432. /// they ran to the iteration limit, and left with no sample for their quad's derivatives,
  4433. /// along every triangle's edges (upstream #908, the fix of #1733 for this tree's form).
  4434. fn first_lane(&mut self, x: V, guard: Option<V>) -> (V, V) {
  4435. let (first, any) = self.first_live_lane(x, guard);
  4436. if !self.s.pixel || !super::helper_own() {
  4437. return (first, any);
  4438. }
  4439. let helper = self.helper_lane();
  4440. let c = self.cur;
  4441. let yes = self.s.m.bool(true);
  4442. (self.s.m.select(c, helper, x, first), self.s.m.select(c, helper, yes, any))
  4443. }
  4444. /// Whether this lane of a pixel shader is a helper lane.
  4445. fn helper_lane(&mut self) -> V {
  4446. let i1t = self.s.t.i1;
  4447. self.s.op(self.cur, "isHelperLane.i1", Attr::ReadOnly, i1t, 221, &[])
  4448. }
  4449. fn first_live_lane(&mut self, x: V, guard: Option<V>) -> (V, V) {
  4450. let c = self.cur;
  4451. let i32t = self.s.t.i32;
  4452. self.s.flags |= flags::WAVE_OPS;
  4453. let first = self.s.op(c, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[x]);
  4454. let Some(g) = guard else {
  4455. return (first, self.s.m.bool(true));
  4456. };
  4457. let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]);
  4458. let r = self.s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[g]);
  4459. let (lo, hi) = (self.s.m.extract(c, r, 0), self.s.m.extract(c, r, 1));
  4460. let (z, k32) = (self.s.m.i32(0), self.s.m.i32(32));
  4461. // FirstbitLo (dx.op 32): the lowest set bit
  4462. let flo = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[lo]);
  4463. let fhi = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[hi]);
  4464. let fhi = self.s.m.bin(c, Bin::Add, fhi, k32);
  4465. let in_lo = self.s.m.cmp(c, pred::NE, lo, z);
  4466. let in_hi = self.s.m.cmp(c, pred::NE, hi, z);
  4467. let any = self.s.m.bin(c, Bin::Or, in_lo, in_hi);
  4468. let lane = self.s.m.select(c, in_lo, flo, fhi);
  4469. // no lane in EXEC: read this lane (one that is here); the read is not used
  4470. let me = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
  4471. let lane = self.s.m.select(c, any, lane, me);
  4472. let at = self.read_lane(x, lane);
  4473. (self.s.m.select(c, any, at, first), any)
  4474. }
  4475. fn read_lane(&mut self, x: V, lane: V) -> V {
  4476. self.s.op(
  4477. self.cur,
  4478. "waveReadLaneAt.i32",
  4479. Attr::NoUnwind,
  4480. self.s.t.i32,
  4481. 117,
  4482. &[x, lane],
  4483. )
  4484. }
  4485. /// The float value of a register value.
  4486. fn float_of(&mut self, v: Value) -> Result<V, Why> {
  4487. if let Some(&f) = self.floats.get(&v) {
  4488. return Ok(f);
  4489. }
  4490. let x = self.i32_of(v)?;
  4491. Ok(self.as_float(x))
  4492. }
  4493. /// The values of VGPRs `reg..reg + n` as `inst` reads them.
  4494. fn vgprs(&mut self, inst: &Inst, op: &Operand, n: u8) -> Result<Vec<V>, Why> {
  4495. let Operand::Vector { reg, .. } = *op else {
  4496. return Err("a vector operand");
  4497. };
  4498. (0..n)
  4499. .map(|k| {
  4500. let v = inst.read(Reg::V(reg + k)).ok_or("an unread operand")?;
  4501. self.i32_of(v)
  4502. })
  4503. .collect()
  4504. }
  4505. /// LDS (thread-group shared memory) and `ds_swizzle`.
  4506. fn ds(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  4507. let Fields::Ds {
  4508. dst,
  4509. addr,
  4510. data,
  4511. offset0,
  4512. offset1,
  4513. gds,
  4514. } = &inst.fields
  4515. else {
  4516. unreachable!()
  4517. };
  4518. if *gds {
  4519. return Err("GDS");
  4520. }
  4521. let name = inst.name();
  4522. let guard = self.guard(b, i)?;
  4523. let c = self.cur;
  4524. let offset = u32::from(*offset0) | u32::from(*offset1) << 8;
  4525. let dst_reg = match dst {
  4526. Some(Operand::Vector { reg, .. }) => Some(*reg),
  4527. _ => None,
  4528. };
  4529. if name == "ds_swizzle_b32" {
  4530. // Bit 15 set: each lane of a quad picks a lane of it; else lanes
  4531. // of each group of 32 combine their index with and/or/xor masks.
  4532. let quad = offset & 0x8000 != 0
  4533. || offset & 0x1C == 0x1C && offset & 0x380 == 0 && offset >> 10 & 0x1F < 4;
  4534. // Mesh: host quads are threads 4n..4n+3 of a 1D group, as the
  4535. // console's, so quad-local swizzles read through quad operations.
  4536. let mesh_quad = self.s.mesh.is_some() && quad;
  4537. if !mesh_quad {
  4538. self.cross_lane(quad)?;
  4539. }
  4540. // The source sits in the address field.
  4541. let x = self.vgprs(inst, addr.as_ref().ok_or("a swizzle source")?, 1)?[0];
  4542. let lane = self.lane_index();
  4543. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  4544. let src = if offset & 0x8000 != 0 {
  4545. let (three, one) = (k(self, 3), k(self, 1));
  4546. let sel = self.s.m.bin(c, Bin::And, lane, three);
  4547. let sh = self.s.m.bin(c, Bin::Shl, sel, one);
  4548. let pattern = k(self, offset & 0xFF);
  4549. let pick = self.s.m.bin(c, Bin::LShr, pattern, sh);
  4550. let pick = self.s.m.bin(c, Bin::And, pick, three);
  4551. let not3 = k(self, !3);
  4552. let base = self.s.m.bin(c, Bin::And, lane, not3);
  4553. self.s.m.bin(c, Bin::Or, base, pick)
  4554. } else {
  4555. let and = k(self, offset & 0x1F | !0x1F);
  4556. let or = k(self, offset >> 5 & 0x1F);
  4557. let xor = k(self, offset >> 10 & 0x1F);
  4558. let t = self.s.m.bin(c, Bin::And, lane, and);
  4559. let t = self.s.m.bin(c, Bin::Or, t, or);
  4560. self.s.m.bin(c, Bin::Xor, t, xor)
  4561. };
  4562. let r = if mesh_quad {
  4563. self.quad_pick(x, src)
  4564. } else if self.helpers_read(quad) {
  4565. let lanes = if offset & 0x8000 != 0 {
  4566. [0, 1, 2, 3].map(|i| (offset >> (2 * i) & 3) as u8)
  4567. } else {
  4568. [0, 1, 2, 3].map(|i| ((i & offset | offset >> 5 & 3) ^ offset >> 10 & 3) as u8 & 3)
  4569. };
  4570. self.quad_read(x, lanes)
  4571. } else {
  4572. self.read_lane(x, src)
  4573. };
  4574. let reg = dst_reg.ok_or("a swizzle result")?;
  4575. self.write(inst, Reg::V(reg), r, guard);
  4576. return Ok(());
  4577. }
  4578. if name == "ds_bpermute_b32" {
  4579. // Backward permute: no LDS is touched. Each lane takes the data
  4580. // register of the lane its address names, (address + offset) / 4
  4581. // within the wave; a source lane outside EXEC gives 0. (
  4582. // the title's checkerboard shadow-mask generators read their
  4583. // neighbours' samples with it; without them every shadowed light
  4584. // was multiplied by an empty mask.)
  4585. // shortcut: a source lane that is not at this instruction on the
  4586. // host (it left through a branch, not a guard) is read as the
  4587. // host gives it; the console reads 0.
  4588. self.cross_lane(false)?;
  4589. if self.exchange.as_ref().is_some_and(|e| !e.1) {
  4590. // a console wave of 64 run as two host waves: the lane named
  4591. // may be in the other one
  4592. return Err("a lane permute across two host waves");
  4593. }
  4594. let at = self.vgprs(inst, addr.as_ref().ok_or("a permute address")?, 1)?[0];
  4595. let x = self.vgprs(inst, data.first().ok_or("a permute source")?, 1)?[0];
  4596. let o = self.s.m.i32(offset);
  4597. let at = self.s.m.bin(c, Bin::Add, at, o);
  4598. let two = self.s.m.i32(2);
  4599. let src = self.s.m.bin(c, Bin::LShr, at, two);
  4600. let last = self.s.m.i32(self.wave() - 1);
  4601. let src = self.s.m.bin(c, Bin::And, src, last);
  4602. let x = match guard {
  4603. Some(g) => {
  4604. let z = self.s.m.i32(0);
  4605. self.s.m.select(c, g, x, z)
  4606. }
  4607. None => x,
  4608. };
  4609. let r = self.read_lane(x, src);
  4610. let reg = dst_reg.ok_or("a permute result")?;
  4611. self.write(inst, Reg::V(reg), r, guard);
  4612. return Ok(());
  4613. }
  4614. if self.s.lds_dwords == 0 {
  4615. return Err("LDS the program does not allocate");
  4616. }
  4617. let a = self.vgprs(inst, addr.as_ref().ok_or("an LDS address")?, 1)?[0];
  4618. // shortcut: LDS addresses are taken as dword-aligned and in bounds
  4619. // (out-of-bounds console accesses read 0 and drop writes).
  4620. let dword = |l: &mut Self, bytes: u32| -> V {
  4621. let c = l.cur;
  4622. let o = l.s.m.i32(bytes);
  4623. let at = l.s.m.bin(c, Bin::Add, a, o);
  4624. let two = l.s.m.i32(2);
  4625. let index = l.s.m.bin(c, Bin::LShr, at, two);
  4626. let lds = l.s.lds();
  4627. l.s.m.element(c, lds, index)
  4628. };
  4629. let width = |n: &str| match n.rsplit('_').next() {
  4630. Some("b64") => 2,
  4631. Some("b96") => 3,
  4632. Some("b128") => 4,
  4633. _ => 1,
  4634. };
  4635. // (byte offset, dwords) per element; read2/write2 scale their two
  4636. // offsets by the element size (×64 for st64).
  4637. let pair = |n: &str| -> Vec<(u32, u32)> {
  4638. let w = width(n);
  4639. let scale = 4 * w * if n.contains("st64") { 64 } else { 1 };
  4640. vec![
  4641. (u32::from(*offset0) * scale, w),
  4642. (u32::from(*offset1) * scale, w),
  4643. ]
  4644. };
  4645. // Bytes and halves: the dword holding them, and their bit position
  4646. // in it (naturally aligned, so they never straddle dwords).
  4647. // `_d16` reads fill a register's low half (`_d16_hi` its high half)
  4648. // and keep the other; `_d16_hi` writes take the data's high half.
  4649. let base = name.trim_end_matches("_hi").trim_end_matches("_d16");
  4650. let sub = match base {
  4651. "ds_read_u8" | "ds_read_i8" | "ds_write_b8" => Some(8u32),
  4652. "ds_read_u16" | "ds_read_i16" | "ds_write_b16" => Some(16),
  4653. _ => None,
  4654. };
  4655. let sub = sub.filter(|_| {
  4656. base == name
  4657. || name.ends_with("_d16") && base.starts_with("ds_read")
  4658. || name.ends_with("_d16_hi")
  4659. });
  4660. if let Some(bits) = sub {
  4661. let p = dword(self, offset);
  4662. let o = self.s.m.i32(offset);
  4663. let at = self.s.m.bin(c, Bin::Add, a, o);
  4664. let three = self.s.m.i32(3);
  4665. let byte = self.s.m.bin(c, Bin::And, at, three);
  4666. let sh = self.s.m.bin(c, Bin::Shl, byte, three);
  4667. let mask = self.s.m.i32((1u32 << bits) - 1);
  4668. if name.starts_with("ds_read") {
  4669. let reg = dst_reg.ok_or("an LDS read result")?;
  4670. let w = self.s.m.load(c, p);
  4671. let x = self.s.m.bin(c, Bin::LShr, w, sh);
  4672. let x = if base.contains("_i") {
  4673. let k = self.s.m.i32(32 - bits);
  4674. let x = self.s.m.bin(c, Bin::Shl, x, k);
  4675. self.s.m.bin(c, Bin::AShr, x, k)
  4676. } else {
  4677. self.s.m.bin(c, Bin::And, x, mask)
  4678. };
  4679. let x = if base == name {
  4680. x
  4681. } else {
  4682. let old = match inst.read(Reg::V(reg)) {
  4683. Some(v) => self.i32_of(v)?,
  4684. None => self.s.m.i32(0),
  4685. };
  4686. let half = self.s.m.i32(0xFFFF);
  4687. let x = self.s.m.bin(c, Bin::And, x, half);
  4688. let (x, keep) = if name.ends_with("_hi") {
  4689. let k16 = self.s.m.i32(16);
  4690. (self.s.m.bin(c, Bin::Shl, x, k16), half)
  4691. } else {
  4692. (x, self.s.m.i32(0xFFFF_0000))
  4693. };
  4694. let old = self.s.m.bin(c, Bin::And, old, keep);
  4695. self.s.m.bin(c, Bin::Or, old, x)
  4696. };
  4697. self.write(inst, Reg::V(reg), x, guard);
  4698. } else {
  4699. // Clear, then set: two atomics, so lanes writing other
  4700. // bytes of the dword keep theirs.
  4701. let mut x = self.vgprs(inst, data.first().ok_or("an LDS write")?, 1)?[0];
  4702. if name != base {
  4703. // The data's high half.
  4704. let k16 = self.s.m.i32(16);
  4705. x = self.s.m.bin(c, Bin::LShr, x, k16);
  4706. }
  4707. let x = self.s.m.bin(c, Bin::And, x, mask);
  4708. let x = self.s.m.bin(c, Bin::Shl, x, sh);
  4709. let m = self.s.m.bin(c, Bin::Shl, mask, sh);
  4710. let ones = self.s.m.i32(u32::MAX);
  4711. let keep = self.s.m.bin(c, Bin::Xor, m, ones);
  4712. use super::bitcode::Rmw;
  4713. let at = self.begin_guarded(guard);
  4714. self.s.m.atomic(self.cur, Rmw::And, p, keep);
  4715. self.s.m.atomic(self.cur, Rmw::Or, p, x);
  4716. self.end_guarded(at, &[]);
  4717. }
  4718. return Ok(());
  4719. }
  4720. if let Some(rest) = name.strip_prefix("ds_read") {
  4721. let elements = if rest.starts_with('2') {
  4722. pair(name)
  4723. } else if matches!(rest, "_b32" | "_b64" | "_b96" | "_b128") {
  4724. vec![(offset, width(name))]
  4725. } else {
  4726. return Err("an LDS read of bytes or halves");
  4727. };
  4728. let reg = dst_reg.ok_or("an LDS read result")?;
  4729. let mut n = 0;
  4730. for (off, w) in elements {
  4731. for k in 0..w {
  4732. let p = dword(self, off + 4 * k);
  4733. let x = self.s.m.load(self.cur, p);
  4734. self.write(inst, Reg::V(reg + n), x, guard);
  4735. n += 1;
  4736. }
  4737. }
  4738. return Ok(());
  4739. }
  4740. if let Some(rest) = name.strip_prefix("ds_write") {
  4741. let elements = if rest.starts_with('2') {
  4742. pair(name)
  4743. } else if matches!(rest, "_b32" | "_b64" | "_b96" | "_b128") {
  4744. vec![(offset, width(name))]
  4745. } else {
  4746. return Err("an LDS write of bytes or halves");
  4747. };
  4748. let mut stores = Vec::new();
  4749. for (e, (off, w)) in elements.into_iter().enumerate() {
  4750. let vals = self.vgprs(inst, data.get(e).ok_or("an LDS write")?, w as u8)?;
  4751. for (k, x) in vals.into_iter().enumerate() {
  4752. stores.push((off + 4 * k as u32, x));
  4753. }
  4754. }
  4755. let at = self.begin_guarded(guard);
  4756. for (off, x) in stores {
  4757. let p = dword(self, off);
  4758. self.s.m.store(self.cur, p, x);
  4759. }
  4760. self.end_guarded(at, &[]);
  4761. return Ok(());
  4762. }
  4763. // Atomics: the old value returns with `_rtn`.
  4764. let op = name
  4765. .strip_prefix("ds_")
  4766. .map(|n| n.replace("_rtn", ""))
  4767. .ok_or("an LDS operation")?;
  4768. use super::bitcode::Rmw;
  4769. let rmw = match op.as_str() {
  4770. "add_u32" => Some(Rmw::Add),
  4771. "sub_u32" => Some(Rmw::Sub),
  4772. "and_b32" => Some(Rmw::And),
  4773. "or_b32" => Some(Rmw::Or),
  4774. "xor_b32" => Some(Rmw::Xor),
  4775. "min_i32" => Some(Rmw::Min),
  4776. "max_i32" => Some(Rmw::Max),
  4777. "min_u32" => Some(Rmw::UMin),
  4778. "max_u32" => Some(Rmw::UMax),
  4779. "wrxchg_b32" => Some(Rmw::Xchg),
  4780. "cmpst_b32" | "max_f32" | "min_f32" => None,
  4781. _ => return Err("an LDS operation"),
  4782. };
  4783. let v0 = self.vgprs(inst, data.first().ok_or("an LDS atomic")?, 1)?[0];
  4784. let v1 = match data.get(1) {
  4785. Some(d) => Some(self.vgprs(inst, d, 1)?[0]),
  4786. None => None,
  4787. };
  4788. let old_reg = dst_reg.and_then(|r| inst.read(Reg::V(r)).map(|v| (r, v)));
  4789. let outside = match old_reg {
  4790. Some((_, v)) => self.i32_of(v).unwrap_or(self.s.m.i32(0)),
  4791. None => self.s.m.i32(0),
  4792. };
  4793. let p = dword(self, offset);
  4794. if let Some(max) = match op.as_str() {
  4795. "max_f32" => Some(true),
  4796. "min_f32" => Some(false),
  4797. _ => None,
  4798. } {
  4799. let at = self.begin_guarded(guard);
  4800. let r = self.lds_float_min_max(p, v0, max);
  4801. let r = self.end_guarded(at, &[(r, outside)])[0];
  4802. if let Some(reg) = dst_reg {
  4803. self.write(inst, Reg::V(reg), r, None);
  4804. }
  4805. return Ok(());
  4806. }
  4807. let at = self.begin_guarded(guard);
  4808. let r = match rmw {
  4809. Some(op) => self.s.m.atomic(self.cur, op, p, v0),
  4810. // Compare with data0, store data1.
  4811. None => self
  4812. .s
  4813. .m
  4814. .cmpxchg(self.cur, p, v0, v1.ok_or("an LDS compare")?),
  4815. };
  4816. let r = self.end_guarded(at, &[(r, outside)])[0];
  4817. if let Some(reg) = dst_reg {
  4818. self.write(inst, Reg::V(reg), r, None);
  4819. }
  4820. Ok(())
  4821. }
  4822. /// `ds_max_f32` (`max`) or `ds_min_f32` on the LDS dword at `p` with
  4823. /// the float bits `data`; the old bits return.
  4824. ///
  4825. /// DXIL has no float atomics on group-shared memory, so this is a
  4826. /// compare-exchange loop around [`Lower::lds_float_pick`], which gives
  4827. /// what RDNA2 writes (measured on gfx1036, reported on the pull
  4828. /// request): an sNaN, data first, then memory, is written quieted;
  4829. /// otherwise a NaN loses to a number (two quiet NaNs give the data);
  4830. /// numbers compare as floats with -0 below +0.
  4831. // shortcut: f32 denormals compare as kept; with the console's MODE
  4832. // flushing them they would order as ±0 first (MODE is not modelled).
  4833. fn lds_float_min_max(&mut self, p: V, data: V, max: bool) -> V {
  4834. let pre = self.cur;
  4835. let init = self.s.m.load(pre, p);
  4836. let (lp, exit) = (self.s.m.new_block(), self.s.m.new_block());
  4837. self.s.m.terminate(pre, Term::Br(lp));
  4838. let i32t = self.s.t.i32;
  4839. let old = self.s.m.phi(lp, i32t);
  4840. self.cur = lp;
  4841. let new = self.lds_float_pick(old, data, max);
  4842. let prev = self.s.m.cmpxchg(lp, p, old, new);
  4843. let done = self.s.m.cmp(lp, pred::EQ, prev, old);
  4844. self.s.m.set_phi(old, vec![(init, pre), (prev, lp)]);
  4845. self.s.m.terminate(lp, Term::CondBr(done, exit, lp));
  4846. self.cur = exit;
  4847. old
  4848. }
  4849. /// What `ds_max_f32` (`max`) or `ds_min_f32` writes over the dword
  4850. /// `mem` with `data` (float bits; see [`Lower::lds_float_min_max`]).
  4851. fn lds_float_pick(&mut self, mem: V, data: V, max: bool) -> V {
  4852. let c = self.cur;
  4853. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  4854. let (abs_mask, inf, quiet, zero) = (
  4855. k(self, 0x7FFF_FFFF),
  4856. k(self, 0x7F80_0000),
  4857. k(self, 0x40_0000),
  4858. k(self, 0),
  4859. );
  4860. let nan = |l: &mut Self, x: V| {
  4861. let m = l.s.m.bin(c, Bin::And, x, abs_mask);
  4862. l.s.m.cmp(c, pred::IUGT, m, inf)
  4863. };
  4864. let snan = |l: &mut Self, x: V| {
  4865. let n = nan(l, x);
  4866. let q = l.s.m.bin(c, Bin::And, x, quiet);
  4867. let sig = l.s.m.cmp(c, pred::EQ, q, zero);
  4868. l.s.m.bin(c, Bin::And, n, sig)
  4869. };
  4870. // A total order of the numbers as signed integers, -0 below +0:
  4871. // negative floats' magnitude bits reversed.
  4872. let key = |l: &mut Self, x: V| {
  4873. let k31 = l.s.m.i32(31);
  4874. let sign = l.s.m.bin(c, Bin::AShr, x, k31);
  4875. let flip = l.s.m.bin(c, Bin::And, sign, abs_mask);
  4876. l.s.m.bin(c, Bin::Xor, x, flip)
  4877. };
  4878. let (dk, mk) = (key(self, data), key(self, mem));
  4879. let take = self
  4880. .s
  4881. .m
  4882. .cmp(c, if max { pred::SGT } else { pred::SLT }, dk, mk);
  4883. let r = self.s.m.select(c, take, data, mem);
  4884. let (dn, mn) = (nan(self, data), nan(self, mem));
  4885. // One NaN: the number; two quiet NaNs: the data.
  4886. let r = self.s.m.select(c, mn, data, r);
  4887. let both = self.s.m.bin(c, Bin::And, dn, mn);
  4888. let only_data = {
  4889. let t = self.s.m.bool(true);
  4890. let not_both = self.s.m.bin(c, Bin::Xor, both, t);
  4891. self.s.m.bin(c, Bin::And, dn, not_both)
  4892. };
  4893. let r = self.s.m.select(c, only_data, mem, r);
  4894. // Signalling NaNs win, quieted: the data's first.
  4895. let qm = self.s.m.bin(c, Bin::Or, mem, quiet);
  4896. let sm = snan(self, mem);
  4897. let r = self.s.m.select(c, sm, qm, r);
  4898. let qd = self.s.m.bin(c, Bin::Or, data, quiet);
  4899. let sd = snan(self, data);
  4900. self.s.m.select(c, sd, qd, r)
  4901. }
  4902. // ---- instructions ----
  4903. // ---- instructions ----
  4904. fn inst(&mut self, b: usize, i: usize) -> Result<(), Stop> {
  4905. let inst: &'a Inst = &self.x.p.blocks[b].insts[i];
  4906. let offset = inst.machine.offset;
  4907. let name = inst.name();
  4908. self.local_ok = name.starts_with("s_bcnt1_i32_")
  4909. || name.starts_with("s_ff1_i32_")
  4910. || name.starts_with("v_mbcnt_");
  4911. self.mask_ok = match self.mask_data {
  4912. MaskData::Console => true,
  4913. MaskData::Host => {
  4914. name.starts_with("s_bcnt1_i32_")
  4915. || name.starts_with("s_ff1_i32_")
  4916. || name.starts_with("v_mbcnt_")
  4917. || matches!(
  4918. name,
  4919. "s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_u64" | "s_cmp_lg_u64"
  4920. )
  4921. }
  4922. // Mesh: only "do all lanes hold the first lane's value?" (`uniform_test`), which
  4923. // each host wave answers for itself.
  4924. MaskData::None => self.uniform_test(inst),
  4925. };
  4926. let effect = matches!(inst.fields, Fields::Exp { .. })
  4927. || matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_")
  4928. || name.contains("store")
  4929. || name.contains("atomic")
  4930. || name == "s_barrier"
  4931. || matches!(inst.fields, Fields::Ds { .. })
  4932. && !(name.starts_with("ds_read")
  4933. || name.starts_with("ds_swizzle")
  4934. || name.contains("permute"));
  4935. if self.split_lds
  4936. && matches!(inst.fields, Fields::Ds { .. })
  4937. && !(name.starts_with("ds_swizzle") || name.contains("permute"))
  4938. && self.lds_meet.as_ref().is_none_or(|(all, _)| all[b])
  4939. {
  4940. // the two host waves of a console wave meet before each LDS access: what the other
  4941. // half wrote is visible, and what it still reads is not overwritten
  4942. let mode = self.s.m.i32(meeting_mode());
  4943. let void = self.s.t.void;
  4944. self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]);
  4945. }
  4946. let r = match &inst.fields {
  4947. Fields::Sop { .. } => self.sop(inst),
  4948. Fields::Sopp { .. } if name == "s_barrier" && self.no_barrier.contains(&b) => Ok(()),
  4949. Fields::Sopp { .. } if name == "s_barrier" => {
  4950. // Thread-group sync with a shared-memory fence, and a UAV
  4951. // fence when the program writes UAVs (the waits before an
  4952. // s_barrier make those writes visible on the console).
  4953. let mut mode = if self.writes_uavs { 1 | 2 | 8 } else { 1 | 8 };
  4954. // Without the wait for the group (bit 0) where not every
  4955. // lane arrives, or where the switch says so.
  4956. let waits = match super::group_sync() {
  4957. 0 => false,
  4958. 1 => !self.fence_only.contains(&b),
  4959. _ => true,
  4960. };
  4961. if !waits {
  4962. mode &= !1;
  4963. }
  4964. let mode = self.s.m.i32(mode);
  4965. let void = self.s.t.void;
  4966. self.s
  4967. .op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]);
  4968. Ok(())
  4969. }
  4970. Fields::Sopp { .. } => Ok(()),
  4971. Fields::Smem { .. } => self.smem(inst, (b, i)),
  4972. Fields::Valu(_) if name.starts_with("v_interp_") => self.interp(inst, (b, i)),
  4973. Fields::Valu(_) => self.valu(inst, b, i),
  4974. Fields::Vintrp { .. } => self.interp(inst, (b, i)),
  4975. // The ray and node test. A failure is a refusal at once: an
  4976. // instruction without a side effect otherwise only stops the
  4977. // program where its results are needed, and two trace programs
  4978. // came out without their test that way.
  4979. Fields::Image { .. } if name.starts_with("image_bvh") => {
  4980. return self
  4981. .bvh(inst, b, i)
  4982. .map_err(|why| unsupported(offset, why));
  4983. }
  4984. Fields::Image { .. } => self.image(inst, b, i),
  4985. Fields::Buffer { .. } => self.buffer(inst, b, i),
  4986. Fields::Exp { .. } => self.export(b, i),
  4987. Fields::Ds { .. } => self.ds(inst, b, i),
  4988. Fields::Flat { .. } if name.starts_with("global_") => self.flat(inst, b, i),
  4989. Fields::Flat { .. } => Err("flat memory"),
  4990. };
  4991. match r {
  4992. Ok(()) => Ok(()),
  4993. Err(why) if effect => Err(unsupported(offset, why)),
  4994. Err(why) => {
  4995. for &(_, v) in &inst.writes {
  4996. self.vals.insert(v, Val::Missing(why));
  4997. }
  4998. Ok(())
  4999. }
  5000. }
  5001. }
  5002. /// The two host waves of a console wave meet (a group barrier with a shared-memory
  5003. /// fence): LDS writes before are seen by reads after.
  5004. fn lds_meeting(&mut self) {
  5005. let mode = self.s.m.i32(meeting_mode());
  5006. let void = self.s.t.void;
  5007. self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]);
  5008. }
  5009. /// Whether `v` is a register no program reads as a number: a descriptor dword without
  5010. /// a host value ([`Self::stale`]), a lane mask's dword (outside compute, where a ballot
  5011. /// gives the mask as data), or a join of only such values. Compiled code joins numbers
  5012. /// with numbers: where one of these meets numbers at a join, the register is dead on
  5013. /// that path (a variable set in one arm of a branch, its use behind a flag kept in a
  5014. /// VGPR).
  5015. fn dead(&self, v: Value, seen: &mut Vec<Value>) -> bool {
  5016. if self.stale.contains(&v) {
  5017. return true;
  5018. }
  5019. let st = self.x.st;
  5020. if self.mask_data != MaskData::Console
  5021. && (st.masks.contains_key(&v) || st.highs.contains_key(&v))
  5022. {
  5023. return true;
  5024. }
  5025. let Some(&(b, i)) = self.phi_at.get(&v) else {
  5026. return false;
  5027. };
  5028. if seen.contains(&v) {
  5029. return true;
  5030. }
  5031. seen.push(v);
  5032. self.x.p.blocks[b].phis[i]
  5033. .args
  5034. .iter()
  5035. .all(|&a| self.dead(a, seen))
  5036. }
  5037. /// `s_bcnt1_i32_b*` of the lanes that differ from the first lane's value:
  5038. /// `v_readfirstlane_b32 s, v`, `v_cmp_eq_u32 m, s, v`, `s_xor_b* d, m, exec`. The
  5039. /// compiler tests a value for being the same in the whole wave this way, to take a
  5040. /// scalar path; both paths give each lane the same result, so the lanes of a host
  5041. /// wave may ask it of their own first lane, whatever the wave's size.
  5042. fn uniform_test(&self, inst: &Inst) -> bool {
  5043. let p = self.x.p;
  5044. let writer = |v: Value| -> Option<&'a Inst> {
  5045. let b = *self.def_block.get(&v)?;
  5046. p.blocks[b]
  5047. .insts
  5048. .iter()
  5049. .find(|i| i.writes.iter().any(|w| w.1 == v))
  5050. };
  5051. let scalar = |i: &Inst, op: &Operand| match *op {
  5052. Operand::Scalar { code, .. } if code != NULL && code != EXEC => i.read(Reg::S(code)),
  5053. _ => None,
  5054. };
  5055. if !inst.name().starts_with("s_bcnt1_i32_") {
  5056. return false;
  5057. }
  5058. let Fields::Sop { src, .. } = &inst.fields else {
  5059. return false;
  5060. };
  5061. let Some(xor) = src.first().and_then(|o| scalar(inst, o)).and_then(writer) else {
  5062. return false;
  5063. };
  5064. let Fields::Sop { src, .. } = &xor.fields else {
  5065. return false;
  5066. };
  5067. if !matches!(xor.name(), "s_xor_b64" | "s_xor_b32")
  5068. || !src
  5069. .iter()
  5070. .any(|o| matches!(o, Operand::Scalar { code: EXEC, .. }))
  5071. {
  5072. return false;
  5073. }
  5074. let Some(cmp) = src.iter().find_map(|o| scalar(xor, o)).and_then(writer) else {
  5075. return false;
  5076. };
  5077. let Fields::Valu(f) = &cmp.fields else {
  5078. return false;
  5079. };
  5080. if !matches!(cmp.name(), "v_cmp_eq_u32" | "v_cmp_eq_i32") || f.sdwa.is_some() || f.dpp.is_some() {
  5081. return false;
  5082. }
  5083. let lanes = f.src.iter().find_map(|o| match *o {
  5084. Operand::Vector { reg, .. } => cmp.read(Reg::V(reg)),
  5085. _ => None,
  5086. });
  5087. let first = f.src.iter().find_map(|o| scalar(cmp, o)).and_then(writer);
  5088. lanes.is_some()
  5089. && first.is_some_and(|fl| {
  5090. fl.name() == "v_readfirstlane_b32"
  5091. && matches!(&fl.fields, Fields::Valu(g)
  5092. if matches!(g.src.first(), Some(&Operand::Vector { reg, .. })
  5093. if fl.read(Reg::V(reg)) == lanes))
  5094. })
  5095. }
  5096. fn is_mask(&self, v: Option<Value>) -> bool {
  5097. v.is_some_and(|v| self.x.st.masks.contains_key(&v))
  5098. }
  5099. fn sop(&mut self, inst: &Inst) -> Result<(), Why> {
  5100. let Fields::Sop { dst, src, imm } = &inst.fields else {
  5101. unreachable!()
  5102. };
  5103. let name = inst.name();
  5104. let scc = inst.write(Reg::Scc);
  5105. let dst_code = match dst {
  5106. Some(Operand::Scalar { code, .. }) => Some(*code),
  5107. _ => None,
  5108. };
  5109. let lo = dst_code.and_then(|c| inst.write(Reg::S(c)));
  5110. if inst.write(Reg::S(EXEC)).is_some() || self.is_mask(lo) {
  5111. return Err(LANE_MASK);
  5112. }
  5113. if matches!(
  5114. name,
  5115. "s_setreg_imm32_b32" | "s_setreg_b32" | "s_swappc_b64" | "s_version"
  5116. ) || name.starts_with("s_waitcnt")
  5117. {
  5118. // shortcut: the float MODE register is not modelled; s_swappc_b64 is the
  5119. // vertex fetch call, whose results arrive as inputs.
  5120. return Err("a register the emitter does not model");
  5121. }
  5122. if name == "s_getpc_b64" {
  5123. // The address of the next instruction is no number the host has: tables in
  5124. // the code are read by their tracked address. As a number the counter is
  5125. // that instruction's offset in the code, so an address paths join before
  5126. // one load is the byte in the code, whichever table each path took
  5127. // (resource tracking gives such a join as the computed term, with no base).
  5128. let z = self.s.m.i32(0);
  5129. let at = self.s.m.i32(inst.machine.offset as u32 + 4);
  5130. let hi = dst_code.and_then(|c| inst.write(Reg::S(c + 1)));
  5131. self.set(lo, Val::I32(at));
  5132. self.set(hi, Val::I32(z));
  5133. return Ok(());
  5134. }
  5135. let c = self.cur;
  5136. let src32 = |l: &mut Self, k: usize| -> Result<V, Why> {
  5137. // SOPK arithmetic reads its destination as the first source.
  5138. if k == 0 && matches!(name, "s_addk_i32" | "s_mulk_i32") {
  5139. let d = dst.as_ref().ok_or("a missing operand")?;
  5140. return l.operand(inst, d);
  5141. }
  5142. let op = src.get(k).ok_or("a missing operand")?;
  5143. l.operand(inst, op)
  5144. };
  5145. let sext16 = |l: &mut Self| l.s.m.i32(i32::from(imm.unwrap_or(0) as i16) as u32);
  5146. // Dword `h` of 64-bit source `k` (inline constants sign-extend).
  5147. let half = |l: &mut Self, k: usize, h: u8| -> Result<V, Why> {
  5148. match src.get(k) {
  5149. Some(&Operand::Scalar { code, .. }) if code != NULL => {
  5150. let v = inst.read(Reg::S(code + h)).ok_or("an unread operand")?;
  5151. l.i32_of(v)
  5152. }
  5153. Some(op) if h == 0 => l.operand(inst, op),
  5154. Some(Operand::Const(k)) => {
  5155. let x = crate::resource::inline(*k).ok_or("a special operand")?;
  5156. Ok(l.s.m.i32(if (x as i32) < 0 { u32::MAX } else { 0 }))
  5157. }
  5158. // Of a signed operand, a literal sign-extends too.
  5159. Some(&Operand::Literal(x)) if name.ends_with("_i64") => {
  5160. Ok(l.s.m.i32(if (x as i32) < 0 { u32::MAX } else { 0 }))
  5161. }
  5162. _ => Ok(l.s.m.i32(0)),
  5163. }
  5164. };
  5165. if let Some(op) = name.strip_prefix("s_bitcmp") {
  5166. // SCC is whether bit src1 (mod 32, or mod 64 for the 64-bit form)
  5167. // of src0 is clear (bitcmp0) or set (bitcmp1).
  5168. let (bit, k31) = (src32(self, 1)?, self.s.m.i32(31));
  5169. let idx = self.s.m.bin(c, Bin::And, bit, k31);
  5170. let word = if op.ends_with("_b64") {
  5171. let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
  5172. let k32 = self.s.m.i32(32);
  5173. let upper = self.s.m.bin(c, Bin::And, bit, k32);
  5174. let z = self.s.m.i32(0);
  5175. let upper = self.s.m.cmp(c, pred::NE, upper, z);
  5176. self.s.m.select(c, upper, b, a)
  5177. } else {
  5178. src32(self, 0)?
  5179. };
  5180. let shifted = self.s.m.bin(c, Bin::LShr, word, idx);
  5181. let one = self.s.m.i32(1);
  5182. let tested = self.s.m.bin(c, Bin::And, shifted, one);
  5183. let want = self.s.m.i32(u32::from(op.starts_with('1')));
  5184. let r = self.s.m.cmp(c, pred::EQ, tested, want);
  5185. self.set(scc, Val::Bit(r));
  5186. return Ok(());
  5187. }
  5188. if let Some(op) = name.strip_prefix("s_cmp_").filter(|o| o.ends_with("_u64")) {
  5189. // eq and lg only: both dwords.
  5190. let mut r = None;
  5191. for h in 0..2 {
  5192. let (a, b) = (half(self, 0, h)?, half(self, 1, h)?);
  5193. let e = self.s.m.cmp(c, pred::EQ, a, b);
  5194. r = Some(match r {
  5195. Some(x) => self.s.m.bin(c, Bin::And, x, e),
  5196. None => e,
  5197. });
  5198. }
  5199. let mut r = r.expect("two dwords");
  5200. if op.starts_with("lg") {
  5201. let t = self.s.m.bool(true);
  5202. r = self.s.m.bin(c, Bin::Xor, r, t);
  5203. }
  5204. self.set(scc, Val::Bit(r));
  5205. return Ok(());
  5206. }
  5207. if let Some(op) = name.strip_prefix("s_cmp_").or(name.strip_prefix("s_cmpk_")) {
  5208. let (a, b) = if name.starts_with("s_cmpk_") {
  5209. let b = if op.ends_with("_i32") {
  5210. sext16(self)
  5211. } else {
  5212. self.s.m.i32(u32::from(imm.unwrap_or(0)))
  5213. };
  5214. (src32(self, 0)?, b)
  5215. } else {
  5216. if op.ends_with("64") {
  5217. return Err("a 64-bit scalar compare");
  5218. }
  5219. (src32(self, 0)?, src32(self, 1)?)
  5220. };
  5221. let signed = op.ends_with("_i32");
  5222. let p = match &op[..2] {
  5223. "eq" => pred::EQ,
  5224. "lg" => pred::NE,
  5225. "gt" if signed => pred::SGT,
  5226. "ge" if signed => pred::SGE,
  5227. "lt" if signed => pred::SLT,
  5228. "le" if signed => pred::SLE,
  5229. "gt" => pred::IUGT,
  5230. "ge" => pred::IUGE,
  5231. "lt" => pred::IULT,
  5232. "le" => pred::IULE,
  5233. _ => return Err("a scalar compare"),
  5234. };
  5235. let r = self.s.m.cmp(c, p, a, b);
  5236. self.set(scc, Val::Bit(r));
  5237. return Ok(());
  5238. }
  5239. let wide = name.ends_with("_b64") || name.ends_with("_u64") || name.ends_with("_i64");
  5240. if wide {
  5241. let hi = dst_code.and_then(|c| inst.write(Reg::S(c + 1)));
  5242. let nonzero = |l: &mut Self, a: V, b: V| {
  5243. let o = l.s.m.bin(c, Bin::Or, a, b);
  5244. let z = l.s.m.i32(0);
  5245. l.s.m.cmp(c, pred::NE, o, z)
  5246. };
  5247. return match name {
  5248. "s_quadmask_b64" => {
  5249. let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
  5250. let low = self.quad_mask(a);
  5251. let high = self.quad_mask(b);
  5252. let k8 = self.s.m.i32(8);
  5253. let high = self.s.m.bin(c, Bin::Shl, high, k8);
  5254. let mask = self.s.m.bin(c, Bin::Or, low, high);
  5255. let zero = self.s.m.i32(0);
  5256. self.set(lo, Val::I32(mask));
  5257. self.set(hi, Val::I32(zero));
  5258. let nonzero = self.s.m.cmp(c, pred::NE, mask, zero);
  5259. self.set(scc, Val::Bit(nonzero));
  5260. Ok(())
  5261. }
  5262. "s_bcnt1_i32_b64" => {
  5263. let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
  5264. let i32t = self.s.t.i32;
  5265. let na = self
  5266. .s
  5267. .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 31, &[a]);
  5268. let nb = self
  5269. .s
  5270. .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 31, &[b]);
  5271. let r = self.s.m.bin(c, Bin::Add, na, nb);
  5272. self.set(lo, Val::I32(r));
  5273. let z = self.s.m.i32(0);
  5274. let s = self.s.m.cmp(c, pred::NE, r, z);
  5275. self.set(scc, Val::Bit(s));
  5276. Ok(())
  5277. }
  5278. "s_ff1_i32_b64" => {
  5279. // The lowest set bit; -1 for none (as DXIL's first bit low).
  5280. let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
  5281. let i32t = self.s.t.i32;
  5282. let fa = self
  5283. .s
  5284. .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[a]);
  5285. let fb = self
  5286. .s
  5287. .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[b]);
  5288. let (z, k32) = (self.s.m.i32(0), self.s.m.i32(32));
  5289. let fb32 = self.s.m.bin(c, Bin::Add, fb, k32);
  5290. let none = self.s.m.cmp(c, pred::EQ, b, z);
  5291. let fb = self.s.m.select(c, none, fb, fb32);
  5292. let low = self.s.m.cmp(c, pred::NE, a, z);
  5293. let r = self.s.m.select(c, low, fa, fb);
  5294. self.set(lo, Val::I32(r));
  5295. Ok(())
  5296. }
  5297. "s_and_b64" | "s_or_b64" | "s_xor_b64" | "s_andn2_b64" | "s_orn2_b64"
  5298. | "s_nand_b64" | "s_nor_b64" | "s_xnor_b64" | "s_not_b64" => {
  5299. let ones = self.s.m.i32(u32::MAX);
  5300. let mut r = Vec::new();
  5301. for h in 0..2u8 {
  5302. let a = half(self, 0, h)?;
  5303. let x = if name == "s_not_b64" {
  5304. self.s.m.bin(c, Bin::Xor, a, ones)
  5305. } else {
  5306. let mut b = half(self, 1, h)?;
  5307. if name.contains("n2") {
  5308. b = self.s.m.bin(c, Bin::Xor, b, ones);
  5309. }
  5310. let op = match &name[2..5] {
  5311. "and" | "nan" => Bin::And,
  5312. "or_" | "orn" | "nor" => Bin::Or,
  5313. _ => Bin::Xor,
  5314. };
  5315. let x = self.s.m.bin(c, op, a, b);
  5316. if matches!(name, "s_nand_b64" | "s_nor_b64" | "s_xnor_b64") {
  5317. self.s.m.bin(c, Bin::Xor, x, ones)
  5318. } else {
  5319. x
  5320. }
  5321. };
  5322. r.push(x);
  5323. }
  5324. self.set(lo, Val::I32(r[0]));
  5325. self.set(hi, Val::I32(r[1]));
  5326. let s = nonzero(self, r[0], r[1]);
  5327. self.set(scc, Val::Bit(s));
  5328. Ok(())
  5329. }
  5330. "s_lshl_b64" | "s_lshr_b64" | "s_ashr_i64" => {
  5331. let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
  5332. let n = src32(self, 1)?;
  5333. let i64t = self.s.m.int(64);
  5334. self.s.flags |= flags::INT64;
  5335. let a = self.s.m.cast(c, Cast::ZExt, a, i64t);
  5336. let b = self.s.m.cast(c, Cast::ZExt, b, i64t);
  5337. let k32 = self.s.m.int_const(i64t, 32);
  5338. let b = self.s.m.bin(c, Bin::Shl, b, k32);
  5339. let x = self.s.m.bin(c, Bin::Or, a, b);
  5340. let k63 = self.s.m.i32(63);
  5341. let n = self.s.m.bin(c, Bin::And, n, k63);
  5342. let n = self.s.m.cast(c, Cast::ZExt, n, i64t);
  5343. let op = match name {
  5344. "s_lshl_b64" => Bin::Shl,
  5345. "s_lshr_b64" => Bin::LShr,
  5346. _ => Bin::AShr,
  5347. };
  5348. let r = self.s.m.bin(c, op, x, n);
  5349. let rl = self.s.m.cast(c, Cast::Trunc, r, self.s.t.i32);
  5350. let rh = self.s.m.bin(c, Bin::LShr, r, k32);
  5351. let rh = self.s.m.cast(c, Cast::Trunc, rh, self.s.t.i32);
  5352. self.set(lo, Val::I32(rl));
  5353. self.set(hi, Val::I32(rh));
  5354. let s = nonzero(self, rl, rh);
  5355. self.set(scc, Val::Bit(s));
  5356. Ok(())
  5357. }
  5358. "s_mov_b64" => {
  5359. // Each half by itself: two numbers that travel as a pair (two scalars
  5360. // parked in neighbouring VGPR lanes, say) need not both have a value.
  5361. for (h, v) in [(0, lo), (1, hi)] {
  5362. let val = match half(self, 0, h) {
  5363. Ok(a) => Val::I32(a),
  5364. Err(why) => Val::Missing(why),
  5365. };
  5366. self.set(v, val);
  5367. }
  5368. Ok(())
  5369. }
  5370. "s_cselect_b64" => {
  5371. let cond = self.scc_in(inst)?;
  5372. for (h, v) in [(0, lo), (1, hi)] {
  5373. let (a, b) = (half(self, 0, h)?, half(self, 1, h)?);
  5374. let r = self.s.m.select(c, cond, a, b);
  5375. self.set(v, Val::I32(r));
  5376. }
  5377. Ok(())
  5378. }
  5379. _ => Err(name),
  5380. };
  5381. }
  5382. let m = &mut self.s.m;
  5383. let _ = m;
  5384. let (r, carry): (V, Option<V>) = match name {
  5385. "s_mov_b32" => (src32(self, 0)?, None),
  5386. "s_movk_i32" => (sext16(self), None),
  5387. "s_quadmask_b32" => {
  5388. let pixels = src32(self, 0)?;
  5389. (self.quad_mask(pixels), None)
  5390. }
  5391. "s_cselect_b32" => {
  5392. let cond = self.scc_in(inst)?;
  5393. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5394. (self.s.m.select(c, cond, a, b), None)
  5395. }
  5396. "s_brev_b32" => {
  5397. let a = src32(self, 0)?;
  5398. let r = self
  5399. .s
  5400. .op(c, "unary.i32", Attr::ReadNone, self.s.t.i32, 30, &[a]);
  5401. (r, None)
  5402. }
  5403. "s_not_b32" => {
  5404. let a = src32(self, 0)?;
  5405. let ones = self.s.m.i32(u32::MAX);
  5406. (self.s.m.bin(c, Bin::Xor, a, ones), None)
  5407. }
  5408. "s_add_u32" | "s_add_i32" | "s_addk_i32" => {
  5409. let a = src32(self, 0)?;
  5410. let b = if name == "s_addk_i32" {
  5411. sext16(self)
  5412. } else {
  5413. src32(self, 1)?
  5414. };
  5415. let r = self.s.m.bin(c, Bin::Add, a, b);
  5416. let carry = if name == "s_add_u32" {
  5417. Some(self.s.m.cmp(c, pred::IULT, r, a))
  5418. } else {
  5419. None
  5420. };
  5421. (r, carry)
  5422. }
  5423. "s_sub_u32" | "s_sub_i32" => {
  5424. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5425. let r = self.s.m.bin(c, Bin::Sub, a, b);
  5426. let carry = (name == "s_sub_u32").then(|| self.s.m.cmp(c, pred::IULT, a, b));
  5427. (r, carry)
  5428. }
  5429. "s_addc_u32" | "s_subb_u32" => {
  5430. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5431. let cin = self.scc_in(inst)?;
  5432. let (r, carry) = self.add_sub_carry(c, name == "s_addc_u32", a, b, Some(cin));
  5433. (r, Some(carry))
  5434. }
  5435. "s_mul_i32" | "s_mulk_i32" => {
  5436. let a = src32(self, 0)?;
  5437. let b = if name == "s_mulk_i32" {
  5438. sext16(self)
  5439. } else {
  5440. src32(self, 1)?
  5441. };
  5442. (self.s.m.bin(c, Bin::Mul, a, b), None)
  5443. }
  5444. "s_mul_hi_u32" | "s_mul_hi_i32" => {
  5445. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5446. (self.mul_hi(a, b, name.ends_with("i32")), None)
  5447. }
  5448. "s_flbit_i32_b32" | "s_flbit_i32" => {
  5449. // The first bit from the top (differing from the sign for
  5450. // the signed form), -1 for none: DXIL's first-bit-high.
  5451. let a = src32(self, 0)?;
  5452. let op = if name == "s_flbit_i32_b32" { 33 } else { 34 };
  5453. let r = self
  5454. .s
  5455. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]);
  5456. (r, None)
  5457. }
  5458. "s_ff1_i32_b32" | "s_bcnt1_i32_b32" => {
  5459. // First set bit (-1 for zero, as DXIL's), or the bit count.
  5460. let a = src32(self, 0)?;
  5461. let op = if name == "s_ff1_i32_b32" { 32 } else { 31 };
  5462. let r = self
  5463. .s
  5464. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]);
  5465. (r, None)
  5466. }
  5467. "s_bfe_u32" | "s_bfe_i32" => {
  5468. // src1: offset in bits 0-4, width in bits 16-22.
  5469. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5470. let (k16, k127) = (self.s.m.i32(16), self.s.m.i32(0x7F));
  5471. let w = self.s.m.bin(c, Bin::LShr, b, k16);
  5472. let w = self.s.m.bin(c, Bin::And, w, k127);
  5473. (self.bfe(a, b, w, name == "s_bfe_i32"), None)
  5474. }
  5475. "s_and_b32" | "s_or_b32" | "s_xor_b32" | "s_andn2_b32" | "s_orn2_b32"
  5476. | "s_nand_b32" | "s_nor_b32" | "s_xnor_b32" => {
  5477. let (a, mut b) = (src32(self, 0)?, src32(self, 1)?);
  5478. let ones = self.s.m.i32(u32::MAX);
  5479. if name.contains("n2") {
  5480. b = self.s.m.bin(c, Bin::Xor, b, ones);
  5481. }
  5482. let op = match &name[2..5] {
  5483. "and" | "nan" => Bin::And,
  5484. "or_" | "orn" | "nor" => Bin::Or,
  5485. _ => Bin::Xor,
  5486. };
  5487. let mut r = self.s.m.bin(c, op, a, b);
  5488. if matches!(name, "s_nand_b32" | "s_nor_b32" | "s_xnor_b32") {
  5489. r = self.s.m.bin(c, Bin::Xor, r, ones);
  5490. }
  5491. (r, None)
  5492. }
  5493. "s_lshl_b32" | "s_lshr_b32" | "s_ashr_i32" => {
  5494. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5495. let k31 = self.s.m.i32(31);
  5496. let b = self.s.m.bin(c, Bin::And, b, k31);
  5497. let op = match name {
  5498. "s_lshl_b32" => Bin::Shl,
  5499. "s_lshr_b32" => Bin::LShr,
  5500. _ => Bin::AShr,
  5501. };
  5502. (self.s.m.bin(c, op, a, b), None)
  5503. }
  5504. "s_lshl1_add_u32" | "s_lshl2_add_u32" | "s_lshl3_add_u32" | "s_lshl4_add_u32" => {
  5505. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5506. let k = self.s.m.i32(u32::from(name.as_bytes()[6] - b'0'));
  5507. let t = self.s.m.bin(c, Bin::Shl, a, k);
  5508. (self.s.m.bin(c, Bin::Add, t, b), None)
  5509. }
  5510. "s_min_u32" | "s_max_u32" | "s_min_i32" | "s_max_i32" => {
  5511. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5512. let p = match name {
  5513. "s_min_u32" => pred::IULT,
  5514. "s_max_u32" => pred::IUGT,
  5515. "s_min_i32" => pred::SLT,
  5516. _ => pred::SGT,
  5517. };
  5518. let t = self.s.m.cmp(c, p, a, b);
  5519. (self.s.m.select(c, t, a, b), None)
  5520. }
  5521. "s_abs_i32" => {
  5522. let a = src32(self, 0)?;
  5523. let z = self.s.m.i32(0);
  5524. let neg = self.s.m.cmp(c, pred::SLT, a, z);
  5525. let n = self.s.m.bin(c, Bin::Sub, z, a);
  5526. (self.s.m.select(c, neg, n, a), None)
  5527. }
  5528. "s_bitset0_b32" | "s_bitset1_b32" => {
  5529. // Sets (clears) bit src[4:0] of the destination it reads.
  5530. let old = self.operand(inst, dst.as_ref().ok_or("a missing operand")?)?;
  5531. let a = src32(self, 0)?;
  5532. let (k31, one) = (self.s.m.i32(31), self.s.m.i32(1));
  5533. let a = self.s.m.bin(c, Bin::And, a, k31);
  5534. let bit = self.s.m.bin(c, Bin::Shl, one, a);
  5535. if name == "s_bitset1_b32" {
  5536. (self.s.m.bin(c, Bin::Or, old, bit), None)
  5537. } else {
  5538. let ones = self.s.m.i32(u32::MAX);
  5539. let nb = self.s.m.bin(c, Bin::Xor, bit, ones);
  5540. (self.s.m.bin(c, Bin::And, old, nb), None)
  5541. }
  5542. }
  5543. "s_bfm_b32" => {
  5544. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5545. let k31 = self.s.m.i32(31);
  5546. let one = self.s.m.i32(1);
  5547. let a = self.s.m.bin(c, Bin::And, a, k31);
  5548. let b = self.s.m.bin(c, Bin::And, b, k31);
  5549. let m = self.s.m.bin(c, Bin::Shl, one, a);
  5550. let m = self.s.m.bin(c, Bin::Sub, m, one);
  5551. (self.s.m.bin(c, Bin::Shl, m, b), None)
  5552. }
  5553. _ => return Err(name),
  5554. };
  5555. self.set(lo, Val::I32(r));
  5556. if let Some(scc) = scc {
  5557. let val = match carry {
  5558. Some(k) => Val::Bit(k),
  5559. None if matches!(
  5560. name,
  5561. "s_mov_b32"
  5562. | "s_movk_i32"
  5563. | "s_cselect_b32"
  5564. | "s_brev_b32"
  5565. | "s_mul_i32"
  5566. | "s_mulk_i32"
  5567. ) =>
  5568. {
  5569. return Ok(());
  5570. }
  5571. None if name.starts_with("s_add") || name.starts_with("s_sub") => {
  5572. Val::Missing("the carry of a scalar operation")
  5573. }
  5574. None => {
  5575. let z = self.s.m.i32(0);
  5576. Val::Bit(self.s.m.cmp(c, pred::NE, r, z))
  5577. }
  5578. };
  5579. self.vals.insert(scc, val);
  5580. }
  5581. Ok(())
  5582. }
  5583. /// Packs whether each consecutive group of four pixels has a set bit.
  5584. fn quad_mask(&mut self, pixels: V) -> V {
  5585. let c = self.cur;
  5586. let one = self.s.m.i32(1);
  5587. let shifted = self.s.m.bin(c, Bin::LShr, pixels, one);
  5588. let mut mask = self.s.m.bin(c, Bin::Or, pixels, shifted);
  5589. // Fold each nibble into its bottom bit, then gather those bits into
  5590. // the low byte in three stages without needing a 64-bit operation.
  5591. for (distance, keep) in [
  5592. (2, 0x1111_1111),
  5593. (3, 0x0303_0303),
  5594. (6, 0x000f_000f),
  5595. (12, 0x0000_00ff),
  5596. ] {
  5597. let distance = self.s.m.i32(distance);
  5598. let shifted = self.s.m.bin(c, Bin::LShr, mask, distance);
  5599. let combined = self.s.m.bin(c, Bin::Or, mask, shifted);
  5600. let keep = self.s.m.i32(keep);
  5601. mask = self.s.m.bin(c, Bin::And, combined, keep);
  5602. }
  5603. mask
  5604. }
  5605. /// `a + b (+ cin)` or `a - b (- cin)` with the carry (borrow) out, as the
  5606. /// scalar and vector add-with-carry instructions set it.
  5607. fn add_sub_carry(&mut self, c: usize, add: bool, a: V, b: V, cin: Option<V>) -> (V, V) {
  5608. let op = if add { Bin::Add } else { Bin::Sub };
  5609. let mut r = self.s.m.bin(c, op, a, b);
  5610. // Without a carry in: a + b wraps below a; a - b borrows when a < b.
  5611. let mut carry = if add {
  5612. self.s.m.cmp(c, pred::IULT, r, a)
  5613. } else {
  5614. self.s.m.cmp(c, pred::IULT, a, b)
  5615. };
  5616. if let Some(cin) = cin {
  5617. let one = self.s.m.cast(c, Cast::ZExt, cin, self.s.t.i32);
  5618. let t = r;
  5619. r = self.s.m.bin(c, op, t, one);
  5620. // The carry in carries on when the partial result is all ones
  5621. // (add) or zero (sub).
  5622. let edge = self.s.m.i32(if add { u32::MAX } else { 0 });
  5623. let at_edge = self.s.m.cmp(c, pred::EQ, t, edge);
  5624. let more = self.s.m.bin(c, Bin::And, cin, at_edge);
  5625. carry = self.s.m.bin(c, Bin::Or, carry, more);
  5626. }
  5627. (r, carry)
  5628. }
  5629. fn scc_in(&mut self, inst: &Inst) -> Result<V, Why> {
  5630. let v = inst.read(Reg::Scc).ok_or("an unread SCC")?;
  5631. match self.get(v) {
  5632. Ok(Val::Bit(x)) => Ok(x),
  5633. Ok(_) => Err("SCC without a value"),
  5634. // Of a mask operation whose result lies within EXEC: whether
  5635. // some lane is left.
  5636. Err(LANE_MASK) if self.within_exec(v) => self.scc_some(v),
  5637. Err(why) => Err(why),
  5638. }
  5639. }
  5640. /// Whether the mask operation that sets the SCC value `scc` gives no
  5641. /// lane outside EXEC a bit.
  5642. fn within_exec(&self, scc: Value) -> bool {
  5643. let Some(&b) = self.def_block.get(&scc) else {
  5644. return false;
  5645. };
  5646. let by = self.x.p.blocks[b].insts.iter().find(|i| i.write(Reg::Scc) == Some(scc));
  5647. by.is_some_and(|i| {
  5648. i.write(Reg::S(EXEC)).is_some()
  5649. || matches!(&i.fields, Fields::Sop { dst: Some(Operand::Scalar { code, .. }), .. }
  5650. if i.write(Reg::S(*code)).is_some_and(|lo| self.x.st.active.contains(&lo)))
  5651. })
  5652. }
  5653. fn smem(&mut self, inst: &Inst, site: Site) -> Result<(), Why> {
  5654. let Fields::Smem {
  5655. data,
  5656. offset,
  5657. soffset,
  5658. ..
  5659. } = &inst.fields
  5660. else {
  5661. unreachable!()
  5662. };
  5663. let name = inst.name();
  5664. if let Some(a) = self.scalar.get(&site).copied().filter(|a| a.param == CODE) {
  5665. return self.code_smem(inst, a);
  5666. }
  5667. if self.scalar.get(&site).is_some_and(|a| a.param == MEMORY) {
  5668. return self.memory_smem(inst);
  5669. }
  5670. let Some(rest) = name.strip_prefix("s_buffer_load_dword") else {
  5671. return self.descriptor_data(inst, site);
  5672. };
  5673. let count = match rest {
  5674. "" => 1,
  5675. "x2" => 2,
  5676. "x4" => 4,
  5677. "x8" => 8,
  5678. "x16" => 16,
  5679. _ => return Err("a scalar buffer load"),
  5680. };
  5681. let Some(Operand::Scalar { code, .. }) = *data else {
  5682. return Err("a scalar buffer load");
  5683. };
  5684. let src = self
  5685. .descriptors
  5686. .get(&(site, false))
  5687. .copied()
  5688. .ok_or("an untracked descriptor")?;
  5689. let kind = self.used_kind(src);
  5690. let c = self.cur;
  5691. let (base, extra) = self.built_offset(src)?;
  5692. let offset = &((*offset as u32).wrapping_add(base) as i32);
  5693. let mut addr = self.s.m.i32(*offset as u32);
  5694. if let Some(x) = extra {
  5695. addr = self.s.m.bin(c, Bin::Add, addr, x);
  5696. }
  5697. if !matches!(soffset, Operand::Scalar { code: NULL, .. }) {
  5698. let so = self.operand(inst, soffset)?;
  5699. addr = self.s.m.bin(c, Bin::Add, addr, so);
  5700. }
  5701. if matches!(src, Source::Built { address, .. } if address.param == CODE) {
  5702. // A descriptor built around a table in the code.
  5703. for k in 0..count {
  5704. let off = self.s.m.i32(4 * k);
  5705. let a = self.s.m.bin(c, Bin::Add, addr, off);
  5706. let x = self.code_dword(a)?;
  5707. self.write(inst, Reg::S(code + k as u8), x, None);
  5708. }
  5709. return Ok(());
  5710. }
  5711. // A buffer the program picks from the view heap by an index it
  5712. // computes (`ResourceHeap`) has no used-resource entry, and the
  5713. // heap holds a buffer view there, not a constant buffer: read as
  5714. // raw bytes, as a table's SRV is below. Read as a constant buffer
  5715. // (the host's validation: "Descriptor Type in Heap: SRV, Register
  5716. // Type: CBV", heap index 17) the loads gave nothing:
  5717. // the title's meshlet culling (BatchCullMeshlets,
  5718. // BatchCullPreSkinnedMeshlets, BatchCullBatchCSMeshlets) reads its
  5719. // batch records, mesh headers and instance transforms this way, so
  5720. // it passed no meshlet and every indirect mesh draw ran empty.
  5721. // The host's table of strides by heap slot tells a buffer view
  5722. // (not 0) from anything else, which is still read as a constant
  5723. // buffer; only the load that fits the slot runs.
  5724. let picked = match kind {
  5725. None => self.slot_stride(src)?,
  5726. Some(_) => None,
  5727. };
  5728. if let Some(stride) = picked {
  5729. let zero = self.s.m.i32(0);
  5730. let is_buffer = self.s.m.cmp(self.cur, pred::NE, stride, zero);
  5731. let at = self.begin_guarded(Some(is_buffer));
  5732. let h = self.handle(site, src, false, (11, 0))?;
  5733. let mut raw = Vec::new();
  5734. for k in 0..count {
  5735. let b = self.cur;
  5736. let off = self.s.m.i32(4 * k);
  5737. let a = self.s.m.bin(b, Bin::Add, addr, off);
  5738. let mask = self.s.m.i8(1);
  5739. let (u, al) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
  5740. let r = self.s.op(
  5741. b,
  5742. "rawBufferLoad.f32",
  5743. Attr::ReadOnly,
  5744. self.s.t.res_ret,
  5745. 139,
  5746. &[h, a, u, mask, al],
  5747. );
  5748. let x = self.s.m.extract(b, r, 0);
  5749. let x = self.as_int(x);
  5750. raw.push((x, zero));
  5751. }
  5752. let raw = self.end_guarded(at, &raw);
  5753. let other = self.s.m.cmp(self.cur, pred::EQ, stride, zero);
  5754. let at = self.begin_guarded(Some(other));
  5755. let h = self.handle(site, src, false, (13, 0x1_0000))?;
  5756. let mut both = Vec::new();
  5757. for (k, &r) in raw.iter().enumerate() {
  5758. let b = self.cur;
  5759. let off = self.s.m.i32(4 * k as u32);
  5760. let a = self.s.m.bin(b, Bin::Add, addr, off);
  5761. let x = self.cbuffer_dword(h, a);
  5762. both.push((x, r));
  5763. }
  5764. let both = self.end_guarded(at, &both);
  5765. for (k, x) in both.into_iter().enumerate() {
  5766. self.write(inst, Reg::S(code + k as u8), x, None);
  5767. }
  5768. return Ok(());
  5769. }
  5770. if matches!(kind, Some(u) if u.kind == ResourceType::Srv) {
  5771. let h = self.handle(site, src, false, (11, 0))?;
  5772. for k in 0..count {
  5773. let off = self.s.m.i32(4 * k);
  5774. let a = self.s.m.bin(c, Bin::Add, addr, off);
  5775. let mask = self.s.m.i8(1);
  5776. let (u, al) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
  5777. let r = self.s.op(
  5778. c,
  5779. "rawBufferLoad.f32",
  5780. Attr::ReadOnly,
  5781. self.s.t.res_ret,
  5782. 139,
  5783. &[h, a, u, mask, al],
  5784. );
  5785. let x = self.s.m.extract(c, r, 0);
  5786. let x = self.as_int(x);
  5787. self.write(inst, Reg::S(code + k as u8), x, None);
  5788. }
  5789. return Ok(());
  5790. }
  5791. let h = self.handle(site, src, false, (13, 0x1_0000))?;
  5792. let constant = match addr {
  5793. V::Const(_)
  5794. if matches!(soffset, Operand::Scalar { code: NULL, .. }) && extra.is_none() =>
  5795. {
  5796. Some(*offset as u32)
  5797. }
  5798. _ => None,
  5799. };
  5800. let mut rows: HashMap<u32, V> = HashMap::new();
  5801. for k in 0..count {
  5802. let x = match constant {
  5803. Some(base) => {
  5804. let byte = base + 4 * k;
  5805. let row = match rows.get(&(byte >> 4)) {
  5806. Some(&r) => r,
  5807. None => {
  5808. let ri = self.s.m.i32(byte >> 4);
  5809. let r = self.s.op(
  5810. c,
  5811. "cbufferLoadLegacy.i32",
  5812. Attr::ReadOnly,
  5813. self.s.t.cbuf_ret,
  5814. 59,
  5815. &[h, ri],
  5816. );
  5817. rows.insert(byte >> 4, r);
  5818. r
  5819. }
  5820. };
  5821. self.s.m.extract(c, row, (byte >> 2) & 3)
  5822. }
  5823. None => {
  5824. let off = self.s.m.i32(4 * k);
  5825. let a = self.s.m.bin(c, Bin::Add, addr, off);
  5826. self.cbuffer_dword(h, a)
  5827. }
  5828. };
  5829. self.write(inst, Reg::S(code + k as u8), x, None);
  5830. }
  5831. Ok(())
  5832. }
  5833. /// A descriptor load (`s_load_dword*` from a table or heap) whose dwords
  5834. /// the code also reads as numbers: the console compiler computes sizes
  5835. /// from descriptor bits (an image's width, height, depth, levels; a
  5836. /// buffer's record count) instead of querying them. Those fields are
  5837. /// rebuilt from the host view's dimensions in the GFX10 layout (image
  5838. /// dword 1 bits 30-31 and dword 2 bits 0-13 width - 1, dword 2 bits
  5839. /// 14-29 height - 1, dword 3 identity swizzle, last level at 16, type at
  5840. /// 28, dword 4 depth or layers - 1; buffer dword 2 the record count).
  5841. // shortcut: the base level reads 0 (the host view starts at its own
  5842. // level 0, so sizes the code shifts by it come out right) and the other
  5843. // dwords (addresses, formats, tiling) have no host value: reading them
  5844. // stops the program.
  5845. fn descriptor_data(&mut self, inst: &Inst, site: Site) -> Result<(), Why> {
  5846. const OTHER: Why = "a descriptor's address or format read as data";
  5847. let Fields::Smem {
  5848. data: Some(Operand::Scalar { code, .. }),
  5849. ..
  5850. } = inst.fields
  5851. else {
  5852. return Err("a scalar memory read as data");
  5853. };
  5854. let count = match inst.name().strip_prefix("s_load_dword") {
  5855. Some("") => 1u32,
  5856. Some("x2") => 2,
  5857. Some("x4") => 4,
  5858. Some("x8") => 8,
  5859. Some("x16") => 16,
  5860. _ => return Err("a scalar memory read as data"),
  5861. };
  5862. // How the program uses the descriptor tells the view's kind: an image or buffer
  5863. // instruction before a scalar buffer load, which reads any buffer.
  5864. let x = self.x;
  5865. let uses = |of: Site| {
  5866. x.res
  5867. .descriptors
  5868. .iter()
  5869. .filter(|d| d.role == Role::Resource)
  5870. .filter_map(move |d| {
  5871. d.source.leaves().into_iter().find_map(|l| match *l {
  5872. Source::Loaded { load, first } if load == of => Some((d.site, first)),
  5873. _ => None,
  5874. })
  5875. })
  5876. };
  5877. let by_scalar_load = |u: &(Site, u8)| {
  5878. matches!(x.p.blocks[u.0.0].insts[u.0.1].fields, Fields::Smem { .. })
  5879. };
  5880. let use_of = |of: Site| uses(of).find(|u| !by_scalar_load(u)).or_else(|| uses(of).next());
  5881. // The console compiler loads a descriptor again wherever it needs it, and for a
  5882. // size it reads the dwords of a load that nothing uses as a descriptor (a texture
  5883. // picked from the heap by an index held per lane: one load for its width, one for
  5884. // its base level, one for each read of the image). Another load of as many dwords
  5885. // from the same address reads the same descriptor, so what uses that one tells
  5886. // this one's kind. The handle is still made from this load's own operands, which
  5887. // hold here.
  5888. let address = self.scalar.get(&site).copied();
  5889. let twin = || {
  5890. let a = address?;
  5891. let same = |s: Site| x.p.blocks[s.0].insts[s.1].name() == inst.name();
  5892. x.res
  5893. .scalar
  5894. .iter()
  5895. .filter(|(s, b)| *s != site && *b == a && same(*s))
  5896. .find_map(|(s, _)| use_of(*s))
  5897. };
  5898. let use_at = use_of(site).or_else(twin);
  5899. // A view whose kind no use tells, but what is read of it does.
  5900. let sized = match use_at {
  5901. Some(_) => None,
  5902. None => self.sized_view(inst, site, code, count),
  5903. };
  5904. // A descriptor nothing uses as one, whose size the code reads all the same (a
  5905. // texture picked from the heap by an index in a constant buffer, its width and
  5906. // height turned into a texel size): the kind from its dwords and its used-resource
  5907. // entry. Only an image whose layers or depth (dword 4) are not read: those are no 2D
  5908. // texture's; and no buffer `sized_view` did not take (a stride of 4 or less may be a
  5909. // typed view's component count, and the address is `view_address`'s below).
  5910. let layers = inst.write(Reg::S(code + 4)).is_some_and(|v| self.read_as_number(v));
  5911. let unused = if use_at.is_none() && sized.is_none() && count == 8 && !layers {
  5912. self.unused_descriptor_kind(inst, site, code, count)
  5913. } else {
  5914. None
  5915. };
  5916. let (first, props, image, uav, used) = if let Some(kind) = unused {
  5917. kind
  5918. } else {
  5919. let Some((at, first)) = use_at.or(sized.map(|_| (site, 0))) else {
  5920. // A descriptor kept per lane in VGPRs (`Resources::lane_copied`): the code only
  5921. // copies its dwords and compares them, lane against first lane, and every load
  5922. // that reaches those lanes reads one address. Each dword stands in as its place
  5923. // in the table, so the lanes compare equal as they do on the console.
  5924. if self.x.res.lane_copied.contains(&site)
  5925. && let Some(a) = self.scalar.get(&site).copied()
  5926. {
  5927. for k in 0..count {
  5928. let x = self.s.m.i32(a.offset / 4 + k);
  5929. self.write(inst, Reg::S(code + k as u8), x, None);
  5930. }
  5931. return Ok(());
  5932. }
  5933. // A sampler's descriptor: no program reads its dwords as numbers, so where one
  5934. // meets numbers at a join the register is dead on that path (`dead`), as a
  5935. // descriptor's address or format is.
  5936. let sampler = x.res.descriptors.iter().any(|d| {
  5937. d.role == Role::Sampler
  5938. && d.source.leaves().into_iter().any(
  5939. |l| matches!(*l, Source::Loaded { load, .. } if load == site),
  5940. )
  5941. });
  5942. if sampler {
  5943. self.stale.extend(inst.writes.iter().map(|w| w.1));
  5944. return Err("a sampler's descriptor read as data");
  5945. }
  5946. // A buffer view the code only takes the address of, to walk
  5947. // the memory behind it (a ray-tracing structure): the address
  5948. // from the host, the other dwords have no value.
  5949. if count <= 4
  5950. && let Some((lo, hi)) = self.view_address(site)
  5951. {
  5952. for k in 0..count {
  5953. let reg = Reg::S(code + k as u8);
  5954. match k {
  5955. 0 => self.write(inst, reg, lo, None),
  5956. 1 => self.write(inst, reg, hi, None),
  5957. _ => {
  5958. if let Some(v) = inst.write(reg) {
  5959. self.vals.insert(v, Val::Missing(OTHER));
  5960. self.stale.insert(v);
  5961. }
  5962. }
  5963. }
  5964. }
  5965. return Ok(());
  5966. }
  5967. if std::env::var_os("VICTORY_DESC_WHY").is_some() {
  5968. eprintln!(
  5969. "DESC-WHY {:#x} {} scalar={:?} lane_copied={}",
  5970. inst.machine.offset,
  5971. inst.name(),
  5972. address,
  5973. self.x.res.lane_copied.contains(&site)
  5974. );
  5975. }
  5976. return Err("a descriptor read only as data");
  5977. };
  5978. let src = Source::Loaded { load: site, first };
  5979. let used = self.used_kind(&src);
  5980. let ui: &Inst = &self.x.p.blocks[at.0].insts[at.1];
  5981. let un = ui.name();
  5982. let uav = un.contains("store")
  5983. || un.contains("atomic")
  5984. || used.is_some_and(|u| u.kind == ResourceType::Uav);
  5985. let u = if uav { 0x1000 } else { 0 };
  5986. let (props, image) = match &ui.fields {
  5987. _ if sized.is_some_and(|image| image) => ((2 | u, 0x409), Some(2)),
  5988. _ if sized.is_some() => ((11 | u, 0), None),
  5989. // A ray-tracing structure in a buffer of the host: read raw.
  5990. Fields::Image { .. } if un.starts_with("image_bvh") => ((11, 0), None),
  5991. Fields::Image { dim, .. } => {
  5992. let kind = match dim {
  5993. 0 => 1,
  5994. 1 => 2,
  5995. 2 => 4,
  5996. 4 => 6,
  5997. 5 => 7,
  5998. _ => return Err("an image dimension (cube or MSAA)"),
  5999. };
  6000. ((kind | u, 0x409), Some(kind))
  6001. }
  6002. Fields::Buffer { idxen, format, .. } => {
  6003. let stride = used.map_or(0, |u| u.stride);
  6004. let counted = inst
  6005. .write(Reg::S(code + first + 2))
  6006. .is_some_and(|v| self.read_as_number(v));
  6007. let props = if un.starts_with("buffer_load_format")
  6008. || un.starts_with("buffer_store_format")
  6009. {
  6010. (10 | u, 0x409)
  6011. } else if !counted
  6012. && *idxen
  6013. && format.is_none()
  6014. && stride >= 4
  6015. && stride.is_multiple_of(4)
  6016. {
  6017. // Nothing reads the count: the query is cleaned up.
  6018. (12 | u, stride)
  6019. } else {
  6020. // Structured ones too: the host's views of them are raw
  6021. // (see `buffer`), which count bytes, and a size asked
  6022. // for as a structured view's is that count on AMD.
  6023. (11 | u, 0)
  6024. };
  6025. if used.is_some_and(|u| u.kind == ResourceType::Cbv) {
  6026. self.stale.extend(inst.writes.iter().map(|w| w.1));
  6027. return Err("a constant buffer's descriptor read as data");
  6028. }
  6029. (props, None)
  6030. }
  6031. // Read by scalar buffer loads alone: the raw view `smem` reads it through.
  6032. Fields::Smem { .. } if used.is_some_and(|u| u.kind == ResourceType::Srv) => {
  6033. ((11, 0), None)
  6034. }
  6035. // A constant buffer: nothing of its descriptor is a number.
  6036. Fields::Smem { .. } => {
  6037. self.stale.extend(inst.writes.iter().map(|w| w.1));
  6038. return Err("a constant buffer's descriptor read as data");
  6039. }
  6040. _ => return Err("a scalar memory read as data"),
  6041. };
  6042. (first, props, image, uav, used)
  6043. };
  6044. let src = Source::Loaded { load: site, first };
  6045. let h = self.handle(site, &src, false, props)?;
  6046. let c = self.cur;
  6047. let i32t = self.s.t.i32;
  6048. let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
  6049. let mip = if image.is_some() && !uav {
  6050. self.s.m.i32(0)
  6051. } else {
  6052. self.s.m.undef(i32t)
  6053. };
  6054. let d = self
  6055. .s
  6056. .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]);
  6057. let field = |l: &mut Self, k: u32| l.s.m.extract(c, d, k);
  6058. let words: Vec<(u32, V)> = match image {
  6059. Some(kind) => {
  6060. let one = self.s.m.i32(1);
  6061. let w = field(self, 0);
  6062. let (height, depth) = match kind {
  6063. 1 => (one, one),
  6064. 2 => (field(self, 1), one),
  6065. 6 => (one, field(self, 1)),
  6066. _ => (field(self, 1), field(self, 2)),
  6067. };
  6068. let levels = if uav { one } else { field(self, 3) };
  6069. let less = |l: &mut Self, x: V| l.s.m.bin(c, Bin::Sub, x, one);
  6070. let (w, height, depth, levels) = (
  6071. less(self, w),
  6072. less(self, height),
  6073. less(self, depth),
  6074. less(self, levels),
  6075. );
  6076. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  6077. let (k30, k2, k14, k16, mask) = (
  6078. k(self, 30),
  6079. k(self, 2),
  6080. k(self, 14),
  6081. k(self, 16),
  6082. k(self, 0x3FFF),
  6083. );
  6084. let d1 = self.s.m.bin(c, Bin::Shl, w, k30);
  6085. let hi = self.s.m.bin(c, Bin::LShr, w, k2);
  6086. let hi = self.s.m.bin(c, Bin::And, hi, mask);
  6087. let ht = self.s.m.bin(c, Bin::Shl, height, k14);
  6088. let d2 = self.s.m.bin(c, Bin::Or, hi, ht);
  6089. let ty = [0, 8, 9, 0, 10, 0, 12, 13][kind as usize];
  6090. let base = k(self, 0xFAC | ty << 28);
  6091. let last = self.s.m.bin(c, Bin::Shl, levels, k16);
  6092. let d3 = self.s.m.bin(c, Bin::Or, base, last);
  6093. vec![(1, d1), (2, d2), (3, d3), (4, depth)]
  6094. }
  6095. None => {
  6096. // A raw view counts bytes; the descriptor's record count is in elements.
  6097. let n = field(self, 0);
  6098. let stride = used.map_or(0, |u| u.stride);
  6099. let counted = inst
  6100. .write(Reg::S(code + first + 2))
  6101. .is_some_and(|v| self.read_as_number(v));
  6102. let n = if props.0 & 0xFF == 11 && stride > 1 {
  6103. let k = self.s.m.i32(stride);
  6104. self.s.m.bin(c, Bin::UDiv, n, k)
  6105. } else if props.0 & 0xFF == 11
  6106. && counted
  6107. && let Some(stride) = self.slot_stride(&src)?
  6108. {
  6109. // Picked from the heap: the host's table has the stride.
  6110. let (i32t, one) = (self.s.t.i32, self.s.m.i32(1));
  6111. let k = self.s.op(c, "binary.i32", Attr::ReadNone, i32t, 39, &[stride, one]);
  6112. self.s.m.bin(c, Bin::UDiv, n, k)
  6113. } else {
  6114. n
  6115. };
  6116. let mut words = vec![(2, n)];
  6117. // Its address too, where the code computes with it and the
  6118. // host can tell it.
  6119. let computed = (0..2u8).any(|k| {
  6120. inst.write(Reg::S(code + first + k))
  6121. .is_some_and(|v| self.computed_with(v, 6))
  6122. });
  6123. // (A descriptor nothing uses as one gets it whenever the host can tell it, as
  6124. // a buffer whose address alone is read does.)
  6125. if first == 0
  6126. && (computed || unused.is_some())
  6127. && let Some((lo, hi)) = self.view_address(site)
  6128. {
  6129. words.extend([(0, lo), (1, hi)]);
  6130. }
  6131. words
  6132. }
  6133. };
  6134. for k in 0..count {
  6135. let rel = k.wrapping_sub(u32::from(first));
  6136. match words.iter().find(|w| w.0 == rel) {
  6137. Some(&(_, x)) => self.write(inst, Reg::S(code + k as u8), x, None),
  6138. None => {
  6139. if let Some(v) = inst.write(Reg::S(code + k as u8)) {
  6140. self.vals.insert(v, Val::Missing(OTHER));
  6141. self.stale.insert(v);
  6142. }
  6143. }
  6144. }
  6145. }
  6146. Ok(())
  6147. }
  6148. /// What [`Self::descriptor_data`] makes of a descriptor load that nothing uses as a
  6149. /// descriptor but whose dwords the code reads: the first dword, the handle properties,
  6150. /// the image kind (none for a buffer), whether it is an unordered view, and its
  6151. /// used-resource entry. An image's eight dwords read as a 2D texture's, a buffer's four
  6152. /// as a raw view's where the code reads its record count (dword 2); none for anything
  6153. /// else (a constant buffer, a sampler, a buffer whose address alone is read).
  6154. // shortcut: an image whose kind nothing tells is taken for a 2D texture (the title's
  6155. // reads are texel sizes of 2D textures: puddle masks, shadow masks); a host view of
  6156. // another kind would answer its own sizes.
  6157. #[allow(clippy::type_complexity)]
  6158. fn unused_descriptor_kind(
  6159. &self,
  6160. inst: &Inst,
  6161. site: Site,
  6162. code: u8,
  6163. count: u32,
  6164. ) -> Option<(u8, (u32, u32), Option<u32>, bool, Option<&'a UsedResource>)> {
  6165. // Kept per lane and compared (`Resources::lane_copied`), or a sampler's: the cases
  6166. // `descriptor_data` handles on their own.
  6167. if self.x.res.lane_copied.contains(&site)
  6168. || self.x.res.descriptors.iter().any(|d| {
  6169. d.role == Role::Sampler
  6170. && d.source.leaves().into_iter().any(
  6171. |l| matches!(*l, Source::Loaded { load, .. } if load == site),
  6172. )
  6173. })
  6174. {
  6175. return None;
  6176. }
  6177. let used = self.used_kind(&Source::Loaded {
  6178. load: site,
  6179. first: 0,
  6180. });
  6181. if used.is_some_and(|u| !matches!(u.kind, ResourceType::Srv | ResourceType::Uav)) {
  6182. return None;
  6183. }
  6184. let read = |k: u32| {
  6185. inst.write(Reg::S(code + k as u8)).is_some_and(|v| {
  6186. self.x
  6187. .p
  6188. .blocks
  6189. .iter()
  6190. .flat_map(|b| &b.insts)
  6191. .any(|i| i.reads.iter().any(|r| r.1 == v))
  6192. })
  6193. };
  6194. let uav = used.is_some_and(|u| u.kind == ResourceType::Uav);
  6195. let u = if uav { 0x1000 } else { 0 };
  6196. match count {
  6197. // width (dwords 1-2), height (2), levels (3), depth (4)
  6198. 8 if (1..5).any(read) && used.is_none_or(|u| u.dwords == 8) => {
  6199. Some((0, (2 | u, 0x409), Some(2), uav, used))
  6200. }
  6201. // the record count
  6202. 4 if read(2) && used.is_none_or(|u| u.dwords == 4) => {
  6203. Some((0, (11 | u, 0), None, uav, used))
  6204. }
  6205. _ => None,
  6206. }
  6207. }
  6208. /// `s_load_dword*` from the program's constant table.
  6209. fn code_smem(&mut self, inst: &Inst, a: Address) -> Result<(), Why> {
  6210. let Fields::Smem {
  6211. data: Some(Operand::Scalar { code, .. }),
  6212. ..
  6213. } = inst.fields
  6214. else {
  6215. return Err("a scalar load");
  6216. };
  6217. let count = match inst.name().strip_prefix("s_load_dword") {
  6218. Some("") => 1u32,
  6219. Some("x2") => 2,
  6220. Some("x4") => 4,
  6221. Some("x8") => 8,
  6222. Some("x16") => 16,
  6223. _ => return Err("a scalar load from the code"),
  6224. };
  6225. let c = self.cur;
  6226. let mut addr = self.s.m.i32(a.offset);
  6227. if let Some(value) = a.dynamic {
  6228. let mut d = self.i32_of(value)?;
  6229. // A term held per lane reached the address through
  6230. // `v_readfirstlane_b32`: the first lane's.
  6231. let per_lane = self.def_block.get(&value).is_some_and(|&b| {
  6232. let writes = |i: &Inst| i.writes.iter().any(|w| w.1 == value && matches!(w.0, Reg::V(_)));
  6233. self.x.p.blocks[b].insts.iter().any(writes)
  6234. });
  6235. if per_lane {
  6236. self.s.flags |= flags::WAVE_OPS;
  6237. let i32t = self.s.t.i32;
  6238. let first = self.s.op(c, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[d]);
  6239. d = if self.s.pixel && super::helper_own() {
  6240. let helper = self.helper_lane();
  6241. self.s.m.select(c, helper, d, first)
  6242. } else {
  6243. first
  6244. };
  6245. }
  6246. addr = self.s.m.bin(c, Bin::Add, addr, d);
  6247. }
  6248. for k in 0..count {
  6249. let off = self.s.m.i32(4 * k);
  6250. let at = self.s.m.bin(c, Bin::Add, addr, off);
  6251. let x = self.code_dword(at)?;
  6252. self.write(inst, Reg::S(code + k as u8), x, None);
  6253. }
  6254. Ok(())
  6255. }
  6256. /// The dword at a computed byte address of a constant buffer.
  6257. fn cbuffer_dword(&mut self, h: V, a: V) -> V {
  6258. let c = self.cur;
  6259. let four = self.s.m.i32(4);
  6260. let ri = self.s.m.bin(c, Bin::LShr, a, four);
  6261. let r = self.s.op(
  6262. c,
  6263. "cbufferLoadLegacy.i32",
  6264. Attr::ReadOnly,
  6265. self.s.t.cbuf_ret,
  6266. 59,
  6267. &[h, ri],
  6268. );
  6269. let two = self.s.m.i32(2);
  6270. let three = self.s.m.i32(3);
  6271. let comp = self.s.m.bin(c, Bin::LShr, a, two);
  6272. let comp = self.s.m.bin(c, Bin::And, comp, three);
  6273. let mut x = self.s.m.extract(c, r, 0);
  6274. for j in 1..4 {
  6275. let e = self.s.m.extract(c, r, j);
  6276. let jc = self.s.m.i32(j);
  6277. let is = self.s.m.cmp(c, pred::EQ, comp, jc);
  6278. x = self.s.m.select(c, is, e, x);
  6279. }
  6280. x
  6281. }
  6282. /// `channels` channels of the element at byte `off` of raw buffer `h`,
  6283. /// converted from the GFX10 buffer format `format` as the hardware's
  6284. /// typed loads do (channels past the format's read 0, 0, 0, 1).
  6285. // shortcut: the descriptor's channel swizzle is taken as the identity
  6286. // (it is for raw views and the descriptors code builds), elements of 4
  6287. // bytes or more as dword-aligned. Norm formats divide, which the AMD
  6288. // driver does 1 ULP off the hardware's correctly rounded conversion for
  6289. // some values; correct it with an integer check if a title compares
  6290. // converted values exactly.
  6291. fn format_load(&mut self, h: V, off: V, format: u8, channels: u32) -> Result<Vec<V>, Why> {
  6292. let (bits, numeric) = buffer_format(format).ok_or("a buffer format")?;
  6293. let c = self.cur;
  6294. let total: u32 = bits.iter().sum();
  6295. let (u, align) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
  6296. let load = |l: &mut Self, at: V, n: u32| -> Vec<V> {
  6297. let mask = l.s.m.i8((1u8 << n) - 1);
  6298. let r = l.s.op(
  6299. c,
  6300. "rawBufferLoad.f32",
  6301. Attr::ReadOnly,
  6302. l.s.t.res_ret,
  6303. 139,
  6304. &[h, at, u, mask, align],
  6305. );
  6306. (0..n)
  6307. .map(|k| {
  6308. let x = l.s.m.extract(c, r, k);
  6309. l.as_int(x)
  6310. })
  6311. .collect()
  6312. };
  6313. let words = if total < 32 {
  6314. // A byte or half inside the dword that holds it.
  6315. let (not3, three) = (self.s.m.i32(!3), self.s.m.i32(3));
  6316. let at = self.s.m.bin(c, Bin::And, off, not3);
  6317. let w = load(self, at, 1)[0];
  6318. let byte = self.s.m.bin(c, Bin::And, off, three);
  6319. let sh = self.s.m.bin(c, Bin::Shl, byte, three);
  6320. vec![self.s.m.bin(c, Bin::LShr, w, sh)]
  6321. } else {
  6322. load(self, off, total / 32)
  6323. };
  6324. let float = |l: &mut Self, f: V| l.as_int(f);
  6325. let mut out = Vec::new();
  6326. let mut at = 0;
  6327. for &w in bits {
  6328. let word = words[(at / 32) as usize];
  6329. let field = if w == 32 {
  6330. word
  6331. } else {
  6332. let sh = self.s.m.i32(at % 32);
  6333. let t = self.s.m.bin(c, Bin::LShr, word, sh);
  6334. let m = self.s.m.i32((1 << w) - 1);
  6335. self.s.m.bin(c, Bin::And, t, m)
  6336. };
  6337. at += w;
  6338. // Sign-extended from the field's top bit.
  6339. let signed = |l: &mut Self| {
  6340. if w == 32 {
  6341. return field;
  6342. }
  6343. let k = l.s.m.i32(32 - w);
  6344. let t = l.s.m.bin(c, Bin::Shl, field, k);
  6345. l.s.m.bin(c, Bin::AShr, t, k)
  6346. };
  6347. let f32t = self.s.t.f32;
  6348. // A normalized format's ends are exactly 1.0 and -1.0. The host
  6349. // may divide through a reciprocal and land just below 1.0: RDNA
  6350. // 4 loaded 16_16_UNORM's 65535 as the half 0x3BFF, not 0x3C00.
  6351. let x = match numeric {
  6352. Numeric::Unorm => {
  6353. let f = self.s.m.cast(c, Cast::UiToFp, field, f32t);
  6354. let top = (1u64 << w) - 1;
  6355. let max = self.s.m.f32((top as f32).to_bits());
  6356. let q = self.s.m.bin(c, Bin::SDiv, f, max);
  6357. let (high, one) = (self.s.m.i32(top as u32), self.s.m.f32(1.0f32.to_bits()));
  6358. let at_top = self.s.m.cmp(c, pred::EQ, field, high);
  6359. let q = self.s.m.select(c, at_top, one, q);
  6360. float(self, q)
  6361. }
  6362. Numeric::Snorm => {
  6363. let s = signed(self);
  6364. let f = self.s.m.cast(c, Cast::SiToFp, s, f32t);
  6365. let top = (1u32 << (w - 1)) - 1;
  6366. let max = self.s.m.f32((top as f32).to_bits());
  6367. let q = self.s.m.bin(c, Bin::SDiv, f, max);
  6368. // The lowest value is -1.0 too, as is the one above it.
  6369. let (high, one) = (self.s.m.i32(top), self.s.m.f32(1.0f32.to_bits()));
  6370. let at_top = self.s.m.cmp(c, pred::SGE, s, high);
  6371. let q = self.s.m.select(c, at_top, one, q);
  6372. let low = self.s.m.i32(top.wrapping_neg());
  6373. let minus_one = self.s.m.f32((-1.0f32).to_bits());
  6374. let at_bottom = self.s.m.cmp(c, pred::SLE, s, low);
  6375. let q = self.s.m.select(c, at_bottom, minus_one, q);
  6376. float(self, q)
  6377. }
  6378. Numeric::Uscaled => {
  6379. let f = self.s.m.cast(c, Cast::UiToFp, field, f32t);
  6380. float(self, f)
  6381. }
  6382. Numeric::Sscaled => {
  6383. let s = signed(self);
  6384. let f = self.s.m.cast(c, Cast::SiToFp, s, f32t);
  6385. float(self, f)
  6386. }
  6387. Numeric::Uint => field,
  6388. Numeric::Sint => signed(self),
  6389. Numeric::Float if w == 32 => field,
  6390. Numeric::Float => {
  6391. let h = match half_shift(w) {
  6392. 0 => field,
  6393. k => {
  6394. let sh = self.s.m.i32(k);
  6395. self.s.m.bin(c, Bin::Shl, field, sh)
  6396. }
  6397. };
  6398. let f = self
  6399. .s
  6400. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]);
  6401. float(self, f)
  6402. }
  6403. };
  6404. out.push(x);
  6405. }
  6406. let one = match numeric {
  6407. Numeric::Uint | Numeric::Sint => 1,
  6408. _ => 1.0f32.to_bits(),
  6409. };
  6410. for k in out.len() as u32..channels {
  6411. out.push(self.s.m.i32(if k == 3 { one } else { 0 }));
  6412. }
  6413. out.truncate(channels as usize);
  6414. Ok(out)
  6415. }
  6416. /// Channels of buffer format `format`, as [`Self::format_load`] gives
  6417. /// them, as d16 data: 16 bits each, two per dword, low half first (an
  6418. /// odd last high half 0). Integer formats keep their low 16 bits; the
  6419. /// others become f16.
  6420. fn d16_channels(&mut self, format: u8, channels: Vec<V>) -> Result<Vec<V>, Why> {
  6421. let (_, numeric) = buffer_format(format).ok_or("a buffer format")?;
  6422. let c = self.cur;
  6423. let mut halves = Vec::new();
  6424. for x in channels {
  6425. halves.push(if matches!(numeric, Numeric::Uint | Numeric::Sint) {
  6426. let m = self.s.m.i32(0xFFFF);
  6427. self.s.m.bin(c, Bin::And, x, m)
  6428. } else {
  6429. let (f, i32t) = (self.as_float(x), self.s.t.i32);
  6430. self.s
  6431. .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f])
  6432. });
  6433. }
  6434. let mut out = Vec::new();
  6435. for pair in halves.chunks(2) {
  6436. out.push(match *pair {
  6437. [lo, hi] => {
  6438. let k16 = self.s.m.i32(16);
  6439. let hi = self.s.m.bin(c, Bin::Shl, hi, k16);
  6440. self.s.m.bin(c, Bin::Or, lo, hi)
  6441. }
  6442. [lo] => lo,
  6443. _ => unreachable!("chunks of one or two"),
  6444. });
  6445. }
  6446. Ok(out)
  6447. }
  6448. /// The byte offset a buffer descriptor built around a root descriptor adds
  6449. /// (constant and computed parts); none for other descriptors.
  6450. fn built_offset(&mut self, src: &Source) -> Result<(u32, Option<V>), Why> {
  6451. match src {
  6452. Source::Built { address, .. } => {
  6453. let mut x = match address.dynamic {
  6454. Some(v) => Some(self.i32_of(v)?),
  6455. None => None,
  6456. };
  6457. if let Some(bias) = self.root_bias(address.param) {
  6458. x = Some(match x {
  6459. Some(d) => self.s.m.bin(self.cur, Bin::Add, d, bias),
  6460. None => bias,
  6461. });
  6462. }
  6463. Ok((address.offset, x))
  6464. }
  6465. _ => Ok((0, None)),
  6466. }
  6467. }
  6468. /// For a root view the host binds as a raw view that may begin before
  6469. /// the title's address (`shader.rs` `USER_VIEW_BIAS`): the bytes to add
  6470. /// to offsets through it. Every root UAV, and the root SRVs of programs
  6471. /// with a spilled user-data table (the others keep the views they
  6472. /// have).
  6473. fn root_bias(&mut self, param: usize) -> Option<V> {
  6474. use super::shader::USER_VIEW_BIAS;
  6475. let rp = *self.x.native.layout.get(param)?;
  6476. if rp.root != RootType::Descriptor {
  6477. return None;
  6478. }
  6479. let kind = self
  6480. .x
  6481. .native
  6482. .used
  6483. .iter()
  6484. .find(|u| u.user_data == rp.user_data)
  6485. .map(|u| u.kind);
  6486. let biased = match kind {
  6487. Some(ResourceType::Uav) => true,
  6488. Some(ResourceType::Srv) => crate::spill::is_spilled(self.x.native),
  6489. _ => false,
  6490. };
  6491. biased.then(|| self.host_word(RootType::Other(USER_VIEW_BIAS), rp.slot, 0))
  6492. }
  6493. /// The used-resource entry a descriptor loaded from a table falls in.
  6494. fn used_kind(&self, src: &Source) -> Option<&'a UsedResource> {
  6495. if let Source::Phi { args, .. } | Source::Select { args, .. } | Source::Lanes { args, .. } =
  6496. src
  6497. {
  6498. return self.used_kind(args.first()?);
  6499. }
  6500. if let Source::LanePhi { args, .. } = src {
  6501. return args.iter().flatten().find_map(|a| self.used_kind(a));
  6502. }
  6503. if let Source::Built { address, .. } = src {
  6504. let rp = self.x.native.layout.get(address.param)?;
  6505. return self
  6506. .x
  6507. .native
  6508. .used
  6509. .iter()
  6510. .find(|u| u.root == RootType::Descriptor && u.user_data == rp.user_data);
  6511. }
  6512. let (Source::Loaded { load, first } | Source::Fetched { load, first }) = src else {
  6513. return None;
  6514. };
  6515. let a = self.scalar.get(load)?;
  6516. let rp = self.x.native.layout.get(a.param)?;
  6517. if rp.root != RootType::Table {
  6518. return None;
  6519. }
  6520. let dword = (a.offset / 4) + u32::from(*first);
  6521. self.x
  6522. .native
  6523. .used
  6524. .iter()
  6525. .filter(|u| {
  6526. u.root == RootType::Table
  6527. && u.user_data == rp.user_data
  6528. && u.table_offset_dwords <= dword
  6529. })
  6530. .max_by_key(|u| u.table_offset_dwords)
  6531. }
  6532. /// A handle for the descriptor `src` read at `site`.
  6533. fn handle(
  6534. &mut self,
  6535. site: Site,
  6536. src: &Source,
  6537. sampler: bool,
  6538. props: (u32, u32),
  6539. ) -> Result<V, Why> {
  6540. match src {
  6541. Source::Loaded { load, first } => {
  6542. let key = (self.cur, *load, *first, sampler, props);
  6543. if let Some(&h) = self.handles.get(&key) {
  6544. return Ok(h);
  6545. }
  6546. let index = self.heap_index(*load, *first, sampler)?;
  6547. let (index, bounded) = self.raw_twin(src, index, sampler, props);
  6548. // A waterfall loop's load at the first lane's offset reads
  6549. // each lane's own entry (see `resource::Waterfall`).
  6550. let per_lane = self.x.res.waterfall.loads.contains(load);
  6551. let h = self
  6552. .s
  6553. .heap_handle_at(self.cur, index, sampler, per_lane, props, bounded);
  6554. self.handles.insert(key, h);
  6555. Ok(h)
  6556. }
  6557. Source::Constant(words) if sampler => {
  6558. let n = self.register_sampler(words, props.0 & 0x8000 != 0)?;
  6559. Ok(self.s.sampler_handle(self.cur, n))
  6560. }
  6561. Source::Constant(_) => Err("a constant resource descriptor"),
  6562. Source::Built { address, .. } => {
  6563. let rp = *self
  6564. .x
  6565. .native
  6566. .layout
  6567. .get(address.param)
  6568. .ok_or("a descriptor built around a table in the code")?;
  6569. let kind = self
  6570. .x
  6571. .native
  6572. .used
  6573. .iter()
  6574. .find(|u| u.user_data == rp.user_data)
  6575. .map(|u| u.kind);
  6576. match (rp.root, kind, props.0) {
  6577. (RootType::Descriptor, Some(ResourceType::Cbv) | None, 13) => {
  6578. Ok(self.s.root_cbv_handle(rp.slot))
  6579. }
  6580. (RootType::Descriptor, Some(ResourceType::Srv), 11) => {
  6581. Ok(self.s.root_srv_handle(rp.slot))
  6582. }
  6583. // A root UAV: a raw buffer whether the access reads
  6584. // (11) or writes (11 with the UAV bit). Indexed
  6585. // accesses reach here as raw ones at index times the
  6586. // entry's stride (`buffer`).
  6587. (RootType::Descriptor, Some(ResourceType::Uav), 11 | 0x100b) => {
  6588. Ok(self.s.root_uav_handle(rp.slot))
  6589. }
  6590. (RootType::Descriptor, Some(ResourceType::Srv), 0x100b) => {
  6591. Err("a write through a root SRV")
  6592. }
  6593. _ => Err("a typed root view"),
  6594. }
  6595. }
  6596. Source::Phi { block, args } => {
  6597. let _ = site;
  6598. let phi = self.descriptor_phi(*block, args, sampler, 8)?;
  6599. let (index, bounded) = self.raw_twin(src, phi, sampler, props);
  6600. Ok(self.s.heap_handle_at(self.cur, index, sampler, false, props, bounded))
  6601. }
  6602. Source::Select { scc, args } => {
  6603. // The heap index of each choice, picked by SCC (uniform).
  6604. let [
  6605. Source::Loaded { load: a, first: fa },
  6606. Source::Loaded { load: b, first: fb },
  6607. ] = args[..]
  6608. else {
  6609. return Err("a descriptor chosen by a condition");
  6610. };
  6611. let cond = match self.get(*scc)? {
  6612. Val::Bit(x) => x,
  6613. _ => return Err("SCC without a value"),
  6614. };
  6615. let set = self.heap_index(a, fa, sampler)?;
  6616. let clear = self.heap_index(b, fb, sampler)?;
  6617. let index = self.s.m.select(self.cur, cond, set, clear);
  6618. let (index, bounded) = self.raw_twin(src, index, sampler, props);
  6619. Ok(self.s.heap_handle_at(self.cur, index, sampler, false, props, bounded))
  6620. }
  6621. Source::Fetched { .. } | Source::Lanes { .. } | Source::LanePhi { .. } => {
  6622. // A descriptor each lane has its own of (a waterfall loop
  6623. // reads it from the first active lane): each lane's heap
  6624. // index, non-uniform.
  6625. let index = self.lane_heap_index(src, sampler)?;
  6626. let (index, bounded) = self.raw_twin(src, index, sampler, props);
  6627. Ok(self.s.heap_handle_at(self.cur, index, sampler, true, props, bounded))
  6628. }
  6629. }
  6630. }
  6631. /// The heap index to read descriptor `src` at, `index` being the title's:
  6632. /// for a buffer picked from the heap itself and read as raw bytes (or as
  6633. /// a constant buffer), the host's raw twin of that slot
  6634. /// ([`super::shader::raw_views`]), whose reads end where the view does.
  6635. /// Everything else (tables, textures, typed buffers) stays in place.
  6636. /// And whether it is a twin's (inside the host's heap).
  6637. fn raw_twin(&mut self, src: &Source, index: V, sampler: bool, props: (u32, u32)) -> (V, bool) {
  6638. // Raw and constant buffers (DXIL resource kinds 11 and 13).
  6639. const RAW: u32 = 11;
  6640. const CONSTANT: u32 = 13;
  6641. let first = super::shader::raw_views();
  6642. let picked = |leaf: &&Source| {
  6643. let (Source::Loaded { load, .. } | Source::Fetched { load, .. }) = leaf else {
  6644. return false;
  6645. };
  6646. self.scalar
  6647. .get(load)
  6648. .and_then(|a| self.x.native.layout.get(a.param))
  6649. .is_some_and(|p| p.root == RootType::ResourceHeap)
  6650. };
  6651. if first == 0 || sampler || !matches!(props.0 & 0xFF, RAW | CONSTANT) || !src.leaves().iter().all(picked) {
  6652. return (index, false);
  6653. }
  6654. let c = self.cur;
  6655. let (last, first) = (self.s.m.i32(first - 1), self.s.m.i32(first));
  6656. let i32t = self.s.t.i32;
  6657. // (As `dx.op.binary` UMin, see `heap_handle`.)
  6658. let index = self.s.op(c, "binary.i32", Attr::ReadNone, i32t, 40, &[index, last]);
  6659. self.s.m.tag(index, Tag::Clamp);
  6660. (self.s.m.bin(c, Bin::Or, index, first), true)
  6661. }
  6662. /// The heap index a descriptor phi picks. Each predecessor computes its
  6663. /// heap index at its end and the join picks one with a phi; a
  6664. /// predecessor whose descriptor is itself chosen by control flow (a
  6665. /// phi of an earlier join, which dominates it) gives that join's phi,
  6666. /// at most `depth` joins deep.
  6667. fn descriptor_phi(
  6668. &mut self,
  6669. block: usize,
  6670. args: &[Source],
  6671. sampler: bool,
  6672. depth: u32,
  6673. ) -> Result<V, Why> {
  6674. const WHY: Why = "a descriptor chosen by control flow";
  6675. let p = self.x.p;
  6676. let mut incoming = Vec::new();
  6677. for (&q, arg) in p.blocks[block].preds.iter().zip(args) {
  6678. if self.block[q].is_none() {
  6679. continue;
  6680. }
  6681. let tail = self.tail[q].ok_or(WHY)?;
  6682. let at = self.edges.get(&(q, block)).copied().unwrap_or(tail);
  6683. let index = match arg {
  6684. Source::Loaded { load, first } => {
  6685. let here = std::mem::replace(&mut self.cur, at);
  6686. let index = self.heap_index(*load, *first, sampler);
  6687. self.cur = here;
  6688. index?
  6689. }
  6690. Source::Phi { block: inner, args: inner_args } if depth > 0 => {
  6691. self.descriptor_phi(*inner, inner_args, sampler, depth - 1)?
  6692. }
  6693. _ => return Err(WHY),
  6694. };
  6695. incoming.push((index, at));
  6696. }
  6697. let join = self.block[block].ok_or(WHY)?;
  6698. let phi = self.s.m.phi(join, self.s.t.i32);
  6699. self.s.m.set_phi(phi, incoming);
  6700. Ok(phi)
  6701. }
  6702. /// Registers an immediate sampler constant and returns its slot index: a
  6703. /// constant used with and without comparison takes one slot for each.
  6704. fn register_sampler(&mut self, words: &[u32], cmp: bool) -> Result<u32, Why> {
  6705. let words: [u32; 4] = words
  6706. .get(..4)
  6707. .and_then(|w| w.try_into().ok())
  6708. .ok_or("a sampler constant")?;
  6709. let slot = self
  6710. .samplers
  6711. .iter()
  6712. .enumerate()
  6713. .position(|(n, w)| *w == words && (self.s.cmp_samplers >> n & 1 != 0) == cmp);
  6714. let n = match slot {
  6715. Some(n) => n,
  6716. None => {
  6717. let n = self.samplers.len();
  6718. if n >= u64::BITS as usize {
  6719. return Err("more than 64 immediate sampler slots");
  6720. }
  6721. self.samplers.push(words);
  6722. self.s.cmp_samplers |= u64::from(cmp) << n;
  6723. n
  6724. }
  6725. };
  6726. Ok(n as u32)
  6727. }
  6728. /// Resolves a control-flow phi of immediate sampler constants into either a
  6729. /// single static sampler register (`One`) or a uniform `i32` phi index over
  6730. /// `regs` (`Many`) for branch dispatch at the sample site.
  6731. fn sampler_phi_choice(
  6732. &mut self,
  6733. block: usize,
  6734. args: &[Source],
  6735. cmp: bool,
  6736. depth: u32,
  6737. ) -> Result<(Option<V>, Vec<u32>), Why> {
  6738. const WHY: Why = "a descriptor chosen by control flow";
  6739. let mut distinct: Vec<[u32; 4]> = Vec::new();
  6740. self.collect_constant_samplers(block, args, depth, &mut distinct)?;
  6741. if distinct.is_empty() {
  6742. return Err(WHY);
  6743. }
  6744. let mut regs = Vec::with_capacity(distinct.len());
  6745. for w in &distinct {
  6746. regs.push(self.register_sampler(w, cmp)?);
  6747. }
  6748. if regs.len() == 1 {
  6749. return Ok((None, regs));
  6750. }
  6751. let idx = self.sampler_index_phi(block, args, 0, &distinct, depth)?;
  6752. Ok((Some(idx), regs))
  6753. }
  6754. fn collect_constant_samplers(
  6755. &self,
  6756. block: usize,
  6757. args: &[Source],
  6758. depth: u32,
  6759. distinct: &mut Vec<[u32; 4]>,
  6760. ) -> Result<(), Why> {
  6761. const WHY: Why = "a descriptor chosen by control flow";
  6762. let p = self.x.p;
  6763. for (&q, arg) in p.blocks[block].preds.iter().zip(args) {
  6764. if self.block[q].is_none() {
  6765. continue;
  6766. }
  6767. match arg {
  6768. Source::Constant(w) if w.len() >= 4 => {
  6769. let k: [u32; 4] = w[..4].try_into().unwrap();
  6770. if !distinct.contains(&k) {
  6771. distinct.push(k);
  6772. }
  6773. }
  6774. Source::Phi {
  6775. block: inner,
  6776. args: inner_args,
  6777. } if depth > 0 => {
  6778. self.collect_constant_samplers(*inner, inner_args, depth - 1, distinct)?;
  6779. }
  6780. _ => return Err(WHY),
  6781. }
  6782. }
  6783. Ok(())
  6784. }
  6785. fn sampler_index_phi(
  6786. &mut self,
  6787. block: usize,
  6788. args: &[Source],
  6789. lower: u32,
  6790. distinct: &[[u32; 4]],
  6791. depth: u32,
  6792. ) -> Result<V, Why> {
  6793. const WHY: Why = "a descriptor chosen by control flow";
  6794. let p = self.x.p;
  6795. let mut incoming = Vec::new();
  6796. for (&q, arg) in p.blocks[block].preds.iter().zip(args) {
  6797. if self.block[q].is_none() {
  6798. continue;
  6799. }
  6800. let tail = self.tail[q].ok_or(WHY)?;
  6801. let at = self.edges.get(&(q, block)).copied().unwrap_or(tail);
  6802. let idx = match arg {
  6803. Source::Constant(w) if w.len() >= 4 => {
  6804. let k: [u32; 4] = w[..4].try_into().unwrap();
  6805. let pos = distinct.iter().position(|d| *d == k).ok_or(WHY)? as u32;
  6806. self.s.m.i32(lower + pos)
  6807. }
  6808. Source::Phi {
  6809. block: inner,
  6810. args: inner_args,
  6811. } if depth > 0 => {
  6812. self.sampler_index_phi(*inner, inner_args, lower, distinct, depth - 1)?
  6813. }
  6814. _ => return Err(WHY),
  6815. };
  6816. incoming.push((idx, at));
  6817. }
  6818. let join = self.block[block].ok_or(WHY)?;
  6819. let phi = self.s.m.phi(join, self.s.t.i32);
  6820. self.s.m.set_phi(phi, incoming);
  6821. Ok(phi)
  6822. }
  6823. /// The bytes per element of the buffer view `src` names, if the program
  6824. /// picks it from the view heap at an index it computes (root type
  6825. /// `ResourceHeap`): read from the host's table by heap slot in the
  6826. /// current block.
  6827. fn slot_stride(&mut self, src: &Source) -> Result<Option<V>, Why> {
  6828. let Source::Loaded { load, first } = src else {
  6829. return Ok(None);
  6830. };
  6831. let heap = self
  6832. .scalar
  6833. .get(load)
  6834. .and_then(|a| self.x.native.layout.get(a.param))
  6835. .is_some_and(|p| p.root == RootType::ResourceHeap);
  6836. if !heap {
  6837. return Ok(None);
  6838. }
  6839. let key = (self.cur, *load, *first);
  6840. if let Some(&v) = self.strides.get(&key) {
  6841. return Ok(Some(v));
  6842. }
  6843. let c = self.cur;
  6844. let slot = self.heap_index(*load, *first, false)?;
  6845. // Inside the table whatever the index (lanes that do not run
  6846. // compute one too): a root view has no bounds of its own.
  6847. let last = self.s.m.i32(super::shader::SLOT_STRIDES_COUNT - 1);
  6848. let i32t = self.s.t.i32;
  6849. let slot = self.s.op(c, "binary.i32", Attr::ReadNone, i32t, 40, &[slot, last]);
  6850. self.s.m.tag(slot, Tag::Clamp);
  6851. let two = self.s.m.i32(2);
  6852. let byte = self.s.m.bin(c, Bin::Shl, slot, two);
  6853. let h = self.s.root_srv_handle(super::shader::SLOT_STRIDES);
  6854. let iu = self.s.m.undef(self.s.t.i32);
  6855. let mask = self.s.m.i8(1);
  6856. let align = self.s.m.i32(4);
  6857. let r = self.s.op(
  6858. c,
  6859. "rawBufferLoad.f32",
  6860. Attr::ReadOnly,
  6861. self.s.t.res_ret,
  6862. 139,
  6863. &[h, byte, iu, mask, align],
  6864. );
  6865. let f = self.s.m.extract(c, r, 0);
  6866. let v = self.as_int(f);
  6867. self.strides.insert(key, v);
  6868. Ok(Some(v))
  6869. }
  6870. /// The heap index of a descriptor that may differ between lanes,
  6871. /// computed in the current block (or, chosen by control flow, at the
  6872. /// join).
  6873. fn lane_heap_index(&mut self, src: &Source, sampler: bool) -> Result<V, Why> {
  6874. match src {
  6875. Source::Loaded { load, first } => self.heap_index(*load, *first, sampler),
  6876. Source::Fetched { load, first } => self.fetched_index(*load, *first, sampler),
  6877. Source::Lanes { mask, args } | Source::Select { scc: mask, args } => {
  6878. let [a, b] = &args[..] else {
  6879. return Err("a descriptor chosen per lane");
  6880. };
  6881. let cond = if matches!(src, Source::Lanes { .. }) {
  6882. let &m = self
  6883. .x
  6884. .st
  6885. .masks
  6886. .get(mask)
  6887. .ok_or("a descriptor chosen per lane by an untracked mask")?;
  6888. self.boolean(m, self.cur)?
  6889. } else {
  6890. match self.get(*mask)? {
  6891. Val::Bit(x) => x,
  6892. _ => return Err("SCC without a value"),
  6893. }
  6894. };
  6895. let set = self.lane_heap_index(a, sampler)?;
  6896. let clear = self.lane_heap_index(b, sampler)?;
  6897. Ok(self.s.m.select(self.cur, cond, set, clear))
  6898. }
  6899. Source::LanePhi { block, args } => {
  6900. // Each predecessor computes its heap index at its end (what
  6901. // it reads is there: the dwords are, on that edge); the join
  6902. // picks the one of the edge the lane came by. An edge no
  6903. // lane reading it takes gives index 0.
  6904. let join =
  6905. self.block[*block].ok_or("a per-lane descriptor chosen by control flow")?;
  6906. let mut incoming = Vec::new();
  6907. for (&q, arg) in self.x.p.blocks[*block].preds.iter().zip(args) {
  6908. if self.block[q].is_none() {
  6909. continue;
  6910. }
  6911. let tail =
  6912. self.tail[q].ok_or("a per-lane descriptor joined from a later block")?;
  6913. let at = self.edges.get(&(q, *block)).copied().unwrap_or(tail);
  6914. let index = match arg {
  6915. Some(arg) => {
  6916. let here = std::mem::replace(&mut self.cur, at);
  6917. let index = self.lane_heap_index(arg, sampler);
  6918. self.cur = here;
  6919. index?
  6920. }
  6921. None => self.s.m.i32(0),
  6922. };
  6923. incoming.push((index, at));
  6924. }
  6925. let phi = self.s.m.phi(join, self.s.t.i32);
  6926. self.s.m.set_phi(phi, incoming);
  6927. Ok(phi)
  6928. }
  6929. _ => Err("a per-lane descriptor from neither a heap load nor a choice of them"),
  6930. }
  6931. }
  6932. /// The heap index of the descriptor at dword `first` of what the global
  6933. /// load at `load` reads, in each lane: its address (base plus offsets)
  6934. /// over the descriptor size.
  6935. fn fetched_index(&mut self, load: Site, first: u8, sampler: bool) -> Result<V, Why> {
  6936. const WHY: Why = "a per-lane descriptor load";
  6937. let a = *self
  6938. .scalar
  6939. .get(&load)
  6940. .ok_or("an untracked descriptor load")?;
  6941. match self.x.native.layout.get(a.param).map(|p| p.root) {
  6942. Some(RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap) => {}
  6943. _ => return Err("a descriptor outside the heaps"),
  6944. }
  6945. let li: &Inst = &self.x.p.blocks[load.0].insts[load.1];
  6946. let Fields::Flat {
  6947. addr: Some(Operand::Vector { reg, .. }),
  6948. saddr,
  6949. offset,
  6950. ..
  6951. } = li.fields
  6952. else {
  6953. return Err(WHY);
  6954. };
  6955. let c = self.cur;
  6956. // The low dword of the address: SGPR base plus VGPR offset, or the
  6957. // VGPR pair's low half (heap addresses fit in 32 bits).
  6958. let mut at = self.i32_of(li.read(Reg::V(reg)).ok_or(WHY)?)?;
  6959. if let Some(Operand::Scalar { code, .. }) = saddr
  6960. && code != NULL
  6961. {
  6962. let base = self.i32_of(li.read(Reg::S(code)).ok_or(WHY)?)?;
  6963. at = self.s.m.bin(c, Bin::Add, base, at);
  6964. }
  6965. let k = self
  6966. .s
  6967. .m
  6968. .i32((offset as i32 as u32).wrapping_add(4 * u32::from(first)));
  6969. at = self.s.m.bin(c, Bin::Add, at, k);
  6970. let shift = self.s.m.i32(if sampler { 4 } else { 5 });
  6971. Ok(self.s.m.bin(c, Bin::LShr, at, shift))
  6972. }
  6973. /// The heap index of the descriptor at dword `first` of what the scalar
  6974. /// load at `load` reads, computed in the current block.
  6975. fn heap_index(&mut self, load: Site, first: u8, sampler: bool) -> Result<V, Why> {
  6976. let a = *self
  6977. .scalar
  6978. .get(&load)
  6979. .ok_or("an untracked descriptor load")?;
  6980. match self.x.native.layout.get(a.param).map(|p| p.root) {
  6981. Some(RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap) => {}
  6982. _ => return Err("a descriptor outside the heaps"),
  6983. }
  6984. let li: &Inst = &self.x.p.blocks[load.0].insts[load.1];
  6985. let Fields::Smem {
  6986. base,
  6987. offset,
  6988. soffset,
  6989. ..
  6990. } = &li.fields
  6991. else {
  6992. return Err("a descriptor load");
  6993. };
  6994. let Operand::Scalar { code, .. } = *base else {
  6995. return Err("a descriptor load");
  6996. };
  6997. let c = self.cur;
  6998. let base = li.read(Reg::S(code)).ok_or("a descriptor load")?;
  6999. let mut addr = self.i32_of(base)?;
  7000. let k = self
  7001. .s
  7002. .m
  7003. .i32((*offset as u32).wrapping_add(4 * u32::from(first)));
  7004. addr = self.s.m.bin(c, Bin::Add, addr, k);
  7005. if !matches!(soffset, Operand::Scalar { code: NULL, .. }) {
  7006. let so = self.operand(li, soffset)?;
  7007. addr = self.s.m.bin(c, Bin::Add, addr, so);
  7008. }
  7009. let shift = self.s.m.i32(if sampler { 4 } else { 5 });
  7010. Ok(self.s.m.bin(c, Bin::LShr, addr, shift))
  7011. }
  7012. fn valu(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  7013. let Fields::Valu(v) = &inst.fields else {
  7014. unreachable!()
  7015. };
  7016. let name = inst.name();
  7017. if self.x.res.waterfall.compares.contains(&(b, i)) {
  7018. // The first lane's dwords of a waterfall loop are each lane's
  7019. // own (see `resource::Waterfall`).
  7020. self.lane(inst, Some(true));
  7021. return Ok(());
  7022. }
  7023. // One lane of a VGPR a whole-wave section left.
  7024. if name == "v_readlane_b32"
  7025. && let Some(&(_, w)) = inst.writes.first()
  7026. && let Some(sh) = self.sections.get(&b).and_then(|s| {
  7027. s.iter().filter(|s| s.1.end < i).find_map(|s| s.1.reads.get(&w).copied())
  7028. })
  7029. {
  7030. let x = self.shape(sh, false)?;
  7031. self.vals.insert(w, Val::I32(x));
  7032. return Ok(());
  7033. }
  7034. if let Some(rest) = name.strip_prefix("v_cmp_").or(name.strip_prefix("v_cmpx_")) {
  7035. let r = if v.dpp.is_some() {
  7036. Err("a compare with DPP")
  7037. } else {
  7038. self.compare(inst, rest)
  7039. };
  7040. if let Err(why) = r {
  7041. for &(_, w) in &inst.writes {
  7042. self.lane_fail.insert(w, why);
  7043. }
  7044. }
  7045. return r;
  7046. }
  7047. let mut guard = self.guard(b, i)?;
  7048. if let Some(d) = v.dpp {
  7049. let (x, enable) = self.dpp(inst, d)?;
  7050. guard = match (guard, enable) {
  7051. (Some(g), Some(e)) => Some(self.s.m.bin(self.cur, Bin::And, g, e)),
  7052. (g, e) => g.or(e),
  7053. };
  7054. self.src0 = Some(x);
  7055. }
  7056. let r = self.valu_op(inst, guard);
  7057. self.src0 = None;
  7058. r
  7059. }
  7060. /// DPP: src0 as read from another lane, and which lanes write their
  7061. /// result (none: all).
  7062. fn dpp(&mut self, inst: &Inst, dpp: Dpp) -> Result<(V, Option<V>), Why> {
  7063. let Fields::Valu(v) = &inst.fields else {
  7064. unreachable!()
  7065. };
  7066. let Some(&Operand::Vector { reg, .. }) = v.src.first() else {
  7067. return Err("a DPP operand");
  7068. };
  7069. let x = self.i32_of(inst.read(Reg::V(reg)).ok_or("a DPP operand")?)?;
  7070. // Quad permutations and DPP8 stay in groups the pixel layout shares.
  7071. let quad = matches!(dpp, Dpp::Row { ctrl: 0..=0xFF, .. });
  7072. let mesh_quad = self.s.mesh.is_some() && quad;
  7073. if !mesh_quad {
  7074. self.cross_lane(quad)?;
  7075. }
  7076. let c = self.cur;
  7077. let lane = self.lane_index();
  7078. let k = |l: &mut Self, n: u32| l.s.m.i32(n);
  7079. let (sixteen_mask, low) = (k(self, !15), k(self, 15));
  7080. let row = self.s.m.bin(c, Bin::And, lane, sixteen_mask);
  7081. let pos = self.s.m.bin(c, Bin::And, lane, low);
  7082. // Source lane, and whether it lies in the row.
  7083. let (src, inside, masks, zero) = match dpp {
  7084. Dpp::Lanes { sel, .. } => {
  7085. let (seven, not7, three) = (k(self, 7), k(self, !7), k(self, 3));
  7086. let p = self.s.m.bin(c, Bin::And, lane, seven);
  7087. let sh = self.s.m.bin(c, Bin::Mul, p, three);
  7088. let sel = k(self, sel);
  7089. let pick = self.s.m.bin(c, Bin::LShr, sel, sh);
  7090. let pick = self.s.m.bin(c, Bin::And, pick, seven);
  7091. let base = self.s.m.bin(c, Bin::And, lane, not7);
  7092. (self.s.m.bin(c, Bin::Or, base, pick), None, None, false)
  7093. }
  7094. Dpp::Row {
  7095. ctrl,
  7096. row_mask,
  7097. bank_mask,
  7098. bound_ctrl,
  7099. ..
  7100. } => {
  7101. let n = u32::from(ctrl & 15);
  7102. let (src, inside) = match ctrl {
  7103. 0..=0xFF => {
  7104. let (three, one, not3) = (k(self, 3), k(self, 1), k(self, !3));
  7105. let p = self.s.m.bin(c, Bin::And, lane, three);
  7106. let sh = self.s.m.bin(c, Bin::Shl, p, one);
  7107. let perm = k(self, u32::from(ctrl));
  7108. let pick = self.s.m.bin(c, Bin::LShr, perm, sh);
  7109. let pick = self.s.m.bin(c, Bin::And, pick, three);
  7110. let base = self.s.m.bin(c, Bin::And, lane, not3);
  7111. (self.s.m.bin(c, Bin::Or, base, pick), None)
  7112. }
  7113. 0x101..=0x10F | 0x111..=0x11F => {
  7114. let nn = k(self, n);
  7115. let left = ctrl < 0x110;
  7116. let (op, p) = if left {
  7117. (Bin::Add, pred::IULT)
  7118. } else {
  7119. (Bin::Sub, pred::IUGE)
  7120. };
  7121. let s = self.s.m.bin(c, op, lane, nn);
  7122. // Left: pos + n < 16; right: pos >= n.
  7123. let bound = if left { k(self, 16 - n) } else { nn };
  7124. (s, Some(self.s.m.cmp(c, p, pos, bound)))
  7125. }
  7126. 0x121..=0x12F => {
  7127. let nn = k(self, n);
  7128. let t = self.s.m.bin(c, Bin::Sub, pos, nn);
  7129. let t = self.s.m.bin(c, Bin::And, t, low);
  7130. (self.s.m.bin(c, Bin::Or, row, t), None)
  7131. }
  7132. 0x140 | 0x141 => {
  7133. let m = k(self, if ctrl == 0x140 { 15 } else { 7 });
  7134. let t = self.s.m.bin(c, Bin::Xor, lane, m);
  7135. (t, None)
  7136. }
  7137. 0x150..=0x15F => {
  7138. let nn = k(self, n);
  7139. (self.s.m.bin(c, Bin::Or, row, nn), None)
  7140. }
  7141. 0x160..=0x16F => {
  7142. let nn = k(self, n);
  7143. (self.s.m.bin(c, Bin::Xor, lane, nn), None)
  7144. }
  7145. _ => return Err("a DPP lane pattern"),
  7146. };
  7147. let masks = (row_mask != 0xF || bank_mask != 0xF).then_some((row_mask, bank_mask));
  7148. (src, inside, masks, bound_ctrl)
  7149. }
  7150. };
  7151. let mut r = if mesh_quad {
  7152. self.quad_pick(x, src)
  7153. } else if let Dpp::Row { ctrl, .. } = dpp
  7154. && self.helpers_read(quad)
  7155. {
  7156. self.quad_read(x, [0, 1, 2, 3].map(|i| (ctrl >> (2 * i) & 3) as u8))
  7157. } else {
  7158. self.read_lane(x, src)
  7159. };
  7160. let mut enable = None;
  7161. if let Some(inside) = inside {
  7162. if zero {
  7163. let z = k(self, 0);
  7164. r = self.s.m.select(c, inside, r, z);
  7165. } else {
  7166. enable = Some(inside);
  7167. }
  7168. }
  7169. if let Some((rows, banks)) = masks {
  7170. // Row (16 lanes) and bank (4 lanes of a row) write masks.
  7171. let (four, two, three) = (k(self, 4), k(self, 2), k(self, 3));
  7172. let ri = self.s.m.bin(c, Bin::LShr, lane, four);
  7173. let ri = self.s.m.bin(c, Bin::And, ri, three);
  7174. let bi = self.s.m.bin(c, Bin::LShr, lane, two);
  7175. let bi = self.s.m.bin(c, Bin::And, bi, three);
  7176. let (rm, bm) = (k(self, u32::from(rows)), k(self, u32::from(banks)));
  7177. let rb = self.s.m.bin(c, Bin::LShr, rm, ri);
  7178. let bb = self.s.m.bin(c, Bin::LShr, bm, bi);
  7179. let both = self.s.m.bin(c, Bin::And, rb, bb);
  7180. let (one, z) = (k(self, 1), k(self, 0));
  7181. let both = self.s.m.bin(c, Bin::And, both, one);
  7182. let on = self.s.m.cmp(c, pred::NE, both, z);
  7183. enable = Some(match enable {
  7184. Some(e) => self.s.m.bin(c, Bin::And, e, on),
  7185. None => on,
  7186. });
  7187. }
  7188. Ok((r, enable))
  7189. }
  7190. fn valu_op(&mut self, inst: &Inst, guard: Option<V>) -> Result<(), Why> {
  7191. let Fields::Valu(v) = &inst.fields else {
  7192. unreachable!()
  7193. };
  7194. let name = inst.name();
  7195. let c = self.cur;
  7196. let f = |l: &mut Self, k| l.fsrc(inst, k);
  7197. let s = |l: &mut Self, k| l.src(inst, k);
  7198. let float = |l: &mut Self, r: V| l.write_f(inst, r, guard);
  7199. let int = |l: &mut Self, r: V| l.write_i(inst, r, guard);
  7200. if let Some(r) = self.valu16(inst, name, guard) {
  7201. return r;
  7202. }
  7203. if let Some(op) = name.strip_prefix("v_pk_") {
  7204. return self.packed16(inst, op, guard);
  7205. }
  7206. match name {
  7207. "v_mad_u64_u32" => {
  7208. // a * b + c, c and the result 64 bits wide; the carry out
  7209. // of the sum is this lane's bit of the mask it names.
  7210. let (a, b) = (s(self, 0)?, s(self, 1)?);
  7211. let x = self.src64(inst, 2)?;
  7212. let i64t = self.s.m.int(64);
  7213. self.s.flags |= flags::INT64;
  7214. let a = self.s.m.cast(c, Cast::ZExt, a, i64t);
  7215. let b = self.s.m.cast(c, Cast::ZExt, b, i64t);
  7216. let product = self.s.m.bin(c, Bin::Mul, a, b);
  7217. let r = self.s.m.bin(c, Bin::Add, product, x);
  7218. let carry = self.s.m.cmp(c, pred::IULT, r, x);
  7219. let Some(Operand::Vector { reg, .. }) = v.dst else {
  7220. return Err("a 64-bit result");
  7221. };
  7222. let (lo, hi) = self.split64(r);
  7223. self.write(inst, Reg::V(reg), lo, guard);
  7224. self.write(inst, Reg::V(reg + 1), hi, guard);
  7225. if let Some(Operand::Scalar { code, .. }) = v.carry
  7226. && let Some(w) = inst.write(Reg::S(code))
  7227. {
  7228. self.lane_bits.insert(w, carry);
  7229. }
  7230. for &(_, w) in &inst.writes {
  7231. self.vals
  7232. .entry(w)
  7233. .or_insert(Val::Missing("a lane mask read as data"));
  7234. }
  7235. Ok(())
  7236. }
  7237. "v_lshlrev_b64" | "v_lshrrev_b64" | "v_ashrrev_i64" => {
  7238. let n = s(self, 0)?;
  7239. let x = self.src64(inst, 1)?;
  7240. let i64t = self.s.m.int(64);
  7241. let k63 = self.s.m.i32(63);
  7242. let n = self.s.m.bin(c, Bin::And, n, k63);
  7243. let n = self.s.m.cast(c, Cast::ZExt, n, i64t);
  7244. let op = match name {
  7245. "v_lshlrev_b64" => Bin::Shl,
  7246. "v_lshrrev_b64" => Bin::LShr,
  7247. _ => Bin::AShr,
  7248. };
  7249. let r = self.s.m.bin(c, op, x, n);
  7250. let Some(Operand::Vector { reg, .. }) = v.dst else {
  7251. return Err("a 64-bit result");
  7252. };
  7253. let (lo, hi) = self.split64(r);
  7254. self.write(inst, Reg::V(reg), lo, guard);
  7255. self.write(inst, Reg::V(reg + 1), hi, guard);
  7256. Ok(())
  7257. }
  7258. "v_cubeid_f32" | "v_cubesc_f32" | "v_cubetc_f32" | "v_cubema_f32" => {
  7259. // Cube-map face coordinates (AMD's ISA): the major axis is z
  7260. // when |z| >= |x| and |z| >= |y|, else y when |y| >= |x|,
  7261. // else x.
  7262. let (x, y, z) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  7263. let (ax, ay, az) = (self.unary(6, x), self.unary(6, y), self.unary(6, z));
  7264. let zx = self.s.m.cmp(c, pred::OGE, az, ax);
  7265. let zy = self.s.m.cmp(c, pred::OGE, az, ay);
  7266. let zmaj = self.s.m.bin(c, Bin::And, zx, zy);
  7267. let ymaj = self.s.m.cmp(c, pred::OGE, ay, ax);
  7268. let zero = self.s.m.f32(0);
  7269. let neg = |l: &mut Self, v: V| l.s.m.cmp(c, pred::OLT, v, zero);
  7270. let minus = |l: &mut Self, v: V| {
  7271. let z = l.s.m.f32(0x8000_0000);
  7272. l.s.m.bin(c, Bin::Sub, z, v)
  7273. };
  7274. let pick = |l: &mut Self, zv: V, yv: V, xv: V| {
  7275. let t = l.s.m.select(c, ymaj, yv, xv);
  7276. l.s.m.select(c, zmaj, zv, t)
  7277. };
  7278. let r = match name {
  7279. "v_cubeid_f32" => {
  7280. let k = |l: &mut Self, v: f32| l.s.m.f32(v.to_bits());
  7281. let (nz, ny, nx) = (neg(self, z), neg(self, y), neg(self, x));
  7282. let (f5, f4, f3, f2, f1, f0) = (
  7283. k(self, 5.0),
  7284. k(self, 4.0),
  7285. k(self, 3.0),
  7286. k(self, 2.0),
  7287. k(self, 1.0),
  7288. k(self, 0.0),
  7289. );
  7290. let zf = self.s.m.select(c, nz, f5, f4);
  7291. let yf = self.s.m.select(c, ny, f3, f2);
  7292. let xf = self.s.m.select(c, nx, f1, f0);
  7293. pick(self, zf, yf, xf)
  7294. }
  7295. "v_cubesc_f32" => {
  7296. let (nz, nx) = (neg(self, z), neg(self, x));
  7297. let (mx, mz) = (minus(self, x), minus(self, z));
  7298. let zf = self.s.m.select(c, nz, mx, x);
  7299. let xf = self.s.m.select(c, nx, z, mz);
  7300. pick(self, zf, x, xf)
  7301. }
  7302. "v_cubetc_f32" => {
  7303. let ny = neg(self, y);
  7304. let (my, mz) = (minus(self, y), minus(self, z));
  7305. let yf = self.s.m.select(c, ny, mz, z);
  7306. pick(self, my, yf, my)
  7307. }
  7308. _ => {
  7309. let t = pick(self, z, y, x);
  7310. let two = self.s.m.f32(2.0f32.to_bits());
  7311. self.s.m.bin(c, Bin::Mul, t, two)
  7312. }
  7313. };
  7314. float(self, r)
  7315. }
  7316. "v_movrels_b32" | "v_movreld_b32" | "v_movrelsd_b32" => {
  7317. // M0 indexes the source (movrels), the destination (movreld)
  7318. // or both, from the encoded register up to the program's
  7319. // VGPR count (the registers the instruction reads or writes).
  7320. let m0 = self.i32_of(inst.read(Reg::S(crate::ir::M0)).ok_or("M0")?)?;
  7321. let (
  7322. Some(&Operand::Vector { reg: sreg, .. }),
  7323. Some(Operand::Vector { reg: dreg, .. }),
  7324. ) = (v.src.first(), v.dst)
  7325. else {
  7326. return Err("an M0-relative move");
  7327. };
  7328. let indexed_src = name != "v_movreld_b32";
  7329. let value = if indexed_src {
  7330. let mut r = self.s.m.i32(0);
  7331. for k in 0..=255u8.saturating_sub(sreg) {
  7332. let Some(x) = inst.read(Reg::V(sreg + k)) else {
  7333. break;
  7334. };
  7335. let x = self.i32_of(x)?;
  7336. let kk = self.s.m.i32(u32::from(k));
  7337. let is = self.s.m.cmp(c, pred::EQ, m0, kk);
  7338. r = self.s.m.select(c, is, x, r);
  7339. }
  7340. r
  7341. } else {
  7342. s(self, 0)?
  7343. };
  7344. if name == "v_movrels_b32" {
  7345. return int(self, value);
  7346. }
  7347. for k in 0..=255u8.saturating_sub(dreg) {
  7348. let Some(_) = inst.write(Reg::V(dreg + k)) else {
  7349. break;
  7350. };
  7351. let old = match inst.read(Reg::V(dreg + k)) {
  7352. Some(o) => self.i32_of(o)?,
  7353. None => self.s.m.i32(0),
  7354. };
  7355. let kk = self.s.m.i32(u32::from(k));
  7356. let is = self.s.m.cmp(c, pred::EQ, m0, kk);
  7357. let x = self.s.m.select(c, is, value, old);
  7358. self.write_placed(inst, Reg::V(dreg + k), x, guard);
  7359. }
  7360. Ok(())
  7361. }
  7362. "v_swap_b32" => {
  7363. let (
  7364. Some(&Operand::Vector { reg: sreg, .. }),
  7365. Some(Operand::Vector { reg: dreg, .. }),
  7366. ) = (v.src.first(), v.dst)
  7367. else {
  7368. return Err("v_swap_b32");
  7369. };
  7370. let a = self.i32_of(inst.read(Reg::V(dreg)).ok_or("v_swap_b32")?)?;
  7371. let b = self.i32_of(inst.read(Reg::V(sreg)).ok_or("v_swap_b32")?)?;
  7372. self.write_placed(inst, Reg::V(dreg), b, guard);
  7373. if dreg != sreg {
  7374. self.write_placed(inst, Reg::V(sreg), a, guard);
  7375. }
  7376. Ok(())
  7377. }
  7378. "v_ffbh_u32" | "v_ffbh_i32" => {
  7379. // Counted from the top bit, -1 when none (DXIL's too).
  7380. let a = s(self, 0)?;
  7381. let op = if name == "v_ffbh_u32" { 33 } else { 34 };
  7382. let r = self
  7383. .s
  7384. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]);
  7385. int(self, r)
  7386. }
  7387. "v_dot4c_i32_i8" => {
  7388. // D += the dot product of four signed bytes, wrapping: DXIL's
  7389. // Dot4AddI8Packed.
  7390. let (a, bb) = (s(self, 0)?, s(self, 1)?);
  7391. let Some(Operand::Vector { reg, .. }) = v.dst else {
  7392. return Err("an accumulator");
  7393. };
  7394. let acc = self.i32_of(inst.read(Reg::V(reg)).ok_or("an accumulator")?)?;
  7395. let i32_ty = self.s.t.i32;
  7396. let r = self.s.op(
  7397. c,
  7398. "dot4AddPacked.i32",
  7399. Attr::ReadNone,
  7400. i32_ty,
  7401. 163,
  7402. &[acc, a, bb],
  7403. );
  7404. int(self, r)
  7405. }
  7406. "v_dot4_i32_i8" => {
  7407. // VOP3P: op_sel picks the half each multiplicand's low half
  7408. // reads, op_sel_hi its high half's; the accumulator is read
  7409. // whole (as AMD's compilers fold constants into it).
  7410. if v.clamp || v.neg_hi != 0 {
  7411. return Err("a saturating or negated dot product");
  7412. }
  7413. let mut xs = Vec::new();
  7414. for k in 0..2 {
  7415. let x = s(self, k)?;
  7416. let (lo, hi) = (v.opsel >> k & 1 != 0, v.opsel_hi >> k & 1 != 0);
  7417. if (lo, hi) == (false, true) {
  7418. xs.push(x);
  7419. continue;
  7420. }
  7421. let (k16, low) = (self.s.m.i32(16), self.s.m.i32(0xFFFF));
  7422. let top = self.s.m.bin(c, Bin::LShr, x, k16);
  7423. let bottom = self.s.m.bin(c, Bin::And, x, low);
  7424. let hi = self
  7425. .s
  7426. .m
  7427. .bin(c, Bin::Shl, if hi { top } else { bottom }, k16);
  7428. xs.push(self.s.m.bin(c, Bin::Or, if lo { top } else { bottom }, hi));
  7429. }
  7430. let acc = s(self, 2)?;
  7431. let i32_ty = self.s.t.i32;
  7432. let r = self.s.op(
  7433. c,
  7434. "dot4AddPacked.i32",
  7435. Attr::ReadNone,
  7436. i32_ty,
  7437. 163,
  7438. &[acc, xs[0], xs[1]],
  7439. );
  7440. int(self, r)
  7441. }
  7442. "v_mov_b32" => {
  7443. if v.abs != 0 || v.neg != 0 || v.clamp || v.omod != 0 {
  7444. let a = f(self, 0)?;
  7445. return float(self, a);
  7446. }
  7447. let a = s(self, 0)?;
  7448. int(self, a)
  7449. }
  7450. "v_add_f32" | "v_sub_f32" | "v_subrev_f32" | "v_mul_f32" | "v_mul_legacy_f32"
  7451. | "v_max_f32" | "v_min_f32" => {
  7452. let (a, bb) = (f(self, 0)?, f(self, 1)?);
  7453. let r = match name {
  7454. "v_add_f32" => self.s.m.bin(c, Bin::Add, a, bb),
  7455. "v_sub_f32" => self.s.m.bin(c, Bin::Sub, a, bb),
  7456. "v_subrev_f32" => self.s.m.bin(c, Bin::Sub, bb, a),
  7457. "v_mul_f32" => self.s.m.bin(c, Bin::Mul, a, bb),
  7458. "v_mul_legacy_f32" => self.legacy_mul(a, bb),
  7459. "v_max_f32" => self.max_min(true, a, bb),
  7460. _ => self.max_min(false, a, bb),
  7461. };
  7462. float(self, r)
  7463. }
  7464. "v_fma_f32" | "v_fmaak_f32" | "v_fmamk_f32" => {
  7465. // shortcut: DXIL has no fused f32 multiply-add; FMad lets the driver fuse.
  7466. let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  7467. let r = self.fmad(a, bb, cc);
  7468. float(self, r)
  7469. }
  7470. "v_div_scale_f32" => {
  7471. // RDNA2 ISA: src0 = value to scale, src1 = denominator, src2 = numerator.
  7472. let (a, den, num) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  7473. let (ai, ni, di) = (self.as_int(a), self.as_int(num), self.as_int(den));
  7474. let (k23, k255, kabs) = (
  7475. self.s.m.i32(23),
  7476. self.s.m.i32(0xFF),
  7477. self.s.m.i32(0x7FFF_FFFF),
  7478. );
  7479. let (zero, k23_exp, k232_exp, k96) = (
  7480. self.s.m.i32(0),
  7481. self.s.m.i32(23),
  7482. self.s.m.i32(232),
  7483. self.s.m.i32(96),
  7484. );
  7485. let exp_of = |l: &mut Self, x: V| {
  7486. let s = l.s.m.bin(c, Bin::LShr, x, k23);
  7487. l.s.m.bin(c, Bin::And, s, k255)
  7488. };
  7489. let (e1, e2) = (exp_of(self, ni), exp_of(self, di));
  7490. let n_abs = self.s.m.bin(c, Bin::And, ni, kabs);
  7491. let d_abs = self.s.m.bin(c, Bin::And, di, kabs);
  7492. let z1 = self.s.m.cmp(c, pred::EQ, n_abs, zero);
  7493. let z2 = self.s.m.cmp(c, pred::EQ, d_abs, zero);
  7494. let any_zero = self.s.m.bin(c, Bin::Or, z1, z2);
  7495. let special = {
  7496. let s1 = self.s.m.cmp(c, pred::EQ, e1, k255);
  7497. let s2 = self.s.m.cmp(c, pred::EQ, e2, k255);
  7498. let a12 = self.s.m.bin(c, Bin::Or, s1, s2);
  7499. self.s.m.bin(c, Bin::Or, a12, any_zero)
  7500. };
  7501. let is_den = self.s.m.cmp(c, pred::EQ, ai, di);
  7502. let diff = self.s.m.bin(c, Bin::Sub, e2, e1);
  7503. let den_tiny = self.s.m.cmp(c, pred::IULE, e2, k23_exp);
  7504. let den_huge = self.s.m.cmp(c, pred::IUGE, e2, k232_exp);
  7505. let num_tiny_exp = self.s.m.cmp(c, pred::IULE, e1, k23_exp);
  7506. let num_huge = self.s.m.cmp(c, pred::IUGE, e1, k232_exp);
  7507. let num_gap = self.s.m.cmp(c, pred::SGE, diff, k96);
  7508. let not_den_huge = {
  7509. let t = self.s.m.bool(true);
  7510. self.s.m.bin(c, Bin::Xor, den_huge, t)
  7511. };
  7512. let num_gap = self.s.m.bin(c, Bin::And, num_gap, not_den_huge);
  7513. let num_tiny = self.s.m.bin(c, Bin::Or, num_tiny_exp, num_gap);
  7514. let up_raw = self.s.m.select(c, is_den, den_tiny, num_tiny);
  7515. let dn_raw = self.s.m.select(c, is_den, den_huge, num_huge);
  7516. let not_special = {
  7517. let t = self.s.m.bool(true);
  7518. self.s.m.bin(c, Bin::Xor, special, t)
  7519. };
  7520. let up = self.s.m.bin(c, Bin::And, up_raw, not_special);
  7521. let dn = self.s.m.bin(c, Bin::And, dn_raw, not_special);
  7522. let uncancelled = {
  7523. let x_tiny = self.s.m.bin(c, Bin::Xor, den_tiny, num_tiny);
  7524. let x_huge = self.s.m.bin(c, Bin::Xor, den_huge, num_huge);
  7525. self.s.m.bin(c, Bin::Or, x_tiny, x_huge)
  7526. };
  7527. let flag_raw = self.s.m.select(c, is_den, uncancelled, up_raw);
  7528. let flag = self.s.m.bin(c, Bin::And, flag_raw, not_special);
  7529. let k_up = self.s.m.f32(0x5F80_0000);
  7530. let k_dn = self.s.m.f32(0x1F80_0000);
  7531. let a_up = self.s.m.bin(c, Bin::Mul, a, k_up);
  7532. let a_dn = self.s.m.bin(c, Bin::Mul, a, k_dn);
  7533. let r = self.s.m.select(c, dn, a_dn, a);
  7534. let r = self.s.m.select(c, up, a_up, r);
  7535. let qnan = self.s.m.f32(0x7FC0_0000);
  7536. let r = self.s.m.select(c, any_zero, qnan, r);
  7537. float(self, r)?;
  7538. if let Some(Operand::Scalar { code, .. }) = v.carry
  7539. && let Some(w) = inst.write(Reg::S(code))
  7540. {
  7541. self.lane_bits.insert(w, flag);
  7542. }
  7543. for &(_, w) in &inst.writes {
  7544. self.vals
  7545. .entry(w)
  7546. .or_insert(Val::Missing("a lane mask read as data"));
  7547. }
  7548. Ok(())
  7549. }
  7550. "v_div_fmas_f32" => {
  7551. let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  7552. let m = inst
  7553. .read(Reg::S(crate::ir::VCC))
  7554. .and_then(|v| self.x.st.masks.get(&v).copied())
  7555. .ok_or("v_div_fmas_f32 without VCC")?;
  7556. let vcc = self.boolean(m, c)?;
  7557. let tmp = self.fmad(a, bb, cc);
  7558. let ci = self.as_int(cc);
  7559. let (k23, k255, k128) = (self.s.m.i32(23), self.s.m.i32(0xFF), self.s.m.i32(128));
  7560. let sh = self.s.m.bin(c, Bin::LShr, ci, k23);
  7561. let exp = self.s.m.bin(c, Bin::And, sh, k255);
  7562. let exp_ge = self.s.m.cmp(c, pred::IUGE, exp, k128);
  7563. let (k_up, k_dn) = (self.s.m.f32(0x5F80_0000), self.s.m.f32(0x1F80_0000));
  7564. let scale = self.s.m.select(c, exp_ge, k_up, k_dn);
  7565. let scaled = self.s.m.bin(c, Bin::Mul, tmp, scale);
  7566. let r = self.s.m.select(c, vcc, scaled, tmp);
  7567. float(self, r)
  7568. }
  7569. "v_div_fixup_f32" => {
  7570. let (q, den, num) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  7571. let (qi, di, ni) = (self.as_int(q), self.as_int(den), self.as_int(num));
  7572. let (ksign, kabs, kinf) = (
  7573. self.s.m.i32(0x8000_0000),
  7574. self.s.m.i32(0x7FFF_FFFF),
  7575. self.s.m.i32(0x7F80_0000),
  7576. );
  7577. let (kqnan_bit, kneg_qnan, zero) = (
  7578. self.s.m.i32(0x0040_0000),
  7579. self.s.m.i32(0xFFC0_0000),
  7580. self.s.m.i32(0),
  7581. );
  7582. let sign = {
  7583. let x = self.s.m.bin(c, Bin::Xor, ni, di);
  7584. self.s.m.bin(c, Bin::And, x, ksign)
  7585. };
  7586. let q_abs = self.s.m.bin(c, Bin::And, qi, kabs);
  7587. let d_abs = self.s.m.bin(c, Bin::And, di, kabs);
  7588. let n_abs = self.s.m.bin(c, Bin::And, ni, kabs);
  7589. let q_nan = self.s.m.cmp(c, pred::IUGT, q_abs, kinf);
  7590. let d_nan = self.s.m.cmp(c, pred::IUGT, d_abs, kinf);
  7591. let n_nan = self.s.m.cmp(c, pred::IUGT, n_abs, kinf);
  7592. let d_inf = self.s.m.cmp(c, pred::EQ, d_abs, kinf);
  7593. let n_inf = self.s.m.cmp(c, pred::EQ, n_abs, kinf);
  7594. let d_zero = self.s.m.cmp(c, pred::EQ, d_abs, zero);
  7595. let n_zero = self.s.m.cmp(c, pred::EQ, n_abs, zero);
  7596. let both_inf = self.s.m.bin(c, Bin::And, n_inf, d_inf);
  7597. let both_zero = self.s.m.bin(c, Bin::And, n_zero, d_zero);
  7598. let invalid = self.s.m.bin(c, Bin::Or, both_inf, both_zero);
  7599. let make_inf = {
  7600. let t = self.s.m.bin(c, Bin::Or, n_inf, d_zero);
  7601. self.s.m.bin(c, Bin::Or, t, q_nan)
  7602. };
  7603. let make_zero = self.s.m.bin(c, Bin::Or, d_inf, n_zero);
  7604. let signed_q = self.s.m.bin(c, Bin::Or, sign, q_abs);
  7605. let signed_inf = self.s.m.bin(c, Bin::Or, sign, kinf);
  7606. let n_qnan = self.s.m.bin(c, Bin::Or, ni, kqnan_bit);
  7607. let d_qnan = self.s.m.bin(c, Bin::Or, di, kqnan_bit);
  7608. let r = self.s.m.select(c, make_zero, sign, signed_q);
  7609. let r = self.s.m.select(c, make_inf, signed_inf, r);
  7610. let r = self.s.m.select(c, invalid, kneg_qnan, r);
  7611. let r = self.s.m.select(c, d_nan, d_qnan, r);
  7612. let r = self.s.m.select(c, n_nan, n_qnan, r);
  7613. let rf = self.as_float(r);
  7614. float(self, rf)
  7615. }
  7616. "v_fmac_f32" | "v_mac_f32" | "v_mac_legacy_f32" => {
  7617. let (a, bb) = (f(self, 0)?, f(self, 1)?);
  7618. let Some(Operand::Vector { reg, .. }) = v.dst else {
  7619. return Err("an accumulator");
  7620. };
  7621. let acc = inst.read(Reg::V(reg)).ok_or("an accumulator")?;
  7622. let acc = match self.floats.get(&acc) {
  7623. Some(&x) => x,
  7624. None => {
  7625. let x = self.i32_of(acc)?;
  7626. self.as_float(x)
  7627. }
  7628. };
  7629. let r = match name {
  7630. "v_fmac_f32" => self.fmad(a, bb, acc),
  7631. "v_mac_f32" => {
  7632. let m = self.s.m.bin(c, Bin::Mul, a, bb);
  7633. self.s.m.bin(c, Bin::Add, m, acc)
  7634. }
  7635. _ => {
  7636. let m = self.legacy_mul(a, bb);
  7637. self.s.m.bin(c, Bin::Add, m, acc)
  7638. }
  7639. };
  7640. float(self, r)
  7641. }
  7642. "v_mad_f32" | "v_madak_f32" | "v_madmk_f32" | "v_mad_legacy_f32" => {
  7643. let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  7644. let m = if name == "v_mad_legacy_f32" {
  7645. self.legacy_mul(a, bb)
  7646. } else {
  7647. self.s.m.bin(c, Bin::Mul, a, bb)
  7648. };
  7649. let r = self.s.m.bin(c, Bin::Add, m, cc);
  7650. float(self, r)
  7651. }
  7652. "v_max3_f32" | "v_min3_f32" | "v_med3_f32" => {
  7653. let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  7654. let r = match name {
  7655. "v_max3_f32" => {
  7656. let t = self.max_min(true, a, bb);
  7657. self.max_min(true, t, cc)
  7658. }
  7659. "v_min3_f32" => {
  7660. let t = self.max_min(false, a, bb);
  7661. self.max_min(false, t, cc)
  7662. }
  7663. _ => self.med3(a, bb, cc),
  7664. };
  7665. float(self, r)
  7666. }
  7667. "v_rcp_f32" | "v_rcp_iflag_f32" => {
  7668. // shortcut: the hardware reciprocal is approximate (1 ULP); this divides.
  7669. let a = f(self, 0)?;
  7670. let one = self.s.m.f32(1.0f32.to_bits());
  7671. let r = self.s.m.bin(c, Bin::SDiv, one, a);
  7672. float(self, r)
  7673. }
  7674. "v_rsq_f32" | "v_sqrt_f32" | "v_log_f32" | "v_exp_f32" | "v_fract_f32"
  7675. | "v_trunc_f32" | "v_floor_f32" | "v_ceil_f32" | "v_rndne_f32" | "v_sin_f32"
  7676. | "v_cos_f32" => {
  7677. let a = f(self, 0)?;
  7678. let op = match name {
  7679. "v_rsq_f32" => 25,
  7680. "v_sqrt_f32" => 24,
  7681. "v_log_f32" => 23,
  7682. "v_exp_f32" => 21,
  7683. "v_fract_f32" => 22,
  7684. "v_trunc_f32" => 29,
  7685. "v_floor_f32" => 27,
  7686. "v_ceil_f32" => 28,
  7687. "v_rndne_f32" => 26,
  7688. "v_sin_f32" => 13,
  7689. _ => 12,
  7690. };
  7691. let r = match op {
  7692. 12 | 13 => self.trig_turns(a, op == 12),
  7693. 22 => self.fract(a, 1.0, f32::from_bits(0x3F7F_FFFF)),
  7694. _ => self.unary(op, a),
  7695. };
  7696. float(self, r)
  7697. }
  7698. "v_cvt_i32_f32" | "v_cvt_u32_f32" | "v_cvt_flr_i32_f32" | "v_cvt_rpi_i32_f32" => {
  7699. let mut a = f(self, 0)?;
  7700. if name == "v_cvt_rpi_i32_f32" {
  7701. let h = self.s.m.f32(0.5f32.to_bits());
  7702. a = self.s.m.bin(c, Bin::Add, a, h);
  7703. }
  7704. if name != "v_cvt_i32_f32" && name != "v_cvt_u32_f32" {
  7705. a = self.unary(27, a);
  7706. }
  7707. // D3D's conversions saturate and give 0 for NaN, as the
  7708. // hardware does (checked on the RX 6700 XT and WARP).
  7709. let op = if name == "v_cvt_u32_f32" {
  7710. Cast::FpToUi
  7711. } else {
  7712. Cast::FpToSi
  7713. };
  7714. let r = self.s.m.cast(c, op, a, self.s.t.i32);
  7715. int(self, r)
  7716. }
  7717. "v_cvt_f32_f64" => {
  7718. let (lo, hi) = self.f64_pair(inst, 0)?;
  7719. let bits = self.f64_to_f32_bits(lo, hi);
  7720. let r = self.as_float(bits);
  7721. float(self, r)
  7722. }
  7723. "v_cvt_f32_i32" | "v_cvt_f32_u32" | "v_cvt_f32_ubyte0" | "v_cvt_f32_ubyte1"
  7724. | "v_cvt_f32_ubyte2" | "v_cvt_f32_ubyte3" => {
  7725. let mut a = s(self, 0)?;
  7726. if let Some(n) = name.strip_prefix("v_cvt_f32_ubyte") {
  7727. let sh = self.s.m.i32(8 * u32::from(n.as_bytes()[0] - b'0'));
  7728. let ff = self.s.m.i32(0xff);
  7729. a = self.s.m.bin(c, Bin::LShr, a, sh);
  7730. a = self.s.m.bin(c, Bin::And, a, ff);
  7731. }
  7732. let op = if name == "v_cvt_f32_i32" {
  7733. Cast::SiToFp
  7734. } else {
  7735. Cast::UiToFp
  7736. };
  7737. let r = self.s.m.cast(c, op, a, self.s.t.f32);
  7738. float(self, r)
  7739. }
  7740. "v_cvt_off_f32_i4" => {
  7741. // The low nibble as a signed 4-bit integer, over 16.
  7742. let a = s(self, 0)?;
  7743. let k28 = self.s.m.i32(28);
  7744. let a = self.s.m.bin(c, Bin::Shl, a, k28);
  7745. let a = self.s.m.bin(c, Bin::AShr, a, k28);
  7746. let f = self.s.m.cast(c, Cast::SiToFp, a, self.s.t.f32);
  7747. let k = self.s.m.f32(0.0625f32.to_bits());
  7748. let r = self.s.m.bin(c, Bin::Mul, f, k);
  7749. float(self, r)
  7750. }
  7751. "v_fma_mix_f32" | "v_fma_mixlo_f16" | "v_fma_mixhi_f16" => {
  7752. // Each source is f32, or with op_sel_hi the low (op_sel: high)
  7753. // f16 half; neg_hi is the absolute value here.
  7754. let mut xs = Vec::new();
  7755. for i in 0..3 {
  7756. let op = v.src.get(i).ok_or("a missing operand")?;
  7757. let mut x = if v.opsel_hi >> i & 1 != 0 {
  7758. let x = self.f16_operand(inst, op)?;
  7759. let h = if v.opsel >> i & 1 != 0 {
  7760. let k16 = self.s.m.i32(16);
  7761. self.s.m.bin(c, Bin::LShr, x, k16)
  7762. } else {
  7763. x
  7764. };
  7765. self.s
  7766. .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[h])
  7767. } else {
  7768. let x = self.operand(inst, op)?;
  7769. self.as_float(x)
  7770. };
  7771. if v.neg_hi >> i & 1 != 0 {
  7772. x = self.unary(6, x);
  7773. }
  7774. if v.neg >> i & 1 != 0 {
  7775. let z = self.s.m.f32(0x8000_0000);
  7776. x = self.s.m.bin(c, Bin::Sub, z, x);
  7777. }
  7778. xs.push(x);
  7779. }
  7780. let mut r = self.fmad(xs[0], xs[1], xs[2]);
  7781. if name == "v_fma_mix_f32" {
  7782. return float(self, r);
  7783. }
  7784. if v.clamp {
  7785. r = self.unary(7, r);
  7786. }
  7787. // The f16 result goes to one half; the other half stays.
  7788. let Some(Operand::Vector { reg, .. }) = v.dst else {
  7789. return Err("a mixed-precision result");
  7790. };
  7791. let old = match inst.read(Reg::V(reg)) {
  7792. Some(o) => self.i32_of(o)?,
  7793. None => self.s.m.i32(0),
  7794. };
  7795. let h = self
  7796. .s
  7797. .op(c, "legacyF32ToF16", Attr::ReadNone, self.s.t.i32, 130, &[r]);
  7798. let (keep, h) = if name == "v_fma_mixhi_f16" {
  7799. let k16 = self.s.m.i32(16);
  7800. (0xFFFF, self.s.m.bin(c, Bin::Shl, h, k16))
  7801. } else {
  7802. (0xFFFF_0000, h)
  7803. };
  7804. let keep = self.s.m.i32(keep);
  7805. let old = self.s.m.bin(c, Bin::And, old, keep);
  7806. let x = self.s.m.bin(c, Bin::Or, old, h);
  7807. self.write(inst, Reg::V(reg), x, guard);
  7808. Ok(())
  7809. }
  7810. "v_cvt_pkrtz_f16_f32" => {
  7811. let (a, bb) = (f(self, 0)?, f(self, 1)?);
  7812. let lo = self.f16_toward_zero(a);
  7813. let hi = self.f16_toward_zero(bb);
  7814. let sh = self.s.m.i32(16);
  7815. let hi = self.s.m.bin(c, Bin::Shl, hi, sh);
  7816. let r = self.s.m.bin(c, Bin::Or, lo, hi);
  7817. int(self, r)
  7818. }
  7819. "v_cvt_f16_f32" if v.opsel == 0 => {
  7820. // Rounded to nearest even (the MODE default) into the low half.
  7821. let a = f(self, 0)?;
  7822. let r = self
  7823. .s
  7824. .op(c, "legacyF32ToF16", Attr::ReadNone, self.s.t.i32, 130, &[a]);
  7825. let Some(Operand::Vector { reg, .. }) = v.dst else {
  7826. return Err("a 16-bit result outside a VGPR");
  7827. };
  7828. let r = self.low_half(inst, reg, r);
  7829. int(self, r)
  7830. }
  7831. "v_pack_b32_f16" => {
  7832. // Two f16 sources (op_sel: their high halves; abs and neg on
  7833. // the sign bit) into the low and high half.
  7834. let mut halves = Vec::new();
  7835. for k in 0..2 {
  7836. let op = v.src.get(k).ok_or("a missing operand")?;
  7837. let mut x = self.f16_operand(inst, op)?;
  7838. if v.opsel >> k & 1 != 0 {
  7839. let k16 = self.s.m.i32(16);
  7840. x = self.s.m.bin(c, Bin::LShr, x, k16);
  7841. }
  7842. let mask = if v.abs >> k & 1 != 0 { 0x7FFF } else { 0xFFFF };
  7843. let mask = self.s.m.i32(mask);
  7844. x = self.s.m.bin(c, Bin::And, x, mask);
  7845. if v.neg >> k & 1 != 0 {
  7846. let sign = self.s.m.i32(0x8000);
  7847. x = self.s.m.bin(c, Bin::Xor, x, sign);
  7848. }
  7849. halves.push(x);
  7850. }
  7851. let k16 = self.s.m.i32(16);
  7852. let hi = self.s.m.bin(c, Bin::Shl, halves[1], k16);
  7853. let r = self.s.m.bin(c, Bin::Or, halves[0], hi);
  7854. int(self, r)
  7855. }
  7856. "v_cvt_f32_f16" if v.opsel == 0 => {
  7857. let a = s(self, 0)?;
  7858. let r = self
  7859. .s
  7860. .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[a]);
  7861. float(self, r)
  7862. }
  7863. "v_cndmask_b32" => {
  7864. let mask = match v.src.get(2) {
  7865. Some(&Operand::Scalar { code, .. }) => inst.read(Reg::S(code)),
  7866. _ => None,
  7867. };
  7868. const UNTRACKED: Why = "a select on an untracked mask";
  7869. let cond = match mask.and_then(|m| self.x.st.masks.get(&m).copied()) {
  7870. Some(m) => self.boolean(m, c)?,
  7871. // A mask the code holds as a number (a constant bit
  7872. // pattern: every other lane, every other pair...):
  7873. // this lane's bit of it. Exact where host lanes are
  7874. // the console's.
  7875. None if self.mask_data == MaskData::Console => {
  7876. // Each host wave taken as a wave of its own has no
  7877. // console lane numbers to pick the bits by.
  7878. if self.local {
  7879. return Err("a constant lane mask in a half-wave");
  7880. }
  7881. let m = mask.ok_or(UNTRACKED)?;
  7882. let lo = self.i32_of(m).map_err(|_| UNTRACKED)?;
  7883. // wave64: the register after it holds lanes 32-63.
  7884. let high = match v.src.get(2) {
  7885. Some(&Operand::Scalar { code, .. }) if self.x.native.wave64 => {
  7886. Some(inst.read(Reg::S(code + 1)).ok_or(UNTRACKED)?)
  7887. }
  7888. _ => None,
  7889. };
  7890. let hi = match high {
  7891. Some(h) => Some(self.i32_of(h).map_err(|_| UNTRACKED)?),
  7892. None => None,
  7893. };
  7894. self.cross_lane(false)?;
  7895. self.lane_bit(c, lo, hi)
  7896. }
  7897. None => return Err(UNTRACKED),
  7898. };
  7899. if v.abs != 0 || v.neg != 0 {
  7900. let (a, bb) = (f(self, 0)?, f(self, 1)?);
  7901. let r = self.s.m.select(c, cond, bb, a);
  7902. return float(self, r);
  7903. }
  7904. let (a, bb) = (s(self, 0)?, s(self, 1)?);
  7905. let r = self.s.m.select(c, cond, bb, a);
  7906. int(self, r)
  7907. }
  7908. "v_add_co_u32" | "v_sub_co_u32" | "v_subrev_co_u32" | "v_add_co_ci_u32"
  7909. | "v_sub_co_ci_u32" | "v_subrev_co_ci_u32" => {
  7910. // The carry (borrow) out is a lane mask: this lane's bit.
  7911. let (mut a, mut bb) = (s(self, 0)?, s(self, 1)?);
  7912. if name.contains("subrev") {
  7913. std::mem::swap(&mut a, &mut bb);
  7914. }
  7915. let cin = if name.ends_with("_ci_u32") {
  7916. let m = match v.src.get(2) {
  7917. Some(&Operand::Scalar { code, .. }) => inst.read(Reg::S(code)),
  7918. _ => None,
  7919. };
  7920. let m = m
  7921. .and_then(|m| self.x.st.masks.get(&m).copied())
  7922. .ok_or("a carry-in from an untracked mask")?;
  7923. Some(self.boolean(m, c)?)
  7924. } else {
  7925. None
  7926. };
  7927. let (r, carry) = self.add_sub_carry(c, name.starts_with("v_add"), a, bb, cin);
  7928. int(self, r)?;
  7929. if let Some(Operand::Scalar { code, .. }) = v.carry
  7930. && let Some(w) = inst.write(Reg::S(code))
  7931. {
  7932. self.lane_bits.insert(w, carry);
  7933. }
  7934. for &(_, w) in &inst.writes {
  7935. self.vals
  7936. .entry(w)
  7937. .or_insert(Val::Missing("a lane mask read as data"));
  7938. }
  7939. Ok(())
  7940. }
  7941. "v_permlane16_b32" | "v_permlanex16_b32" => {
  7942. // RDNA2 ISA 12.12: each nibble of {src2, src1} selects a lane
  7943. // in this row of 16, or the other row of the same 32-lane half.
  7944. // OP_SEL[0:1] are fetch-inactive and bound-control, not half selects.
  7945. if v.abs != 0 || v.neg != 0 || v.opsel & !3 != 0 {
  7946. return Err("permlane input modifiers");
  7947. }
  7948. self.cross_lane(false)?;
  7949. let fetch_inactive = v.opsel & 1 != 0;
  7950. if fetch_inactive
  7951. && !all_lane_blocks(self.x.st).is_some_and(|all| all[self.cur_ir])
  7952. {
  7953. // DXIL cannot read the last VGPR value of a host invocation
  7954. // that has left through a lane branch. A guard keeps it here.
  7955. return Err("a permlane fetch from lanes outside the host branch");
  7956. }
  7957. let (x, lo, hi) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  7958. let lane = self.lane_index();
  7959. let (k7, k8, k15, k16, k31, k32, k4, one, zero) = (
  7960. self.s.m.i32(7),
  7961. self.s.m.i32(8),
  7962. self.s.m.i32(15),
  7963. self.s.m.i32(16),
  7964. self.s.m.i32(31),
  7965. self.s.m.i32(32),
  7966. self.s.m.i32(4),
  7967. self.s.m.i32(1),
  7968. self.s.m.i32(0),
  7969. );
  7970. let pos = self.s.m.bin(c, Bin::And, lane, k15);
  7971. let lower = self.s.m.cmp(c, pred::IULT, pos, k8);
  7972. let packed = self.s.m.select(c, lower, lo, hi);
  7973. let shift = self.s.m.bin(c, Bin::And, pos, k7);
  7974. let shift = self.s.m.bin(c, Bin::Mul, shift, k4);
  7975. let pick = self.s.m.bin(c, Bin::LShr, packed, shift);
  7976. let pick = self.s.m.bin(c, Bin::And, pick, k15);
  7977. let not15 = self.s.m.i32(!15);
  7978. let mut row = self.s.m.bin(c, Bin::And, lane, not15);
  7979. if name == "v_permlanex16_b32" {
  7980. row = self.s.m.bin(c, Bin::Xor, row, k16);
  7981. }
  7982. let src = self.s.m.bin(c, Bin::Or, row, pick);
  7983. let r = if fetch_inactive {
  7984. self.read_lane(x, src)
  7985. } else {
  7986. // Ballot the console EXEC guard as well as the host's active
  7987. // invocations. Never shuffle from an inactive host lane.
  7988. let enabled = guard.unwrap_or_else(|| self.s.m.bool(true));
  7989. let i32t = self.s.t.i32;
  7990. let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]);
  7991. let mask = self.s.op(
  7992. c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[enabled],
  7993. );
  7994. let lo = self.s.m.extract(c, mask, 0);
  7995. let hi = self.s.m.extract(c, mask, 1);
  7996. let lower = self.s.m.cmp(c, pred::IULT, src, k32);
  7997. let word = self.s.m.select(c, lower, lo, hi);
  7998. let bit = self.s.m.bin(c, Bin::And, src, k31);
  7999. let bit = self.s.m.bin(c, Bin::LShr, word, bit);
  8000. let bit = self.s.m.bin(c, Bin::And, bit, one);
  8001. let active = self.s.m.cmp(c, pred::NE, bit, zero);
  8002. let safe = self.s.m.select(c, active, src, lane);
  8003. let read = self.read_lane(x, safe);
  8004. let fallback = if v.opsel & 2 != 0 {
  8005. zero
  8006. } else {
  8007. let Some(Operand::Vector { reg, .. }) = v.dst else {
  8008. return Err("a permlane result outside a VGPR");
  8009. };
  8010. self.i32_of(inst.read(Reg::V(reg)).ok_or("a permlane old value")?)?
  8011. };
  8012. self.s.m.select(c, active, read, fallback)
  8013. };
  8014. int(self, r)
  8015. }
  8016. "v_readlane_b32" => {
  8017. let (a, lane) = (s(self, 0)?, s(self, 1)?);
  8018. // A computed lane in a pixel or vertex program is a host lane
  8019. // (from a mask or `v_mbcnt`); a constant one is the console's.
  8020. if self.mask_data == MaskData::Host && !matches!(lane, V::Const(_)) {
  8021. self.s.flags |= flags::WAVE_OPS;
  8022. } else {
  8023. self.cross_lane(false)?;
  8024. }
  8025. if let Some(slot) = self.exchange.as_ref().map(|e| e.0) {
  8026. if self.local && self.local_any {
  8027. // this host wave's lane of that number (lanes 32..63 are 0..31 here)
  8028. let k31 = self.s.m.i32(31);
  8029. let here = self.s.m.bin(self.cur, Bin::And, lane, k31);
  8030. let r = self.read_lane(a, here);
  8031. return int(self, r);
  8032. }
  8033. if self.local {
  8034. return Err("a lane read in a half-wave");
  8035. }
  8036. if self.exchange.as_ref().is_some_and(|e| e.1) {
  8037. // a group of 32 or fewer: the lane is in this host wave
  8038. let r = self.read_lane(a, lane);
  8039. return int(self, r);
  8040. }
  8041. // the lane that holds it may be in the other host wave: it gives it through LDS
  8042. if !self.all_lanes(self.cur_ir) {
  8043. need(self.cur_ir);
  8044. return Err("a lane read where not every lane runs");
  8045. }
  8046. let cl = self.console_lane();
  8047. let is = self.s.m.cmp(self.cur, pred::EQ, cl, lane);
  8048. let k = self.exchange_pair(slot);
  8049. let at = self.begin_guarded(Some(is));
  8050. let lds = self.s.lds();
  8051. let ptr = self.s.m.element(self.cur, lds, k);
  8052. self.s.m.store(self.cur, ptr, a);
  8053. self.end_guarded(at, &[]);
  8054. let c2 = self.cur;
  8055. self.group_sync(c2);
  8056. let ptr = self.s.m.element(c2, lds, k);
  8057. let r = self.s.m.load(c2, ptr);
  8058. self.group_sync(c2);
  8059. return int(self, r);
  8060. }
  8061. let r = self.read_lane(a, lane);
  8062. int(self, r)
  8063. }
  8064. "v_writelane_b32" => {
  8065. // The lane given takes the scalar; the others keep their value.
  8066. let (a, lane) = (s(self, 0)?, s(self, 1)?);
  8067. let Some(Operand::Vector { reg, .. }) = v.dst else {
  8068. return Err("a lane write");
  8069. };
  8070. let old = match inst.read(Reg::V(reg)) {
  8071. Some(o) => self.i32_of(o)?,
  8072. None => self.s.m.i32(0),
  8073. };
  8074. self.cross_lane(false)?;
  8075. if self.local && !self.local_any {
  8076. return Err("a lane write in a half-wave");
  8077. }
  8078. let me = self.console_lane();
  8079. let is = self.s.m.cmp(c, pred::EQ, me, lane);
  8080. let r = self.s.m.select(c, is, a, old);
  8081. int(self, r)
  8082. }
  8083. "v_readfirstlane_b32"
  8084. if inst
  8085. .writes
  8086. .first()
  8087. .is_some_and(|w| self.x.res.waterfall.reads.contains(&w.1)) =>
  8088. {
  8089. // A waterfall loop's read of a descriptor dword: the lane's own.
  8090. let a = s(self, 0)?;
  8091. int(self, a)
  8092. }
  8093. "v_readfirstlane_b32"
  8094. if matches!(v.src.first(), Some(&Operand::Vector { reg, .. })
  8095. if inst.read(Reg::V(reg)).is_some_and(|x| self.own_bits.alike.contains(&x))) =>
  8096. {
  8097. // The bits a loop over a wave OR has still to visit (`own_bits`): every lane of
  8098. // the host wave holds the same, so the first lane's is the lane's own.
  8099. let a = s(self, 0)?;
  8100. int(self, a)
  8101. }
  8102. "v_readfirstlane_b32" => {
  8103. let a = s(self, 0)?;
  8104. let (mine, any) = self.first_lane(a, guard);
  8105. // two host waves that exchange: the console's first lane may be in the other
  8106. // one, unless every lane holds the same value
  8107. let alike = match v.src.first() {
  8108. Some(&Operand::Vector { reg, .. }) => {
  8109. inst.read(Reg::V(reg)).is_some_and(|x| self.uniform.contains(&x))
  8110. }
  8111. _ => true,
  8112. };
  8113. let halves = self.exchange.as_ref().is_some_and(|e| !e.1) && !self.local;
  8114. let r = if halves && !alike {
  8115. if !self.all_lanes(self.cur_ir) {
  8116. // shortcut: `VICTORY_FIRSTLANE_OWN=1` takes the host wave's own
  8117. // first lane, exact when the value is the same in every lane of
  8118. // the console wave (the ray-tracing builder's scans read a sum of
  8119. // scalars this way, inside a loop whose exit is per console wave).
  8120. static OWN: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  8121. if *OWN.get_or_init(|| std::env::var_os("VICTORY_FIRSTLANE_OWN").is_some_and(|v| v == "1")) {
  8122. return int(self, mine);
  8123. }
  8124. need(self.cur_ir);
  8125. return Err("a first-lane read where not every lane runs");
  8126. }
  8127. let c = self.cur;
  8128. if guard.is_none() && super::shader_opt() & super::bitcode::opt::FIRST != 0 {
  8129. // Every lane is in EXEC: the console's first lane is
  8130. // lane 0, which the lower half of every console wave
  8131. // has. No half needs to ask the other whether it has
  8132. // a lane (an exchange of the constant 1: two group
  8133. // barriers), and the lower half's value is the answer.
  8134. let (lo, _) = self.exchange_halves(c, mine);
  8135. lo
  8136. } else {
  8137. let i32t = self.s.t.i32;
  8138. let has = self.s.m.cast(c, Cast::ZExt, any, i32t);
  8139. let (lo_has, hi_has) = self.exchange_halves(c, has);
  8140. let (lo, hi) = self.exchange_halves(c, mine);
  8141. let z = self.s.m.i32(0);
  8142. let in_lo = self.s.m.cmp(c, pred::NE, lo_has, z);
  8143. let in_hi = self.s.m.cmp(c, pred::NE, hi_has, z);
  8144. // neither half has a lane in EXEC: the console reads lane 0
  8145. let hi = self.s.m.select(c, in_hi, hi, lo);
  8146. self.s.m.select(c, in_lo, lo, hi)
  8147. }
  8148. } else {
  8149. mine
  8150. };
  8151. int(self, r)
  8152. }
  8153. _ => {
  8154. let r = self.integer(inst, name)?;
  8155. int(self, r)
  8156. }
  8157. }
  8158. }
  8159. /// A 64-bit source (a register pair; inline constants sign-extend).
  8160. fn src64(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  8161. let Fields::Valu(v) = &inst.fields else {
  8162. unreachable!()
  8163. };
  8164. if v.abs >> k & 1 != 0 || v.neg >> k & 1 != 0 || v.sdwa.is_some() || v.dpp.is_some() {
  8165. return Err("64-bit operand modifiers");
  8166. }
  8167. let c = self.cur;
  8168. let i64t = self.s.m.int(64);
  8169. self.s.flags |= flags::INT64;
  8170. let op = *v.src.get(k).ok_or("a missing operand")?;
  8171. let pair = |l: &mut Self, r: Reg, r1: Reg| -> Result<V, Why> {
  8172. let lo = l.i32_of(inst.read(r).ok_or("an unread operand")?)?;
  8173. let hi = l.i32_of(inst.read(r1).ok_or("an unread operand")?)?;
  8174. Ok(l.join64(lo, hi))
  8175. };
  8176. match op {
  8177. Operand::Vector { reg, .. } => pair(self, Reg::V(reg), Reg::V(reg + 1)),
  8178. Operand::Scalar { code, .. } if code != NULL => {
  8179. pair(self, Reg::S(code), Reg::S(code + 1))
  8180. }
  8181. Operand::Const(k @ 128..=208) => {
  8182. let x = crate::resource::inline(k).ok_or("a special operand")?;
  8183. Ok(self.s.m.int_const(i64t, i64::from(x as i32)))
  8184. }
  8185. // A signed 64-bit operand sign-extends its 32-bit literal, as
  8186. // the hardware does (LLVM's AMDGPU operand rules).
  8187. Operand::Literal(x) if inst.name().ends_with("_i64") => {
  8188. Ok(self.s.m.int_const(i64t, i64::from(x as i32)))
  8189. }
  8190. _ => {
  8191. // Literals (of unsigned and bit operands) and the null
  8192. // register: zero-extended.
  8193. let x = self.operand(inst, &op)?;
  8194. Ok(self.s.m.cast(c, Cast::ZExt, x, i64t))
  8195. }
  8196. }
  8197. }
  8198. /// Reads an IEEE-754 binary64 operand as `(lo, hi)` 32-bit words, applying
  8199. /// `abs` and `neg` input modifiers on operand `k`.
  8200. fn f64_pair(&mut self, inst: &Inst, k: usize) -> Result<(V, V), Why> {
  8201. let Fields::Valu(v) = &inst.fields else {
  8202. unreachable!()
  8203. };
  8204. if v.sdwa.is_some() || v.dpp.is_some() {
  8205. return Err("64-bit operand modifiers");
  8206. }
  8207. let op = *v.src.get(k).ok_or("a missing operand")?;
  8208. let pair = |l: &mut Self, r: Reg, r1: Reg| -> Result<(V, V), Why> {
  8209. let lo = l.i32_of(inst.read(r).ok_or("an unread operand")?)?;
  8210. let hi = l.i32_of(inst.read(r1).ok_or("an unread operand")?)?;
  8211. Ok((lo, hi))
  8212. };
  8213. let (lo, mut hi) = match op {
  8214. Operand::Vector { reg, .. } => pair(self, Reg::V(reg), Reg::V(reg + 1))?,
  8215. Operand::Scalar { code, .. } if code != NULL => {
  8216. pair(self, Reg::S(code), Reg::S(code + 1))?
  8217. }
  8218. Operand::Const(128) => (self.s.m.i32(0), self.s.m.i32(0)),
  8219. Operand::Const(c @ 240..=248) => {
  8220. const INLINE_F64: [f64; 9] = [
  8221. 0.5,
  8222. -0.5,
  8223. 1.0,
  8224. -1.0,
  8225. 2.0,
  8226. -2.0,
  8227. 4.0,
  8228. -4.0,
  8229. 1.0 / std::f64::consts::TAU,
  8230. ];
  8231. let bits = INLINE_F64[(c - 240) as usize].to_bits();
  8232. (self.s.m.i32(bits as u32), self.s.m.i32((bits >> 32) as u32))
  8233. }
  8234. // GFX10 places a 32-bit literal in the high 32 bits of a 64-bit float operand.
  8235. Operand::Literal(x) => (self.s.m.i32(0), self.s.m.i32(x)),
  8236. _ => return Err("a 64-bit float operand"),
  8237. };
  8238. let c = self.cur;
  8239. if v.abs >> k & 1 != 0 {
  8240. let mask = self.s.m.i32(0x7FFF_FFFF);
  8241. hi = self.s.m.bin(c, Bin::And, hi, mask);
  8242. }
  8243. if v.neg >> k & 1 != 0 {
  8244. let sign = self.s.m.i32(0x8000_0000);
  8245. hi = self.s.m.bin(c, Bin::Xor, hi, sign);
  8246. }
  8247. Ok((lo, hi))
  8248. }
  8249. /// Converts IEEE-754 binary64 `(lo, hi)` to binary32 bits with round-to-nearest-even,
  8250. /// without requiring host `DOUBLES` (`f64`) support.
  8251. fn f64_to_f32_bits(&mut self, lo: V, hi: V) -> V {
  8252. let c = self.cur;
  8253. let k0 = self.s.m.i32(0);
  8254. let k1 = self.s.m.i32(1);
  8255. let sign_mask = self.s.m.i32(0x8000_0000);
  8256. let sign = self.s.m.bin(c, Bin::And, hi, sign_mask);
  8257. let k20 = self.s.m.i32(20);
  8258. let k7ff = self.s.m.i32(0x7FF);
  8259. let exp64 = self.s.m.bin(c, Bin::LShr, hi, k20);
  8260. let exp64 = self.s.m.bin(c, Bin::And, exp64, k7ff);
  8261. let frac_mask = self.s.m.i32(0x000F_FFFF);
  8262. let frac_hi = self.s.m.bin(c, Bin::And, hi, frac_mask);
  8263. let frac_any = self.s.m.bin(c, Bin::Or, frac_hi, lo);
  8264. let frac_nz = self.s.m.cmp(c, pred::NE, frac_any, k0);
  8265. let k3 = self.s.m.i32(3);
  8266. let k29 = self.s.m.i32(29);
  8267. let m23_hi = self.s.m.bin(c, Bin::Shl, frac_hi, k3);
  8268. let m23_lo = self.s.m.bin(c, Bin::LShr, lo, k29);
  8269. let m23 = self.s.m.bin(c, Bin::Or, m23_hi, m23_lo);
  8270. let rem_mask = self.s.m.i32(0x1FFF_FFFF);
  8271. let rem = self.s.m.bin(c, Bin::And, lo, rem_mask);
  8272. let half_rem = self.s.m.i32(0x1000_0000);
  8273. let gt_half = self.s.m.cmp(c, pred::IUGT, rem, half_rem);
  8274. let eq_half = self.s.m.cmp(c, pred::EQ, rem, half_rem);
  8275. let m23_odd_bit = self.s.m.bin(c, Bin::And, m23, k1);
  8276. let m23_odd = self.s.m.cmp(c, pred::NE, m23_odd_bit, k0);
  8277. let tie_up = self.s.m.bin(c, Bin::And, eq_half, m23_odd);
  8278. let norm_round = self.s.m.bin(c, Bin::Or, gt_half, tie_up);
  8279. let norm_inc = self.s.m.select(c, norm_round, k1, k0);
  8280. // Normal range: exp64 in [897, 1150] -> exp32 in [1, 254].
  8281. let k896 = self.s.m.i32(896);
  8282. let k23 = self.s.m.i32(23);
  8283. let exp32 = self.s.m.bin(c, Bin::Sub, exp64, k896);
  8284. let exp32_sh = self.s.m.bin(c, Bin::Shl, exp32, k23);
  8285. let norm_body = self.s.m.bin(c, Bin::Add, exp32_sh, m23);
  8286. let norm_body = self.s.m.bin(c, Bin::Add, norm_body, norm_inc);
  8287. let norm_res = self.s.m.bin(c, Bin::Or, sign, norm_body);
  8288. // Subnormal range: exp64 in [874, 896] -> shift in [1, 23].
  8289. let k897 = self.s.m.i32(897);
  8290. let k32 = self.s.m.i32(32);
  8291. let k31 = self.s.m.i32(31);
  8292. let imp = self.s.m.i32(0x0080_0000);
  8293. let sig24 = self.s.m.bin(c, Bin::Or, imp, m23);
  8294. let raw_shift = self.s.m.bin(c, Bin::Sub, k897, exp64);
  8295. // Clamp shift to [1, 23] so shifts never produce poison outside the subnormal branch.
  8296. let lt1 = self.s.m.cmp(c, pred::IULT, raw_shift, k1);
  8297. let shift = self.s.m.select(c, lt1, k1, raw_shift);
  8298. let gt23 = self.s.m.cmp(c, pred::IUGT, shift, k23);
  8299. let shift = self.s.m.select(c, gt23, k23, shift);
  8300. let sub_m = self.s.m.bin(c, Bin::LShr, sig24, shift);
  8301. let inv_shift = self.s.m.bin(c, Bin::Sub, k32, shift);
  8302. let lost = self.s.m.bin(c, Bin::Shl, sig24, inv_shift);
  8303. let round_bit = self.s.m.bin(c, Bin::LShr, lost, k31);
  8304. let round_on = self.s.m.cmp(c, pred::NE, round_bit, k0);
  8305. let low31 = self.s.m.i32(0x7FFF_FFFF);
  8306. let lost_lo = self.s.m.bin(c, Bin::And, lost, low31);
  8307. let sticky = self.s.m.bin(c, Bin::Or, lost_lo, rem);
  8308. let sticky_on = self.s.m.cmp(c, pred::NE, sticky, k0);
  8309. let sub_odd_bit = self.s.m.bin(c, Bin::And, sub_m, k1);
  8310. let sub_odd = self.s.m.cmp(c, pred::NE, sub_odd_bit, k0);
  8311. let sub_tie = self.s.m.bin(c, Bin::Or, sticky_on, sub_odd);
  8312. let sub_round = self.s.m.bin(c, Bin::And, round_on, sub_tie);
  8313. let sub_inc = self.s.m.select(c, sub_round, k1, k0);
  8314. let sub_body = self.s.m.bin(c, Bin::Add, sub_m, sub_inc);
  8315. let sub_res = self.s.m.bin(c, Bin::Or, sign, sub_body);
  8316. // Underflow range: exp64 < 874. Only exp64 == 873 with non-zero fraction rounds up to min subnormal (1).
  8317. let k873 = self.s.m.i32(873);
  8318. let eq873 = self.s.m.cmp(c, pred::EQ, exp64, k873);
  8319. let round_min = self.s.m.bin(c, Bin::And, eq873, frac_nz);
  8320. let min_bit = self.s.m.select(c, round_min, k1, k0);
  8321. let under_res = self.s.m.bin(c, Bin::Or, sign, min_bit);
  8322. // Overflow / Inf / NaN: exp64 >= 1151.
  8323. let is_exp_all = self.s.m.cmp(c, pred::EQ, exp64, k7ff);
  8324. let is_nan = self.s.m.bin(c, Bin::And, is_exp_all, frac_nz);
  8325. let inf_bits = self.s.m.i32(0x7F80_0000);
  8326. let qnan_bits = self.s.m.i32(0x7FC0_0000);
  8327. let nan_body = self.s.m.bin(c, Bin::Or, qnan_bits, m23);
  8328. let over_body = self.s.m.select(c, is_nan, nan_body, inf_bits);
  8329. let over_res = self.s.m.bin(c, Bin::Or, sign, over_body);
  8330. // Select final result by exponent range.
  8331. let k874 = self.s.m.i32(874);
  8332. let k1151 = self.s.m.i32(1151);
  8333. let is_under = self.s.m.cmp(c, pred::IULT, exp64, k874);
  8334. let is_sub = self.s.m.cmp(c, pred::IULT, exp64, k897);
  8335. let is_over = self.s.m.cmp(c, pred::IUGE, exp64, k1151);
  8336. let r = self.s.m.select(c, is_over, over_res, norm_res);
  8337. let r = self.s.m.select(c, is_sub, sub_res, r);
  8338. self.s.m.select(c, is_under, under_res, r)
  8339. }
  8340. fn join64(&mut self, lo: V, hi: V) -> V {
  8341. let c = self.cur;
  8342. let ty = self.s.m.int(64);
  8343. let lo = self.s.m.cast(c, Cast::ZExt, lo, ty);
  8344. let hi = self.s.m.cast(c, Cast::ZExt, hi, ty);
  8345. let shift = self.s.m.int_const(ty, 32);
  8346. let hi = self.s.m.bin(c, Bin::Shl, hi, shift);
  8347. self.s.m.bin(c, Bin::Or, lo, hi)
  8348. }
  8349. /// The bits of the float nearest the double whose dwords are `lo` and
  8350. /// `hi`, on 32-bit integers: round to nearest even, infinities and NaN
  8351. /// kept (a NaN stays quiet), a result below the smallest normal float
  8352. /// signed zero (flushed, as the console's default float mode does).
  8353. // The flush-to-zero form of v_cvt_f32_f64: kept beside the IEEE form in use until the console's
  8354. // float mode for this instruction is checked.
  8355. #[allow(dead_code)]
  8356. fn f64_bits_to_f32_bits(&mut self, lo: V, hi: V) -> V {
  8357. let c = self.cur;
  8358. let k = |l: &mut Self, x: u32| l.s.m.i32(x);
  8359. let (k20, k29, k3, k23) = (k(self, 20), k(self, 29), k(self, 3), k(self, 23));
  8360. let sign_mask = k(self, 0x8000_0000);
  8361. let sign = self.s.m.bin(c, Bin::And, hi, sign_mask);
  8362. let e = self.s.m.bin(c, Bin::LShr, hi, k20);
  8363. let e_mask = k(self, 0x7ff);
  8364. let e = self.s.m.bin(c, Bin::And, e, e_mask);
  8365. // The top 23 bits of the 52-bit mantissa, and the 29 below them.
  8366. let m_mask = k(self, 0x000f_ffff);
  8367. let mh = self.s.m.bin(c, Bin::And, hi, m_mask);
  8368. let mh = self.s.m.bin(c, Bin::Shl, mh, k3);
  8369. let ml = self.s.m.bin(c, Bin::LShr, lo, k29);
  8370. let m = self.s.m.bin(c, Bin::Or, mh, ml);
  8371. let rest_mask = k(self, 0x1fff_ffff);
  8372. let rest = self.s.m.bin(c, Bin::And, lo, rest_mask);
  8373. // Round to nearest even: up past half, or at half when odd.
  8374. let half = k(self, 0x1000_0000);
  8375. let one = k(self, 1);
  8376. let above = self.s.m.cmp(c, pred::IUGT, rest, half);
  8377. let at = self.s.m.cmp(c, pred::EQ, rest, half);
  8378. let odd = self.s.m.bin(c, Bin::And, m, one);
  8379. let zero = k(self, 0);
  8380. let odd = self.s.m.cmp(c, pred::NE, odd, zero);
  8381. let tie = self.s.m.bin(c, Bin::And, at, odd);
  8382. let up = self.s.m.bin(c, Bin::Or, above, tie);
  8383. let up = self.s.m.select(c, up, one, zero);
  8384. // Rebias the exponent (1023 → 127); a carry out of the mantissa
  8385. // steps the exponent, up to infinity.
  8386. let bias = k(self, 1023 - 127);
  8387. let e32 = self.s.m.bin(c, Bin::Sub, e, bias);
  8388. let ex = self.s.m.bin(c, Bin::Shl, e32, k23);
  8389. let normal = self.s.m.bin(c, Bin::Add, ex, m);
  8390. let normal = self.s.m.bin(c, Bin::Add, normal, up);
  8391. let normal = self.s.m.bin(c, Bin::Or, normal, sign);
  8392. // Exponents out of the float's range (signed, after rebiasing).
  8393. let inf = k(self, 0x7f80_0000);
  8394. let inf = self.s.m.bin(c, Bin::Or, inf, sign);
  8395. let k255 = k(self, 255);
  8396. let big = self.s.m.cmp(c, pred::SGE, e32, k255);
  8397. let small = self.s.m.cmp(c, pred::SLE, e32, zero);
  8398. let r = self.s.m.select(c, big, inf, normal);
  8399. let r = self.s.m.select(c, small, sign, r);
  8400. // Infinity and NaN (a NaN with any mantissa bit set stays a NaN).
  8401. let all = k(self, 0x7ff);
  8402. let special = self.s.m.cmp(c, pred::EQ, e, all);
  8403. let any = self.s.m.bin(c, Bin::Or, mh, ml);
  8404. let any = self.s.m.bin(c, Bin::Or, any, rest);
  8405. let nan = self.s.m.cmp(c, pred::NE, any, zero);
  8406. let quiet = k(self, 0x0040_0000);
  8407. let quiet = self.s.m.select(c, nan, quiet, zero);
  8408. let special_bits = self.s.m.bin(c, Bin::Or, inf, quiet);
  8409. self.s.m.select(c, special, special_bits, r)
  8410. }
  8411. /// The low and high dwords of an i64.
  8412. fn split64(&mut self, x: V) -> (V, V) {
  8413. let c = self.cur;
  8414. let i64t = self.s.m.int(64);
  8415. let k32 = self.s.m.int_const(i64t, 32);
  8416. let lo = self.s.m.cast(c, Cast::Trunc, x, self.s.t.i32);
  8417. let hi = self.s.m.bin(c, Bin::LShr, x, k32);
  8418. let hi = self.s.m.cast(c, Cast::Trunc, hi, self.s.t.i32);
  8419. (lo, hi)
  8420. }
  8421. /// Source `k` of a 16-bit operation in the low 16 bits (the rest 0):
  8422. /// op_sel (or an SDWA word select) picks the high half; inline float
  8423. /// constants are f16 values here.
  8424. fn half_src(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  8425. let Fields::Valu(v) = &inst.fields else {
  8426. unreachable!()
  8427. };
  8428. let op = *v.src.get(k).ok_or("a missing operand")?;
  8429. let mut high = v.opsel >> k & 1 != 0;
  8430. if let Some(sd) = v.sdwa {
  8431. match sd.src_sel.get(k).copied().unwrap_or(6) {
  8432. 4 => {}
  8433. 5 => high = true,
  8434. 6 => {}
  8435. _ => return Err("a byte select on a 16-bit operation"),
  8436. }
  8437. }
  8438. let x = match self.src0 {
  8439. Some(x) if k == 0 => x,
  8440. _ => self.f16_operand(inst, &op)?,
  8441. };
  8442. let c = self.cur;
  8443. let x = if high {
  8444. let k16 = self.s.m.i32(16);
  8445. self.s.m.bin(c, Bin::LShr, x, k16)
  8446. } else {
  8447. x
  8448. };
  8449. let m = self.s.m.i32(0xFFFF);
  8450. Ok(self.s.m.bin(c, Bin::And, x, m))
  8451. }
  8452. /// An f16 source as an f32 (exact), with its abs/neg modifiers.
  8453. fn half_fsrc(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  8454. let Fields::Valu(v) = &inst.fields else {
  8455. unreachable!()
  8456. };
  8457. let h = self.half_src(inst, k)?;
  8458. let f32t = self.s.t.f32;
  8459. let mut f = self
  8460. .s
  8461. .op(self.cur, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]);
  8462. if v.abs >> k & 1 != 0 {
  8463. f = self.unary(6, f);
  8464. }
  8465. if v.neg >> k & 1 != 0 {
  8466. let z = self.s.m.f32(0x8000_0000);
  8467. f = self.s.m.bin(self.cur, Bin::Sub, z, f);
  8468. }
  8469. Ok(f)
  8470. }
  8471. /// Writes a 16-bit result (low bits of `x`) into the destination's low
  8472. /// half, or its high half with op_sel bit 3 (or an SDWA WORD_1 select);
  8473. /// the other half is kept (GFX10).
  8474. fn write_half(&mut self, inst: &Inst, x: V, guard: Option<V>) -> Result<(), Why> {
  8475. let Fields::Valu(v) = &inst.fields else {
  8476. unreachable!()
  8477. };
  8478. let Some(Operand::Vector { reg, .. }) = v.dst else {
  8479. return Err("a 16-bit result outside a VGPR");
  8480. };
  8481. let mut high = v.opsel >> 3 & 1 != 0;
  8482. // SDWA: the word written, the other one kept (preserve) or zero
  8483. // (pad; a sign extension above the high word adds nothing).
  8484. let mut keep = true;
  8485. if let Some(sd) = v.sdwa {
  8486. match (sd.dst_sel, sd.dst_unused) {
  8487. (4, 2) => {}
  8488. (5, 2) => high = true,
  8489. (4 | 6, _) => keep = false,
  8490. (5, _) => (high, keep) = (true, false),
  8491. _ => return Err("an SDWA destination of a 16-bit operation"),
  8492. }
  8493. }
  8494. let c = self.cur;
  8495. let old = match inst.read(Reg::V(reg)).map(|o| self.i32_of(o)) {
  8496. Some(Ok(o)) if keep => o,
  8497. _ => self.s.m.i32(0),
  8498. };
  8499. let (k16, low) = (self.s.m.i32(16), self.s.m.i32(0xFFFF));
  8500. let x = self.s.m.bin(c, Bin::And, x, low);
  8501. let r = if high {
  8502. let o = self.s.m.bin(c, Bin::And, old, low);
  8503. let x = self.s.m.bin(c, Bin::Shl, x, k16);
  8504. self.s.m.bin(c, Bin::Or, o, x)
  8505. } else {
  8506. let keep = self.s.m.i32(0xFFFF_0000);
  8507. let o = self.s.m.bin(c, Bin::And, old, keep);
  8508. self.s.m.bin(c, Bin::Or, o, x)
  8509. };
  8510. self.write_placed(inst, Reg::V(reg), r, guard);
  8511. Ok(())
  8512. }
  8513. /// 16-bit operations, computed in f32 or i32: f16 sums, differences and
  8514. /// products are exact there and round once to f16 (f32 has the 2 x 11 +
  8515. /// 2 bits that make double rounding harmless); `None` if `name` is none.
  8516. fn valu16(&mut self, inst: &Inst, name: &str, guard: Option<V>) -> Option<Result<(), Why>> {
  8517. const FLOAT2: &[&str] = &[
  8518. "v_add_f16",
  8519. "v_sub_f16",
  8520. "v_subrev_f16",
  8521. "v_mul_f16",
  8522. "v_max_f16",
  8523. "v_min_f16",
  8524. ];
  8525. const FLOAT3: &[&str] = &[
  8526. "v_fma_f16",
  8527. "v_mad_f16",
  8528. "v_fmac_f16",
  8529. "v_mac_f16",
  8530. "v_max3_f16",
  8531. "v_min3_f16",
  8532. "v_med3_f16",
  8533. ];
  8534. const FLOAT1: &[&str] = &[
  8535. "v_rcp_f16",
  8536. "v_sqrt_f16",
  8537. "v_rsq_f16",
  8538. "v_log_f16",
  8539. "v_exp_f16",
  8540. "v_fract_f16",
  8541. "v_trunc_f16",
  8542. "v_floor_f16",
  8543. "v_ceil_f16",
  8544. "v_rndne_f16",
  8545. "v_sin_f16",
  8546. "v_cos_f16",
  8547. "v_cvt_f16_u16",
  8548. "v_cvt_f16_i16",
  8549. ];
  8550. const INT: &[&str] = &[
  8551. "v_add_nc_u16",
  8552. "v_sub_nc_u16",
  8553. "v_subrev_nc_u16",
  8554. "v_mul_lo_u16",
  8555. "v_lshlrev_b16",
  8556. "v_lshrrev_b16",
  8557. "v_ashrrev_i16",
  8558. "v_max_u16",
  8559. "v_max_i16",
  8560. "v_min_u16",
  8561. "v_min_i16",
  8562. "v_cvt_u16_f16",
  8563. "v_cvt_i16_f16",
  8564. "v_cvt_norm_i16_f16",
  8565. "v_cvt_norm_u16_f16",
  8566. ];
  8567. let all = [FLOAT1, FLOAT2, FLOAT3, INT];
  8568. if !all.iter().any(|l| l.contains(&name))
  8569. && !matches!(name, "v_cvt_f16_f32" | "v_cvt_f32_f16")
  8570. {
  8571. return None;
  8572. }
  8573. Some(self.valu16_op(inst, name, guard, FLOAT1, FLOAT2, FLOAT3))
  8574. }
  8575. #[allow(clippy::too_many_arguments)]
  8576. fn valu16_op(
  8577. &mut self,
  8578. inst: &Inst,
  8579. name: &str,
  8580. guard: Option<V>,
  8581. float1: &[&str],
  8582. float2: &[&str],
  8583. float3: &[&str],
  8584. ) -> Result<(), Why> {
  8585. let Fields::Valu(v) = &inst.fields else {
  8586. unreachable!()
  8587. };
  8588. let c = self.cur;
  8589. let i32t = self.s.t.i32;
  8590. let f32t = self.s.t.f32;
  8591. if name == "v_cvt_f32_f16" {
  8592. let f = self.half_fsrc(inst, 0)?;
  8593. return self.write_f(inst, f, guard);
  8594. }
  8595. let float_result = |l: &mut Self, mut f: V| -> Result<(), Why> {
  8596. match v.omod {
  8597. 0 => {}
  8598. k => {
  8599. let factor = [1.0f32, 2.0, 4.0, 0.5][usize::from(k)];
  8600. let k = l.s.m.f32(factor.to_bits());
  8601. f = l.s.m.bin(l.cur, Bin::Mul, f, k);
  8602. }
  8603. }
  8604. if v.clamp {
  8605. f = l.unary(7, f);
  8606. }
  8607. // The console rounds to nearest; the host's conversion may round toward zero
  8608. // (NVIDIA's does), one step of the last place lower where the two differ.
  8609. // shortcut: the host's conversion unless `VICTORY_F16_NEAREST=1`
  8610. // ([`f16_nearest_on`]), which costs a dozen instructions per result.
  8611. let h = if f16_nearest_on() {
  8612. l.f16_nearest(f)
  8613. } else {
  8614. l.s.op(l.cur, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f])
  8615. };
  8616. l.write_half(inst, h, guard)
  8617. };
  8618. if name == "v_cvt_f16_f32" {
  8619. let f = self.fsrc(inst, 0)?;
  8620. return float_result(self, f);
  8621. }
  8622. if float2.contains(&name) {
  8623. let (a, b) = (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?);
  8624. let r = match name {
  8625. "v_add_f16" => self.s.m.bin(c, Bin::Add, a, b),
  8626. "v_sub_f16" => self.s.m.bin(c, Bin::Sub, a, b),
  8627. "v_subrev_f16" => self.s.m.bin(c, Bin::Sub, b, a),
  8628. "v_mul_f16" => self.s.m.bin(c, Bin::Mul, a, b),
  8629. "v_max_f16" => self.max_min(true, a, b),
  8630. _ => self.max_min(false, a, b),
  8631. };
  8632. return float_result(self, r);
  8633. }
  8634. if float3.contains(&name) {
  8635. let (a, b) = (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?);
  8636. let acc = if matches!(name, "v_fmac_f16" | "v_mac_f16") {
  8637. // The accumulator is the destination's half that is written.
  8638. let Some(Operand::Vector { reg, .. }) = v.dst else {
  8639. return Err("an accumulator");
  8640. };
  8641. let x = self.i32_of(inst.read(Reg::V(reg)).ok_or("an accumulator")?)?;
  8642. let x = if v.opsel >> 3 & 1 != 0 {
  8643. let k16 = self.s.m.i32(16);
  8644. self.s.m.bin(c, Bin::LShr, x, k16)
  8645. } else {
  8646. x
  8647. };
  8648. let m = self.s.m.i32(0xFFFF);
  8649. let x = self.s.m.bin(c, Bin::And, x, m);
  8650. self.s
  8651. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x])
  8652. } else {
  8653. self.half_fsrc(inst, 2)?
  8654. };
  8655. let r = match name {
  8656. // shortcut: fused f16 multiply-adds as FMad in f32 (the
  8657. // product is exact; the sum rounds twice).
  8658. "v_fma_f16" | "v_fmac_f16" | "v_mad_f16" | "v_mac_f16" => self.fmad(a, b, acc),
  8659. "v_max3_f16" => {
  8660. let t = self.max_min(true, a, b);
  8661. self.max_min(true, t, acc)
  8662. }
  8663. "v_min3_f16" => {
  8664. let t = self.max_min(false, a, b);
  8665. self.max_min(false, t, acc)
  8666. }
  8667. _ => self.med3(a, b, acc),
  8668. };
  8669. return float_result(self, r);
  8670. }
  8671. if float1.contains(&name) {
  8672. let r = match name {
  8673. "v_cvt_f16_u16" | "v_cvt_f16_i16" => {
  8674. let mut x = self.half_src(inst, 0)?;
  8675. let op = if name == "v_cvt_f16_i16" {
  8676. let k16 = self.s.m.i32(16);
  8677. let t = self.s.m.bin(c, Bin::Shl, x, k16);
  8678. x = self.s.m.bin(c, Bin::AShr, t, k16);
  8679. Cast::SiToFp
  8680. } else {
  8681. Cast::UiToFp
  8682. };
  8683. self.s.m.cast(c, op, x, f32t)
  8684. }
  8685. "v_rcp_f16" => {
  8686. let a = self.half_fsrc(inst, 0)?;
  8687. let one = self.s.m.f32(1.0f32.to_bits());
  8688. self.s.m.bin(c, Bin::SDiv, one, a)
  8689. }
  8690. _ => {
  8691. let a = self.half_fsrc(inst, 0)?;
  8692. let op = match name {
  8693. "v_sqrt_f16" => 24,
  8694. "v_rsq_f16" => 25,
  8695. "v_log_f16" => 23,
  8696. "v_exp_f16" => 21,
  8697. "v_fract_f16" => 22,
  8698. "v_trunc_f16" => 29,
  8699. "v_floor_f16" => 27,
  8700. "v_ceil_f16" => 28,
  8701. "v_rndne_f16" => 26,
  8702. "v_sin_f16" => 13,
  8703. _ => 12,
  8704. };
  8705. match op {
  8706. 12 | 13 => self.trig_turns(a, op == 12),
  8707. // Any f16 in (-2^-11, 0) has fract >= 1 - 2^-12; clamp to 0x3bff (1 - 2^-11).
  8708. 22 => self.fract(a, 1.0 - 1.0 / 4096.0, 1.0 - 1.0 / 2048.0),
  8709. _ => self.unary(op, a),
  8710. }
  8711. }
  8712. };
  8713. return float_result(self, r);
  8714. }
  8715. if matches!(name, "v_cvt_u16_f16" | "v_cvt_i16_f16") {
  8716. if v.clamp || v.omod != 0 {
  8717. return Err("modifiers on a 16-bit integer operation");
  8718. }
  8719. // Toward zero, saturating at the 16-bit range (infinities
  8720. // included); NaN gives 0. Clamped in f32 first, where every
  8721. // f16 is exact, so the conversion never leaves i32's range
  8722. // (upstream PR #384's arithmetic; the source's abs and neg
  8723. // modifiers are applied by `half_fsrc`, as before).
  8724. let a = self.half_fsrc(inst, 0)?;
  8725. let (lo, hi) = if name == "v_cvt_u16_f16" {
  8726. (0.0f32, 65535.0f32)
  8727. } else {
  8728. (-32768.0, 32767.0)
  8729. };
  8730. let (lo, hi) = (self.s.m.f32(lo.to_bits()), self.s.m.f32(hi.to_bits()));
  8731. let t = self.binary(35, a, lo);
  8732. let t = self.binary(36, t, hi);
  8733. let r = self.s.m.cast(c, Cast::FpToSi, t, i32t);
  8734. let nan = self.s.m.cmp(c, pred::UNO, a, a);
  8735. let z = self.s.m.i32(0);
  8736. let r = self.s.m.select(c, nan, z, r);
  8737. return self.write_half(inst, r, guard);
  8738. }
  8739. if matches!(name, "v_cvt_norm_i16_f16" | "v_cvt_norm_u16_f16") {
  8740. if v.clamp || v.omod != 0 {
  8741. return Err("modifiers on a 16-bit integer operation");
  8742. }
  8743. let r = self.cvt_norm16(inst, name == "v_cvt_norm_i16_f16")?;
  8744. return self.write_half(inst, r, guard);
  8745. }
  8746. // 16-bit integers: computed on the low halves, the low 16 bits kept.
  8747. if v.clamp || v.omod != 0 || v.abs != 0 || v.neg != 0 {
  8748. return Err("modifiers on a 16-bit integer operation");
  8749. }
  8750. let r = {
  8751. let (mut a, mut b) = (self.half_src(inst, 0)?, self.half_src(inst, 1)?);
  8752. let k16 = self.s.m.i32(16);
  8753. let sext = |l: &mut Self, x: V| {
  8754. let t = l.s.m.bin(c, Bin::Shl, x, k16);
  8755. l.s.m.bin(c, Bin::AShr, t, k16)
  8756. };
  8757. if name.ends_with("_i16") {
  8758. a = sext(self, a);
  8759. b = sext(self, b);
  8760. }
  8761. let k15 = self.s.m.i32(15);
  8762. match name {
  8763. "v_add_nc_u16" => self.s.m.bin(c, Bin::Add, a, b),
  8764. "v_sub_nc_u16" => self.s.m.bin(c, Bin::Sub, a, b),
  8765. "v_subrev_nc_u16" => self.s.m.bin(c, Bin::Sub, b, a),
  8766. "v_mul_lo_u16" => self.s.m.bin(c, Bin::Mul, a, b),
  8767. "v_lshlrev_b16" | "v_lshrrev_b16" | "v_ashrrev_i16" => {
  8768. // src0 is the shift (4 bits), src1 the value.
  8769. let sh = self.s.m.bin(c, Bin::And, a, k15);
  8770. let x = if name == "v_ashrrev_i16" {
  8771. sext(self, b)
  8772. } else {
  8773. b
  8774. };
  8775. let op = match name {
  8776. "v_lshlrev_b16" => Bin::Shl,
  8777. "v_lshrrev_b16" => Bin::LShr,
  8778. _ => Bin::AShr,
  8779. };
  8780. self.s.m.bin(c, op, x, sh)
  8781. }
  8782. _ => {
  8783. let p = match name {
  8784. "v_max_u16" => pred::IUGT,
  8785. "v_min_u16" => pred::IULT,
  8786. "v_max_i16" => pred::SGT,
  8787. _ => pred::SLT,
  8788. };
  8789. let t = self.s.m.cmp(c, p, a, b);
  8790. self.s.m.select(c, t, a, b)
  8791. }
  8792. }
  8793. };
  8794. self.write_half(inst, r, guard)
  8795. }
  8796. /// `v_cvt_norm_i16_f16` / `v_cvt_norm_u16_f16`: the f16 source (with its
  8797. /// abs/neg modifiers) clamped to [-1, 1] or [0, 1], times 32767 or 65535,
  8798. /// rounded to nearest even once from the exact product; NaN gives 0.
  8799. /// Worked on the f16's bits in integers, because in f32 the product
  8800. /// (up to 26 significant bits) would round before the rounding to an
  8801. /// integer.
  8802. fn cvt_norm16(&mut self, inst: &Inst, signed: bool) -> Result<V, Why> {
  8803. let Fields::Valu(v) = &inst.fields else {
  8804. unreachable!()
  8805. };
  8806. let c = self.cur;
  8807. let k = |l: &mut Self, x: u32| l.s.m.i32(x);
  8808. let mut h = self.half_src(inst, 0)?;
  8809. if v.abs & 1 != 0 {
  8810. let m = k(self, 0x7FFF);
  8811. h = self.s.m.bin(c, Bin::And, h, m);
  8812. }
  8813. if v.neg & 1 != 0 {
  8814. let m = k(self, 0x8000);
  8815. h = self.s.m.bin(c, Bin::Xor, h, m);
  8816. }
  8817. let scale = if signed { 0x7FFF } else { 0xFFFF };
  8818. let (k0, k1, k10) = (k(self, 0), k(self, 1), k(self, 10));
  8819. let mag_mask = k(self, 0x7FFF);
  8820. let mag = self.s.m.bin(c, Bin::And, h, mag_mask);
  8821. let k15 = k(self, 15);
  8822. let neg = self.s.m.bin(c, Bin::LShr, h, k15);
  8823. let neg = self.s.m.cmp(c, pred::NE, neg, k0);
  8824. // |x| < 1: x = m * 2^-s with m < 2^11 and 11 <= s <= 24.
  8825. let exp = self.s.m.bin(c, Bin::LShr, mag, k10);
  8826. let man_mask = k(self, 0x3FF);
  8827. let man = self.s.m.bin(c, Bin::And, mag, man_mask);
  8828. let implicit = k(self, 0x400);
  8829. let normal = self.s.m.bin(c, Bin::Or, man, implicit);
  8830. let sub = self.s.m.cmp(c, pred::EQ, exp, k0);
  8831. let m = self.s.m.select(c, sub, man, normal);
  8832. let k25 = k(self, 25);
  8833. let s_norm = self.s.m.bin(c, Bin::Sub, k25, exp);
  8834. let k24 = k(self, 24);
  8835. let sh = self.s.m.select(c, sub, k24, s_norm);
  8836. let ks = k(self, scale);
  8837. let p = self.s.m.bin(c, Bin::Mul, m, ks);
  8838. let q = self.s.m.bin(c, Bin::LShr, p, sh);
  8839. let one_s = self.s.m.bin(c, Bin::Shl, k1, sh);
  8840. let low_mask = self.s.m.bin(c, Bin::Sub, one_s, k1);
  8841. let rem = self.s.m.bin(c, Bin::And, p, low_mask);
  8842. let half = self.s.m.bin(c, Bin::LShr, one_s, k1);
  8843. let above = self.s.m.cmp(c, pred::IUGT, rem, half);
  8844. let tie = self.s.m.cmp(c, pred::EQ, rem, half);
  8845. let odd = self.s.m.bin(c, Bin::And, q, k1);
  8846. let odd = self.s.m.cmp(c, pred::NE, odd, k0);
  8847. let tie_up = self.s.m.bin(c, Bin::And, tie, odd);
  8848. let up = self.s.m.bin(c, Bin::Or, above, tie_up);
  8849. let r = self.s.m.select(c, up, k1, k0);
  8850. let r = self.s.m.bin(c, Bin::Add, q, r);
  8851. // |x| >= 1 (and infinity) saturates; NaN gives 0.
  8852. let one_h = k(self, 0x3C00);
  8853. let big = self.s.m.cmp(c, pred::IUGE, mag, one_h);
  8854. let r = self.s.m.select(c, big, ks, r);
  8855. let inf = k(self, 0x7C00);
  8856. let nan = self.s.m.cmp(c, pred::IUGT, mag, inf);
  8857. let r = self.s.m.select(c, nan, k0, r);
  8858. let r = if signed {
  8859. let n = self.s.m.bin(c, Bin::Sub, k0, r);
  8860. self.s.m.select(c, neg, n, r)
  8861. } else {
  8862. self.s.m.select(c, neg, k0, r)
  8863. };
  8864. let m16 = k(self, 0xFFFF);
  8865. Ok(self.s.m.bin(c, Bin::And, r, m16))
  8866. }
  8867. /// Half `high` of source `k` of a packed (VOP3P) operation, in the low
  8868. /// 16 bits: op_sel picks the half the low result reads, op_sel_hi the
  8869. /// half the high result reads. Packed integer instructions see the f32
  8870. /// bits of an inline float constant.
  8871. fn packed_src(&mut self, inst: &Inst, k: usize, high: bool, float: bool) -> Result<V, Why> {
  8872. let Fields::Valu(v) = &inst.fields else {
  8873. unreachable!()
  8874. };
  8875. let op = *v.src.get(k).ok_or("a missing operand")?;
  8876. let sel = if high { v.opsel_hi } else { v.opsel } >> k & 1 != 0;
  8877. let x = if float {
  8878. self.f16_operand(inst, &op)?
  8879. } else {
  8880. self.operand(inst, &op)?
  8881. };
  8882. let c = self.cur;
  8883. let x = if sel {
  8884. let k16 = self.s.m.i32(16);
  8885. self.s.m.bin(c, Bin::LShr, x, k16)
  8886. } else {
  8887. x
  8888. };
  8889. let m = self.s.m.i32(0xFFFF);
  8890. Ok(self.s.m.bin(c, Bin::And, x, m))
  8891. }
  8892. /// Half `high` of source `k` of `v_pk_fmac_f16`, in the low 16 bits: a
  8893. /// VOP2 operation (no op_sel) whose third source is its destination.
  8894. fn fmac_half(&mut self, inst: &Inst, k: usize, high: bool) -> Result<V, Why> {
  8895. let Fields::Valu(v) = &inst.fields else {
  8896. unreachable!()
  8897. };
  8898. let op = if k == 2 { v.dst } else { v.src.get(k).copied() };
  8899. let op = op.ok_or("a missing operand")?;
  8900. if matches!(op, Operand::Const(_) | Operand::Literal(_)) {
  8901. // shortcut: no constant operand seen; its high half is not known.
  8902. return Err("a constant operand of v_pk_fmac_f16");
  8903. }
  8904. let x = self.operand(inst, &op)?;
  8905. let c = self.cur;
  8906. let x = if high {
  8907. let k16 = self.s.m.i32(16);
  8908. self.s.m.bin(c, Bin::LShr, x, k16)
  8909. } else {
  8910. x
  8911. };
  8912. let m = self.s.m.i32(0xFFFF);
  8913. Ok(self.s.m.bin(c, Bin::And, x, m))
  8914. }
  8915. /// Packed 16-bit operations (`v_pk_*`): each half computed as the
  8916. /// 16-bit operation does, f16 through f32 as in [`Self::valu16`].
  8917. fn packed16(&mut self, inst: &Inst, op: &str, guard: Option<V>) -> Result<(), Why> {
  8918. let Fields::Valu(v) = &inst.fields else {
  8919. unreachable!()
  8920. };
  8921. let float = op.ends_with("_f16");
  8922. let n = match op {
  8923. "fma_f16" | "fmac_f16" | "mad_u16" | "mad_i16" => 3,
  8924. "add_f16" | "mul_f16" | "min_f16" | "max_f16" | "add_u16" | "sub_u16" | "add_i16"
  8925. | "sub_i16" | "mul_lo_u16" | "lshlrev_b16" | "lshrrev_b16" | "ashrrev_i16"
  8926. | "max_u16" | "min_u16" | "max_i16" | "min_i16" => 2,
  8927. _ => return Err("a packed 16-bit operation"),
  8928. };
  8929. if v.omod != 0 || !float && (v.clamp || v.neg != 0 || v.neg_hi != 0) {
  8930. return Err("modifiers on a packed integer operation");
  8931. }
  8932. let c = self.cur;
  8933. let (i32t, f32t) = (self.s.t.i32, self.s.t.f32);
  8934. let mut halves = Vec::new();
  8935. for high in [false, true] {
  8936. let mut xs = Vec::new();
  8937. for k in 0..n {
  8938. let h = if op == "fmac_f16" {
  8939. self.fmac_half(inst, k, high)?
  8940. } else {
  8941. self.packed_src(inst, k, high, float)?
  8942. };
  8943. if float {
  8944. let mut f = self
  8945. .s
  8946. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]);
  8947. let neg = if high { v.neg_hi } else { v.neg };
  8948. if neg >> k & 1 != 0 {
  8949. let z = self.s.m.f32(0x8000_0000);
  8950. f = self.s.m.bin(c, Bin::Sub, z, f);
  8951. }
  8952. xs.push(f);
  8953. } else {
  8954. xs.push(h);
  8955. }
  8956. }
  8957. let r = if float {
  8958. let mut f = match op {
  8959. "add_f16" => self.s.m.bin(c, Bin::Add, xs[0], xs[1]),
  8960. "mul_f16" => self.s.m.bin(c, Bin::Mul, xs[0], xs[1]),
  8961. "min_f16" => self.max_min(false, xs[0], xs[1]),
  8962. "max_f16" => self.max_min(true, xs[0], xs[1]),
  8963. // shortcut: FMad in f32, as v_fma_f16.
  8964. _ => self.fmad(xs[0], xs[1], xs[2]),
  8965. };
  8966. if v.clamp {
  8967. f = self.unary(7, f);
  8968. }
  8969. self.s
  8970. .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f])
  8971. } else {
  8972. let k16 = self.s.m.i32(16);
  8973. let sext = |l: &mut Self, x: V| {
  8974. let t = l.s.m.bin(c, Bin::Shl, x, k16);
  8975. l.s.m.bin(c, Bin::AShr, t, k16)
  8976. };
  8977. if op.ends_with("_i16") {
  8978. for x in &mut xs {
  8979. *x = sext(self, *x);
  8980. }
  8981. }
  8982. let k15 = self.s.m.i32(15);
  8983. match op {
  8984. "add_u16" | "add_i16" => self.s.m.bin(c, Bin::Add, xs[0], xs[1]),
  8985. "sub_u16" | "sub_i16" => self.s.m.bin(c, Bin::Sub, xs[0], xs[1]),
  8986. "mul_lo_u16" => self.s.m.bin(c, Bin::Mul, xs[0], xs[1]),
  8987. "mad_u16" | "mad_i16" => {
  8988. let m = self.s.m.bin(c, Bin::Mul, xs[0], xs[1]);
  8989. self.s.m.bin(c, Bin::Add, m, xs[2])
  8990. }
  8991. "lshlrev_b16" | "lshrrev_b16" | "ashrrev_i16" => {
  8992. let sh = self.s.m.bin(c, Bin::And, xs[0], k15);
  8993. let o = match op {
  8994. "lshlrev_b16" => Bin::Shl,
  8995. "lshrrev_b16" => Bin::LShr,
  8996. _ => Bin::AShr,
  8997. };
  8998. let x = if op == "ashrrev_i16" {
  8999. sext(self, xs[1])
  9000. } else {
  9001. xs[1]
  9002. };
  9003. self.s.m.bin(c, o, x, sh)
  9004. }
  9005. _ => {
  9006. let p = match op {
  9007. "max_u16" => pred::IUGT,
  9008. "min_u16" => pred::IULT,
  9009. "max_i16" => pred::SGT,
  9010. _ => pred::SLT,
  9011. };
  9012. let t = self.s.m.cmp(c, p, xs[0], xs[1]);
  9013. self.s.m.select(c, t, xs[0], xs[1])
  9014. }
  9015. }
  9016. };
  9017. let m = self.s.m.i32(0xFFFF);
  9018. halves.push(self.s.m.bin(c, Bin::And, r, m));
  9019. }
  9020. let k16 = self.s.m.i32(16);
  9021. let hi = self.s.m.bin(c, Bin::Shl, halves[1], k16);
  9022. let r = self.s.m.bin(c, Bin::Or, halves[0], hi);
  9023. let Some(Operand::Vector { reg, .. }) = v.dst else {
  9024. return Err("a packed result outside a VGPR");
  9025. };
  9026. self.write(inst, Reg::V(reg), r, guard);
  9027. Ok(())
  9028. }
  9029. fn integer(&mut self, inst: &Inst, name: &'static str) -> Result<V, Why> {
  9030. let c = self.cur;
  9031. let s = |l: &mut Self, k| l.src(inst, k);
  9032. let k = |l: &mut Self, x: u32| l.s.m.i32(x);
  9033. let m31 = |l: &mut Self, x: V| {
  9034. let k31 = l.s.m.i32(31);
  9035. l.s.m.bin(c, Bin::And, x, k31)
  9036. };
  9037. Ok(match name {
  9038. "v_and_b32" | "v_or_b32" | "v_xor_b32" | "v_add_nc_u32" | "v_sub_nc_u32"
  9039. | "v_subrev_nc_u32" | "v_mul_lo_u32" => {
  9040. let (a, b) = (s(self, 0)?, s(self, 1)?);
  9041. let (op, a, b) = match name {
  9042. "v_and_b32" => (Bin::And, a, b),
  9043. "v_or_b32" => (Bin::Or, a, b),
  9044. "v_xor_b32" => (Bin::Xor, a, b),
  9045. "v_add_nc_u32" => (Bin::Add, a, b),
  9046. "v_sub_nc_u32" => (Bin::Sub, a, b),
  9047. "v_subrev_nc_u32" => (Bin::Sub, b, a),
  9048. _ => (Bin::Mul, a, b),
  9049. };
  9050. self.s.m.bin(c, op, a, b)
  9051. }
  9052. "v_xnor_b32" => {
  9053. let (a, b) = (s(self, 0)?, s(self, 1)?);
  9054. let x = self.s.m.bin(c, Bin::Xor, a, b);
  9055. let ones = k(self, u32::MAX);
  9056. self.s.m.bin(c, Bin::Xor, x, ones)
  9057. }
  9058. "v_not_b32" => {
  9059. let a = s(self, 0)?;
  9060. let ones = k(self, u32::MAX);
  9061. self.s.m.bin(c, Bin::Xor, a, ones)
  9062. }
  9063. "v_lshlrev_b32" | "v_lshrrev_b32" | "v_ashrrev_i32" => {
  9064. let (sh, a) = (s(self, 0)?, s(self, 1)?);
  9065. let sh = m31(self, sh);
  9066. let op = match name {
  9067. "v_lshlrev_b32" => Bin::Shl,
  9068. "v_lshrrev_b32" => Bin::LShr,
  9069. _ => Bin::AShr,
  9070. };
  9071. self.s.m.bin(c, op, a, sh)
  9072. }
  9073. "v_lshl_add_u32" | "v_lshl_or_b32" | "v_add_lshl_u32" | "v_and_or_b32"
  9074. | "v_or3_b32" | "v_xad_u32" | "v_add3_u32" | "v_xor3_b32" => {
  9075. let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  9076. match name {
  9077. "v_lshl_add_u32" | "v_lshl_or_b32" => {
  9078. let b = m31(self, b);
  9079. let t = self.s.m.bin(c, Bin::Shl, a, b);
  9080. let op = if name == "v_lshl_add_u32" {
  9081. Bin::Add
  9082. } else {
  9083. Bin::Or
  9084. };
  9085. self.s.m.bin(c, op, t, d)
  9086. }
  9087. "v_add_lshl_u32" => {
  9088. let t = self.s.m.bin(c, Bin::Add, a, b);
  9089. let d = m31(self, d);
  9090. self.s.m.bin(c, Bin::Shl, t, d)
  9091. }
  9092. _ => {
  9093. let (o1, o2) = match name {
  9094. "v_and_or_b32" => (Bin::And, Bin::Or),
  9095. "v_or3_b32" => (Bin::Or, Bin::Or),
  9096. "v_xad_u32" => (Bin::Xor, Bin::Add),
  9097. "v_add3_u32" => (Bin::Add, Bin::Add),
  9098. _ => (Bin::Xor, Bin::Xor),
  9099. };
  9100. let t = self.s.m.bin(c, o1, a, b);
  9101. self.s.m.bin(c, o2, t, d)
  9102. }
  9103. }
  9104. }
  9105. "v_mul_u32_u24" | "v_mul_i32_i24" => {
  9106. let (a, b) = (s(self, 0)?, s(self, 1)?);
  9107. let (sh, op) = (
  9108. k(self, 8),
  9109. if name == "v_mul_i32_i24" {
  9110. Bin::AShr
  9111. } else {
  9112. Bin::LShr
  9113. },
  9114. );
  9115. let a = self.s.m.bin(c, Bin::Shl, a, sh);
  9116. let a = self.s.m.bin(c, op, a, sh);
  9117. let b = self.s.m.bin(c, Bin::Shl, b, sh);
  9118. let b = self.s.m.bin(c, op, b, sh);
  9119. self.s.m.bin(c, Bin::Mul, a, b)
  9120. }
  9121. "v_mul_hi_u32_u24" | "v_mul_hi_i32_i24" => {
  9122. // The high dword of the same 48-bit product: the low 24 bits
  9123. // of each operand, zero- or sign-extended, multiplied.
  9124. let (a, b) = (s(self, 0)?, s(self, 1)?);
  9125. let signed = name == "v_mul_hi_i32_i24";
  9126. let (sh, op) = (k(self, 8), if signed { Bin::AShr } else { Bin::LShr });
  9127. let a = self.s.m.bin(c, Bin::Shl, a, sh);
  9128. let a = self.s.m.bin(c, op, a, sh);
  9129. let b = self.s.m.bin(c, Bin::Shl, b, sh);
  9130. let b = self.s.m.bin(c, op, b, sh);
  9131. self.mul_hi(a, b, signed)
  9132. }
  9133. "v_bfe_u32" | "v_bfe_i32" => {
  9134. let (a, off, w) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  9135. let w = m31(self, w);
  9136. self.bfe(a, off, w, name == "v_bfe_i32")
  9137. }
  9138. "v_bfi_b32" => {
  9139. let (m, a, b) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  9140. let ones = k(self, u32::MAX);
  9141. let nm = self.s.m.bin(c, Bin::Xor, m, ones);
  9142. let x = self.s.m.bin(c, Bin::And, m, a);
  9143. let y = self.s.m.bin(c, Bin::And, nm, b);
  9144. self.s.m.bin(c, Bin::Or, x, y)
  9145. }
  9146. "v_max_i32" | "v_min_i32" | "v_max_u32" | "v_min_u32" => {
  9147. let (a, b) = (s(self, 0)?, s(self, 1)?);
  9148. let p = match name {
  9149. "v_max_i32" => pred::SGT,
  9150. "v_min_i32" => pred::SLT,
  9151. "v_max_u32" => pred::IUGT,
  9152. _ => pred::IULT,
  9153. };
  9154. let t = self.s.m.cmp(c, p, a, b);
  9155. self.s.m.select(c, t, a, b)
  9156. }
  9157. "v_mul_hi_u32" | "v_mul_hi_i32" => {
  9158. let (a, b) = (s(self, 0)?, s(self, 1)?);
  9159. self.mul_hi(a, b, name == "v_mul_hi_i32")
  9160. }
  9161. "v_alignbit_b32" | "v_alignbyte_b32" => {
  9162. // The low dword of {a, b} >> shift.
  9163. let (a, b, sh) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  9164. let sh = if name == "v_alignbyte_b32" {
  9165. let three = k(self, 3);
  9166. let t = self.s.m.bin(c, Bin::And, sh, three);
  9167. let k3 = k(self, 3);
  9168. self.s.m.bin(c, Bin::Shl, t, k3)
  9169. } else {
  9170. m31(self, sh)
  9171. };
  9172. let k32 = k(self, 32);
  9173. let lo = self.s.m.bin(c, Bin::LShr, b, sh);
  9174. let left = self.s.m.bin(c, Bin::Sub, k32, sh);
  9175. let left = m31(self, left);
  9176. let hi = self.s.m.bin(c, Bin::Shl, a, left);
  9177. let zero = k(self, 0);
  9178. let none = self.s.m.cmp(c, pred::EQ, sh, zero);
  9179. let hi = self.s.m.select(c, none, zero, hi);
  9180. self.s.m.bin(c, Bin::Or, lo, hi)
  9181. }
  9182. "v_bfrev_b32" => {
  9183. let a = s(self, 0)?;
  9184. self.s
  9185. .op(c, "unary.i32", Attr::ReadNone, self.s.t.i32, 30, &[a])
  9186. }
  9187. "v_bcnt_u32_b32" => {
  9188. let (a, b) = (s(self, 0)?, s(self, 1)?);
  9189. let n = self
  9190. .s
  9191. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 31, &[a]);
  9192. self.s.m.bin(c, Bin::Add, n, b)
  9193. }
  9194. "v_mad_u32_u24" | "v_mad_i32_i24" => {
  9195. let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  9196. let (sh, op) = (
  9197. k(self, 8),
  9198. if name == "v_mad_i32_i24" {
  9199. Bin::AShr
  9200. } else {
  9201. Bin::LShr
  9202. },
  9203. );
  9204. let a = self.s.m.bin(c, Bin::Shl, a, sh);
  9205. let a = self.s.m.bin(c, op, a, sh);
  9206. let b = self.s.m.bin(c, Bin::Shl, b, sh);
  9207. let b = self.s.m.bin(c, op, b, sh);
  9208. let m = self.s.m.bin(c, Bin::Mul, a, b);
  9209. self.s.m.bin(c, Bin::Add, m, d)
  9210. }
  9211. "v_sad_u8" | "v_sad_hi_u8" | "v_sad_u16" | "v_sad_u32" | "v_msad_u8" => {
  9212. // src2 plus the sum of the unsigned differences |a - b| of
  9213. // the operands' bytes, halves or whole dwords, wrapping at 32
  9214. // bits. v_sad_hi_u8 adds the sum shifted to the high half;
  9215. // v_msad_u8 leaves out a byte whose mask byte (src1) is 0.
  9216. let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  9217. let (width, parts) = match name {
  9218. "v_sad_u16" => (16, 2),
  9219. "v_sad_u32" => (32, 1),
  9220. _ => (8, 4),
  9221. };
  9222. let zero = k(self, 0);
  9223. let mut sum = zero;
  9224. for i in 0..parts {
  9225. let (mut x, mut y) = (a, b);
  9226. if width < 32 {
  9227. let (sh, mask) = (k(self, width * i), k(self, (1 << width) - 1));
  9228. x = self.s.m.bin(c, Bin::LShr, x, sh);
  9229. x = self.s.m.bin(c, Bin::And, x, mask);
  9230. y = self.s.m.bin(c, Bin::LShr, y, sh);
  9231. y = self.s.m.bin(c, Bin::And, y, mask);
  9232. }
  9233. let above = self.s.m.cmp(c, pred::IUGT, x, y);
  9234. let hi = self.s.m.select(c, above, x, y);
  9235. let lo = self.s.m.select(c, above, y, x);
  9236. let mut diff = self.s.m.bin(c, Bin::Sub, hi, lo);
  9237. if name == "v_msad_u8" {
  9238. let masked = self.s.m.cmp(c, pred::NE, y, zero);
  9239. diff = self.s.m.select(c, masked, diff, zero);
  9240. }
  9241. sum = self.s.m.bin(c, Bin::Add, sum, diff);
  9242. }
  9243. if name == "v_sad_hi_u8" {
  9244. let k16 = k(self, 16);
  9245. sum = self.s.m.bin(c, Bin::Shl, sum, k16);
  9246. }
  9247. self.s.m.bin(c, Bin::Add, sum, d)
  9248. }
  9249. "v_min3_i32" | "v_max3_i32" | "v_min3_u32" | "v_max3_u32" | "v_med3_i32"
  9250. | "v_med3_u32" => {
  9251. let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  9252. let signed = name.ends_with("i32");
  9253. let (lt, gt) = if signed {
  9254. (pred::SLT, pred::SGT)
  9255. } else {
  9256. (pred::IULT, pred::IUGT)
  9257. };
  9258. let pick = |l: &mut Self, p, x, y| {
  9259. let t = l.s.m.cmp(c, p, x, y);
  9260. l.s.m.select(c, t, x, y)
  9261. };
  9262. match &name[2..6] {
  9263. "min3" => {
  9264. let t = pick(self, lt, a, b);
  9265. pick(self, lt, t, d)
  9266. }
  9267. "max3" => {
  9268. let t = pick(self, gt, a, b);
  9269. pick(self, gt, t, d)
  9270. }
  9271. _ => {
  9272. let lo = pick(self, lt, a, b);
  9273. let hi = pick(self, gt, a, b);
  9274. let t = pick(self, lt, hi, d);
  9275. pick(self, gt, lo, t)
  9276. }
  9277. }
  9278. }
  9279. "v_perm_b32" => {
  9280. // Byte i of the result is byte S of {src0, src1} (src1 the
  9281. // low dword) for selector byte S below 8; 8-11 repeat the
  9282. // sign of bytes 1 and 3 of src1, then of src0; 12 is 0x00,
  9283. // higher 0xFF.
  9284. let Fields::Valu(v) = &inst.fields else {
  9285. unreachable!()
  9286. };
  9287. let sel = match v.src.get(2) {
  9288. Some(&Operand::Literal(x)) => x,
  9289. Some(&Operand::Const(k)) => crate::resource::inline(k).ok_or(name)?,
  9290. _ => {
  9291. // A computed selector: each byte picked at run time.
  9292. let (a, b, sv) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  9293. let mut r = k(self, 0);
  9294. for i in 0..4u32 {
  9295. let (sh, ff) = (k(self, 8 * i), k(self, 0xFF));
  9296. let sel = self.s.m.bin(c, Bin::LShr, sv, sh);
  9297. let sel = self.s.m.bin(c, Bin::And, sel, ff);
  9298. // Select a dword and a byte within it.
  9299. // Later selects handle codes 8 and above.
  9300. let four = k(self, 4);
  9301. let zero = k(self, 0);
  9302. let high = self.s.m.bin(c, Bin::And, sel, four);
  9303. let high = self.s.m.cmp(c, pred::NE, high, zero);
  9304. let word = self.s.m.select(c, high, a, b);
  9305. let three = k(self, 3);
  9306. let index = self.s.m.bin(c, Bin::And, sel, three);
  9307. let bits = self.s.m.bin(c, Bin::Shl, index, three);
  9308. let x = self.s.m.bin(c, Bin::LShr, word, bits);
  9309. let mut byte = self.s.m.bin(c, Bin::And, x, ff);
  9310. // 8-11: the sign of bytes 1, 3 of src1, then of src0.
  9311. for (n, src, bit) in [(8, b, 15), (9, b, 31), (10, a, 15), (11, a, 31)]
  9312. {
  9313. let left = k(self, 31 - bit);
  9314. let t = self.s.m.bin(c, Bin::Shl, src, left);
  9315. let k31 = k(self, 31);
  9316. let t = self.s.m.bin(c, Bin::AShr, t, k31);
  9317. let t = self.s.m.bin(c, Bin::And, t, ff);
  9318. let kn = k(self, n);
  9319. let is = self.s.m.cmp(c, pred::EQ, sel, kn);
  9320. byte = self.s.m.select(c, is, t, byte);
  9321. }
  9322. let (k12, z) = (k(self, 12), k(self, 0));
  9323. let is12 = self.s.m.cmp(c, pred::EQ, sel, k12);
  9324. byte = self.s.m.select(c, is12, z, byte);
  9325. let above = self.s.m.cmp(c, pred::IUGT, sel, k12);
  9326. byte = self.s.m.select(c, above, ff, byte);
  9327. let at = k(self, 8 * i);
  9328. let byte = self.s.m.bin(c, Bin::Shl, byte, at);
  9329. r = self.s.m.bin(c, Bin::Or, r, byte);
  9330. }
  9331. return Ok(r);
  9332. }
  9333. };
  9334. let (a, b) = (s(self, 0)?, s(self, 1)?);
  9335. let mut r = k(self, 0);
  9336. for i in 0..4 {
  9337. let pick = sel >> (8 * i) & 0xFF;
  9338. let byte = match pick {
  9339. 0..=7 => {
  9340. let (src, n) = if pick < 4 { (b, pick) } else { (a, pick - 4) };
  9341. let sh = k(self, 8 * n);
  9342. let t = self.s.m.bin(c, Bin::LShr, src, sh);
  9343. let ff = k(self, 0xFF);
  9344. self.s.m.bin(c, Bin::And, t, ff)
  9345. }
  9346. 8..=11 => {
  9347. let src = if pick < 10 { b } else { a };
  9348. let bit = if pick % 2 == 0 { 15 } else { 31 };
  9349. let left = k(self, 31 - bit);
  9350. let t = self.s.m.bin(c, Bin::Shl, src, left);
  9351. let k31 = k(self, 31);
  9352. let t = self.s.m.bin(c, Bin::AShr, t, k31);
  9353. let ff = k(self, 0xFF);
  9354. self.s.m.bin(c, Bin::And, t, ff)
  9355. }
  9356. 12 => continue,
  9357. _ => k(self, 0xFF),
  9358. };
  9359. let at = k(self, 8 * i);
  9360. let byte = self.s.m.bin(c, Bin::Shl, byte, at);
  9361. r = self.s.m.bin(c, Bin::Or, r, byte);
  9362. }
  9363. r
  9364. }
  9365. "v_bfm_b32" => {
  9366. // ((1 << src0[4:0]) - 1) << src1[4:0]
  9367. let (a, b) = (s(self, 0)?, s(self, 1)?);
  9368. let one = k(self, 1);
  9369. let (a, b) = (m31(self, a), m31(self, b));
  9370. let m = self.s.m.bin(c, Bin::Shl, one, a);
  9371. let m = self.s.m.bin(c, Bin::Sub, m, one);
  9372. self.s.m.bin(c, Bin::Shl, m, b)
  9373. }
  9374. "v_cvt_pk_u8_f32" => {
  9375. // src0 rounded to nearest even and saturated to a byte, into
  9376. // byte src1[1:0] of src2.
  9377. let f = self.fsrc(inst, 0)?;
  9378. let (b, d) = (s(self, 1)?, s(self, 2)?);
  9379. let f = self.unary(26, f);
  9380. let (zero, max) = (self.s.m.f32(0), self.s.m.f32(255.0f32.to_bits()));
  9381. let f = self.binary(35, f, zero);
  9382. let f = self.binary(36, f, max);
  9383. let x = self.s.m.cast(c, Cast::FpToUi, f, self.s.t.i32);
  9384. let (three, k3) = (k(self, 3), k(self, 3));
  9385. let sh = self.s.m.bin(c, Bin::And, b, three);
  9386. let sh = self.s.m.bin(c, Bin::Shl, sh, k3);
  9387. let x = self.s.m.bin(c, Bin::Shl, x, sh);
  9388. let ff = k(self, 0xFF);
  9389. let hole = self.s.m.bin(c, Bin::Shl, ff, sh);
  9390. let ones = k(self, u32::MAX);
  9391. let hole = self.s.m.bin(c, Bin::Xor, hole, ones);
  9392. let d = self.s.m.bin(c, Bin::And, d, hole);
  9393. self.s.m.bin(c, Bin::Or, d, x)
  9394. }
  9395. "v_ffbl_b32" => {
  9396. // -1 for zero, as DXIL's first-bit-low.
  9397. let a = s(self, 0)?;
  9398. self.s
  9399. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 32, &[a])
  9400. }
  9401. "v_mbcnt_lo_u32_b32" | "v_mbcnt_hi_u32_b32" => {
  9402. // Bits of the mask's low (high) half below this lane, plus src1:
  9403. // with an all-ones mask, the lane index.
  9404. let (a, b) = (s(self, 0)?, s(self, 1)?);
  9405. // Mesh lanes are the console's by construction; pixel and
  9406. // vertex lanes are the host's, as their masks are.
  9407. if self.mask_data == MaskData::Host {
  9408. // Host lanes: the mask must be one (a ballot) or all lanes.
  9409. let Fields::Valu(v) = &inst.fields else {
  9410. unreachable!()
  9411. };
  9412. let host = match v.src.first() {
  9413. Some(&Operand::Const(193)) => true,
  9414. Some(&Operand::Scalar { code, .. }) => {
  9415. inst.read(Reg::S(code)).is_some_and(|m| {
  9416. self.x.st.masks.contains_key(&m) || self.x.st.highs.contains_key(&m)
  9417. })
  9418. }
  9419. _ => false,
  9420. };
  9421. if !host {
  9422. return Err("v_mbcnt of a mask that is no ballot (console lane layout)");
  9423. }
  9424. self.s.flags |= flags::WAVE_OPS;
  9425. } else if self.s.mesh.is_none() {
  9426. self.cross_lane(false)?;
  9427. }
  9428. let lane = self.console_lane();
  9429. let below = if name == "v_mbcnt_lo_u32_b32" {
  9430. lane
  9431. } else {
  9432. let (k32, z) = (k(self, 32), k(self, 0));
  9433. let t = self.s.m.bin(c, Bin::Sub, lane, k32);
  9434. let low = self.s.m.cmp(c, pred::IULT, lane, k32);
  9435. self.s.m.select(c, low, z, t)
  9436. };
  9437. // (1 << below) - 1, all ones from 32 on.
  9438. let (one, k32, ones) = (k(self, 1), k(self, 32), k(self, u32::MAX));
  9439. let sh = m31(self, below);
  9440. let m = self.s.m.bin(c, Bin::Shl, one, sh);
  9441. let m = self.s.m.bin(c, Bin::Sub, m, one);
  9442. let full = self.s.m.cmp(c, pred::IUGE, below, k32);
  9443. let m = self.s.m.select(c, full, ones, m);
  9444. let x = self.s.m.bin(c, Bin::And, a, m);
  9445. let n = self
  9446. .s
  9447. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 31, &[x]);
  9448. self.s.m.bin(c, Bin::Add, n, b)
  9449. }
  9450. _ => return Err(name),
  9451. })
  9452. }
  9453. fn compare(&mut self, inst: &Inst, rest: &str) -> Result<(), Why> {
  9454. let (op, ty) = rest.rsplit_once('_').ok_or("a compare")?;
  9455. let c = self.cur;
  9456. let r = match ty {
  9457. "f32" | "f16" if op == "class" => {
  9458. // Bit k of src1 tests class k: signalling NaN, quiet NaN,
  9459. // -inf, -normal, -denormal, -0, +0, +denormal, +normal, +inf.
  9460. let f16 = ty == "f16";
  9461. let x = if f16 {
  9462. let Fields::Valu(v) = &inst.fields else {
  9463. unreachable!()
  9464. };
  9465. let mut h = self.half_src(inst, 0)?;
  9466. if v.abs & 1 != 0 {
  9467. let m = self.s.m.i32(0x7FFF);
  9468. h = self.s.m.bin(c, Bin::And, h, m);
  9469. }
  9470. if v.neg & 1 != 0 {
  9471. let s = self.s.m.i32(0x8000);
  9472. h = self.s.m.bin(c, Bin::Xor, h, s);
  9473. }
  9474. h
  9475. } else {
  9476. let x = self.fsrc(inst, 0)?;
  9477. self.as_int(x)
  9478. };
  9479. let mask = self.src(inst, 1)?;
  9480. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  9481. let (exp_sh, sign_sh, exp_mask, mant_mask, quiet_bit) = if f16 {
  9482. (10, 15, 0x1F, 0x03FF, 0x0200)
  9483. } else {
  9484. (23, 31, 0xFF, 0x7F_FFFF, 0x40_0000)
  9485. };
  9486. let (k_exp, k_sign, k_emax, mant, quiet) = (
  9487. k(self, exp_sh),
  9488. k(self, sign_sh),
  9489. k(self, exp_mask),
  9490. k(self, mant_mask),
  9491. k(self, quiet_bit),
  9492. );
  9493. let e = self.s.m.bin(c, Bin::LShr, x, k_exp);
  9494. let e = self.s.m.bin(c, Bin::And, e, k_emax);
  9495. let m = self.s.m.bin(c, Bin::And, x, mant);
  9496. let neg = self.s.m.bin(c, Bin::LShr, x, k_sign);
  9497. let zero = k(self, 0);
  9498. let (e0, emax) = (
  9499. self.s.m.cmp(c, pred::EQ, e, zero),
  9500. self.s.m.cmp(c, pred::EQ, e, k_emax),
  9501. );
  9502. let m0 = self.s.m.cmp(c, pred::EQ, m, zero);
  9503. let q = self.s.m.bin(c, Bin::And, x, quiet);
  9504. let q = self.s.m.cmp(c, pred::NE, q, zero);
  9505. // Positive classes 6-9; negative ones are 11 minus those.
  9506. let (normal, inf, zero_c, denorm) =
  9507. (k(self, 8), k(self, 9), k(self, 6), k(self, 7));
  9508. let t = self.s.m.select(c, m0, zero_c, denorm);
  9509. let t = self.s.m.select(c, e0, t, normal);
  9510. let t = self.s.m.select(c, emax, inf, t);
  9511. let eleven = k(self, 11);
  9512. let mirrored = self.s.m.bin(c, Bin::Sub, eleven, t);
  9513. let is_neg = self.s.m.cmp(c, pred::NE, neg, zero);
  9514. let t = self.s.m.select(c, is_neg, mirrored, t);
  9515. let (one, snan) = (k(self, 1), k(self, 0));
  9516. let nan_class = self.s.m.select(c, q, one, snan);
  9517. let yes = self.s.m.bool(true);
  9518. let nan = self.s.m.bin(c, Bin::Xor, m0, yes);
  9519. let nan = self.s.m.bin(c, Bin::And, nan, emax);
  9520. let t = self.s.m.select(c, nan, nan_class, t);
  9521. let bit = self.s.m.bin(c, Bin::LShr, mask, t);
  9522. let bit = self.s.m.bin(c, Bin::And, bit, one);
  9523. self.s.m.cmp(c, pred::NE, bit, zero)
  9524. }
  9525. "f32" | "f16" => {
  9526. let (a, b) = if ty == "f16" {
  9527. (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?)
  9528. } else {
  9529. (self.fsrc(inst, 0)?, self.fsrc(inst, 1)?)
  9530. };
  9531. if op == "lg" {
  9532. // Ordered and not equal, false for a NaN, as `olt | ogt`.
  9533. // `fcmp one` means the same, but the AMD D3D12 driver
  9534. // runs it as unordered (true for a NaN) where NVIDIA
  9535. // and WARP do not; olt and ogt agree on all three.
  9536. let lt = self.s.m.cmp(c, pred::OLT, a, b);
  9537. let gt = self.s.m.cmp(c, pred::OGT, a, b);
  9538. self.s.m.bin(c, Bin::Or, lt, gt)
  9539. } else {
  9540. let p = match op {
  9541. "f" => pred::FALSE,
  9542. "lt" => pred::OLT,
  9543. "eq" => pred::OEQ,
  9544. "le" => pred::OLE,
  9545. "gt" => pred::OGT,
  9546. "ge" => pred::OGE,
  9547. "o" => pred::ORD,
  9548. "u" => pred::UNO,
  9549. "nge" => pred::ULT,
  9550. "nlg" => pred::UEQ,
  9551. "ngt" => pred::ULE,
  9552. "nle" => pred::UGT,
  9553. "neq" => pred::UNE,
  9554. "nlt" => pred::UGE,
  9555. "tru" => pred::TRUE,
  9556. _ => return Err(inst.name()),
  9557. };
  9558. self.s.m.cmp(c, p, a, b)
  9559. }
  9560. }
  9561. "u64" | "i64" => {
  9562. let (a, b) = (self.src64(inst, 0)?, self.src64(inst, 1)?);
  9563. let signed = ty == "i64";
  9564. let p = match op {
  9565. "eq" => pred::EQ,
  9566. "ne" | "lg" => pred::NE,
  9567. "lt" if signed => pred::SLT,
  9568. "le" if signed => pred::SLE,
  9569. "gt" if signed => pred::SGT,
  9570. "ge" if signed => pred::SGE,
  9571. "lt" => pred::IULT,
  9572. "le" => pred::IULE,
  9573. "gt" => pred::IUGT,
  9574. "ge" => pred::IUGE,
  9575. _ => return Err("a 64-bit compare"),
  9576. };
  9577. self.s.m.cmp(c, p, a, b)
  9578. }
  9579. "u32" | "i32" | "u16" | "i16" => {
  9580. let (a, b) = if ty.ends_with("16") {
  9581. let (mut a, mut b) = (self.half_src(inst, 0)?, self.half_src(inst, 1)?);
  9582. if ty == "i16" {
  9583. let k16 = self.s.m.i32(16);
  9584. for x in [&mut a, &mut b] {
  9585. let t = self.s.m.bin(c, Bin::Shl, *x, k16);
  9586. *x = self.s.m.bin(c, Bin::AShr, t, k16);
  9587. }
  9588. }
  9589. (a, b)
  9590. } else {
  9591. (self.src(inst, 0)?, self.src(inst, 1)?)
  9592. };
  9593. let signed = ty == "i32" || ty == "i16";
  9594. let p = match op {
  9595. "eq" => pred::EQ,
  9596. "ne" | "lg" => pred::NE,
  9597. "lt" if signed => pred::SLT,
  9598. "le" if signed => pred::SLE,
  9599. "gt" if signed => pred::SGT,
  9600. "ge" if signed => pred::SGE,
  9601. "lt" => pred::IULT,
  9602. "le" => pred::IULE,
  9603. "gt" => pred::IUGT,
  9604. "ge" => pred::IUGE,
  9605. "f" | "t" => {
  9606. self.lane(inst, Some(op == "t"));
  9607. return Ok(());
  9608. }
  9609. _ => return Err("an integer compare"),
  9610. };
  9611. self.s.m.cmp(c, p, a, b)
  9612. }
  9613. _ => return Err(inst.name()),
  9614. };
  9615. self.lane_bits_for(inst, r);
  9616. Ok(())
  9617. }
  9618. fn lane(&mut self, inst: &Inst, value: Option<bool>) {
  9619. let b = self.s.m.bool(value == Some(true));
  9620. self.lane_bits_for(inst, b);
  9621. }
  9622. fn lane_bits_for(&mut self, inst: &Inst, r: V) {
  9623. let Fields::Valu(v) = &inst.fields else {
  9624. return;
  9625. };
  9626. let code = if inst.name().starts_with("v_cmpx") {
  9627. Some(EXEC)
  9628. } else {
  9629. match v.dst {
  9630. Some(Operand::Scalar { code, .. }) => Some(code),
  9631. _ => None,
  9632. }
  9633. };
  9634. if let Some(lo) = code.and_then(|c| inst.write(Reg::S(c))) {
  9635. self.lane_bits.insert(lo, r);
  9636. }
  9637. for &(_, w) in &inst.writes {
  9638. self.vals
  9639. .entry(w)
  9640. .or_insert(Val::Missing("a lane mask read as data"));
  9641. }
  9642. }
  9643. fn interp(&mut self, inst: &Inst, site: Site) -> Result<(), Why> {
  9644. let Some(&interp) = self.interps.get(&site) else {
  9645. // The first half of a pair: its second half interpolates the
  9646. // attribute itself, so nothing needs this half's partial sum.
  9647. // But an f16 second half that writes the high half of the
  9648. // register this one wrote keeps the low half as it was (the
  9649. // console compiler reuses the register; the low half is not
  9650. // read), so the register needs a value: 0.
  9651. let name = inst.name();
  9652. if name == "v_interp_p1_f32" || name == "v_interp_p1ll_f16" {
  9653. let dst = match &inst.fields {
  9654. Fields::Vintrp { dst, .. } => Some(*dst),
  9655. Fields::Valu(v) => v.dst,
  9656. _ => None,
  9657. };
  9658. if let Some(Operand::Vector { reg, .. }) = dst {
  9659. let zero = self.s.m.i32(0);
  9660. self.write(inst, Reg::V(reg), zero, None);
  9661. return Ok(());
  9662. }
  9663. }
  9664. return Err(FIRST_HALF);
  9665. };
  9666. let name = inst.name();
  9667. let (dst, src) = match &inst.fields {
  9668. Fields::Vintrp { dst, src, .. } => (*dst, Some(*src)),
  9669. Fields::Valu(v) => {
  9670. if v.abs != 0 || v.neg != 0 {
  9671. return Err("interpolation operand modifiers");
  9672. }
  9673. (v.dst.ok_or("an interpolation")?, v.src.get(1).copied())
  9674. }
  9675. _ => unreachable!(),
  9676. };
  9677. let Operand::Vector { reg, .. } = dst else {
  9678. return Err("an interpolation");
  9679. };
  9680. // A float operand of the instruction.
  9681. let float = |l: &mut Self, op: Option<Operand>| -> Result<V, Why> {
  9682. let x = l.operand(inst, &op.ok_or("an interpolation operand")?)?;
  9683. Ok(l.as_float(x))
  9684. };
  9685. // What the result adds to the evaluated channel (a second half's
  9686. // first half, when the halves evaluate on their own).
  9687. let mut add = None;
  9688. let (attribute, eval) = match *interp {
  9689. Interp::Interpolated {
  9690. attribute,
  9691. barycentric,
  9692. ..
  9693. } => {
  9694. let mode = interp_mode(barycentric).ok_or("pull-model interpolation")?;
  9695. let eval = if self.per_vertex(attribute.row) {
  9696. // The element is read per vertex elsewhere, so it is
  9697. // constant: weigh its vertices with SV_Barycentrics.
  9698. let mut ij = [None; 2];
  9699. for (index, w) in ij.iter_mut().enumerate() {
  9700. let x = match self.barycentric(barycentric, index as u8) {
  9701. Val::I32(x) => x,
  9702. Val::Missing(w) => return Err(w),
  9703. Val::Bit(_) => unreachable!(),
  9704. };
  9705. *w = Some(self.as_float(x));
  9706. }
  9707. Eval::Weights {
  9708. p0: true,
  9709. i: ij[0],
  9710. j: ij[1],
  9711. }
  9712. } else {
  9713. Eval::Mode(mode)
  9714. };
  9715. (attribute, eval)
  9716. }
  9717. // P0, the provoking vertex: a flat (nointerpolation) input.
  9718. Interp::Vertex {
  9719. attribute,
  9720. vertex: 2,
  9721. } => (attribute, Eval::Mode(1)),
  9722. // P10 and P20: what the first and second halves weigh, P1 - P0
  9723. // and P2 - P0, which is what the hardware holds for an
  9724. // attribute the program also interpolates.
  9725. Interp::Vertex { attribute, vertex } if self.interpolated(attribute.row) => {
  9726. let one = Some(self.s.m.f32(1f32.to_bits()));
  9727. let (i, j) = if vertex == 0 {
  9728. (one, None)
  9729. } else {
  9730. (None, one)
  9731. };
  9732. (attribute, Eval::Weights { p0: false, i, j })
  9733. }
  9734. Interp::Vertex { .. } => return Err("a non-provoking vertex value"),
  9735. // A half of an interpolation with computed i or j: P0 + i P10,
  9736. // or the old dst (f16: the third operand) + j P20.
  9737. Interp::Weighted { attribute } if name.starts_with("v_interp_p1") => {
  9738. let i = Some(float(self, src)?);
  9739. (
  9740. attribute,
  9741. Eval::Weights {
  9742. p0: true,
  9743. i,
  9744. j: None,
  9745. },
  9746. )
  9747. }
  9748. Interp::Weighted { attribute } => {
  9749. let old = match &inst.fields {
  9750. Fields::Valu(v) => v.src.get(2).copied(),
  9751. _ => Some(dst),
  9752. };
  9753. add = Some(float(self, old)?);
  9754. let j = Some(float(self, src)?);
  9755. (
  9756. attribute,
  9757. Eval::Weights {
  9758. p0: false,
  9759. i: None,
  9760. j,
  9761. },
  9762. )
  9763. }
  9764. };
  9765. let packing = match &self.x.native.io {
  9766. StageIo::Ps { inputs, .. } => inputs
  9767. .iter()
  9768. .find(|i| i.row == attribute.row && i.fp16)
  9769. .map(|i| {
  9770. let packs = if i.pack2 {
  9771. input_packs(&self.x.native.io, &self.s.inputs)
  9772. } else {
  9773. Vec::new()
  9774. };
  9775. (i.pack2, packs)
  9776. }),
  9777. _ => None,
  9778. };
  9779. let f16 = name.ends_with("_f16");
  9780. // The evaluated channel plus `add`, as a float.
  9781. let total = |l: &mut Self, row: u8, ch: u8| -> Result<V, Why> {
  9782. let x = l.eval_channel(row, ch, eval)?;
  9783. let x = l.as_float(x);
  9784. Ok(match add {
  9785. Some(a) => l.s.m.bin(l.cur, Bin::Add, a, x),
  9786. None => x,
  9787. })
  9788. };
  9789. let x = match packing {
  9790. None if f16 || attribute.high => return Err("a 16-bit read of a 32-bit input"),
  9791. None => {
  9792. let x = total(self, attribute.row, attribute.channel)?;
  9793. self.as_int(x)
  9794. }
  9795. Some((pack2, packs)) => {
  9796. // 16-bit values: one in the low half of each dword, or two
  9797. // per dword (`packed_half`); the host's are 32-bit floats.
  9798. let half = |l: &mut Self, h: u8| -> Result<Option<V>, Why> {
  9799. let src = if pack2 {
  9800. packed_half(&l.s.inputs, &packs, attribute.row, h)
  9801. } else {
  9802. h.is_multiple_of(2).then_some((attribute.row, h / 2))
  9803. };
  9804. match src {
  9805. Some((row, ch)) => total(l, row, ch).map(Some),
  9806. None => Ok(None),
  9807. }
  9808. };
  9809. let to_f16 = |l: &mut Self, f: V| {
  9810. let i32t = l.s.t.i32;
  9811. l.s.op(l.cur, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f])
  9812. };
  9813. let h = 2 * attribute.channel + u8::from(attribute.high);
  9814. let c = self.cur;
  9815. if name == "v_interp_p1ll_f16" {
  9816. // An f32 result from 16-bit vertex values.
  9817. let f = half(self, h)?.ok_or("a packed input half no element holds")?;
  9818. self.as_int(f)
  9819. } else if f16 {
  9820. let mut f = half(self, h)?.ok_or("a packed input half no element holds")?;
  9821. if let Fields::Valu(v) = &inst.fields {
  9822. // omod, then clamp, before the one rounding to 16 bits; op_sel[3]
  9823. // picks the destination half (VIctory e29391f: the low half was
  9824. // always written, the high one's value never arrived).
  9825. let (omod, clamp) = (v.omod, v.clamp);
  9826. if omod != 0 {
  9827. let factor = [1.0f32, 2.0, 4.0, 0.5][usize::from(omod)];
  9828. let k = self.s.m.f32(factor.to_bits());
  9829. f = self.s.m.bin(c, Bin::Mul, f, k);
  9830. }
  9831. if clamp {
  9832. f = self.unary(7, f);
  9833. }
  9834. let lo = to_f16(self, f);
  9835. return self.write_half(inst, lo, None);
  9836. }
  9837. let lo = to_f16(self, f);
  9838. self.low_half(inst, reg, lo)
  9839. } else if matches!(eval, Eval::Mode(1)) {
  9840. // The whole dword of a flat input: both halves.
  9841. let h = 2 * attribute.channel;
  9842. let z = self.s.m.i32(0);
  9843. let lo = match half(self, h)? {
  9844. Some(f) => to_f16(self, f),
  9845. None => z,
  9846. };
  9847. let hi = match half(self, h + 1)? {
  9848. Some(f) => to_f16(self, f),
  9849. None => z,
  9850. };
  9851. let k16 = self.s.m.i32(16);
  9852. let hi = self.s.m.bin(c, Bin::Shl, hi, k16);
  9853. self.s.m.bin(c, Bin::Or, lo, hi)
  9854. } else {
  9855. return Err("32-bit interpolation of a 16-bit input");
  9856. }
  9857. }
  9858. };
  9859. // A pixel interpolates in every lane; guards only hide inactive ones.
  9860. self.write(inst, Reg::V(reg), x, None);
  9861. Ok(())
  9862. }
  9863. /// Whether the program reads attribute row `row` per vertex (an
  9864. /// interpolation with computed barycentrics, or P10 or P20): then its
  9865. /// element is declared constant and read with `attributeAtVertex`.
  9866. fn per_vertex(&self, row: u8) -> bool {
  9867. self.x.io.interps.iter().any(|(_, i)| match *i {
  9868. Interp::Weighted { attribute } => attribute.row == row,
  9869. Interp::Vertex { attribute, vertex } => {
  9870. attribute.row == row && vertex != 2 && self.interpolated(row)
  9871. }
  9872. Interp::Interpolated { .. } => false,
  9873. })
  9874. }
  9875. /// Whether the program interpolates attribute row `row` (so the
  9876. /// hardware holds P1 - P0 and P2 - P0 for it).
  9877. fn interpolated(&self, row: u8) -> bool {
  9878. self.x.io.interps.iter().any(|(_, i)| match *i {
  9879. Interp::Interpolated { attribute, .. } | Interp::Weighted { attribute } => {
  9880. attribute.row == row
  9881. }
  9882. Interp::Vertex { .. } => false,
  9883. })
  9884. }
  9885. /// Channel `ch` of input row `row` evaluated as `eval` says, as raw bits.
  9886. fn eval_channel(&mut self, row: u8, ch: u8, eval: Eval) -> Result<V, Why> {
  9887. let (id, col) = self
  9888. .find_input(row, ch)
  9889. .ok_or("an input the signature lacks")?;
  9890. let mode = match eval {
  9891. Eval::Mode(mode) => mode,
  9892. Eval::Weights { .. } => 1,
  9893. };
  9894. let e = &mut self.s.inputs[id];
  9895. if e.interp != mode && e.usage != 0 {
  9896. return Err("one input interpolated two ways");
  9897. }
  9898. e.interp = mode;
  9899. let Eval::Weights { p0, i, j } = eval else {
  9900. return match self.load_any_input(id, col) {
  9901. Val::I32(x) => Ok(x),
  9902. _ => Err("an input"),
  9903. };
  9904. };
  9905. let v0 = self.vertex_input(id, col, 0);
  9906. let c = self.cur;
  9907. let mut acc = p0.then_some(v0);
  9908. for (k, w) in [(1, i), (2, j)] {
  9909. let Some(w) = w else { continue };
  9910. let vk = self.vertex_input(id, col, k);
  9911. let d = self.s.m.bin(c, Bin::Sub, vk, v0);
  9912. acc = Some(match acc {
  9913. Some(a) => self.fmad(w, d, a),
  9914. None => self.s.m.bin(c, Bin::Mul, w, d),
  9915. });
  9916. }
  9917. let acc = acc.ok_or("an interpolation")?;
  9918. Ok(self.as_int(acc))
  9919. }
  9920. /// Vertex `k` (0 the provoking vertex, as `barycentric` orders them)
  9921. /// of a constant input element's channel, as a float.
  9922. fn vertex_input(&mut self, id: usize, col: u8, k: u8) -> V {
  9923. let e = &mut self.s.inputs[id];
  9924. e.usage |= 1 << col;
  9925. let int = e.comp != 9;
  9926. let (ty, suffix) = if int {
  9927. (self.s.t.i32, ".i32")
  9928. } else {
  9929. (self.s.t.f32, ".f32")
  9930. };
  9931. self.s.flags |= flags::BARYCENTRICS;
  9932. let entry = self.s.entry;
  9933. let args = [
  9934. self.s.m.i32(id as u32),
  9935. self.s.m.i32(0),
  9936. self.s.m.i8(col),
  9937. self.s.m.i8(k),
  9938. ];
  9939. let v = self.s.op(
  9940. entry,
  9941. &format!("attributeAtVertex{suffix}"),
  9942. Attr::ReadNone,
  9943. ty,
  9944. 137,
  9945. &args,
  9946. );
  9947. if int {
  9948. self.s.m.cast(entry, Cast::Bitcast, v, self.s.t.f32)
  9949. } else {
  9950. v
  9951. }
  9952. }
  9953. /// `x` (an f16 in the low bits) as the low half of VGPR `reg`: 16-bit
  9954. /// results keep the register's high half (GFX10).
  9955. fn low_half(&mut self, inst: &Inst, reg: u8, x: V) -> V {
  9956. let c = self.cur;
  9957. let old = match inst.read(Reg::V(reg)).map(|o| self.i32_of(o)) {
  9958. Some(Ok(o)) => o,
  9959. _ => self.s.m.i32(0),
  9960. };
  9961. let (high, low) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF));
  9962. let old = self.s.m.bin(c, Bin::And, old, high);
  9963. let x = self.s.m.bin(c, Bin::And, x, low);
  9964. self.s.m.bin(c, Bin::Or, old, x)
  9965. }
  9966. fn image(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  9967. let Fields::Image {
  9968. data,
  9969. addr,
  9970. dmask,
  9971. dim,
  9972. unorm,
  9973. a16,
  9974. d16,
  9975. tfe,
  9976. lwe,
  9977. ..
  9978. } = &inst.fields
  9979. else {
  9980. unreachable!()
  9981. };
  9982. if *tfe || *lwe {
  9983. return Err("an image access with tfe or lwe");
  9984. }
  9985. let name = inst.name();
  9986. // A load or sample with no channel enabled returns the first.
  9987. let dmask = if *dmask == 0 { &1 } else { dmask };
  9988. let site = (b, i);
  9989. let guard = self.guard(b, i)?;
  9990. let c = self.cur;
  9991. let (kind, coords) = match dim {
  9992. 0 => (1, 1),
  9993. 1 => (2, 2),
  9994. 2 => (4, 3),
  9995. // Sampled (face coordinates and face, see `cube_direction`) or
  9996. // sized only.
  9997. 3 if name.starts_with("image_sample")
  9998. || name.starts_with("image_gather")
  9999. || name == "image_get_resinfo" =>
  10000. {
  10001. (5, 3)
  10002. }
  10003. 4 => (6, 2),
  10004. 5 => (7, 3),
  10005. _ => return Err("an image dimension (cube loads or MSAA)"),
  10006. };
  10007. // Address VGPRs in order.
  10008. let mut regs = Vec::new();
  10009. for a in addr {
  10010. if let Operand::Vector { reg, dwords } = *a {
  10011. regs.extend((0..dwords).map(|k| reg + k));
  10012. }
  10013. }
  10014. // Full 32-bit address VGPR at `reg_idx` (offset, bias, z-compare).
  10015. let addr_u32 = |l: &mut Self, reg_idx: usize| -> Result<V, Why> {
  10016. let r = *regs.get(reg_idx).ok_or("an image address")?;
  10017. let v = inst.read(Reg::V(r)).ok_or("an image address")?;
  10018. l.i32_of(v)
  10019. };
  10020. // With a16, two 16-bit components per VGPR starting at `base_reg`, low half first.
  10021. let addr_packed = |l: &mut Self, base_reg: usize, k: usize| -> Result<V, Why> {
  10022. let x = addr_u32(l, base_reg + if *a16 { k / 2 } else { k })?;
  10023. if !*a16 {
  10024. return Ok(x);
  10025. }
  10026. let c = l.cur;
  10027. let (sh, mask) = (l.s.m.i32(16 * (k as u32 % 2)), l.s.m.i32(0xFFFF));
  10028. let x = l.s.m.bin(c, Bin::LShr, x, sh);
  10029. Ok(l.s.m.bin(c, Bin::And, x, mask))
  10030. };
  10031. let addr_val = |l: &mut Self, k: usize| -> Result<V, Why> { addr_packed(l, 0, k) };
  10032. let src = self
  10033. .descriptors
  10034. .get(&(site, false))
  10035. .copied()
  10036. .ok_or("an untracked image")?;
  10037. let store = name.starts_with("image_store");
  10038. let uav = store
  10039. || self
  10040. .used_kind(src)
  10041. .is_some_and(|u| u.kind == ResourceType::Uav);
  10042. // A UAV inside an ordered section is a rasterizer ordered view.
  10043. let ordered = uav && self.ordered.contains(&site);
  10044. if ordered {
  10045. self.s.flags |= flags::ROVS;
  10046. }
  10047. let rov = if ordered { 0x2000 } else { 0 };
  10048. let props = (kind | if uav { 0x1000 } else { 0 } | rov, 0x409);
  10049. if let Some(op) = name.strip_prefix("image_atomic_") {
  10050. // GLC returns the old value. DXIL implements subtraction by adding
  10051. // the two's complement of the operand at the same width.
  10052. let code = match op {
  10053. "add" | "sub" => 0,
  10054. "and" => 1,
  10055. "or" => 2,
  10056. "xor" => 3,
  10057. "smin" => 4,
  10058. "smax" => 5,
  10059. "umin" => 6,
  10060. "umax" => 7,
  10061. "swap" => 8,
  10062. "cmpswap" => u32::MAX,
  10063. _ => return Err(name),
  10064. };
  10065. let Fields::Image { cache, .. } = &inst.fields else {
  10066. unreachable!()
  10067. };
  10068. // 16-bit coordinates (a16) are read as `addr_val` reads them.
  10069. if *d16 {
  10070. return Err("a 16-bit image atomic");
  10071. }
  10072. // Compare-exchange consumes a replacement followed by a comparand.
  10073. let compare = code == u32::MAX;
  10074. let wide = match (compare, *dmask) {
  10075. (false, 1) | (true, 3) => false,
  10076. (false, 3) | (true, 15) => true,
  10077. _ => return Err("an image atomic data mask"),
  10078. };
  10079. let iu = self.s.m.undef(self.s.t.i32);
  10080. let mut cs = vec![iu; 3];
  10081. for (k, slot) in cs.iter_mut().enumerate().take(coords) {
  10082. *slot = addr_val(self, k)?;
  10083. }
  10084. let Operand::Vector { reg, .. } = *data else {
  10085. return Err("image atomic data");
  10086. };
  10087. let width = if wide { 2 } else { 1 };
  10088. let vals = self.vgprs(inst, data, if compare { 2 * width } else { width })?;
  10089. let (ty, component) = if wide {
  10090. self.s.flags |= flags::INT64 | flags::ATOMIC_TYPED64 | flags::ATOMIC_HEAP64;
  10091. (self.s.m.int(64), 0x107) // one uint64_t in an R32G32_UINT view
  10092. } else {
  10093. (self.s.t.i32, 0x105)
  10094. };
  10095. let original = if wide {
  10096. self.join64(vals[0], vals[1])
  10097. } else {
  10098. vals[0]
  10099. };
  10100. let value = if op == "sub" {
  10101. let zero = self.s.m.int_const(ty, 0);
  10102. self.s.m.bin(c, Bin::Sub, zero, original)
  10103. } else {
  10104. original
  10105. };
  10106. let h = self.handle(site, src, false, (kind | 0x1000 | rov, component))?;
  10107. let mut args = vec![h];
  10108. let (intrinsic, opcode) = if compare {
  10109. let comparand = if wide {
  10110. self.join64(vals[2], vals[3])
  10111. } else {
  10112. vals[1]
  10113. };
  10114. args.extend(cs);
  10115. args.extend([comparand, value]);
  10116. let intrinsic = if wide {
  10117. "atomicCompareExchange.i64"
  10118. } else {
  10119. "atomicCompareExchange.i32"
  10120. };
  10121. (intrinsic, 79)
  10122. } else {
  10123. args.push(self.s.m.i32(code));
  10124. args.extend(cs);
  10125. args.push(value);
  10126. (
  10127. if wide {
  10128. "atomicBinOp.i64"
  10129. } else {
  10130. "atomicBinOp.i32"
  10131. },
  10132. 78,
  10133. )
  10134. };
  10135. let at = self.begin_guarded(guard);
  10136. let r = self
  10137. .s
  10138. .op(self.cur, intrinsic, Attr::NoUnwind, ty, opcode, &args);
  10139. if cache.glc {
  10140. let old = self.end_guarded(at, &[(r, original)])[0];
  10141. if wide {
  10142. let (lo, hi) = self.split64(old);
  10143. self.write(inst, Reg::V(reg), lo, None);
  10144. self.write(inst, Reg::V(reg + 1), hi, None);
  10145. } else {
  10146. self.write(inst, Reg::V(reg), old, None);
  10147. }
  10148. } else {
  10149. self.end_guarded(at, &[]);
  10150. }
  10151. return Ok(());
  10152. }
  10153. if store {
  10154. if name != "image_store" {
  10155. return Err("an image store to a mip level");
  10156. }
  10157. // shortcut: stores are taken to write all four channels of a
  10158. // float format (the console converts by the view's format).
  10159. // One channel goes into a view the program also counts in.
  10160. let counter = *dmask == 1 && self.is_counter(src);
  10161. if *dmask != 0xF && !counter {
  10162. return Err("an image store of some channels");
  10163. }
  10164. let iu = self.s.m.undef(self.s.t.i32);
  10165. let mut cs = vec![iu; 3];
  10166. for (k, slot) in cs.iter_mut().enumerate().take(coords) {
  10167. *slot = addr_val(self, k)?;
  10168. }
  10169. let Operand::Vector { reg, .. } = *data else {
  10170. return Err("image store data");
  10171. };
  10172. if counter {
  10173. let v = inst.read(Reg::V(reg)).ok_or("image store data")?;
  10174. let x = self.i32_of(v)?;
  10175. // A 16-bit integer, extended by the view's sign: the same
  10176. // number either way only if it is known to be small.
  10177. if *d16 && !self.s.m.int_k(x).is_some_and(|(_, k)| k < 0x8000) {
  10178. return Err("a 16-bit image store of one channel");
  10179. }
  10180. let h = self.handle(site, src, false, (kind | 0x1000 | rov, 0x105))?;
  10181. let at = self.begin_guarded(guard);
  10182. // All four channels are written (the validator wants them
  10183. // all): the view has the first alone.
  10184. let mut args = vec![h];
  10185. args.extend(cs);
  10186. args.extend([x; 4]);
  10187. args.push(self.s.m.i8(0xF));
  10188. let void = self.s.t.void;
  10189. self.s.op(
  10190. self.cur,
  10191. "textureStore.i32",
  10192. Attr::NoUnwind,
  10193. void,
  10194. 67,
  10195. &args,
  10196. );
  10197. self.end_guarded(at, &[]);
  10198. return Ok(());
  10199. }
  10200. let mut vals = Vec::new();
  10201. for k in 0..4u8 {
  10202. // d16: two f16 channels per VGPR, low half first.
  10203. let r = if *d16 { k / 2 } else { k };
  10204. let v = inst.read(Reg::V(reg + r)).ok_or("image store data")?;
  10205. vals.push(if *d16 {
  10206. let mut x = self.i32_of(v)?;
  10207. if k % 2 == 1 {
  10208. let k16 = self.s.m.i32(16);
  10209. x = self.s.m.bin(self.cur, Bin::LShr, x, k16);
  10210. }
  10211. let f32t = self.s.t.f32;
  10212. self.s
  10213. .op(self.cur, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x])
  10214. } else {
  10215. self.float_of(v)?
  10216. });
  10217. }
  10218. let h = self.handle(site, src, false, props)?;
  10219. let at = self.begin_guarded(guard);
  10220. let mut args = vec![h];
  10221. args.extend(cs);
  10222. args.extend(vals);
  10223. args.push(self.s.m.i8(0xF));
  10224. let void = self.s.t.void;
  10225. self.s.op(
  10226. self.cur,
  10227. "textureStore.f32",
  10228. Attr::NoUnwind,
  10229. void,
  10230. 67,
  10231. &args,
  10232. );
  10233. self.end_guarded(at, &[]);
  10234. return Ok(());
  10235. }
  10236. let has_cl = name.ends_with("_cl");
  10237. let (op, sample) = match name {
  10238. "image_sample" | "image_sample_o" | "image_sample_cl" => (60, true),
  10239. "image_sample_lz" | "image_sample_l" | "image_sample_lz_o" => (62, true),
  10240. "image_sample_b" | "image_sample_b_cl" => (61, true),
  10241. "image_sample_c_lz" => (65, true),
  10242. "image_sample_d" | "image_sample_d_cl" => (63, true),
  10243. "image_get_lod" if self.s.pixel => (81, true),
  10244. // Implicit derivatives: pixel shaders only.
  10245. "image_sample_c" if self.s.pixel => (64, true),
  10246. "image_sample_c_cl" if self.s.pixel => (64, true),
  10247. "image_gather4" | "image_gather4_lz" | "image_gather4_lz_o" | "image_gather4_l" | "image_gather4_l_o" => (73, true),
  10248. "image_load" | "image_load_mip" => (66, false),
  10249. "image_get_resinfo" => (72, false),
  10250. _ => return Err(name),
  10251. };
  10252. if op == 72 {
  10253. // Width, height, depth or layers, levels (per dmask) of the level
  10254. // in the first address: DXIL's dimensions; a channel DXIL leaves
  10255. // out reads 1 (UAVs: one level).
  10256. let h = self.handle(site, src, false, props)?;
  10257. let mip = if uav {
  10258. self.s.m.undef(self.s.t.i32)
  10259. } else {
  10260. addr_val(self, 0)?
  10261. };
  10262. let i32t = self.s.t.i32;
  10263. let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
  10264. let d = self
  10265. .s
  10266. .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]);
  10267. let one = self.s.m.i32(1);
  10268. let present = match kind {
  10269. 1 => [true, false, false, true],
  10270. 2 | 5 | 6 => [true, true, false, true],
  10271. _ => [true, true, true, true],
  10272. };
  10273. let Operand::Vector { reg, .. } = *data else {
  10274. return Err("an image result");
  10275. };
  10276. for (k, ch) in (0..4u32).filter(|ch| dmask >> ch & 1 != 0).enumerate() {
  10277. let x = if ch == 3 && uav || !present[ch as usize] {
  10278. one
  10279. } else {
  10280. self.s.m.extract(c, d, ch)
  10281. };
  10282. self.write(inst, Reg::V(reg + k as u8), x, guard);
  10283. }
  10284. return Ok(());
  10285. }
  10286. if uav && op != 66 {
  10287. return Err("sampling a UAV");
  10288. }
  10289. let h = self.handle(site, src, false, props)?;
  10290. let fu = self.s.m.undef(self.s.t.f32);
  10291. let iu = self.s.m.undef(self.s.t.i32);
  10292. // A gather at a named level, done as four texel reads (below).
  10293. let mut gathered: Option<[V; 4]> = None;
  10294. let r = if sample {
  10295. let ss = self
  10296. .descriptors
  10297. .get(&(site, true))
  10298. .copied()
  10299. .ok_or("an untracked sampler")?;
  10300. // Comparison: the reference value is the first address after
  10301. // the bias, and the sampler is a comparison sampler.
  10302. let cmp = matches!(op, 64 | 65);
  10303. if cmp && (*a16 || dmask.count_ones() != 1) {
  10304. return Err("a comparison sample of 16-bit coordinates or several channels");
  10305. }
  10306. let mut sampler_choice: Option<(V, Vec<u32>)> = None;
  10307. let sh = match ss {
  10308. Source::Phi { block, args } => {
  10309. match self.sampler_phi_choice(*block, args, cmp, 8) {
  10310. Ok((None, regs)) => self.s.sampler_handle(self.cur, regs[0]),
  10311. Ok((Some(idx), regs)) => {
  10312. let first = self.s.sampler_handle(self.cur, regs[0]);
  10313. sampler_choice = Some((idx, regs));
  10314. first
  10315. }
  10316. Err(_) => {
  10317. self.handle(site, ss, true, (14 | if cmp { 0x8000 } else { 0 }, 0))?
  10318. }
  10319. }
  10320. }
  10321. _ => self.handle(site, ss, true, (14 | if cmp { 0x8000 } else { 0 }, 0))?,
  10322. };
  10323. // Texel offsets (`_o`) come first: x in bits 0-5, y in 8-13,
  10324. // signed (programmable offsets: gathers only).
  10325. let offset_word = name.ends_with("_o");
  10326. let first = usize::from(offset_word)
  10327. + usize::from(name.starts_with("image_sample_b"))
  10328. + usize::from(cmp);
  10329. // Coordinates the size divides (not the array slice); explicit
  10330. // gradients (x then y) come before the coordinates.
  10331. let spatial = coords - usize::from(kind == 6 || kind == 7);
  10332. // A cube's gradients are the two of its face coordinates.
  10333. let grads = if kind == 5 { 2 } else { spatial };
  10334. let deriv_regs = if op == 63 {
  10335. if *a16 {
  10336. grads.div_ceil(2)
  10337. } else {
  10338. grads
  10339. }
  10340. } else {
  10341. 0
  10342. };
  10343. let coord_base = first + 2 * deriv_regs;
  10344. let mut cs = vec![fu; 4];
  10345. // With a16, sampling coordinates, gradients, LOD and clamp are f16.
  10346. let to_float = |l: &mut Self, x: V| {
  10347. if *a16 {
  10348. let f = l.s.t.f32;
  10349. l.s.op(l.cur, "legacyF16ToF32", Attr::ReadNone, f, 131, &[x])
  10350. } else {
  10351. l.as_float(x)
  10352. }
  10353. };
  10354. if kind == 5 && (*unorm || op == 81) {
  10355. return Err("a cube sample with texel coordinates or a level query");
  10356. }
  10357. for (k, slot) in cs.iter_mut().enumerate().take(coords) {
  10358. let x = addr_packed(self, coord_base, k)?;
  10359. *slot = to_float(self, x);
  10360. }
  10361. if kind == 5 {
  10362. let dir = self.cube_direction(cs[0], cs[1], cs[2]);
  10363. cs[..3].copy_from_slice(&dir);
  10364. }
  10365. if *unorm {
  10366. // Texel coordinates: divided by the size of level 0.
  10367. let i32t = self.s.t.i32;
  10368. let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
  10369. let z = self.s.m.i32(0);
  10370. let d = self
  10371. .s
  10372. .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, z]);
  10373. for (k, slot) in cs.iter_mut().enumerate().take(spatial) {
  10374. let n = self.s.m.extract(c, d, k as u32);
  10375. let n = self.s.m.cast(c, Cast::UiToFp, n, self.s.t.f32);
  10376. *slot = self.s.m.bin(c, Bin::SDiv, *slot, n);
  10377. }
  10378. }
  10379. if op == 81 {
  10380. // The clamped then the unclamped level of detail.
  10381. let Operand::Vector { reg, .. } = *data else {
  10382. return Err("an image result");
  10383. };
  10384. let f32t = self.s.t.f32;
  10385. for (k, ch) in (0..2u32).filter(|ch| dmask >> ch & 1 != 0).enumerate() {
  10386. let clamped = self.s.m.bool(ch == 0);
  10387. let lod = self.s.op(
  10388. c,
  10389. "calculateLOD.f32",
  10390. Attr::ReadOnly,
  10391. f32t,
  10392. 81,
  10393. &[h, sh, cs[0], cs[1], cs[2], clamped],
  10394. );
  10395. let x = self.as_int(lod);
  10396. self.write(inst, Reg::V(reg + k as u8), x, guard);
  10397. }
  10398. return Ok(());
  10399. }
  10400. let offsets = if kind == 5 {
  10401. 0
  10402. } else {
  10403. (coords - usize::from(kind == 6 || kind == 7)).min(3)
  10404. };
  10405. let zero = self.s.m.i32(0);
  10406. let mut os = vec![iu; 3];
  10407. for o in os.iter_mut().take(offsets) {
  10408. *o = zero;
  10409. }
  10410. if offset_word && offsets > 0 {
  10411. let w = addr_val(self, 0)?;
  10412. for (k, at) in [(0, 26), (1, 18)].into_iter().take(offsets.min(2)) {
  10413. // Bits at..at+5 sign-extended: shift up, then down.
  10414. let left = self.s.m.i32(at);
  10415. let t = self.s.m.bin(c, Bin::Shl, w, left);
  10416. let k26 = self.s.m.i32(26);
  10417. os[k] = self.s.m.bin(c, Bin::AShr, t, k26);
  10418. }
  10419. }
  10420. let mut args = vec![h, sh];
  10421. args.extend(&cs);
  10422. let clamp = if has_cl {
  10423. let x = addr_packed(self, coord_base, coords)?;
  10424. to_float(self, x)
  10425. } else {
  10426. fu
  10427. };
  10428. let call_sample = |l: &mut Self,
  10429. intrinsic: &str,
  10430. opcode: u32,
  10431. args: &[V],
  10432. gathered: &mut Option<[V; 4]>|
  10433. -> V {
  10434. let Some((idx, ref regs)) = sampler_choice else {
  10435. return l
  10436. .s
  10437. .op(c, intrinsic, Attr::ReadOnly, l.s.t.res_ret, opcode, args);
  10438. };
  10439. let merge = l.s.m.new_block();
  10440. let mut cur_test = c;
  10441. let mut per_ch: [Vec<(V, usize)>; 4] = Default::default();
  10442. let mut last_r = args[0];
  10443. for (i, &reg) in regs.iter().enumerate() {
  10444. let arm = if i + 1 == regs.len() {
  10445. cur_test
  10446. } else {
  10447. let arm = l.s.m.new_block();
  10448. let next = l.s.m.new_block();
  10449. let k = l.s.m.i32(i as u32);
  10450. let cond = l.s.m.cmp(cur_test, pred::EQ, idx, k);
  10451. l.s.m.terminate(cur_test, Term::CondBr(cond, arm, next));
  10452. cur_test = next;
  10453. arm
  10454. };
  10455. let mut arm_args = args.to_vec();
  10456. arm_args[1] = l.s.sampler_handle(arm, reg);
  10457. let r_i = l.s.op(
  10458. arm,
  10459. intrinsic,
  10460. Attr::ReadOnly,
  10461. l.s.t.res_ret,
  10462. opcode,
  10463. &arm_args,
  10464. );
  10465. for (ch, slot) in per_ch.iter_mut().enumerate() {
  10466. let v = l.s.m.extract(arm, r_i, ch as u32);
  10467. slot.push((v, arm));
  10468. }
  10469. l.s.m.terminate(arm, Term::Br(merge));
  10470. last_r = r_i;
  10471. }
  10472. let mut phis = [fu; 4];
  10473. for (ch, incoming) in per_ch.into_iter().enumerate() {
  10474. let phi = l.s.m.phi(merge, l.s.t.f32);
  10475. l.s.m.set_phi(phi, incoming);
  10476. phis[ch] = phi;
  10477. }
  10478. *gathered = Some(phis);
  10479. l.cur = merge;
  10480. last_r
  10481. };
  10482. match op {
  10483. // Outside a pixel shader there are no screen derivatives:
  10484. // the validator refuses `sample` there ("features
  10485. // incompatible with the shader stage": 730 compute programs,
  10486. // among them the G-buffer resolves and the sky), and what a
  10487. // driver does with it is its own affair.
  10488. // shortcut: such a sample reads level 0 (a bias: that
  10489. // level). The console takes derivatives from neighbouring
  10490. // lanes there; compute them from the lanes if a resolve
  10491. // shows the wrong mip.
  10492. 60 if !self.s.pixel => {
  10493. args.extend(&os);
  10494. args.push(self.s.m.f32(0));
  10495. call_sample(self, "sampleLevel.f32", 62, &args, &mut gathered)
  10496. }
  10497. 60 => {
  10498. if offset_word {
  10499. // DXIL wants immediate offsets in -8..=7 here; the
  10500. // console's are 6-bit and may be computed. A
  10501. // constant word in range becomes immediates
  10502. // (upstream PR #634); anything else keeps the
  10503. // offsets computed above (upstream refuses those).
  10504. let w = addr_val(self, 0)?;
  10505. if let Some(w) = self.s.m.int_value(w) {
  10506. let w = w as u32;
  10507. let field = |k: usize| {
  10508. let x = (w >> (8 * k) & 0x3F) as i32;
  10509. if x >= 32 { x - 64 } else { x }
  10510. };
  10511. let n = offsets.min(2);
  10512. if (0..n).all(|k| (-8..=7).contains(&field(k))) {
  10513. for (k, o) in os.iter_mut().enumerate().take(n) {
  10514. *o = self.s.m.i32(field(k) as u32);
  10515. }
  10516. }
  10517. }
  10518. }
  10519. args.extend(&os);
  10520. args.push(clamp);
  10521. call_sample(self, "sample.f32", 60, &args, &mut gathered)
  10522. }
  10523. 61 => {
  10524. // With a16 the bias is an f16 in the low half of its
  10525. // word (the word is whole, the value is not).
  10526. let bias = addr_u32(self, usize::from(offset_word))?;
  10527. let bias = if *a16 {
  10528. let low = self.s.m.i32(0xFFFF);
  10529. let bias = self.s.m.bin(c, Bin::And, bias, low);
  10530. to_float(self, bias)
  10531. } else {
  10532. self.as_float(bias)
  10533. };
  10534. args.extend(&os);
  10535. if self.s.pixel {
  10536. args.extend([bias, clamp]);
  10537. call_sample(self, "sampleBias.f32", 61, &args, &mut gathered)
  10538. } else {
  10539. // As above: the bias is the level.
  10540. args.push(bias);
  10541. call_sample(self, "sampleLevel.f32", 62, &args, &mut gathered)
  10542. }
  10543. }
  10544. 63 if kind == 5 => {
  10545. // A cube with explicit gradients: the host wants them
  10546. // as changes of the direction, the console gives the
  10547. // changes of the face coordinates (the face is one
  10548. // unit wide). The level they select is taken from the
  10549. // longer of the two, in texels, and sampled directly.
  10550. // shortcut: no anisotropic filtering for these samples
  10551. // (the longer axis alone decides the level).
  10552. let mut len = [fu; 2];
  10553. for (axis, slot) in len.iter_mut().enumerate() {
  10554. let mut sum = self.s.m.f32(0);
  10555. for k in 0..2 {
  10556. let x = addr_packed(self, first + axis * deriv_regs, k)?;
  10557. let x = to_float(self, x);
  10558. let sq = self.s.m.bin(c, Bin::Mul, x, x);
  10559. sum = self.s.m.bin(c, Bin::Add, sum, sq);
  10560. }
  10561. *slot = self.unary(24, sum); // square root
  10562. }
  10563. let longer = self.binary(35, len[0], len[1]); // maximum
  10564. let i32t = self.s.t.i32;
  10565. let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
  10566. let z = self.s.m.i32(0);
  10567. let d = self
  10568. .s
  10569. .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, z]);
  10570. let width = self.s.m.extract(c, d, 0);
  10571. let width = self.s.m.cast(c, Cast::UiToFp, width, self.s.t.f32);
  10572. let texels = self.s.m.bin(c, Bin::Mul, longer, width);
  10573. // log2 = natural logarithm / ln 2; a length of 0 gives
  10574. // minus infinity, which the sampler clamps to level 0.
  10575. let ln = self.unary(23, texels);
  10576. let per_ln2 = self.s.m.f32(std::f32::consts::LOG2_E.to_bits());
  10577. let lod = self.s.m.bin(c, Bin::Mul, ln, per_ln2);
  10578. args.extend(&os);
  10579. args.push(lod);
  10580. call_sample(self, "sampleLevel.f32", 62, &args, &mut gathered)
  10581. }
  10582. 63 => {
  10583. let mut g = vec![fu; 6];
  10584. for k in 0..spatial {
  10585. let x = addr_packed(self, first, k)?;
  10586. g[k] = to_float(self, x);
  10587. let y = addr_packed(self, first + deriv_regs, k)?;
  10588. g[3 + k] = to_float(self, y);
  10589. }
  10590. args.extend(&os);
  10591. args.extend(g);
  10592. args.push(clamp);
  10593. call_sample(self, "sampleGrad.f32", 63, &args, &mut gathered)
  10594. }
  10595. 64 | 65 => {
  10596. let reference = addr_u32(self, first - 1)?;
  10597. let reference = self.as_float(reference);
  10598. args.extend(&os);
  10599. args.push(reference);
  10600. let name = if op == 64 {
  10601. args.push(clamp);
  10602. "sampleCmp.f32"
  10603. } else {
  10604. "sampleCmpLevelZero.f32"
  10605. };
  10606. call_sample(self, name, op, &args, &mut gathered)
  10607. }
  10608. 62 => {
  10609. let lod = if name == "image_sample_l" {
  10610. let x = addr_packed(self, coord_base, coords)?;
  10611. to_float(self, x)
  10612. } else {
  10613. self.s.m.f32(0)
  10614. };
  10615. args.extend(&os);
  10616. args.push(lod);
  10617. call_sample(self, "sampleLevel.f32", 62, &args, &mut gathered)
  10618. }
  10619. _ => {
  10620. if name == "image_gather4" {
  10621. return Err("a gather with implicit level");
  10622. }
  10623. if dmask.count_ones() != 1 {
  10624. return Err("a gather of several channels");
  10625. }
  10626. if matches!(name, "image_gather4_l" | "image_gather4_l_o")
  10627. && coords == 2
  10628. && spatial == 2
  10629. {
  10630. // The host's gather has no level: it read level 0
  10631. // where the title names one (the depth pyramid its
  10632. // occlusion tests read: most of the world was
  10633. // culled against the wrong depths). The four texels
  10634. // are read at the level instead, in the gather's
  10635. // order: (u0,v1) (u1,v1) (u1,v0) (u0,v0).
  10636. // With an offset too (`image_gather4_l_o`): the
  10637. // offset is in texels of that level.
  10638. // The title's meshlet culling takes a 4x4 block of
  10639. // the pyramid as one gather and three offset ones
  10640. // ((2,0), (0,2), (2,2)); the three read level 0,
  10641. // two texels beside the first one's place, so a
  10642. // meshlet three or four texels wide was tested
  10643. // against a quarter of what it covers.
  10644. // shortcut: the level is rounded to a whole one and
  10645. // coordinates past the edge are clamped, whatever
  10646. // the sampler says.
  10647. let lod = addr_packed(self, coord_base, coords)?;
  10648. let lod = to_float(self, lod);
  10649. let (i32t, f32t) = (self.s.t.i32, self.s.t.f32);
  10650. let zero = self.s.m.f32(0);
  10651. let lod = self.binary(35, lod, zero); // maximum
  10652. let lod = self.unary(26, lod); // round to nearest
  10653. let mip = self.s.m.cast(c, Cast::FpToUi, lod, i32t);
  10654. let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
  10655. let d = self
  10656. .s
  10657. .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]);
  10658. let half = self.s.m.f32(0.5f32.to_bits());
  10659. let one = self.s.m.f32(1.0f32.to_bits());
  10660. let (mut lo, mut hi) = ([iu; 2], [iu; 2]);
  10661. for k in 0..2 {
  10662. let n = self.s.m.extract(c, d, k as u32);
  10663. let n = self.s.m.cast(c, Cast::UiToFp, n, f32t);
  10664. let last = self.s.m.bin(c, Bin::Sub, n, one);
  10665. let t = self.s.m.bin(c, Bin::Mul, cs[k], n);
  10666. let t = self.s.m.bin(c, Bin::Sub, t, half);
  10667. let first = self.unary(27, t); // round down
  10668. // The offset word's field (0 without one).
  10669. let by = self.s.m.cast(c, Cast::SiToFp, os[k], f32t);
  10670. let first = self.s.m.bin(c, Bin::Add, first, by);
  10671. let next = self.s.m.bin(c, Bin::Add, first, one);
  10672. for (slot, x) in [(&mut lo[k], first), (&mut hi[k], next)] {
  10673. let x = self.binary(35, x, zero); // maximum
  10674. let x = self.binary(36, x, last); // minimum
  10675. *slot = self.s.m.cast(c, Cast::FpToSi, x, i32t);
  10676. }
  10677. }
  10678. let ch = dmask.trailing_zeros();
  10679. let mut g = [fu; 4];
  10680. let mut read = None;
  10681. let texels = [(lo[0], hi[1]), (hi[0], hi[1]), (hi[0], lo[1]), (lo[0], lo[1])];
  10682. for (slot, (x, y)) in g.iter_mut().zip(texels) {
  10683. let r = self.s.op(
  10684. c,
  10685. "textureLoad.f32",
  10686. Attr::ReadOnly,
  10687. self.s.t.res_ret,
  10688. 66,
  10689. &[h, mip, x, y, iu, iu, iu, iu],
  10690. );
  10691. *slot = self.s.m.extract(c, r, ch);
  10692. read = Some(r);
  10693. }
  10694. gathered = Some(g);
  10695. read.expect("four reads")
  10696. } else {
  10697. args.extend(&os[..2]);
  10698. args.push(self.s.m.i32(dmask.trailing_zeros()));
  10699. call_sample(self, "textureGather.f32", 73, &args, &mut gathered)
  10700. }
  10701. }
  10702. }
  10703. } else {
  10704. let mut cs = vec![iu; 3];
  10705. for (k, slot) in cs.iter_mut().enumerate().take(coords) {
  10706. *slot = addr_val(self, k)?;
  10707. }
  10708. let mip = if name == "image_load_mip" {
  10709. addr_val(self, coords)?
  10710. } else if uav {
  10711. // Our declarations have four channels.
  10712. self.s.flags |= flags::TYPED_UAV_LOADS;
  10713. iu
  10714. } else {
  10715. self.s.m.i32(0)
  10716. };
  10717. let mut args = vec![h, mip];
  10718. args.extend(&cs);
  10719. args.extend([iu, iu, iu]);
  10720. self.s.op(
  10721. c,
  10722. "textureLoad.f32",
  10723. Attr::ReadOnly,
  10724. self.s.t.res_ret,
  10725. 66,
  10726. &args,
  10727. )
  10728. };
  10729. let Operand::Vector { reg, .. } = *data else {
  10730. return Err("an image result");
  10731. };
  10732. let channels: Vec<u32> = if op == 73 {
  10733. vec![0, 1, 2, 3]
  10734. } else {
  10735. (0..4).filter(|ch| dmask >> ch & 1 != 0).collect()
  10736. };
  10737. let mut xs = Vec::new();
  10738. for ch in channels {
  10739. let x = match gathered {
  10740. Some(g) => g[ch as usize],
  10741. None => self.s.m.extract(c, r, ch),
  10742. };
  10743. xs.push(if *d16 {
  10744. // shortcut: d16 results are taken as floats (rounded to
  10745. // nearest even); integer formats would keep 16 bits.
  10746. let i32t = self.s.t.i32;
  10747. self.s
  10748. .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[x])
  10749. } else {
  10750. self.as_int(x)
  10751. });
  10752. }
  10753. if *d16 {
  10754. // Two channels per VGPR, low half first (an odd last high half 0).
  10755. let k16 = self.s.m.i32(16);
  10756. xs = xs
  10757. .chunks(2)
  10758. .map(|p| match *p {
  10759. [lo, hi] => {
  10760. let hi = self.s.m.bin(c, Bin::Shl, hi, k16);
  10761. self.s.m.bin(c, Bin::Or, lo, hi)
  10762. }
  10763. _ => p[0],
  10764. })
  10765. .collect();
  10766. }
  10767. for (k, x) in xs.into_iter().enumerate() {
  10768. self.write(inst, Reg::V(reg + k as u8), x, guard);
  10769. }
  10770. Ok(())
  10771. }
  10772. /// The direction a cube sample's face coordinates stand for: the
  10773. /// console takes s and t in [1, 2] (`v_cubesc`/`v_cubetc` over
  10774. /// `|v_cubema|`, plus 1.5) and the face id (`v_cubeid`), which the
  10775. /// host's cube sampling turns back into the same texel.
  10776. // shortcut: the view is taken as a cube, not a cube array (whose face
  10777. // operand adds 8 × the slice).
  10778. fn cube_direction(&mut self, s: V, t: V, face: V) -> [V; 3] {
  10779. let c = self.cur;
  10780. let k = |l: &mut Self, v: f32| l.s.m.f32(v.to_bits());
  10781. let (two, three) = (k(self, 2.0), k(self, 3.0));
  10782. let u = self.s.m.bin(c, Bin::Mul, s, two);
  10783. let u = self.s.m.bin(c, Bin::Sub, u, three);
  10784. let v = self.s.m.bin(c, Bin::Mul, t, two);
  10785. let v = self.s.m.bin(c, Bin::Sub, v, three);
  10786. let z = self.s.m.f32(0x8000_0000);
  10787. let (nu, nv) = (
  10788. self.s.m.bin(c, Bin::Sub, z, u),
  10789. self.s.m.bin(c, Bin::Sub, z, v),
  10790. );
  10791. let (one, mone) = (k(self, 1.0), k(self, -1.0));
  10792. let f = self.s.m.cast(c, Cast::FpToUi, face, self.s.t.i32);
  10793. // Per face +x, -x, +y, -y, +z, -z.
  10794. let table = [
  10795. [one, mone, u, u, u, nu],
  10796. [nv, nv, one, mone, nv, nv],
  10797. [nu, u, v, nv, one, mone],
  10798. ];
  10799. table.map(|row| {
  10800. let mut r = row[0];
  10801. for (n, &x) in row.iter().enumerate().skip(1) {
  10802. let kn = self.s.m.i32(n as u32);
  10803. let is = self.s.m.cmp(c, pred::EQ, f, kn);
  10804. r = self.s.m.select(c, is, x, r);
  10805. }
  10806. r
  10807. })
  10808. }
  10809. fn buffer(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  10810. let Fields::Buffer {
  10811. data,
  10812. addr,
  10813. soffset,
  10814. offset,
  10815. offen,
  10816. idxen,
  10817. format,
  10818. lds,
  10819. tfe,
  10820. ..
  10821. } = &inst.fields
  10822. else {
  10823. unreachable!()
  10824. };
  10825. let name = inst.name();
  10826. if name == "buffer_gl0_inv" || name == "buffer_gl1_inv" {
  10827. // The host has no console buffer cache to invalidate.
  10828. return Ok(());
  10829. }
  10830. if *lds || *tfe {
  10831. return Err("a buffer access to LDS or with tfe");
  10832. }
  10833. if format.is_some() && !name.starts_with("tbuffer_load_format_") {
  10834. return Err(name);
  10835. }
  10836. let site = (b, i);
  10837. let guard = self.guard(b, i)?;
  10838. let c = self.cur;
  10839. let store = name.starts_with("buffer_store_");
  10840. // DXIL atomic operations: add, and, or, xor, signed and unsigned
  10841. // min and max, exchange; compare-exchange apart.
  10842. let atomic = match name.strip_prefix("buffer_atomic_") {
  10843. None => None,
  10844. Some("add") => Some(0),
  10845. Some("and") => Some(1),
  10846. Some("or") => Some(2),
  10847. Some("xor") => Some(3),
  10848. Some("smin") => Some(4),
  10849. Some("smax") => Some(5),
  10850. Some("umin") => Some(6),
  10851. Some("umax") => Some(7),
  10852. Some("swap") => Some(8),
  10853. Some("cmpswap") => Some(u32::MAX),
  10854. Some(_) => return Err(name),
  10855. };
  10856. // Byte and 16-bit accesses: bits, and whether a load sign-extends.
  10857. let narrow = match name {
  10858. "buffer_load_ubyte" | "buffer_store_byte" => Some((8, false)),
  10859. "buffer_load_sbyte" => Some((8, true)),
  10860. "buffer_load_ushort" | "buffer_store_short" => Some((16, false)),
  10861. "buffer_load_sshort" => Some((16, true)),
  10862. _ => None,
  10863. };
  10864. // d16: two 16-bit channels per VGPR, low half first (buffer and
  10865. // tbuffer formats alike).
  10866. let d16 = name.contains("_format_d16_");
  10867. let plain = name.replace("_format_d16_", "_format_");
  10868. let (typed, count) = match plain
  10869. .strip_prefix("buffer_load_")
  10870. .or(plain.strip_prefix("buffer_store_"))
  10871. .or(plain.strip_prefix("tbuffer_load_"))
  10872. {
  10873. _ if atomic.is_some() || narrow.is_some() => (false, 1),
  10874. Some("dword") => (false, 1),
  10875. Some("dwordx2") => (false, 2),
  10876. Some("dwordx3") => (false, 3),
  10877. Some("dwordx4") => (false, 4),
  10878. Some("format_x") => (true, 1),
  10879. Some("format_xy") => (true, 2),
  10880. Some("format_xyz") => (true, 3),
  10881. Some("format_xyzw") => (true, 4),
  10882. _ => return Err(name),
  10883. };
  10884. let Operand::Vector { reg: areg, .. } = *addr else {
  10885. return Err("a buffer address");
  10886. };
  10887. let vaddr = |l: &mut Self, k: u8| -> Result<V, Why> {
  10888. let v = inst.read(Reg::V(areg + k)).ok_or("a buffer address")?;
  10889. l.i32_of(v)
  10890. };
  10891. let index = if *idxen { Some(vaddr(self, 0)?) } else { None };
  10892. let mut off = self.s.m.i32(u32::from(*offset));
  10893. if *offen {
  10894. let o = vaddr(self, u8::from(*idxen))?;
  10895. off = self.s.m.bin(c, Bin::Add, off, o);
  10896. }
  10897. if !matches!(
  10898. soffset,
  10899. Operand::Scalar { code: NULL, .. } | Operand::Const(128)
  10900. ) {
  10901. let so = self.operand(inst, soffset)?;
  10902. off = self.s.m.bin(c, Bin::Add, off, so);
  10903. }
  10904. let src = self
  10905. .descriptors
  10906. .get(&(site, false))
  10907. .copied()
  10908. .ok_or("an untracked buffer")?;
  10909. let used = self.used_kind(src);
  10910. let (base, extra) = self.built_offset(src)?;
  10911. if base != 0 {
  10912. let b = self.s.m.i32(base);
  10913. off = self.s.m.bin(c, Bin::Add, off, b);
  10914. }
  10915. if let Some(x) = extra {
  10916. off = self.s.m.bin(c, Bin::Add, off, x);
  10917. }
  10918. // A buffer the program picks from the view heap by an index it
  10919. // computes: no used-resource entry gives its stride, the host's
  10920. // table by heap slot does; the access becomes a raw one at the
  10921. // element's byte. (Also tells the host this shader reads such
  10922. // buffers.)
  10923. let mut index = index;
  10924. if let Some(stride) = self.slot_stride(src)?
  10925. && let Some(element) = index
  10926. && !typed
  10927. && used.is_none()
  10928. {
  10929. let at = self.s.m.bin(c, Bin::Mul, element, stride);
  10930. off = self.s.m.bin(c, Bin::Add, at, off);
  10931. index = None;
  10932. }
  10933. // A structured buffer by its used-resource entry's stride: raw
  10934. // bytes too. The host makes its buffer views raw (a raw read
  10935. // through a structured view gives zeros on NVIDIA), and one kind
  10936. // of view can then serve every shader that reads the buffer.
  10937. if let (Some(element), Some(u)) = (index, used)
  10938. && !typed
  10939. && u.kind != ResourceType::Cbv
  10940. && u.stride >= 4
  10941. && u.stride.is_multiple_of(4)
  10942. {
  10943. let k = self.s.m.i32(u.stride);
  10944. let at = self.s.m.bin(c, Bin::Mul, element, k);
  10945. off = self.s.m.bin(c, Bin::Add, at, off);
  10946. index = None;
  10947. }
  10948. if used.is_some_and(|u| u.kind == ResourceType::Cbv) && !typed {
  10949. // A constant buffer read per lane (a dynamically indexed array).
  10950. // shortcut: the console's CBV descriptor is taken to have a 16-byte
  10951. // stride, as the vector loads of whole rows suggest.
  10952. let h = self.handle(site, src, false, (13, 0x1_0000))?;
  10953. let byte = match index {
  10954. Some(i) => {
  10955. let sixteen = self.s.m.i32(16);
  10956. let rows = self.s.m.bin(c, Bin::Mul, i, sixteen);
  10957. self.s.m.bin(c, Bin::Add, rows, off)
  10958. }
  10959. None => off,
  10960. };
  10961. let Some(Operand::Vector { reg, .. }) = *data else {
  10962. return Err("a buffer result");
  10963. };
  10964. for k in 0..count {
  10965. let four = self.s.m.i32(4 * k);
  10966. let a = self.s.m.bin(c, Bin::Add, byte, four);
  10967. let x = self.cbuffer_dword(h, a);
  10968. self.write(inst, Reg::V(reg + k as u8), x, guard);
  10969. }
  10970. return Ok(());
  10971. }
  10972. let uav = store || atomic.is_some() || used.is_some_and(|u| u.kind == ResourceType::Uav);
  10973. let mut u = if uav { 0x1000 } else { 0 };
  10974. if uav && !typed && self.entry(src).is_some_and(|e| self.coherent.contains(&e)) {
  10975. u |= 0x4000;
  10976. }
  10977. let iu = self.s.m.undef(self.s.t.i32);
  10978. if let Some((bits, signed)) = narrow {
  10979. // Below a dword: raw buffers are read and written in dwords on
  10980. // 4 bytes, so the dword that holds the value is read and
  10981. // shifted, or changed with two atomic operations that touch
  10982. // only the value's own bits (other lanes may write the rest of
  10983. // the dword at the same time). A 16-bit value at a dword's
  10984. // last byte continues in the next dword.
  10985. let byte = match index {
  10986. None => off,
  10987. Some(index) if used.is_some_and(|u| u.stride == 1) => {
  10988. self.s.m.bin(c, Bin::Add, index, off)
  10989. }
  10990. Some(_) => return Err("a byte or 16-bit buffer access by index"),
  10991. };
  10992. let h = self.handle(site, src, false, (11 | u, 0))?;
  10993. let k3 = self.s.m.i32(3);
  10994. let within = self.s.m.bin(c, Bin::And, byte, k3);
  10995. let aligned = self.s.m.bin(c, Bin::Sub, byte, within);
  10996. let shift = self.s.m.bin(c, Bin::Shl, within, k3);
  10997. let four = self.s.m.i32(4);
  10998. let next = self.s.m.bin(c, Bin::Add, aligned, four);
  10999. let ones = self.s.m.i32(if bits == 8 { 0xff } else { 0xffff });
  11000. let zero = self.s.m.i32(0);
  11001. let k8 = self.s.m.i32(8);
  11002. let straddles = self.s.m.cmp(c, pred::EQ, within, k3);
  11003. if !store {
  11004. let mask = self.s.m.i8(1);
  11005. let align = self.s.m.i32(4);
  11006. let dword = |l: &mut Self, at: V| {
  11007. let r = l.s.op(
  11008. c,
  11009. "rawBufferLoad.f32",
  11010. Attr::ReadOnly,
  11011. l.s.t.res_ret,
  11012. 139,
  11013. &[h, at, iu, mask, align],
  11014. );
  11015. let f = l.s.m.extract(c, r, 0);
  11016. l.as_int(f)
  11017. };
  11018. let low = dword(self, aligned);
  11019. let mut x = self.s.m.bin(c, Bin::LShr, low, shift);
  11020. if bits == 16 {
  11021. let high = dword(self, next);
  11022. let high = self.s.m.bin(c, Bin::Shl, high, k8);
  11023. let high = self.s.m.select(c, straddles, high, zero);
  11024. x = self.s.m.bin(c, Bin::Or, x, high);
  11025. }
  11026. x = self.s.m.bin(c, Bin::And, x, ones);
  11027. if signed {
  11028. let up = self.s.m.i32(32 - bits);
  11029. x = self.s.m.bin(c, Bin::Shl, x, up);
  11030. x = self.s.m.bin(c, Bin::AShr, x, up);
  11031. }
  11032. let Some(Operand::Vector { reg, .. }) = *data else {
  11033. return Err("a buffer result");
  11034. };
  11035. self.write(inst, Reg::V(reg), x, guard);
  11036. return Ok(());
  11037. }
  11038. let d = data.as_ref().ok_or("buffer store data")?;
  11039. let v = self.vgprs(inst, d, 1)?[0];
  11040. let v = self.s.m.bin(c, Bin::And, v, ones);
  11041. let all = self.s.m.i32(u32::MAX);
  11042. let clear = self.s.m.bin(c, Bin::Shl, ones, shift);
  11043. let keep = self.s.m.bin(c, Bin::Xor, clear, all);
  11044. let set = self.s.m.bin(c, Bin::Shl, v, shift);
  11045. let keep_next = self.s.m.i32(0xffff_ff00);
  11046. let set_next = self.s.m.bin(c, Bin::LShr, v, k8);
  11047. let (and, or) = (self.s.m.i32(1), self.s.m.i32(2));
  11048. let i32t = self.s.t.i32;
  11049. let at = self.begin_guarded(guard);
  11050. for (op, x) in [(and, keep), (or, set)] {
  11051. let args = [h, op, aligned, iu, iu, x];
  11052. self.s
  11053. .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args);
  11054. }
  11055. if bits == 16 {
  11056. let second = self.begin_guarded(Some(straddles));
  11057. for (op, x) in [(and, keep_next), (or, set_next)] {
  11058. let args = [h, op, next, iu, iu, x];
  11059. self.s
  11060. .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args);
  11061. }
  11062. self.end_guarded(second, &[]);
  11063. }
  11064. self.end_guarded(at, &[]);
  11065. return Ok(());
  11066. }
  11067. if let Some(op) = atomic {
  11068. let d = data.as_ref().ok_or("buffer atomic data")?;
  11069. let vals = self.vgprs(inst, d, if op == u32::MAX { 2 } else { 1 })?;
  11070. let (h, coords) = match index {
  11071. // A raw buffer (stride 1) read by index: the index is the byte.
  11072. Some(index) if used.is_some_and(|u| u.stride == 1) => {
  11073. let byte = self.s.m.bin(c, Bin::Add, index, off);
  11074. (self.handle(site, src, false, (11 | u, 0))?, [byte, iu, iu])
  11075. }
  11076. Some(index) => {
  11077. let stride = used.map_or(0, |u| u.stride);
  11078. if stride < 4 || !stride.is_multiple_of(4) {
  11079. return Err("a structured buffer of unknown stride");
  11080. }
  11081. let h = self.handle(site, src, false, (12 | u, stride))?;
  11082. (h, [index, off, iu])
  11083. }
  11084. None => (self.handle(site, src, false, (11 | u, 0))?, [off, iu, iu]),
  11085. };
  11086. let Operand::Vector { reg, .. } = *d else {
  11087. return Err("buffer atomic data");
  11088. };
  11089. let returns = matches!(inst.fields, Fields::Buffer { cache, .. } if cache.glc);
  11090. let old = match inst.read(Reg::V(reg)) {
  11091. Some(v) if returns => self.i32_of(v)?,
  11092. _ => self.s.m.i32(0),
  11093. };
  11094. let at = self.begin_guarded(guard);
  11095. let i32t = self.s.t.i32;
  11096. let r = if op == u32::MAX {
  11097. // cmpswap: data is (new, compare).
  11098. let mut args = vec![h];
  11099. args.extend(coords);
  11100. args.extend([vals[1], vals[0]]);
  11101. self.s.op(
  11102. self.cur,
  11103. "atomicCompareExchange.i32",
  11104. Attr::NoUnwind,
  11105. i32t,
  11106. 79,
  11107. &args,
  11108. )
  11109. } else {
  11110. let mut args = vec![h, self.s.m.i32(op)];
  11111. args.extend(coords);
  11112. args.push(vals[0]);
  11113. self.s
  11114. .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args)
  11115. };
  11116. let r = self.end_guarded(at, &[(r, old)])[0];
  11117. if returns {
  11118. self.write(inst, Reg::V(reg), r, None);
  11119. }
  11120. return Ok(());
  11121. }
  11122. if store {
  11123. let regs = if d16 { count.div_ceil(2) } else { count };
  11124. let mut vals =
  11125. self.vgprs(inst, data.as_ref().ok_or("buffer store data")?, regs as u8)?;
  11126. if d16 {
  11127. // shortcut: d16 data is taken as f16 (integer formats would
  11128. // keep 16 bits), widened for the 32-bit float store.
  11129. let mut wide = Vec::new();
  11130. for k in 0..count {
  11131. let mut x = vals[(k / 2) as usize];
  11132. if k % 2 == 1 {
  11133. let k16 = self.s.m.i32(16);
  11134. x = self.s.m.bin(c, Bin::LShr, x, k16);
  11135. }
  11136. let f32t = self.s.t.f32;
  11137. let f = self
  11138. .s
  11139. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]);
  11140. wide.push(self.as_int(f));
  11141. }
  11142. vals = wide;
  11143. }
  11144. let mut args = Vec::new();
  11145. let (op, name) = if typed {
  11146. // shortcut: typed stores are taken to write all four channels
  11147. // of a float format.
  11148. if count != 4 || *offen || *offset != 0 {
  11149. return Err("a typed buffer store of some channels or at an offset");
  11150. }
  11151. args.push(self.handle(site, src, false, (10 | u, 0x409))?);
  11152. args.extend([index.unwrap_or(self.s.m.i32(0)), iu]);
  11153. for x in vals {
  11154. args.push(self.as_float(x));
  11155. }
  11156. (69, "bufferStore.f32")
  11157. } else {
  11158. match index {
  11159. // A raw buffer (stride 1) written by index: the index is the byte.
  11160. Some(index) if used.is_some_and(|u| u.stride == 1) => {
  11161. let byte = self.s.m.bin(c, Bin::Add, index, off);
  11162. args.push(self.handle(site, src, false, (11 | u, 0))?);
  11163. args.extend([byte, iu]);
  11164. }
  11165. Some(index) => {
  11166. let stride = used.map_or(0, |u| u.stride);
  11167. if stride < 4 || !stride.is_multiple_of(4) {
  11168. return Err("a structured buffer of unknown stride");
  11169. }
  11170. args.push(self.handle(site, src, false, (12 | u, stride))?);
  11171. args.extend([index, off]);
  11172. }
  11173. None => {
  11174. args.push(self.handle(site, src, false, (11 | u, 0))?);
  11175. args.extend([off, iu]);
  11176. }
  11177. }
  11178. args.extend(&vals);
  11179. args.resize(3 + 4, iu);
  11180. (140, "rawBufferStore.i32")
  11181. };
  11182. args.push(self.s.m.i8(if typed { 0xF } else { (1u8 << count) - 1 }));
  11183. if !typed {
  11184. args.push(self.s.m.i32(4));
  11185. }
  11186. let at = self.begin_guarded(guard);
  11187. let void = self.s.t.void;
  11188. self.s.op(self.cur, name, Attr::NoUnwind, void, op, &args);
  11189. self.end_guarded(at, &[]);
  11190. return Ok(());
  11191. }
  11192. if let Some(f) = *format {
  11193. if index.is_some() {
  11194. return Err("a typed-format load by index");
  11195. }
  11196. let h = self.handle(site, src, false, (11 | u, 0))?;
  11197. let Some(Operand::Vector { reg, .. }) = *data else {
  11198. return Err("a buffer result");
  11199. };
  11200. let mut xs = self.format_load(h, off, f, count)?;
  11201. if d16 {
  11202. xs = self.d16_channels(f, xs)?;
  11203. }
  11204. for (k, x) in xs.into_iter().enumerate() {
  11205. self.write(inst, Reg::V(reg + k as u8), x, guard);
  11206. }
  11207. return Ok(());
  11208. }
  11209. let r = if typed {
  11210. if *offen || matches!(off, V::Inst(_)) || *offset != 0 {
  11211. return Err("a typed buffer load at an offset");
  11212. }
  11213. if uav {
  11214. self.s.flags |= flags::TYPED_UAV_LOADS;
  11215. }
  11216. let h = self.handle(site, src, false, (10 | u, 0x409))?;
  11217. let index = index.unwrap_or(self.s.m.i32(0));
  11218. self.s.op(
  11219. c,
  11220. "bufferLoad.f32",
  11221. Attr::ReadOnly,
  11222. self.s.t.res_ret,
  11223. 68,
  11224. &[h, index, iu],
  11225. )
  11226. } else {
  11227. let mask = self.s.m.i8((1u8 << count) - 1);
  11228. let align = self.s.m.i32(4);
  11229. match index {
  11230. // A raw buffer (stride 1) read by index: the index is the byte.
  11231. Some(index) if used.is_some_and(|u| u.stride == 1) => {
  11232. let byte = self.s.m.bin(c, Bin::Add, index, off);
  11233. let h = self.handle(site, src, false, (11 | u, 0))?;
  11234. self.s.op(
  11235. c,
  11236. "rawBufferLoad.f32",
  11237. Attr::ReadOnly,
  11238. self.s.t.res_ret,
  11239. 139,
  11240. &[h, byte, iu, mask, align],
  11241. )
  11242. }
  11243. Some(index) => {
  11244. let stride = used.map_or(0, |u| u.stride);
  11245. if stride < 4 || !stride.is_multiple_of(4) {
  11246. return Err("a structured buffer of unknown stride");
  11247. }
  11248. let h = self.handle(site, src, false, (12 | u, stride))?;
  11249. self.s.op(
  11250. c,
  11251. "rawBufferLoad.f32",
  11252. Attr::ReadOnly,
  11253. self.s.t.res_ret,
  11254. 139,
  11255. &[h, index, off, mask, align],
  11256. )
  11257. }
  11258. None => {
  11259. let h = self.handle(site, src, false, (11 | u, 0))?;
  11260. self.s.op(
  11261. c,
  11262. "rawBufferLoad.f32",
  11263. Attr::ReadOnly,
  11264. self.s.t.res_ret,
  11265. 139,
  11266. &[h, off, iu, mask, align],
  11267. )
  11268. }
  11269. }
  11270. };
  11271. let Some(Operand::Vector { reg, .. }) = *data else {
  11272. return Err("a buffer result");
  11273. };
  11274. if d16 {
  11275. // Two f16 channels per VGPR (an odd last high half 0).
  11276. let k16 = self.s.m.i32(16);
  11277. let i32t = self.s.t.i32;
  11278. for k in 0..count.div_ceil(2) {
  11279. let mut x = None;
  11280. for ch in (2 * k..(2 * k + 2).min(count)).rev() {
  11281. let f = self.s.m.extract(c, r, ch);
  11282. let h = self
  11283. .s
  11284. .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]);
  11285. x = Some(match x {
  11286. Some(hi) => {
  11287. let hi = self.s.m.bin(c, Bin::Shl, hi, k16);
  11288. self.s.m.bin(c, Bin::Or, h, hi)
  11289. }
  11290. None => h,
  11291. });
  11292. }
  11293. self.write(inst, Reg::V(reg + k as u8), x.expect("a channel"), guard);
  11294. }
  11295. return Ok(());
  11296. }
  11297. for k in 0..count {
  11298. let x = self.s.m.extract(c, r, k);
  11299. let x = self.as_int(x);
  11300. self.write(inst, Reg::V(reg + k as u8), x, guard);
  11301. }
  11302. Ok(())
  11303. }
  11304. fn export(&mut self, b: usize, i: usize) -> Result<(), Why> {
  11305. let e = *self
  11306. .exports
  11307. .get(&(b, i))
  11308. .ok_or("an export I/O raising did not see")?;
  11309. if e.compressed {
  11310. return Err("a compressed export");
  11311. }
  11312. let guard = self.guard(b, i)?;
  11313. let mesh = self.s.mesh.is_some();
  11314. let c = self.cur;
  11315. if let Some(g) = guard
  11316. && !mesh
  11317. {
  11318. if !(e.done && self.s.pixel) {
  11319. return Err("a conditional export");
  11320. }
  11321. let t = self.s.m.bool(true);
  11322. let kill = self.s.m.bin(c, Bin::Xor, g, t);
  11323. self.s
  11324. .op(c, "discard", Attr::NoUnwind, self.s.t.void, 82, &[kill]);
  11325. }
  11326. if mesh && e.target == Target::Primitive {
  11327. return self.emit_indices(e, guard);
  11328. }
  11329. let param_row = |usage: Usage, row: u8| match usage {
  11330. // The 2020 compiler leaves a mesh program's first entry zeroed
  11331. // (usage "position"): its row is the one no other entry names.
  11332. Usage::Other(0) if mesh => self.unnamed_row(),
  11333. _ => Some(row),
  11334. };
  11335. // (output element, channel) per exported channel; per-primitive
  11336. // outputs are elements of `prims`.
  11337. let mut stores = Vec::new();
  11338. let primitive = matches!(e.target, Target::PrimitiveParam { .. });
  11339. let outputs = if primitive {
  11340. &self.s.prims
  11341. } else {
  11342. &self.s.outputs
  11343. };
  11344. let by_kind = |kind: u8| outputs.iter().position(|o| o.kind == kind);
  11345. // 16-bit vertex outputs: the halves each dword carries, as (output
  11346. // element, channel, high half) per channel.
  11347. let halves = match e.target {
  11348. Target::Param { usage, row } => {
  11349. param_row(usage, row).and_then(|r| self.half_outputs.get(&r).map(|&h| (r, h)))
  11350. }
  11351. _ => None,
  11352. };
  11353. if let Some((row, (pack2, _))) = halves {
  11354. let packs: Vec<(u8, Option<u8>)> = self
  11355. .half_outputs
  11356. .iter()
  11357. .filter(|(_, h)| h.0)
  11358. .map(|(&r, h)| (r, h.1))
  11359. .collect();
  11360. for ch in 0..4u8 {
  11361. let Some(value) = e.values[usize::from(ch)] else {
  11362. continue;
  11363. };
  11364. for high in [false, true] {
  11365. let h = 2 * ch + u8::from(high);
  11366. let src = if pack2 {
  11367. packed_half(outputs, &packs, row, h)
  11368. } else {
  11369. (!high).then_some((row, ch))
  11370. };
  11371. let found = src.and_then(|(r, c)| {
  11372. outputs.iter().position(|o| {
  11373. o.row == Some(u32::from(r)) && c >= o.col && c < o.col + o.cols
  11374. })
  11375. });
  11376. if let Some(id) = found {
  11377. let col = src.expect("found").1 - outputs[id].col;
  11378. stores.push((id, col, value, Some(high)));
  11379. }
  11380. }
  11381. }
  11382. }
  11383. for ch in 0..4u8 {
  11384. let Some(value) = e.values[usize::from(ch)] else {
  11385. continue;
  11386. };
  11387. if halves.is_some() {
  11388. break;
  11389. }
  11390. let found = match e.target {
  11391. Target::Color(n) => outputs
  11392. .iter()
  11393. .position(|o| o.kind == 16 && o.row == Some(u32::from(n)))
  11394. .map(|id| (id, ch)),
  11395. Target::Position(0) => by_kind(3).map(|id| (id, ch)),
  11396. Target::Depth => match ch {
  11397. 0 => by_kind(17)
  11398. .or(by_kind(18))
  11399. .or(by_kind(19))
  11400. .map(|id| (id, 0)),
  11401. 1 => by_kind(20).map(|id| (id, 0)),
  11402. 2 => by_kind(14).map(|id| (id, 0)),
  11403. _ => None,
  11404. },
  11405. Target::Param { usage, row } | Target::PrimitiveParam { usage, row } => {
  11406. let row = param_row(usage, row);
  11407. outputs
  11408. .iter()
  11409. .position(|o| {
  11410. row.is_some_and(|r| o.row == Some(u32::from(r)))
  11411. && ch >= o.col
  11412. && ch < o.col + o.cols
  11413. })
  11414. .map(|id| (id, ch - outputs[id].col))
  11415. }
  11416. Target::Null | Target::Unread => None,
  11417. Target::Position(n @ 1..=2) => {
  11418. // shortcut: without the misc vector (point size, render
  11419. // target or viewport index) pos1 and pos2 carry the clip
  11420. // then cull distances, in semantic order.
  11421. if outputs.iter().any(|o| matches!(o.kind, 4 | 5)) {
  11422. return Err("render-target or viewport index exports");
  11423. }
  11424. let mut dists: Vec<usize> = (0..outputs.len())
  11425. .filter(|&i| matches!(outputs[i].kind, 6 | 7))
  11426. .collect();
  11427. dists.sort_by_key(|&i| (outputs[i].kind, outputs[i].index));
  11428. let flat: Vec<(usize, u8)> = dists
  11429. .iter()
  11430. .flat_map(|&i| (0..outputs[i].cols).map(move |c| (i, c)))
  11431. .collect();
  11432. // Channels past the distances the signature declares are
  11433. // ones the clipper does not enable (`PA_CL_VS_OUT_CNTL`).
  11434. let k = usize::from(n - 1) * 4 + usize::from(ch);
  11435. flat.get(k).copied()
  11436. }
  11437. Target::Position(_) => return Err("clip, cull or point-size exports"),
  11438. Target::Primitive => return Err("a primitive export"),
  11439. };
  11440. if let Some((id, col)) = found {
  11441. stores.push((id, col, value, None));
  11442. }
  11443. }
  11444. fn elements<'l>(l: &'l mut Lower, primitive: bool) -> &'l mut Vec<SigElement> {
  11445. if primitive {
  11446. &mut l.s.prims
  11447. } else {
  11448. &mut l.s.outputs
  11449. }
  11450. }
  11451. if stores
  11452. .iter()
  11453. .any(|s| s.3.is_none() && elements(self, primitive)[s.0].half)
  11454. {
  11455. return Err("a 16-bit output the stage data does not mark");
  11456. }
  11457. // A mesh lane writes its own vertex or primitive, where it exports.
  11458. let at = if mesh {
  11459. let flat = self.mesh_thread();
  11460. let limit = if let Some(m) = self.s.mesh {
  11461. if primitive {
  11462. m.max_primitives
  11463. } else {
  11464. m.max_vertices
  11465. }
  11466. } else {
  11467. 0
  11468. };
  11469. let threads = self.s.threads.map(|t| t[0]).unwrap_or(u32::MAX);
  11470. let mesh_guard = if limit > 0 && threads > limit {
  11471. let lim = self.s.m.i32(limit);
  11472. let in_bounds = self.s.m.cmp(self.cur, pred::IULT, flat, lim);
  11473. match guard {
  11474. Some(g) => Some(self.s.m.bin(self.cur, Bin::And, g, in_bounds)),
  11475. None => Some(in_bounds),
  11476. }
  11477. } else {
  11478. guard
  11479. };
  11480. self.begin_guarded(mesh_guard)
  11481. } else {
  11482. None
  11483. };
  11484. let (name, opcode) = match (mesh, primitive) {
  11485. (false, _) => ("storeOutput", 5),
  11486. (true, false) => ("storeVertexOutput", 171),
  11487. (true, true) => ("storePrimitiveOutput", 172),
  11488. };
  11489. for (id, col, value, half) in stores {
  11490. let mut x = self.i32_of(value)?;
  11491. if let Some(high) = half {
  11492. // An f16 half, declared a 32-bit float on the host.
  11493. let c = self.cur;
  11494. if high {
  11495. let k16 = self.s.m.i32(16);
  11496. x = self.s.m.bin(c, Bin::LShr, x, k16);
  11497. }
  11498. let f32t = self.s.t.f32;
  11499. let f = self
  11500. .s
  11501. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]);
  11502. x = self.as_int(f);
  11503. }
  11504. let el = &mut elements(self, primitive)[id];
  11505. el.usage |= 1 << col;
  11506. let (suffix, x) = match el.comp {
  11507. 9 if half.is_some() => (".f32", self.as_float(x)),
  11508. 9 => {
  11509. let f = match self.floats.get(&value) {
  11510. Some(&f) => f,
  11511. None => self.as_float(x),
  11512. };
  11513. (".f32", f)
  11514. }
  11515. _ => (".i32", x),
  11516. };
  11517. let mut args = vec![
  11518. self.s.m.i32(id as u32),
  11519. self.s.m.i32(0),
  11520. self.s.m.i8(col),
  11521. x,
  11522. ];
  11523. if mesh {
  11524. args.push(self.mesh_thread());
  11525. }
  11526. let void = self.s.t.void;
  11527. self.s.op(
  11528. self.cur,
  11529. &format!("{name}{suffix}"),
  11530. Attr::NoUnwind,
  11531. void,
  11532. opcode,
  11533. &args,
  11534. );
  11535. }
  11536. self.end_guarded(at, &[]);
  11537. Ok(())
  11538. }
  11539. /// Mesh: `exp prim` as the lane's primitive. Each corner takes ten
  11540. /// bits: a 9-bit vertex index and, above it, its edge flag (bits 9, 19
  11541. /// and 29), which only the console's edge-flag rasterisation reads and
  11542. /// which is no part of the index. Bit 31 culls it (all indices 0: no
  11543. /// area).
  11544. fn emit_indices(&mut self, e: &Export, guard: Option<V>) -> Result<(), Why> {
  11545. let v = e.values[0].ok_or("a primitive export without its indices")?;
  11546. let x = self.i32_of(v)?;
  11547. let flat = self.mesh_thread();
  11548. let guard = if let Some(mesh) = self.s.mesh {
  11549. let threads = self.s.threads.map(|t| t[0]).unwrap_or(u32::MAX);
  11550. if threads > mesh.max_primitives {
  11551. let p = self.s.m.i32(mesh.max_primitives);
  11552. let in_bounds = self.s.m.cmp(self.cur, pred::IULT, flat, p);
  11553. match guard {
  11554. Some(g) => Some(self.s.m.bin(self.cur, Bin::And, g, in_bounds)),
  11555. None => Some(in_bounds),
  11556. }
  11557. } else {
  11558. guard
  11559. }
  11560. } else {
  11561. guard
  11562. };
  11563. let at = self.begin_guarded(guard);
  11564. let c = self.cur;
  11565. let z = self.s.m.i32(0);
  11566. let mut culled = self.s.m.cmp(c, pred::SLT, x, z);
  11567. // A primitive that names a vertex past the declared count, or one
  11568. // no lane writes (lane n writes vertex n alone), is culled too: the
  11569. // host would read a vertex nothing set, at any position.
  11570. let written = self.s.mesh.map(|m| {
  11571. m.max_vertices
  11572. .min(self.s.threads.map_or(u32::MAX, |t| t[0]))
  11573. });
  11574. let mut indices = [z; 3];
  11575. for (k, slot) in indices.iter_mut().enumerate() {
  11576. let (shift, mask) = (self.s.m.i32(10 * k as u32), self.s.m.i32(0x1FF));
  11577. let i = self.s.m.bin(c, Bin::LShr, x, shift);
  11578. let i = self.s.m.bin(c, Bin::And, i, mask);
  11579. if let Some(n) = written {
  11580. let n = self.s.m.i32(n);
  11581. let past = self.s.m.cmp(c, pred::IUGE, i, n);
  11582. culled = self.s.m.bin(c, Bin::Or, culled, past);
  11583. }
  11584. *slot = i;
  11585. }
  11586. let mut args = vec![flat];
  11587. for i in indices {
  11588. args.push(self.s.m.select(c, culled, z, i));
  11589. }
  11590. let void = self.s.t.void;
  11591. self.s
  11592. .op(c, "emitIndices", Attr::NoUnwind, void, 169, &args);
  11593. self.end_guarded(at, &[]);
  11594. Ok(())
  11595. }
  11596. /// The per-vertex arbitrary row no mesh output entry names but one
  11597. /// (the 2020 compiler's zeroed entry).
  11598. fn unnamed_row(&self) -> Option<u8> {
  11599. let StageIo::Ms(ms) = &self.x.native.io else {
  11600. return None;
  11601. };
  11602. let named = |r: u32| {
  11603. ms.outputs
  11604. .iter()
  11605. .any(|o| o.param & 0x80 == 0 && o.usage != Usage::Other(0) && u32::from(o.row) == r)
  11606. };
  11607. let free: std::collections::BTreeSet<u32> = self
  11608. .s
  11609. .outputs
  11610. .iter()
  11611. .filter(|o| o.kind == 0)
  11612. .filter_map(|o| o.row)
  11613. .filter(|&r| !named(r))
  11614. .collect();
  11615. match free.into_iter().collect::<Vec<_>>()[..] {
  11616. [r] => u8::try_from(r).ok(),
  11617. _ => None,
  11618. }
  11619. }
  11620. fn exit(&mut self, b: usize) -> Result<(), Stop> {
  11621. let offset = self.x.p.blocks[b]
  11622. .insts
  11623. .last()
  11624. .map_or(self.x.p.blocks[b].offset, |i| i.machine.offset);
  11625. let term = match self.x.st.exits[b] {
  11626. LaneExit::Jump(t) if self.counters.contains_key(&t) && self.rpo[t] <= self.rpo[b] => {
  11627. let ok = self.count_iteration(t, pred::IULT);
  11628. let abort = self.abort_block();
  11629. Term::CondBr(ok, self.block[t].expect("reachable"), abort)
  11630. }
  11631. LaneExit::Jump(t) => {
  11632. self.enter_loop(b, t, self.cur);
  11633. Term::Br(self.block[t].expect("reachable"))
  11634. }
  11635. LaneExit::Branch {
  11636. when,
  11637. taken,
  11638. not_taken,
  11639. } => {
  11640. // A negated condition branches the other way round.
  11641. let (cond, taken, not_taken) = match self.x.st.bools.node(when) {
  11642. _ if self.x.st.wide.contains(&b) => {
  11643. let c = self.wave_wide(b, when).map_err(|w| unsupported(offset, w))?;
  11644. (c, taken, not_taken)
  11645. }
  11646. Some((atom, Bool::TRUE, Bool::FALSE)) => {
  11647. let a = self
  11648. .atom(atom, self.cur)
  11649. .map_err(|w| unsupported(offset, w))?;
  11650. (a, not_taken, taken)
  11651. }
  11652. _ => {
  11653. let c = self
  11654. .boolean(when, self.cur)
  11655. .map_err(|w| unsupported(offset, w))?;
  11656. (c, taken, not_taken)
  11657. }
  11658. };
  11659. // A back edge is taken only below the iteration limit.
  11660. let back =
  11661. |l: &Self, to: usize| l.counters.contains_key(&to) && l.rpo[to] <= l.rpo[b];
  11662. // (No `xor` of a compare: a loop exit testing one hung the
  11663. // AMD driver.)
  11664. let cond = if back(self, taken) {
  11665. let ok = self.count_iteration(taken, pred::IULT);
  11666. self.s.m.bin(self.cur, Bin::And, cond, ok)
  11667. } else if back(self, not_taken) {
  11668. let stop = self.count_iteration(not_taken, pred::IUGE);
  11669. self.s.m.bin(self.cur, Bin::Or, cond, stop)
  11670. } else {
  11671. cond
  11672. };
  11673. // Critical edges get a block of their own, so loops have
  11674. // dedicated exits and preheaders as DXC emits them.
  11675. let (t, f) = (self.edge(b, taken), self.edge(b, not_taken));
  11676. for (to, via) in [(taken, t), (not_taken, f)] {
  11677. if !back(self, to) {
  11678. // From an edge block, or from here.
  11679. let from = if Some(via) == self.block[to] {
  11680. self.cur
  11681. } else {
  11682. via
  11683. };
  11684. self.enter_loop(b, to, from);
  11685. }
  11686. }
  11687. Term::CondBr(cond, t, f)
  11688. }
  11689. LaneExit::End => {
  11690. if self.s.pixel && !self.exported[b] && !self.has_done_export(b) {
  11691. // A lane leaving without its final export was killed.
  11692. let t = self.s.m.bool(true);
  11693. self.s
  11694. .op(self.cur, "discard", Attr::NoUnwind, self.s.t.void, 82, &[t]);
  11695. }
  11696. Term::Ret
  11697. }
  11698. LaneExit::Indirect => return Err(unsupported(offset, "an indirect jump")),
  11699. };
  11700. let _ = Exit::End;
  11701. self.s.m.terminate(self.cur, term);
  11702. Ok(())
  11703. }
  11704. /// A forward edge into loop header `to` (from DXIL block `via`) starts
  11705. /// its count at 0.
  11706. fn enter_loop(&mut self, _from: usize, to: usize, via: usize) {
  11707. if let Some((_, incoming)) = self.counters.get_mut(&to) {
  11708. let z = self.s.m.i32(0);
  11709. incoming.push((z, via));
  11710. }
  11711. }
  11712. /// A back edge to header `to` (a back edge keeps its block, no
  11713. /// critical-edge block): the count goes up; the result compares it with
  11714. /// [`LOOP_LIMIT`] by `p` (below: go on; at or above: stop).
  11715. fn count_iteration(&mut self, to: usize, p: u8) -> V {
  11716. let c = self.cur;
  11717. let (phi, _) = self.counters[&to];
  11718. let one = self.s.m.i32(1);
  11719. let next = self.s.m.bin(c, Bin::Add, phi, one);
  11720. self.s.m.tag(phi, Tag::Counter);
  11721. self.s.m.tag(next, Tag::Counter);
  11722. // Per stage unless the switch names one: a loop that never meets its
  11723. // exit (a count read from a buffer the host has not got yet, say)
  11724. // runs to the limit in every lane. A million iterations a pixel
  11725. // hung the GPU for seconds a draw until Windows reset it
  11726. // (PS_Textured_Eight, 2026-11-24, run 12).
  11727. // shortcut: a pixel loop past 128 iterations, a vertex or mesh loop
  11728. // past 256 or a compute loop past 4,096 is cut short. (They were
  11729. // 1,024, 4,096 and 65,536: the opening cutscene then lost the card
  11730. // 14-25 frames in, in a minimap or shadow mesh draw; with every
  11731. // loop cut at 64 it ran 90 frames. Raise them again once shaders
  11732. // stop reading data that is not there yet.)
  11733. let limit = match super::loop_limit() {
  11734. LOOP_LIMIT if self.s.pixel => 1 << 7,
  11735. LOOP_LIMIT if self.s.mesh.is_some() || self.s.threads.is_none() => 1 << 8,
  11736. LOOP_LIMIT => 1 << 12,
  11737. named => named,
  11738. };
  11739. let limit = self.s.m.i32(limit);
  11740. self.counters
  11741. .get_mut(&to)
  11742. .expect("header")
  11743. .1
  11744. .push((next, c));
  11745. let over = self.s.m.cmp(c, p, next, limit);
  11746. self.s.m.tag(over, Tag::Counter);
  11747. over
  11748. }
  11749. /// The block a lane stopped by [`LOOP_LIMIT`] leaves through.
  11750. fn abort_block(&mut self) -> usize {
  11751. if let Some(a) = self.abort {
  11752. return a;
  11753. }
  11754. let a = self.s.m.new_block();
  11755. if self.s.pixel {
  11756. let t = self.s.m.bool(true);
  11757. self.s
  11758. .op(a, "discard", Attr::NoUnwind, self.s.t.void, 82, &[t]);
  11759. }
  11760. self.s.m.terminate(a, Term::Ret);
  11761. self.abort = Some(a);
  11762. a
  11763. }
  11764. /// The DXIL block a branch from IR block `from` to `to` goes to.
  11765. fn edge(&mut self, from: usize, to: usize) -> usize {
  11766. let target = self.block[to].expect("reachable");
  11767. let preds = self.x.p.blocks[to]
  11768. .preds
  11769. .iter()
  11770. .filter(|&&q| self.block[q].is_some())
  11771. .count();
  11772. // Back edges stay as they are: the exiting block is the latch.
  11773. if preds < 2 || self.rpo[to] <= self.rpo[from] {
  11774. return target;
  11775. }
  11776. let e = self.s.m.new_block();
  11777. self.s.m.terminate(e, Term::Br(target));
  11778. self.edges.insert((from, to), e);
  11779. e
  11780. }
  11781. fn fill_phis(&mut self) -> Result<(), Stop> {
  11782. let p = self.x.p;
  11783. // Lane-mask joins first (what an edge brings may ask for more joins,
  11784. // of masks and of numbers): each edge's mask as the structure
  11785. // tracked it, a constant or a scalar-built one included.
  11786. let st = self.x.st;
  11787. while let Some((v, b, i)) = self.pending_masks.pop() {
  11788. let phi = &p.blocks[b].phis[i];
  11789. let offset = p.blocks[b].offset;
  11790. let args = st
  11791. .phi_masks
  11792. .get(&phi.value)
  11793. .ok_or_else(|| unsupported(offset, "a lane-mask join of an untracked mask"))?;
  11794. let mut incoming = Vec::new();
  11795. for (n, &q) in p.blocks[b].preds.iter().enumerate() {
  11796. let Some(qb) = self.tail[q] else { continue };
  11797. let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb);
  11798. let x = self.boolean(args[n], qb).map_err(|w| unsupported(offset, w))?;
  11799. incoming.push((x, qb));
  11800. }
  11801. self.s.m.set_phi(v, incoming);
  11802. }
  11803. // A join that only another join reads is read wherever that one is. Left
  11804. // unmarked, a value without a DXIL form coming into it became zero without a
  11805. // word (the looked-up tint of the material resolve programs, whose size
  11806. // computation had no value, was zero in every lane that way).
  11807. // shortcut: only with `VICTORY_STRICT_JOINS` set (the offline pack
  11808. // listing sets it to count them): 40 programs that translate today
  11809. // stop by name with it (vehicle paint pixel shaders at "the first
  11810. // half of an interpolation", foliage mesh shaders); until those are
  11811. // lowered they keep drawing with that zero.
  11812. static STRICT: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  11813. let strict = *STRICT.get_or_init(|| std::env::var_os("VICTORY_STRICT_JOINS").is_some());
  11814. let mut work: Vec<Value> = if strict {
  11815. self.read_phis.iter().copied().collect()
  11816. } else {
  11817. Vec::new()
  11818. };
  11819. while let Some(v) = work.pop() {
  11820. let Some(&(b, i)) = self.phi_at.get(&v) else {
  11821. continue;
  11822. };
  11823. for &a in &p.blocks[b].phis[i].args {
  11824. if self.phi_at.contains_key(&a) && self.read_phis.insert(a) {
  11825. work.push(a);
  11826. }
  11827. }
  11828. }
  11829. for (v, b, i) in std::mem::take(&mut self.data_phis) {
  11830. let phi = &p.blocks[b].phis[i];
  11831. let bit = phi.reg == Reg::Scc;
  11832. // A join of numbers with dead registers (`dead`): the paths that bring those
  11833. // never read the result, so they bring zero. Not for a join that is itself a
  11834. // lane mask (a ballot gives that one as data).
  11835. let st = self.x.st;
  11836. let numbers = !bit
  11837. && !st.masks.contains_key(&phi.value)
  11838. && !st.highs.contains_key(&phi.value)
  11839. && phi
  11840. .args
  11841. .iter()
  11842. .any(|a| matches!(self.vals.get(a), Some(Val::I32(_))));
  11843. let mut incoming = Vec::new();
  11844. for (n, &q) in p.blocks[b].preds.iter().enumerate() {
  11845. let Some(qb) = self.tail[q] else { continue };
  11846. let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb);
  11847. let arg = phi.args[n];
  11848. if self.read_phis.contains(&phi.value) && !self.vals.contains_key(&arg) {
  11849. let _ = self.lazy_barycentric(arg);
  11850. // A root parameter nothing read before the join (user
  11851. // data is loaded on first use, in the entry block).
  11852. if !self.vals.contains_key(&arg)
  11853. && let Some(&(param, dword)) = self.params.get(&arg)
  11854. {
  11855. let val = self.user(param, dword);
  11856. self.vals.insert(arg, val);
  11857. }
  11858. }
  11859. let x = match (self.vals.get(&arg).copied(), bit) {
  11860. (Some(Val::I32(x)), false) | (Some(Val::Bit(x)), true) => x,
  11861. (Some(Val::Missing(_)) | None, false)
  11862. if numbers && self.dead(arg, &mut Vec::new()) =>
  11863. {
  11864. self.s.m.i32(0)
  11865. }
  11866. // A lane mask joined with numbers (a traversal that keeps its lanes' masks on
  11867. // a stack with its node numbers): the mask comes as the number it is, the
  11868. // ballot of its lanes where it is written.
  11869. (Some(Val::Missing(_)) | None, false)
  11870. if self.read_phis.contains(&phi.value)
  11871. && self.mask_data == MaskData::Console
  11872. && (st.masks.contains_key(&arg) || st.highs.contains_key(&arg)) =>
  11873. {
  11874. match self.mask_dword(arg) {
  11875. Ok(x) => x,
  11876. Err(why) => return Err(Stop::Retry(phi.value, why)),
  11877. }
  11878. }
  11879. // SCC of a mask operation ("some lane is left") joined with a scalar test:
  11880. // the compiler branches around code that sets SCC and tests SCC after it,
  11881. // the skip bringing "no lane" along. As data it is "some lane of the wave
  11882. // has the bit" - right only if the wave took that skip together, as the
  11883. // console does: a lane that skipped alone would bring "some lane" where the
  11884. // console has the skipped code's SCC. So the branch must be one the wave
  11885. // takes together; else its region is named for `emit`'s retry to widen it.
  11886. (Some(Val::Missing(_)) | None, true)
  11887. if self.read_phis.contains(&phi.value)
  11888. && self.mask_data == MaskData::Console
  11889. && st.scc_some.contains_key(&arg) =>
  11890. {
  11891. let per_lane = !st.wide.contains(&q)
  11892. && matches!(st.exits[q], LaneExit::Branch { when, .. }
  11893. if !st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_))));
  11894. if per_lane {
  11895. for &other in p.blocks[b].preds.iter().filter(|&&o| o != q) {
  11896. need(other);
  11897. }
  11898. return Err(Stop::Retry(phi.value, LANE_MASK));
  11899. }
  11900. match self.scc_some(arg) {
  11901. Ok(x) => x,
  11902. Err(why) => return Err(Stop::Retry(phi.value, why)),
  11903. }
  11904. }
  11905. (Some(Val::Bit(_)), false) if self.read_phis.contains(&phi.value) => {
  11906. return Err(Stop::Retry(phi.value, "an SCC joined with SGPR values"));
  11907. }
  11908. (Some(Val::Missing(why)), _) if self.read_phis.contains(&phi.value) => {
  11909. return Err(Stop::Retry(phi.value, why));
  11910. }
  11911. _ if self.read_phis.contains(&phi.value) => {
  11912. return Err(Stop::Retry(phi.value, "a join of mismatched values"));
  11913. }
  11914. _ if bit => self.s.m.bool(false),
  11915. _ => self.s.m.i32(0),
  11916. };
  11917. incoming.push((x, qb));
  11918. }
  11919. self.s.m.set_phi(v, incoming);
  11920. }
  11921. for (phi, incoming) in std::mem::take(&mut self.counters).into_values() {
  11922. self.s.m.set_phi(phi, incoming);
  11923. }
  11924. Ok(())
  11925. }
  11926. }
  11927. /// The DXIL interpolation mode of a kind of barycentrics (none for the
  11928. /// pull model).
  11929. fn interp_mode(kind: Barycentric) -> Option<u8> {
  11930. Some(match kind {
  11931. Barycentric::PerspectiveCenter => 2,
  11932. Barycentric::PerspectiveCentroid => 3,
  11933. Barycentric::PerspectiveSample => 6,
  11934. Barycentric::LinearCenter => 4,
  11935. Barycentric::LinearCentroid => 5,
  11936. Barycentric::LinearSample => 7,
  11937. Barycentric::PerspectivePullModel => return None,
  11938. })
  11939. }
  11940. #[cfg(test)]
  11941. mod tests {
  11942. use super::{Lowered, Numeric, Parts, buffer_format, half_shift, lower};
  11943. use crate::native::{
  11944. ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource,
  11945. };
  11946. use crate::{io, ir, resource, structure};
  11947. const S_ENDPGM: u32 = 0xBF81_0000;
  11948. #[test]
  11949. fn packed_pixel_inputs_find_their_second_row() {
  11950. use super::super::container::SigElement;
  11951. use super::half_input_partners;
  11952. use crate::native::{PsInput, Usage};
  11953. let entry = |row, row2, pack2| PsInput {
  11954. usage: Usage::Generic,
  11955. row,
  11956. mask: 0xF,
  11957. attr: row,
  11958. flat: false,
  11959. fp16: true,
  11960. pack2,
  11961. row2,
  11962. };
  11963. let element = |row| SigElement {
  11964. name: "TEXCOORD".into(),
  11965. index: row,
  11966. kind: 0,
  11967. comp: 9,
  11968. interp: 2,
  11969. row: Some(row),
  11970. col: 0,
  11971. cols: 4,
  11972. usage: 0,
  11973. half: true,
  11974. };
  11975. // Rows 0 and 3 pack and leave their second row out; 5 names its
  11976. // own (6). Unnamed 16-bit rows: 1, 4, 6, 7.
  11977. let io = StageIo::Ps {
  11978. inputs: vec![entry(0, 0, true), entry(3, 3, true), entry(5, 6, true)],
  11979. input_addr: 0,
  11980. db_shader_control: 0,
  11981. patches: vec![],
  11982. };
  11983. let sig: Vec<_> = [0, 1, 3, 4, 5, 6, 7].map(element).into();
  11984. let p = half_input_partners(&io, &sig);
  11985. assert_eq!(p.get(&0), Some(&1));
  11986. assert_eq!(p.get(&3), Some(&4));
  11987. assert_eq!(p.get(&5), None);
  11988. }
  11989. /// The packed pedestrian layouts of the title: an element
  11990. /// behind another one in its register follows in the first parameter
  11991. /// with a dword left, and is not a half of its register's row.
  11992. #[test]
  11993. fn packed_elements_behind_another_take_the_first_free_dword() {
  11994. use super::super::container::SigElement;
  11995. use super::packed_half;
  11996. let element = |index, row, col, cols| SigElement {
  11997. name: "TEXCOORD".into(),
  11998. index,
  11999. kind: 0,
  12000. comp: 9,
  12001. interp: 2,
  12002. row: Some(row),
  12003. col,
  12004. cols,
  12005. usage: 0,
  12006. half: true,
  12007. };
  12008. // MS_VS_PedTransformPreSkinD_Packed 005fe88ec1bdc0c7 and its pixel
  12009. // shader 93667197d3d05e1c: TEXCOORD6 is one value at register 4
  12010. // column 3; parameter 3 (rows 6 and 7) carries it in dword 3.
  12011. let sig = vec![
  12012. element(1, 2, 0, 4),
  12013. element(2, 3, 0, 4),
  12014. element(4, 4, 0, 3),
  12015. element(6, 4, 3, 1),
  12016. element(3, 5, 0, 4),
  12017. element(5, 6, 0, 4),
  12018. element(7, 7, 0, 2),
  12019. element(9, 9, 0, 3),
  12020. element(11, 10, 0, 3),
  12021. element(15, 12, 0, 4),
  12022. ];
  12023. let packs = [
  12024. (2, Some(3)),
  12025. (4, Some(5)),
  12026. (6, Some(7)),
  12027. (9, Some(10)),
  12028. (12, None),
  12029. ];
  12030. let at = |a, h| packed_half(&sig, &packs, a, h);
  12031. // Parameter 2: TEXCOORD4's three values, a zero half, TEXCOORD3.
  12032. assert_eq!(at(4, 2), Some((4, 2)));
  12033. assert_eq!(at(4, 3), None);
  12034. assert_eq!(at(4, 4), Some((5, 0)));
  12035. assert_eq!(at(4, 7), Some((5, 3)));
  12036. // Parameter 3: TEXCOORD5, TEXCOORD7, then TEXCOORD6 alone.
  12037. assert_eq!(at(6, 3), Some((6, 3)));
  12038. assert_eq!(at(6, 5), Some((7, 1)));
  12039. assert_eq!(at(6, 6), Some((4, 3)));
  12040. assert_eq!(at(6, 7), None);
  12041. // Parameters without such an element are as before.
  12042. assert_eq!(at(9, 3), None);
  12043. assert_eq!(at(9, 4), Some((10, 0)));
  12044. assert_eq!(at(12, 3), Some((12, 3)));
  12045. assert_eq!(at(12, 4), None);
  12046. // The common layout (29805d23a495cdf8): TEXCOORD7 is two values at
  12047. // register 1 columns 2-3; parameter 0 is TEXCOORD0, TEXCOORD1,
  12048. // TEXCOORD7.
  12049. let sig = vec![
  12050. element(0, 1, 0, 2),
  12051. element(7, 1, 2, 2),
  12052. element(1, 2, 0, 4),
  12053. element(2, 3, 0, 4),
  12054. element(4, 4, 0, 3),
  12055. ];
  12056. let packs = [(3, Some(4)), (1, Some(2))];
  12057. let at = |a, h| packed_half(&sig, &packs, a, h);
  12058. assert_eq!(at(1, 1), Some((1, 1)));
  12059. assert_eq!(at(1, 2), Some((2, 0)));
  12060. assert_eq!(at(1, 5), Some((2, 3)));
  12061. assert_eq!(at(1, 6), Some((1, 2)));
  12062. assert_eq!(at(1, 7), Some((1, 3)));
  12063. assert_eq!(at(3, 6), Some((4, 2)));
  12064. assert_eq!(at(3, 7), None);
  12065. // A row no element holds gives nothing, as before.
  12066. assert_eq!(packed_half(&sig, &[(8, None)], 8, 0), None);
  12067. }
  12068. /// Whether a synthetic compute program translates with these input registers.
  12069. fn lowers(words: &[u32], rsrc2: u32) -> Result<(), crate::ShaderError> {
  12070. let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
  12071. let native = NativeProgram {
  12072. stage: HwStage::Cs,
  12073. wave64: false,
  12074. vgprs: 256,
  12075. layout: vec![],
  12076. used: vec![],
  12077. io: StageIo::Cs(ComputeIo {
  12078. rsrc2,
  12079. threads: [1, 1, 1],
  12080. }),
  12081. code,
  12082. };
  12083. let p = ir::build(&native.code, false, 256).unwrap();
  12084. let st = structure::structure(&p).unwrap();
  12085. let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
  12086. let io = io::raise(&p, &native).unwrap();
  12087. lower(&Parts {
  12088. native: &native,
  12089. p: &p,
  12090. st: &st,
  12091. io: &io,
  12092. res: &res,
  12093. inputs: vec![],
  12094. outputs: vec![],
  12095. prims: vec![],
  12096. mesh_stride: 0,
  12097. })
  12098. .map(|_| ())
  12099. }
  12100. /// Lowers a compute program with the root parameters `layout` (in user
  12101. /// SGPRs from s0 on) and the used resources `used`.
  12102. fn lower_with(
  12103. words: &[u32],
  12104. layout: Vec<RootParam>,
  12105. used: Vec<UsedResource>,
  12106. ) -> Result<Lowered, crate::ShaderError> {
  12107. lower_wave(words, layout, used, false)
  12108. }
  12109. /// [`lower_with`] in wave64 if `wave64`.
  12110. fn lower_wave(
  12111. words: &[u32],
  12112. layout: Vec<RootParam>,
  12113. used: Vec<UsedResource>,
  12114. wave64: bool,
  12115. ) -> Result<Lowered, crate::ShaderError> {
  12116. let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
  12117. let sgprs: u32 = layout.iter().map(|p| p.sgprs).sum();
  12118. let native = NativeProgram {
  12119. stage: HwStage::Cs,
  12120. wave64,
  12121. vgprs: 256,
  12122. layout,
  12123. used,
  12124. io: StageIo::Cs(ComputeIo {
  12125. // The layout's user SGPRs (at least two), 512 bytes of LDS.
  12126. rsrc2: 1 << 15 | sgprs.max(2) << 1,
  12127. threads: [1, 1, 1],
  12128. }),
  12129. code,
  12130. };
  12131. let p = ir::build(&native.code, wave64, 256).unwrap();
  12132. let st = structure::structure(&p).unwrap();
  12133. let res = resource::track(&p, &native.layout, native.stage, Some(&st))?;
  12134. let io = io::raise(&p, &native).unwrap();
  12135. lower(&Parts {
  12136. native: &native,
  12137. p: &p,
  12138. st: &st,
  12139. io: &io,
  12140. res: &res,
  12141. inputs: vec![],
  12142. outputs: vec![],
  12143. prims: vec![],
  12144. mesh_stride: 0,
  12145. })
  12146. }
  12147. /// Root parameter `slot` in user SGPRs from `user_data` on.
  12148. fn root(root: RootType, user_data: u8, slot: u8) -> RootParam {
  12149. RootParam {
  12150. root,
  12151. table_offset_dwords: 0,
  12152. sgprs: if root == RootType::Descriptor { 2 } else { 1 },
  12153. base_register: 0,
  12154. user_data,
  12155. slot,
  12156. }
  12157. }
  12158. /// Lowers a one-thread compute program that copies four root constants
  12159. /// (s0..s3) into v1..v4, runs `body`, and stores v0 to a raw buffer from a
  12160. /// descriptor table, so the vector instructions in `body` have an effect.
  12161. fn lowers_valu(body: &[u32]) -> Result<(), crate::ShaderError> {
  12162. let mut words = vec![
  12163. 0xBE85_0380, // s_mov_b32 s5, 0
  12164. 0xF408_0202, // s_load_dwordx4 s[8:11], s[4:5], 0
  12165. 0xFA00_0000,
  12166. ];
  12167. // v_mov_b32 v1..v4, s0..s3
  12168. words.extend((0..4u32).map(|i| 0x7E00_0200 | (i + 1) << 17 | i));
  12169. words.extend_from_slice(body);
  12170. words.extend_from_slice(&[
  12171. 0xE070_0000, // buffer_store_dword v0, off, s[8:11], 0
  12172. 0x8002_0000,
  12173. S_ENDPGM,
  12174. ]);
  12175. let constants = RootParam {
  12176. sgprs: 4,
  12177. ..root(RootType::Constants, 0, 0)
  12178. };
  12179. let buffer = UsedResource {
  12180. kind: ResourceType::Uav,
  12181. root: RootType::Table,
  12182. table_offset_dwords: 0,
  12183. lower_bound: 0,
  12184. stride: 0,
  12185. dwords: 4,
  12186. user_data: 4,
  12187. slot: 1,
  12188. };
  12189. lower_with(
  12190. &words,
  12191. vec![constants, root(RootType::Table, 4, 1)],
  12192. vec![buffer],
  12193. )
  12194. .map(|_| ())
  12195. }
  12196. #[test]
  12197. fn the_24_bit_multiplies_lower_both_halves() {
  12198. // VOP2 `op v0, v1, v2`: v_mul_i32_i24 and v_mul_u32_u24 (the low
  12199. // dword) and v_mul_hi_i32_i24 and v_mul_hi_u32_u24 (the high one).
  12200. for op in [0x09u32, 0x0A, 0x0B, 0x0C] {
  12201. let word = op << 25 | 2 << 9 | 0x101;
  12202. lowers_valu(&[word]).unwrap_or_else(|e| panic!("VOP2 {op:#x}: {e}"));
  12203. }
  12204. }
  12205. #[test]
  12206. fn buffer_cache_invalidations_lower_as_no_ops() {
  12207. // MUBUF opcode 0x071/0x072 with no data operand: the title asks the
  12208. // host to invalidate its cached view of a buffer.
  12209. assert!(lowers(&[0xE1C4_0000, 0, S_ENDPGM], 0).is_ok(), "buffer_gl0_inv");
  12210. assert!(lowers(&[0xE1C8_0000, 0, S_ENDPGM], 0).is_ok(), "buffer_gl1_inv");
  12211. }
  12212. #[test]
  12213. fn sums_of_absolute_differences_lower() {
  12214. // VOP3 `op v0, v1, v2, v3`: v_sad_u8, v_sad_hi_u8, v_sad_u16,
  12215. // v_sad_u32 and v_msad_u8.
  12216. for op in [0x15Au32, 0x15B, 0x15C, 0x15D, 0x171] {
  12217. let words = [0xD400_0000 | op << 16, 0x101 | 0x102 << 9 | 0x103 << 18];
  12218. lowers_valu(&words).unwrap_or_else(|e| panic!("VOP3 {op:#x}: {e}"));
  12219. }
  12220. }
  12221. #[test]
  12222. fn a_scalar_carry_chain_reaches_the_select() {
  12223. // The high dword of a 64-bit add or subtract, then a select on the
  12224. // carry (borrow) the high half leaves in SCC, and a branch on it
  12225. // (only code with an effect needs its operands).
  12226. let add = [
  12227. 0xBE80_03C1, // s_mov_b32 s0, -1
  12228. 0xBE81_0380, // s_mov_b32 s1, 0
  12229. 0x8000_8100, // s_add_u32 s0, s0, 1
  12230. 0x8201_8001, // s_addc_u32 s1, s1, 0
  12231. 0x8502_0001, // s_cselect_b32 s2, s1, s0
  12232. 0xBF07_8002, // s_cmp_lg_u32 s2, 0
  12233. 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm
  12234. 0xBE83_0380, // s_mov_b32 s3, 0
  12235. S_ENDPGM,
  12236. ];
  12237. let sub = [
  12238. 0xBE80_0380, // s_mov_b32 s0, 0
  12239. 0xBE81_0380, // s_mov_b32 s1, 0
  12240. 0x8080_8100, // s_sub_u32 s0, s0, 1
  12241. 0x8281_8001, // s_subb_u32 s1, s1, 0
  12242. 0x8502_0001, // s_cselect_b32 s2, s1, s0
  12243. 0xBF07_8002, // s_cmp_lg_u32 s2, 0
  12244. 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm
  12245. 0xBE83_0380, // s_mov_b32 s3, 0
  12246. S_ENDPGM,
  12247. ];
  12248. for words in [add, sub] {
  12249. lowers(&words, 0).unwrap();
  12250. }
  12251. }
  12252. fn perm_features(selector: u32) -> u64 {
  12253. // Synthetic compute shader:
  12254. // v0 is the thread ID and can supply a dynamic selector.
  12255. // Store the result in LDS to keep the permutation live.
  12256. let words = [
  12257. 0x7E02_02FFu32,
  12258. 0x817F_34AB,
  12259. 0x7E04_02FF,
  12260. 0xFE01_56CD,
  12261. 0xD744_0003,
  12262. 257 | (258 << 9) | (selector << 18),
  12263. 0x3408_0082,
  12264. 0xD834_0000,
  12265. 0x0000_0304,
  12266. S_ENDPGM,
  12267. ];
  12268. let code: Vec<u8> = words.iter()
  12269. .flat_map(|w| w.to_le_bytes())
  12270. .collect();
  12271. let native = NativeProgram {
  12272. stage: HwStage::Cs,
  12273. wave64: false,
  12274. vgprs: 256,
  12275. layout: vec![],
  12276. used: vec![],
  12277. io: StageIo::Cs(ComputeIo {
  12278. rsrc2: 1 << 15,
  12279. threads: [64, 1, 1],
  12280. }),
  12281. code,
  12282. };
  12283. let p = ir::build(&native.code, false, 256).unwrap();
  12284. assert!(p.blocks.iter()
  12285. .flat_map(|b| &b.insts)
  12286. .any(|i| i.name() == "v_perm_b32"));
  12287. let st = structure::structure(&p).unwrap();
  12288. let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
  12289. let io = io::raise(&p, &native).unwrap();
  12290. let emitted = lower(&Parts {
  12291. native: &native,
  12292. p: &p,
  12293. st: &st,
  12294. io: &io,
  12295. res: &res,
  12296. inputs: vec![],
  12297. outputs: vec![],
  12298. prims: vec![],
  12299. mesh_stride: 0,
  12300. }).unwrap();
  12301. let container =
  12302. crate::Container::parse(&emitted.dxil).unwrap();
  12303. let features =
  12304. container.part(crate::FourCC::SFI0).unwrap();
  12305. u64::from_le_bytes(features.data.try_into().unwrap())
  12306. }
  12307. #[test]
  12308. fn perm_constant_selector_needs_no_int64() {
  12309. assert_eq!(perm_features(128) & 0x8000, 0);
  12310. }
  12311. #[test]
  12312. fn perm_dynamic_selector_needs_no_int64() {
  12313. assert_eq!(
  12314. perm_features(256) & 0x8000,
  12315. 0,
  12316. "dynamic v_perm_b32 must not require INT64"
  12317. );
  12318. }
  12319. #[test]
  12320. fn a_descriptor_selected_by_scc_picks_its_heap_index() {
  12321. // Two buffer descriptors loaded from the table at s0, one picked by
  12322. // a root constant (s1) with s_cselect_b64 per half, and loaded
  12323. // through by index and stored to LDS so the load is needed.
  12324. let words = [
  12325. 0xBE84_0300, // s_mov_b32 s4, s0
  12326. 0xBE85_0380, // s_mov_b32 s5, 0
  12327. 0xF408_0202,
  12328. 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null
  12329. 0xF408_0302,
  12330. 0xFA00_0010, // s_load_dwordx4 s[12:15], s[4:5], 0x10
  12331. 0xBF06_8001, // s_cmp_eq_u32 s1, 0
  12332. 0x8590_0C08, // s_cselect_b64 s[16:17], s[8:9], s[12:13]
  12333. 0x8592_0E0A, // s_cselect_b64 s[18:19], s[10:11], s[14:15]
  12334. 0xE030_2000,
  12335. 0x8004_0100, // buffer_load_dword v1, v0, s[16:19], 0 idxen
  12336. 0xD834_0000,
  12337. 0x0000_0100, // ds_write_b32 v0, v1
  12338. S_ENDPGM,
  12339. ];
  12340. let layout = || vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)];
  12341. // Both are structured buffers of dwords in the table's range.
  12342. let used = || {
  12343. vec![UsedResource {
  12344. kind: ResourceType::Srv,
  12345. root: RootType::Table,
  12346. table_offset_dwords: 0,
  12347. lower_bound: 0,
  12348. stride: 4,
  12349. dwords: 4,
  12350. user_data: 0,
  12351. slot: 0,
  12352. }]
  12353. };
  12354. lower_with(&words, layout(), used()).unwrap();
  12355. }
  12356. /// Tables of 2D textures at s0 and samplers at s1.
  12357. fn texture_tables() -> (Vec<RootParam>, Vec<UsedResource>) {
  12358. let range = |kind, user_data, slot| UsedResource {
  12359. kind,
  12360. root: RootType::Table,
  12361. table_offset_dwords: 0,
  12362. lower_bound: 0,
  12363. stride: 0,
  12364. dwords: if kind == ResourceType::Sampler { 4 } else { 8 },
  12365. user_data,
  12366. slot,
  12367. };
  12368. (
  12369. vec![root(RootType::Table, 0, 0), root(RootType::Table, 1, 1)],
  12370. vec![
  12371. range(ResourceType::Srv, 0, 0),
  12372. range(ResourceType::Sampler, 1, 1),
  12373. ],
  12374. )
  12375. }
  12376. #[test]
  12377. fn waterfall_loops_over_per_lane_descriptors_sample_with_each_lanes_own() {
  12378. use crate::resource::tests::{
  12379. WATERFALL_FETCHED_WAVE32, WATERFALL_FETCHED_WAVE64, WATERFALL_PICKED_WAVE32,
  12380. };
  12381. for (words, wave64) in [
  12382. (WATERFALL_FETCHED_WAVE32, false),
  12383. (WATERFALL_FETCHED_WAVE64, true),
  12384. (WATERFALL_PICKED_WAVE32, false),
  12385. ] {
  12386. let (layout, used) = texture_tables();
  12387. let l = lower_wave(words, layout, used, wave64).unwrap();
  12388. // The loop's reads of the first lane became each lane's own
  12389. // dwords: no wave operation is left.
  12390. assert_eq!(l.nonuniform_handles, 1);
  12391. assert!(!l.wave_ops);
  12392. }
  12393. }
  12394. /// [`texture_tables`] with a raw buffer UAV at dword 16 of the first.
  12395. pub(crate) fn texture_and_uav_tables() -> (Vec<RootParam>, Vec<UsedResource>) {
  12396. let (layout, mut used) = texture_tables();
  12397. used.push(UsedResource {
  12398. kind: ResourceType::Uav,
  12399. root: RootType::Table,
  12400. table_offset_dwords: 16,
  12401. lower_bound: 0,
  12402. stride: 0,
  12403. dwords: 4,
  12404. user_data: 0,
  12405. slot: 0,
  12406. });
  12407. (layout, used)
  12408. }
  12409. #[test]
  12410. fn waterfall_loops_over_descriptors_joined_per_lane_sample_with_each_lanes_own() {
  12411. use crate::resource::tests::{WATERFALL_JOINED_MIXED_WAVE32, WATERFALL_JOINED_WAVE32};
  12412. for words in [WATERFALL_JOINED_WAVE32, WATERFALL_JOINED_MIXED_WAVE32] {
  12413. let (layout, used) = texture_and_uav_tables();
  12414. let l = lower_wave(words, layout, used, false).unwrap();
  12415. // One image handle, from the join's per-lane heap index.
  12416. assert_eq!(l.nonuniform_handles, 1);
  12417. assert!(!l.wave_ops);
  12418. }
  12419. }
  12420. #[test]
  12421. fn scalar_bit_tests_lower() {
  12422. // Each tests one bit of a constant into SCC and branches on it (only
  12423. // code with an effect needs its operands).
  12424. let tail = [
  12425. 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm
  12426. 0xBE84_0380, // s_mov_b32 s4, 0
  12427. S_ENDPGM,
  12428. ];
  12429. let bit_tests: [&[u32]; 4] = [
  12430. &[0xBE81_0387, 0xBF0C_8301], // s_mov_b32 s1, 7; s_bitcmp0_b32 s1, 3
  12431. &[0xBE81_0387, 0xBF0D_8301], // s_mov_b32 s1, 7; s_bitcmp1_b32 s1, 3
  12432. &[
  12433. 0xBE80_0387, // s_mov_b32 s0, 7
  12434. 0xBE81_0380, // s_mov_b32 s1, 0
  12435. 0xBF0E_8300, // s_bitcmp0_b64 s[0:1], 3
  12436. ],
  12437. &[
  12438. 0xBE80_0387, // s_mov_b32 s0, 7
  12439. 0xBE81_0380, // s_mov_b32 s1, 0
  12440. 0xBF0F_8300, // s_bitcmp1_b64 s[0:1], 3
  12441. ],
  12442. ];
  12443. for head in bit_tests {
  12444. let words: Vec<u32> = head.iter().chain(&tail).copied().collect();
  12445. lowers(&words, 0).unwrap();
  12446. }
  12447. }
  12448. #[test]
  12449. #[ignore = "ours marks joins read through joins only with VICTORY_STRICT_JOINS (40 programs stop otherwise)"]
  12450. fn a_missing_value_stays_missing_through_two_live_joins() {
  12451. let mut words = [
  12452. 0xF490_0180,
  12453. 0, // s_memtime s[6:7]
  12454. 0xBF06_8000, // s_cmp_eq_u32 s0, 0 (s0 = group id X)
  12455. 0xBF85_0001, // skip the first overwrite
  12456. 0xBE86_0380, // s_mov_b32 s6, 0
  12457. 0xBF06_8101, // s_cmp_eq_u32 s1, 1 (s1 = group id Y)
  12458. 0xBF85_0001, // skip the second overwrite
  12459. 0xBE86_0381, // s_mov_b32 s6, 1
  12460. 0xBF07_8006, // s_cmp_lg_u32 s6, 0
  12461. 0xBF85_0001, // use the result to branch
  12462. 0xBE83_0380,
  12463. S_ENDPGM,
  12464. ];
  12465. let group_ids_xy = 3 << 7;
  12466. // Compare to a direct read so future timestamp support works in both cases.
  12467. let refusal = |code: &[u32]| match lowers(code, group_ids_xy) {
  12468. Ok(()) => None,
  12469. Err(crate::ShaderError::Unsupported { what, .. }) => Some(what),
  12470. Err(error) => panic!("{error}"),
  12471. };
  12472. let direct = [&words[..2], &words[8..]].concat();
  12473. assert_eq!(refusal(&words), refusal(&direct));
  12474. words[8] = 0xBF07_8000; // read the group id instead; the timestamp is dead
  12475. lowers(&words, group_ids_xy).expect("dead timestamp");
  12476. }
  12477. #[test]
  12478. fn buffer_formats_by_number() {
  12479. // The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM,
  12480. // 2_10_10_10_UNORM, 16_FLOAT, 32_32_32_32_FLOAT.
  12481. assert_eq!(buffer_format(56), Some((&[8, 8, 8, 8][..], Numeric::Unorm)));
  12482. assert_eq!(buffer_format(24), Some((&[16, 16][..], Numeric::Snorm)));
  12483. assert_eq!(
  12484. buffer_format(50),
  12485. Some((&[10, 10, 10, 2][..], Numeric::Unorm))
  12486. );
  12487. assert_eq!(buffer_format(13), Some((&[16][..], Numeric::Float)));
  12488. assert_eq!(
  12489. buffer_format(77),
  12490. Some((&[32, 32, 32, 32][..], Numeric::Float))
  12491. );
  12492. // Invalid, past the table.
  12493. assert_eq!(buffer_format(0), None);
  12494. assert_eq!(buffer_format(78), None);
  12495. }
  12496. #[test]
  12497. fn packed_buffer_formats_by_number() {
  12498. // LLVM's `UfmtGFX10`: 10_11_11 is 30-36, 11_11_10 37-43,
  12499. // 10_10_10_2 44-49. Channels from the lowest bits: R11G11B10_FLOAT
  12500. // is 10_11_11 (Mesa), 10_10_10_2 has the 2-bit channel first.
  12501. assert_eq!(buffer_format(30), Some((&[11, 11, 10][..], Numeric::Unorm)));
  12502. assert_eq!(buffer_format(36), Some((&[11, 11, 10][..], Numeric::Float)));
  12503. assert_eq!(buffer_format(37), Some((&[10, 11, 11][..], Numeric::Unorm)));
  12504. assert_eq!(buffer_format(43), Some((&[10, 11, 11][..], Numeric::Float)));
  12505. assert_eq!(
  12506. buffer_format(44),
  12507. Some((&[2, 10, 10, 10][..], Numeric::Unorm))
  12508. );
  12509. assert_eq!(
  12510. buffer_format(45),
  12511. Some((&[2, 10, 10, 10][..], Numeric::Snorm))
  12512. );
  12513. assert_eq!(
  12514. buffer_format(46),
  12515. Some((&[2, 10, 10, 10][..], Numeric::Uscaled))
  12516. );
  12517. assert_eq!(
  12518. buffer_format(47),
  12519. Some((&[2, 10, 10, 10][..], Numeric::Sscaled))
  12520. );
  12521. assert_eq!(
  12522. buffer_format(48),
  12523. Some((&[2, 10, 10, 10][..], Numeric::Uint))
  12524. );
  12525. assert_eq!(
  12526. buffer_format(49),
  12527. Some((&[2, 10, 10, 10][..], Numeric::Sint))
  12528. );
  12529. }
  12530. /// A half's value (sign, 5-bit exponent biased 15, 10-bit mantissa), as
  12531. /// `legacyF16ToF32` widens it.
  12532. fn half(h: u32) -> f32 {
  12533. let (s, e, m) = ((h >> 15) & 1, (h >> 10) & 31, h & 1023);
  12534. let v = match e {
  12535. 0 => m as f32 * 2f32.powi(-24),
  12536. 31 if m == 0 => f32::INFINITY,
  12537. 31 => f32::NAN,
  12538. _ => (1024 + m) as f32 * 2f32.powi(e as i32 - 25),
  12539. };
  12540. if s == 1 { -v } else { v }
  12541. }
  12542. #[test]
  12543. fn small_floats_widen_as_halves() {
  12544. // Unsigned 11- and 10-bit floats: a 5-bit exponent biased 15 over a
  12545. // 6- or 5-bit mantissa, no sign; values from the D3D/GL spec.
  12546. let f11 = |x: u32| half(x << half_shift(11));
  12547. let f10 = |x: u32| half(x << half_shift(10));
  12548. assert_eq!(f11(0), 0.0);
  12549. assert_eq!(f11(0x001), 2f32.powi(-20)); // smallest denormal
  12550. assert_eq!(f11(0x03F), 63.0 * 2f32.powi(-20)); // largest denormal
  12551. assert_eq!(f11(0x040), 2f32.powi(-14)); // smallest normal
  12552. assert_eq!(f11(0x3C0), 1.0);
  12553. assert_eq!(f11(0x3E0), 1.5);
  12554. assert_eq!(f11(0x7BF), 65024.0); // largest
  12555. assert_eq!(f11(0x7C0), f32::INFINITY);
  12556. assert!(f11(0x7C1).is_nan());
  12557. assert_eq!(f10(0x001), 2f32.powi(-19));
  12558. assert_eq!(f10(0x020), 2f32.powi(-14));
  12559. assert_eq!(f10(0x1E0), 1.0);
  12560. assert_eq!(f10(0x3DF), 64512.0);
  12561. assert_eq!(f10(0x3E0), f32::INFINITY);
  12562. assert!(f10(0x3FF).is_nan());
  12563. // A 16-bit float is a half already, sign included.
  12564. assert_eq!(half(0xBC00 << half_shift(16)), -1.0);
  12565. }
  12566. }